Walking skeleton: server, packaging, dev builds
ci / go (push) Successful in 2m25s
ci / package (push) Failing after 1m25s

- cmd/sharestead: binary with -version; HTTPS on :8443 with a self-signed
  certificate generated once into /var/lib/sharestead/tls (0600, atomic write)
- internal/server: health endpoint, embedded placeholder UI, security headers
  (CSP, HSTS, nosniff, no-referrer), timeouts, graceful shutdown; tests
- packaging: .deb for amd64 + arm64 via nfpm (depends samba, smbclient, acl;
  recommends wsdd2|wsdd, avahi-daemon, nfs-kernel-server), hardened systemd
  unit, maintainer scripts (enable on install, try-restart on upgrade,
  data removed only on purge)
- versions: VERSION + dev suffix → 0.1.0~dev.<time>.g<commit> in the .deb;
  ordering checked with dpkg --compare-versions
- CI: package job on main uploads to the Gitea Debian registry (channel dev)

Installed manually on CT 151: service active, healthz/UI/headers verified
over the network from CT 140.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nico.stoerzbachandClaude Opus 5.5 committed 2026-11-28 20:47:42 +01:00
1 parent 4476671491
commit 71ca6305af
18 files changed
+546

No files matched your search

+26
View File
@@ -25,3 +25,29 @@ jobs:
run: make fuzz-short
- name: known vulnerabilities
run: go run golang.org/x/vuln/cmd/govulncheck@latest ./...
package:
# dev packages for every push to main → Gitea Debian registry, channel "dev"
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
needs: go
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- uses: actions/setup-go@v6
with:
go-version-file: go.mod
- name: build .deb (amd64, arm64)
run: scripts/build-packages.sh
- name: upload to the dev channel
env:
TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
owner="${GITHUB_REPOSITORY%%/*}"
for deb in dist/*.deb; do
code=$(curl -s -o /tmp/resp -w '%{http_code}' --user "${GITHUB_ACTOR}:${TOKEN}" \
--upload-file "$deb" "${GITHUB_SERVER_URL}/api/packages/${owner}/debian/pool/dev/main/upload")
echo "$deb → HTTP $code"; cat /tmp/resp; echo
[ "$code" = 201 ] || [ "$code" = 409 ] || exit 1
done
+3
View File
@@ -12,12 +12,15 @@ keep working and show up in the UI.
```bash
go test -race -cover ./... # unit tests
make fuzz-short # short fuzz run (needs make)
scripts/build-packages.sh # .deb packages into dist/
```
| Path | What |
|---|---|
| `internal/format/smbconf` | lossless reader/writer for `smb.conf` (round-trip byte-identical, edits touch only their lines) |
| `internal/format/exports` | same for NFS `/etc/exports` and `exports.d` |
| `cmd/sharestead`, `internal/server` | the binary: HTTPS server (self-signed cert on first start), health endpoint, placeholder UI |
| `packaging/`, `scripts/build-packages.sh` | `.deb` for amd64/arm64 with systemd unit; dev builds on every push to `main` |
| `docs/planning/` | discovery, requirements, design, mockups, plan |
## Licence
+1
View File
@@ -0,0 +1 @@
0.1.0
+47
View File
@@ -0,0 +1,47 @@
// Command sharestead runs the Sharestead web UI.
package main
import (
"context"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"path/filepath"
"syscall"
"sharestead/internal/server"
"sharestead/internal/tlscert"
"sharestead/internal/version"
)
func main() {
listen := flag.String("listen", ":8443", "address for the web UI (HTTPS)")
dataDir := flag.String("data-dir", "/var/lib/sharestead", "directory for app data (TLS certificate, database)")
showVersion := flag.Bool("version", false, "print the version and exit")
flag.Parse()
if *showVersion {
fmt.Println("sharestead", version.String())
return
}
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
if err := run(*listen, *dataDir, log); err != nil {
log.Error("stopped", "error", err)
os.Exit(1)
}
}
func run(listen, dataDir string, log *slog.Logger) error {
host, _ := os.Hostname()
cert, err := tlscert.LoadOrCreate(filepath.Join(dataDir, "tls", "cert.pem"), filepath.Join(dataDir, "tls", "key.pem"), []string{host, "localhost"})
if err != nil {
return fmt.Errorf("TLS certificate: %w", err)
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
log.Info("starting", "version", version.String())
return server.New(listen, cert, log).Run(ctx)
}
+92
View File
@@ -0,0 +1,92 @@
// Package server is the HTTP(S) entry point: web UI assets, health endpoint
// and (later) the REST API. It is a driving adapter and contains no business
// logic.
package server
import (
"context"
"crypto/tls"
"embed"
"encoding/json"
"errors"
"io/fs"
"log/slog"
"net/http"
"time"
"sharestead/internal/version"
)
//go:embed static
var staticFiles embed.FS
// Server serves the web UI and API.
type Server struct {
http *http.Server
log *slog.Logger
}
// New creates a server listening on addr with the given certificate.
func New(addr string, cert tls.Certificate, log *slog.Logger) *Server {
mux := http.NewServeMux()
static, _ := fs.Sub(staticFiles, "static")
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServerFS(static)))
mux.HandleFunc("GET /healthz", health)
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
http.ServeFileFS(w, r, static, "index.html")
})
return &Server{
log: log,
http: &http.Server{
Addr: addr,
Handler: securityHeaders(mux),
TLSConfig: &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12},
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 60 * time.Second,
IdleTimeout: 120 * time.Second,
MaxHeaderBytes: 64 << 10,
},
}
}
// Run serves until ctx is cancelled, then shuts down gracefully.
func (s *Server) Run(ctx context.Context) error {
errc := make(chan error, 1)
go func() {
s.log.Info("listening", "addr", s.http.Addr)
errc <- s.http.ListenAndServeTLS("", "")
}()
select {
case err := <-errc:
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
case <-ctx.Done():
shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return s.http.Shutdown(shutdown)
}
}
// Handler returns the HTTP handler (for tests).
func (s *Server) Handler() http.Handler { return s.http.Handler }
func health(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(map[string]string{"status": "ok", "version": version.Version})
}
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("Content-Security-Policy", "default-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "no-referrer")
h.Set("Strict-Transport-Security", "max-age=31536000")
next.ServeHTTP(w, r)
})
}
+63
View File
@@ -0,0 +1,63 @@
package server
import (
"crypto/tls"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func newTestHandler() http.Handler {
return New(":0", tls.Certificate{}, slog.New(slog.NewTextHandler(io.Discard, nil))).Handler()
}
func TestHealth(t *testing.T) {
rec := httptest.NewRecorder()
newTestHandler().ServeHTTP(rec, httptest.NewRequest("GET", "/healthz", nil))
if rec.Code != 200 {
t.Fatalf("status %d", rec.Code)
}
var body map[string]string
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil || body["status"] != "ok" {
t.Fatalf("body %v err %v", body, err)
}
}
func TestIndexAndStatic(t *testing.T) {
for path, want := range map[string]string{"/": "<title>Sharestead</title>", "/static/app.js": "healthz"} {
rec := httptest.NewRecorder()
newTestHandler().ServeHTTP(rec, httptest.NewRequest("GET", path, nil))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), want) {
t.Errorf("%s: status %d, body %.80q", path, rec.Code, rec.Body.String())
}
}
}
func TestSecurityHeadersOnEveryResponse(t *testing.T) {
for _, path := range []string{"/", "/healthz", "/does-not-exist"} {
rec := httptest.NewRecorder()
newTestHandler().ServeHTTP(rec, httptest.NewRequest("GET", path, nil))
for _, h := range []string{"Content-Security-Policy", "X-Content-Type-Options", "Referrer-Policy", "Strict-Transport-Security"} {
if rec.Header().Get(h) == "" {
t.Errorf("%s: missing %s", path, h)
}
}
}
}
func TestUnknownPathIs404AndWrongMethodRejected(t *testing.T) {
rec := httptest.NewRecorder()
newTestHandler().ServeHTTP(rec, httptest.NewRequest("GET", "/nope", nil))
if rec.Code != 404 {
t.Errorf("GET /nope: %d", rec.Code)
}
rec = httptest.NewRecorder()
newTestHandler().ServeHTTP(rec, httptest.NewRequest("POST", "/healthz", nil))
if rec.Code != 405 {
t.Errorf("POST /healthz: %d", rec.Code)
}
}
+4
View File
@@ -0,0 +1,4 @@
body{margin:0;font:15px/1.5 system-ui,sans-serif;background:#f6f7f9;color:#1d2330;display:grid;place-items:center;min-height:100vh}
main{background:#fff;border:1px solid #e4e7ec;border-radius:12px;padding:32px 40px;max-width:480px}
h1{margin:0 0 8px}.muted{color:#667085}
@media (prefers-color-scheme:dark){body{background:#0f141c;color:#e6e9ef}main{background:#171e29;border-color:#283244}.muted{color:#98a2b3}}
+1
View File
@@ -0,0 +1 @@
fetch('/healthz').then(r => r.json()).then(d => { document.getElementById('v').textContent = d.version; });
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sharestead</title>
<link rel="stylesheet" href="/static/app.css">
</head>
<body>
<main>
<h1>Sharestead</h1>
<p>Your own homestead for files. The web UI is under construction.</p>
<p class="muted">Version <span id="v">…</span></p>
</main>
<script src="/static/app.js"></script>
</body>
</html>
+120
View File
@@ -0,0 +1,120 @@
// Package tlscert provides the TLS certificate for the web UI: an existing
// certificate/key pair, or a self-signed one that is generated once and kept.
package tlscert
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"math/big"
"net"
"os"
"path/filepath"
"time"
)
// LoadOrCreate loads certFile/keyFile. If neither exists, it creates a
// self-signed certificate valid for 10 years for the given host names and
// all local IP addresses, and stores it with mode 0600.
func LoadOrCreate(certFile, keyFile string, hosts []string) (tls.Certificate, error) {
_, certErr := os.Stat(certFile)
_, keyErr := os.Stat(keyFile)
switch {
case certErr == nil && keyErr == nil:
return tls.LoadX509KeyPair(certFile, keyFile)
case errors.Is(certErr, os.ErrNotExist) && errors.Is(keyErr, os.ErrNotExist):
if err := create(certFile, keyFile, hosts); err != nil {
return tls.Certificate{}, err
}
return tls.LoadX509KeyPair(certFile, keyFile)
default:
return tls.Certificate{}, fmt.Errorf("TLS: only one of %s and %s exists — remove the other or provide both", certFile, keyFile)
}
}
func create(certFile, keyFile string, hosts []string) error {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return err
}
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
if err != nil {
return err
}
tmpl := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{CommonName: firstOr(hosts, "sharestead"), Organization: []string{"Sharestead (self-signed)"}},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().AddDate(10, 0, 0),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
tmpl.IPAddresses = append(tmpl.IPAddresses, ip)
} else if h != "" {
tmpl.DNSNames = append(tmpl.DNSNames, h)
}
}
tmpl.IPAddresses = append(tmpl.IPAddresses, localIPs()...)
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
return err
}
keyDER, err := x509.MarshalECPrivateKey(key)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(certFile), 0o700); err != nil {
return err
}
if err := writePEM(keyFile, "EC PRIVATE KEY", keyDER); err != nil {
return err
}
return writePEM(certFile, "CERTIFICATE", der)
}
func writePEM(path, typ string, der []byte) error {
tmp := path + ".tmp"
f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
return err
}
if err := pem.Encode(f, &pem.Block{Type: typ, Bytes: der}); err != nil {
f.Close()
return err
}
if err := f.Sync(); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(tmp, path)
}
func localIPs() []net.IP {
var out []net.IP
addrs, _ := net.InterfaceAddrs()
for _, a := range addrs {
if n, ok := a.(*net.IPNet); ok {
out = append(out, n.IP)
}
}
return out
}
func firstOr(s []string, def string) string {
if len(s) > 0 && s[0] != "" {
return s[0]
}
return def
}
+41
View File
@@ -0,0 +1,41 @@
package tlscert
import (
"bytes"
"os"
"path/filepath"
"testing"
)
func TestCreatesOnceThenReuses(t *testing.T) {
dir := t.TempDir()
cert, key := filepath.Join(dir, "tls", "cert.pem"), filepath.Join(dir, "tls", "key.pem")
if _, err := LoadOrCreate(cert, key, []string{"nas", "192.168.0.5"}); err != nil {
t.Fatal(err)
}
first, _ := os.ReadFile(cert)
for _, p := range []string{cert, key} {
st, err := os.Stat(p)
if err != nil || st.Mode().Perm() != 0o600 {
t.Fatalf("%s: mode %v err %v", p, st.Mode().Perm(), err)
}
}
if _, err := LoadOrCreate(cert, key, nil); err != nil {
t.Fatal(err)
}
second, _ := os.ReadFile(cert)
if !bytes.Equal(first, second) {
t.Fatal("certificate was regenerated instead of reused")
}
}
func TestOnlyOneFileIsAnError(t *testing.T) {
dir := t.TempDir()
cert, key := filepath.Join(dir, "cert.pem"), filepath.Join(dir, "key.pem")
if err := os.WriteFile(cert, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := LoadOrCreate(cert, key, nil); err == nil {
t.Fatal("expected an error when only the certificate exists")
}
}
+16
View File
@@ -0,0 +1,16 @@
// Package version holds build information, set at build time via -ldflags.
package version
import "fmt"
// Set by the build: -ldflags "-X sharestead/internal/version.Version=… -X …Commit=… -X …Date=…"
var (
Version = "0.0.0-dev"
Commit = "unknown"
Date = "unknown"
)
// String returns a one-line description, e.g. "0.1.0 (4476671, 2026-11-28)".
func String() string {
return fmt.Sprintf("%s (%s, %s)", Version, Commit, Date)
}
+37
View File
@@ -0,0 +1,37 @@
# Debian package definition (https://nfpm.goreleaser.com). Built by scripts/build-packages.sh.
name: sharestead
arch: ${ARCH}
platform: linux
version: ${VERSION}
version_schema: semver
section: net
priority: optional
maintainer: Nico Störzbach <noreply@sharestead.invalid>
description: |-
Web UI for network shares (SMB and NFS)
Users, groups, permissions, quotas and discovery for Samba and NFS,
living entirely inside one container, VM or Debian system. Config files
stay the source of truth; hand edits show up in the UI.
homepage: https://git.nstoerzbach.de/nico.stoerzbach/sharestead
license: GPL-3.0-only
depends:
- samba
- smbclient
- acl
recommends:
- wsdd2 | wsdd
- avahi-daemon
- nfs-kernel-server
contents:
- src: dist/${ARCH}/sharestead
dst: /usr/bin/sharestead
file_info:
mode: 0755
- src: packaging/systemd/sharestead.service
dst: /usr/lib/systemd/system/sharestead.service
- src: LICENSE
dst: /usr/share/doc/sharestead/copyright
scripts:
postinstall: packaging/scripts/postinst.sh
preremove: packaging/scripts/prerm.sh
postremove: packaging/scripts/postrm.sh
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
set -e
if [ "$1" = "configure" ]; then
systemctl daemon-reload >/dev/null 2>&1 || true
if [ -z "$2" ]; then
systemctl enable --now sharestead.service >/dev/null 2>&1 || true
echo "Sharestead is running: https://$(hostname -I 2>/dev/null | awk '{print $1}'):8443"
else
systemctl try-restart sharestead.service >/dev/null 2>&1 || true
fi
fi
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -e
systemctl daemon-reload >/dev/null 2>&1 || true
if [ "$1" = "purge" ]; then
rm -rf /var/lib/sharestead
fi
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -e
if [ "$1" = "remove" ]; then
systemctl disable --now sharestead.service >/dev/null 2>&1 || true
fi
+33
View File
@@ -0,0 +1,33 @@
[Unit]
Description=Sharestead — web UI for network shares
Documentation=https://git.nstoerzbach.de/nico.stoerzbach/sharestead
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/bin/sharestead -listen :8443 -data-dir /var/lib/sharestead
Restart=on-failure
RestartSec=2s
StateDirectory=sharestead
StateDirectoryMode=0700
# Hardening. The app manages Samba/NFS config and users as root, so the file
# system stays writable; kernel, devices and other namespaces are locked down.
NoNewPrivileges=yes
PrivateTmp=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
RestrictSUIDSGID=yes
RestrictRealtime=yes
RestrictNamespaces=yes
LockPersonality=yes
SystemCallArchitectures=native
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
[Install]
WantedBy=multi-user.target
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
# Builds sharestead binaries and .deb packages for amd64 and arm64 into dist/.
# Usage: scripts/build-packages.sh [version] (default: dev version from VERSION + date + commit)
set -euo pipefail
cd "$(dirname "$0")/.."
commit=$(git rev-parse --short HEAD 2>/dev/null || echo unknown)
date=$(date -u +%Y-%m-%d)
version=${1:-"$(cat VERSION)-dev.$(date -u +%Y%m%d%H%M).g${commit}"}
version=${version#v}
rm -rf dist && mkdir -p dist
for arch in amd64 arm64; do
mkdir -p "dist/$arch"
CGO_ENABLED=0 GOOS=linux GOARCH=$arch go build -trimpath \
-ldflags "-s -w -X sharestead/internal/version.Version=$version -X sharestead/internal/version.Commit=$commit -X sharestead/internal/version.Date=$date" \
-o "dist/$arch/sharestead" ./cmd/sharestead
sed -e "s|\${ARCH}|$arch|g" -e "s|\${VERSION}|$version|g" packaging/nfpm.yaml > "dist/nfpm-$arch.yaml"
go run github.com/goreleaser/nfpm/v2/cmd/nfpm@v2.43.1 \
package --config "dist/nfpm-$arch.yaml" --packager deb --target dist/
done
ls -l dist/*.deb
echo "version: $version"