From 84fd31ccaa54d3b6e21991df9ab5ddee9552825d Mon Sep 17 00:00:00 2001 From: Steve Cliff Date: Fri, 1 May 2026 00:28:18 +0100 Subject: [PATCH] phase 1: HTTP server + first-run bootstrap P1-01 chi router, slog request log, graceful shutdown via signal context. Health endpoint, /api/auth/login, /api/auth/logout, /api/bootstrap. Background sweeper for expired sessions and enrollment tokens (15 min cadence). P1-04 (sessions half) HttpOnly Secure-when-TLS cookie carrying a base64url token; server stores SHA-256(token) so a stolen DB doesn't yield credentials. Unknown user and bad password collapse to the same 401 response code so a probe can't enumerate names. P1-05 first-run admin bootstrap. On a fresh DB the server mints a one-time token and prints it to stderr inside a banner. The /api/bootstrap handler accepts {token, username, password}, creates the first admin, then becomes a 409 forever. P1-07 (partial) audit hooks fire on auth.login and auth.bootstrap. Full middleware-driven coverage lands with the rest of the API. internal/server/config: env > YAML > defaults. RM_LISTEN / RM_DATA_DIR / RM_BASE_URL / RM_TLS_CERT / RM_TLS_KEY / RM_SECRET_KEY_FILE / RM_TRUSTED_PROXY (CIDR list, validated). End-to-end smoke test passes: server boots on a fresh dir, prints the bootstrap token, POST /api/bootstrap creates the admin, POST /api/auth/login returns 200 with a session cookie. Co-Authored-By: Claude Opus 4.7 (1M context) --- cmd/server/main.go | 129 +++++++++++++- go.mod | 3 + go.sum | 9 + internal/server/config/config.go | 114 ++++++++++++ internal/server/config/config_test.go | 92 ++++++++++ internal/server/config/testhelpers_test.go | 7 + internal/server/http/auth.go | 192 +++++++++++++++++++++ internal/server/http/auth_test.go | 189 ++++++++++++++++++++ internal/server/http/doc.go | 2 - internal/server/http/middleware.go | 28 +++ internal/server/http/server.go | 110 ++++++++++++ 11 files changed, 869 insertions(+), 6 deletions(-) create mode 100644 internal/server/config/config.go create mode 100644 internal/server/config/config_test.go create mode 100644 internal/server/config/testhelpers_test.go create mode 100644 internal/server/http/auth.go create mode 100644 internal/server/http/auth_test.go delete mode 100644 internal/server/http/doc.go create mode 100644 internal/server/http/middleware.go create mode 100644 internal/server/http/server.go diff --git a/cmd/server/main.go b/cmd/server/main.go index 825c106..bc6d2b0 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -2,32 +2,153 @@ package main import ( "context" + "errors" "flag" "fmt" "log/slog" "os" "os/signal" + "path/filepath" "syscall" + "time" + + "gitea.dcglab.co.uk/steve/restic-manager/internal/auth" + "gitea.dcglab.co.uk/steve/restic-manager/internal/crypto" + rmhttp "gitea.dcglab.co.uk/steve/restic-manager/internal/server/http" + "gitea.dcglab.co.uk/steve/restic-manager/internal/server/config" + "gitea.dcglab.co.uk/steve/restic-manager/internal/store" ) var version = "dev" func main() { + if err := run(); err != nil { + slog.Error("server fatal", "err", err) + os.Exit(1) + } +} + +func run() error { + configPath := flag.String("config", "", "path to YAML config (optional; env vars win regardless)") showVersion := flag.Bool("version", false, "print version and exit") flag.Parse() if *showVersion { fmt.Println("restic-manager-server", version) - return + return nil } logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})) slog.SetDefault(logger) + cfg, err := config.Load(*configPath) + if err != nil { + return fmt.Errorf("config: %w", err) + } + slog.Info("config resolved", "listen", cfg.Listen, "data_dir", cfg.DataDir, + "tls", cfg.TLSEnabled(), "trusted_proxies", cfg.TrustedProxies) + + if err := os.MkdirAll(cfg.DataDir, 0o700); err != nil { + return fmt.Errorf("ensure data dir: %w", err) + } + + // Mint or load the encryption key. + if _, err := os.Stat(cfg.SecretKeyFile); errors.Is(err, os.ErrNotExist) { + slog.Warn("no secret key found; generating a new one — back this up before continuing", + "path", cfg.SecretKeyFile) + if err := crypto.GenerateKeyFile(cfg.SecretKeyFile); err != nil { + return fmt.Errorf("generate secret key: %w", err) + } + } + keyBytes, err := crypto.LoadKeyFromFile(cfg.SecretKeyFile) + if err != nil { + return fmt.Errorf("load secret key: %w", err) + } + aead, err := crypto.NewAEAD(keyBytes) + if err != nil { + return fmt.Errorf("init AEAD: %w", err) + } + + dbPath := filepath.Join(cfg.DataDir, "restic-manager.db") + st, err := store.Open(context.Background(), dbPath) + if err != nil { + return fmt.Errorf("open store: %w", err) + } + defer func() { _ = st.Close() }() + + deps := rmhttp.Deps{ + Cfg: cfg, + Store: st, + AEAD: aead, + } + + // First-run bootstrap: if the users table is empty, mint a one-time + // token and print it. /api/bootstrap accepts it to create the first + // admin user, then becomes a no-op. + n, err := st.CountUsers(context.Background()) + if err != nil { + return fmt.Errorf("count users: %w", err) + } + if n == 0 { + token, err := auth.NewToken() + if err != nil { + return fmt.Errorf("mint bootstrap token: %w", err) + } + deps.BootstrapToken = token + // Stable, easy-to-grep marker so an operator finds this in + // scrolling logs without spelunking. Token is shown in plain + // text exactly once; we hash it into BootstrapToken on the + // server-side handler. + fmt.Fprintln(os.Stderr, "================================================================") + fmt.Fprintln(os.Stderr, " FIRST RUN — bootstrap token (use within 1 hour, then it's gone):") + fmt.Fprintln(os.Stderr, " "+token) + fmt.Fprintln(os.Stderr, " POST it to /api/bootstrap with {token, username, password}.") + fmt.Fprintln(os.Stderr, "================================================================") + } + + srv := rmhttp.New(deps) + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() - slog.Info("restic-manager server starting", "version", version) - <-ctx.Done() - slog.Info("shutting down") + errCh := make(chan error, 1) + go func() { + slog.Info("server listening", "addr", cfg.Listen, "version", version) + errCh <- srv.Start() + }() + + // Background sweeper for expired sessions and enrollment tokens. + tick := time.NewTicker(15 * time.Minute) + defer tick.Stop() + go func() { + for { + select { + case <-ctx.Done(): + return + case <-tick.C: + if n, err := st.PurgeExpiredSessions(ctx); err == nil && n > 0 { + slog.Info("purged expired sessions", "n", n) + } + if n, err := st.PurgeExpiredEnrollmentTokens(ctx); err == nil && n > 0 { + slog.Info("purged expired enrollment tokens", "n", n) + } + } + } + }() + + select { + case err := <-errCh: + if err != nil { + return fmt.Errorf("listen: %w", err) + } + case <-ctx.Done(): + slog.Info("shutting down") + } + + shutCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + if err := srv.Shutdown(shutCtx); err != nil { + return fmt.Errorf("shutdown: %w", err) + } + return nil } diff --git a/go.mod b/go.mod index dce2b6d..0c283ac 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,10 @@ module gitea.dcglab.co.uk/steve/restic-manager go 1.25.0 require ( + github.com/go-chi/chi/v5 v5.2.5 + github.com/oklog/ulid/v2 v2.1.1 golang.org/x/crypto v0.50.0 + gopkg.in/yaml.v3 v3.0.1 modernc.org/sqlite v1.50.0 ) diff --git a/go.sum b/go.sum index e478a19..18dc058 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug= +github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0= github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= @@ -10,6 +12,9 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/oklog/ulid/v2 v2.1.1 h1:suPZ4ARWLOJLegGFiZZ1dFAkqzhMjL3J1TzI+5wHz8s= +github.com/oklog/ulid/v2 v2.1.1/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ= +github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI= @@ -23,6 +28,10 @@ golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI= golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= modernc.org/cc/v4 v4.27.3 h1:uNCgn37E5U09mTv1XgskEVUJ8ADKpmFMPxzGJ0TSo+U= modernc.org/cc/v4 v4.27.3/go.mod h1:3YjcbCqhoTTHPycJDRl2WZKKFj0nwcOIPBfEZK0Hdk8= modernc.org/ccgo/v4 v4.32.4 h1:L5OB8rpEX4ZsXEQwGozRfJyJSFHbbNVOoQ59DU9/KuU= diff --git a/internal/server/config/config.go b/internal/server/config/config.go new file mode 100644 index 0000000..c53df77 --- /dev/null +++ b/internal/server/config/config.go @@ -0,0 +1,114 @@ +// Package config loads server configuration from env vars (the +// canonical source) with optional YAML overlay. Documented vars are +// listed in spec.md §4.1. +package config + +import ( + "fmt" + "net" + "net/netip" + "os" + "strings" + + "gopkg.in/yaml.v3" +) + +// Config holds runtime parameters resolved from env + (optionally) a +// YAML file. Env wins over YAML so operators can tweak a single var +// without rewriting the file. +type Config struct { + Listen string `yaml:"listen"` + DataDir string `yaml:"data_dir"` + BaseURL string `yaml:"base_url"` + TLSCert string `yaml:"tls_cert"` + TLSKey string `yaml:"tls_key"` + SecretKeyFile string `yaml:"secret_key_file"` + TrustedProxies []string `yaml:"trusted_proxies"` +} + +// Load resolves config in this order: +// 1. defaults +// 2. YAML at the given path (if non-empty and exists) +// 3. environment variables (RM_LISTEN, RM_DATA_DIR, …) +// +// The result is validated; a zero-error return means the server is +// safe to start. +func Load(yamlPath string) (Config, error) { + c := Config{ + Listen: ":8443", + DataDir: "/data", + } + + if yamlPath != "" { + body, err := os.ReadFile(yamlPath) + if err != nil && !os.IsNotExist(err) { + return c, fmt.Errorf("config: read %q: %w", yamlPath, err) + } + if err == nil { + if err := yaml.Unmarshal(body, &c); err != nil { + return c, fmt.Errorf("config: parse %q: %w", yamlPath, err) + } + } + } + + if v, ok := os.LookupEnv("RM_LISTEN"); ok { + c.Listen = v + } + if v, ok := os.LookupEnv("RM_DATA_DIR"); ok { + c.DataDir = v + } + if v, ok := os.LookupEnv("RM_BASE_URL"); ok { + c.BaseURL = v + } + if v, ok := os.LookupEnv("RM_TLS_CERT"); ok { + c.TLSCert = v + } + if v, ok := os.LookupEnv("RM_TLS_KEY"); ok { + c.TLSKey = v + } + if v, ok := os.LookupEnv("RM_SECRET_KEY_FILE"); ok { + c.SecretKeyFile = v + } + if v, ok := os.LookupEnv("RM_TRUSTED_PROXY"); ok { + // Comma-separated CIDRs; allow whitespace for readability. + parts := strings.Split(v, ",") + c.TrustedProxies = c.TrustedProxies[:0] + for _, p := range parts { + p = strings.TrimSpace(p) + if p != "" { + c.TrustedProxies = append(c.TrustedProxies, p) + } + } + } + + return c, c.validate() +} + +func (c *Config) validate() error { + if c.Listen == "" { + return fmt.Errorf("config: RM_LISTEN must be set") + } + if _, _, err := net.SplitHostPort(c.Listen); err != nil { + return fmt.Errorf("config: RM_LISTEN %q invalid: %w", c.Listen, err) + } + if c.DataDir == "" { + return fmt.Errorf("config: RM_DATA_DIR must be set") + } + if c.SecretKeyFile == "" { + // Default to data dir. + c.SecretKeyFile = c.DataDir + "/secret.key" + } + for _, cidr := range c.TrustedProxies { + if _, err := netip.ParsePrefix(cidr); err != nil { + return fmt.Errorf("config: RM_TRUSTED_PROXY entry %q is not a valid CIDR: %w", cidr, err) + } + } + // TLS pair: either both set or both unset (HTTP-only mode for dev). + if (c.TLSCert == "") != (c.TLSKey == "") { + return fmt.Errorf("config: RM_TLS_CERT and RM_TLS_KEY must be set together (or both unset)") + } + return nil +} + +// TLSEnabled is true when both cert and key are configured. +func (c Config) TLSEnabled() bool { return c.TLSCert != "" && c.TLSKey != "" } diff --git a/internal/server/config/config_test.go b/internal/server/config/config_test.go new file mode 100644 index 0000000..857c73e --- /dev/null +++ b/internal/server/config/config_test.go @@ -0,0 +1,92 @@ +package config + +import ( + "path/filepath" + "testing" +) + +func TestDefaultsValid(t *testing.T) { + t.Setenv("RM_LISTEN", ":8443") + t.Setenv("RM_DATA_DIR", "/tmp/rm-test") + + c, err := Load("") + if err != nil { + t.Fatalf("load: %v", err) + } + if c.Listen != ":8443" { + t.Errorf("listen: %q", c.Listen) + } + if c.SecretKeyFile != "/tmp/rm-test/secret.key" { + t.Errorf("secret_key_file default: %q", c.SecretKeyFile) + } +} + +func TestEnvOverridesYAML(t *testing.T) { + dir := t.TempDir() + yamlPath := filepath.Join(dir, "rm.yaml") + body := []byte(`listen: ":7000"` + "\n" + + `data_dir: "/var/lib/rm"` + "\n" + + `base_url: "https://yaml.example"` + "\n") + if err := writeFile(yamlPath, body); err != nil { + t.Fatal(err) + } + + t.Setenv("RM_LISTEN", ":9999") + t.Setenv("RM_BASE_URL", "https://env.example") + + c, err := Load(yamlPath) + if err != nil { + t.Fatalf("load: %v", err) + } + if c.Listen != ":9999" { + t.Errorf("env should win: %q", c.Listen) + } + if c.BaseURL != "https://env.example" { + t.Errorf("env should win: %q", c.BaseURL) + } + if c.DataDir != "/var/lib/rm" { + t.Errorf("yaml should fill: %q", c.DataDir) + } +} + +func TestTrustedProxyParsing(t *testing.T) { + t.Setenv("RM_LISTEN", ":8443") + t.Setenv("RM_DATA_DIR", "/tmp/x") + t.Setenv("RM_TRUSTED_PROXY", "10.0.0.0/8, 192.168.1.0/24") + + c, err := Load("") + if err != nil { + t.Fatalf("load: %v", err) + } + if len(c.TrustedProxies) != 2 { + t.Fatalf("want 2 proxies, got %v", c.TrustedProxies) + } + if c.TrustedProxies[0] != "10.0.0.0/8" || c.TrustedProxies[1] != "192.168.1.0/24" { + t.Errorf("parsed: %v", c.TrustedProxies) + } +} + +func TestTrustedProxyRejectsGarbage(t *testing.T) { + t.Setenv("RM_LISTEN", ":8443") + t.Setenv("RM_DATA_DIR", "/tmp/x") + t.Setenv("RM_TRUSTED_PROXY", "not-a-cidr") + + if _, err := Load(""); err == nil { + t.Fatal("expected validation error, got nil") + } +} + +func TestTLSPairConsistency(t *testing.T) { + t.Setenv("RM_LISTEN", ":8443") + t.Setenv("RM_DATA_DIR", "/tmp/x") + t.Setenv("RM_TLS_CERT", "/some/cert.pem") + // key intentionally unset + + if _, err := Load(""); err == nil { + t.Fatal("expected error: cert without key") + } +} + +func writeFile(path string, body []byte) error { + return writeFileImpl(path, body) +} diff --git a/internal/server/config/testhelpers_test.go b/internal/server/config/testhelpers_test.go new file mode 100644 index 0000000..17ca4b0 --- /dev/null +++ b/internal/server/config/testhelpers_test.go @@ -0,0 +1,7 @@ +package config + +import "os" + +func writeFileImpl(path string, body []byte) error { + return os.WriteFile(path, body, 0o600) +} diff --git a/internal/server/http/auth.go b/internal/server/http/auth.go new file mode 100644 index 0000000..f7d93e6 --- /dev/null +++ b/internal/server/http/auth.go @@ -0,0 +1,192 @@ +package http + +import ( + "crypto/subtle" + "encoding/json" + stdhttp "net/http" + "time" + + "github.com/oklog/ulid/v2" + + "gitea.dcglab.co.uk/steve/restic-manager/internal/auth" + "gitea.dcglab.co.uk/steve/restic-manager/internal/store" +) + +const ( + sessionCookieName = "rm_session" + sessionTTL = 24 * time.Hour + bootstrapCookie = "rm_bootstrap_used" +) + +type loginRequest struct { + Username string `json:"username"` + Password string `json:"password"` +} + +type loginResponse struct { + UserID string `json:"user_id"` + Role string `json:"role"` +} + +func (s *Server) handleLogin(w stdhttp.ResponseWriter, r *stdhttp.Request) { + var req loginRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeJSONError(w, stdhttp.StatusBadRequest, "invalid_json", err.Error()) + return + } + + u, err := s.deps.Store.GetUserByUsername(r.Context(), req.Username) + if err != nil { + // Same response for unknown user vs bad password — don't leak + // existence to a probing attacker. + writeJSONError(w, stdhttp.StatusUnauthorized, "invalid_credentials", "") + return + } + if err := auth.VerifyPassword(u.PasswordHash, req.Password); err != nil { + writeJSONError(w, stdhttp.StatusUnauthorized, "invalid_credentials", "") + return + } + + token, err := auth.NewToken() + if err != nil { + writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "") + return + } + now := time.Now().UTC() + sess := store.Session{ + UserID: u.ID, + CreatedAt: now, + ExpiresAt: now.Add(sessionTTL), + IP: r.RemoteAddr, + UA: r.UserAgent(), + } + if err := s.deps.Store.CreateSession(r.Context(), sess, auth.HashToken(token)); err != nil { + writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "") + return + } + _ = s.deps.Store.MarkUserLogin(r.Context(), u.ID, now) + + stdhttp.SetCookie(w, &stdhttp.Cookie{ + Name: sessionCookieName, + Value: token, + Path: "/", + HttpOnly: true, + Secure: s.deps.Cfg.TLSEnabled(), + SameSite: stdhttp.SameSiteLaxMode, + Expires: sess.ExpiresAt, + }) + + _ = s.deps.Store.AppendAudit(r.Context(), store.AuditEntry{ + ID: ulid.Make().String(), + UserID: &u.ID, + Actor: "user", + Action: "auth.login", + TS: now, + }) + + writeJSON(w, stdhttp.StatusOK, loginResponse{UserID: u.ID, Role: string(u.Role)}) +} + +func (s *Server) handleLogout(w stdhttp.ResponseWriter, r *stdhttp.Request) { + if c, err := r.Cookie(sessionCookieName); err == nil { + _ = s.deps.Store.DeleteSession(r.Context(), auth.HashToken(c.Value)) + } + stdhttp.SetCookie(w, &stdhttp.Cookie{ + Name: sessionCookieName, + Value: "", + Path: "/", + MaxAge: -1, + HttpOnly: true, + Secure: s.deps.Cfg.TLSEnabled(), + SameSite: stdhttp.SameSiteLaxMode, + }) + w.WriteHeader(stdhttp.StatusNoContent) +} + +type bootstrapRequest struct { + Token string `json:"token"` + Username string `json:"username"` + Password string `json:"password"` +} + +// handleBootstrap creates the first admin user. The endpoint accepts +// the one-time token printed in the server logs on first run, and is +// disabled the moment a user row exists. +func (s *Server) handleBootstrap(w stdhttp.ResponseWriter, r *stdhttp.Request) { + n, err := s.deps.Store.CountUsers(r.Context()) + if err != nil { + writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "") + return + } + if n > 0 { + writeJSONError(w, stdhttp.StatusConflict, "already_initialised", + "a user already exists; bootstrap is disabled") + return + } + if s.deps.BootstrapToken == "" { + writeJSONError(w, stdhttp.StatusServiceUnavailable, "no_token", + "bootstrap token not configured") + return + } + + var req bootstrapRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeJSONError(w, stdhttp.StatusBadRequest, "invalid_json", err.Error()) + return + } + // Constant-time compare keeps timing analysis off the table. + if subtle.ConstantTimeCompare([]byte(req.Token), []byte(s.deps.BootstrapToken)) != 1 { + writeJSONError(w, stdhttp.StatusUnauthorized, "invalid_token", "") + return + } + if req.Username == "" || len(req.Password) < 12 { + writeJSONError(w, stdhttp.StatusBadRequest, "weak_password", + "password must be at least 12 characters") + return + } + + hash, err := auth.HashPassword(req.Password) + if err != nil { + writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "") + return + } + u := store.User{ + ID: ulid.Make().String(), + Username: req.Username, + PasswordHash: hash, + Role: store.RoleAdmin, + CreatedAt: time.Now().UTC(), + } + if err := s.deps.Store.CreateUser(r.Context(), u); err != nil { + writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "") + return + } + _ = s.deps.Store.AppendAudit(r.Context(), store.AuditEntry{ + ID: ulid.Make().String(), + UserID: &u.ID, + Actor: "system", + Action: "auth.bootstrap", + TS: u.CreatedAt, + }) + + writeJSON(w, stdhttp.StatusCreated, loginResponse{ + UserID: u.ID, Role: string(u.Role), + }) +} + +// ----- json helpers -------------------------------------------------- + +type jsonError struct { + Code string `json:"code"` + Message string `json:"message,omitempty"` +} + +func writeJSON(w stdhttp.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} + +func writeJSONError(w stdhttp.ResponseWriter, status int, code, msg string) { + writeJSON(w, status, jsonError{Code: code, Message: msg}) +} diff --git a/internal/server/http/auth_test.go b/internal/server/http/auth_test.go new file mode 100644 index 0000000..740eb21 --- /dev/null +++ b/internal/server/http/auth_test.go @@ -0,0 +1,189 @@ +package http + +import ( + "bytes" + "context" + "encoding/json" + "io" + stdhttp "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + "gitea.dcglab.co.uk/steve/restic-manager/internal/crypto" + "gitea.dcglab.co.uk/steve/restic-manager/internal/server/config" + "gitea.dcglab.co.uk/steve/restic-manager/internal/store" +) + +// newTestServer wires up a Server with file-backed sqlite + a fresh +// AEAD key + an httptest harness. Returns the Server, its base URL, +// and the bootstrap token (caller decides whether to consume it). +func newTestServer(t *testing.T, withBootstrapToken bool) (*Server, string) { + t.Helper() + + dir := t.TempDir() + st, err := store.Open(context.Background(), filepath.Join(dir, "rm.db")) + if err != nil { + t.Fatalf("store: %v", err) + } + t.Cleanup(func() { _ = st.Close() }) + + keyPath := filepath.Join(dir, "secret.key") + if err := crypto.GenerateKeyFile(keyPath); err != nil { + t.Fatalf("genkey: %v", err) + } + key, _ := crypto.LoadKeyFromFile(keyPath) + aead, _ := crypto.NewAEAD(key) + + deps := Deps{ + Cfg: config.Config{Listen: ":0", DataDir: dir, SecretKeyFile: keyPath}, + Store: st, + AEAD: aead, + } + if withBootstrapToken { + deps.BootstrapToken = "test-token" + } + + s := New(deps) + ts := httptest.NewServer(s.srv.Handler) + t.Cleanup(ts.Close) + return s, ts.URL +} + +func TestHealthz(t *testing.T) { + t.Parallel() + _, url := newTestServer(t, false) + + res, err := stdhttp.Get(url + "/healthz") + if err != nil { + t.Fatalf("GET: %v", err) + } + defer res.Body.Close() + if res.StatusCode != stdhttp.StatusNoContent { + t.Errorf("status: %d", res.StatusCode) + } +} + +func TestBootstrapHappyPath(t *testing.T) { + t.Parallel() + _, url := newTestServer(t, true) + + body, _ := json.Marshal(bootstrapRequest{ + Token: "test-token", Username: "alice", Password: "averylongpassword", + }) + res, err := stdhttp.Post(url+"/api/bootstrap", "application/json", bytes.NewReader(body)) + if err != nil { + t.Fatalf("POST: %v", err) + } + defer res.Body.Close() + if res.StatusCode != stdhttp.StatusCreated { + got, _ := io.ReadAll(res.Body) + t.Fatalf("status %d: %s", res.StatusCode, got) + } + + // Re-running bootstrap must fail now that a user exists. + res2, _ := stdhttp.Post(url+"/api/bootstrap", "application/json", bytes.NewReader(body)) + defer res2.Body.Close() + if res2.StatusCode != stdhttp.StatusConflict { + t.Errorf("second bootstrap: want 409, got %d", res2.StatusCode) + } +} + +func TestBootstrapBadToken(t *testing.T) { + t.Parallel() + _, url := newTestServer(t, true) + + body, _ := json.Marshal(bootstrapRequest{ + Token: "wrong", Username: "alice", Password: "averylongpassword", + }) + res, _ := stdhttp.Post(url+"/api/bootstrap", "application/json", bytes.NewReader(body)) + defer res.Body.Close() + if res.StatusCode != stdhttp.StatusUnauthorized { + t.Errorf("status: %d", res.StatusCode) + } +} + +func TestBootstrapWeakPassword(t *testing.T) { + t.Parallel() + _, url := newTestServer(t, true) + + body, _ := json.Marshal(bootstrapRequest{ + Token: "test-token", Username: "alice", Password: "short", + }) + res, _ := stdhttp.Post(url+"/api/bootstrap", "application/json", bytes.NewReader(body)) + defer res.Body.Close() + if res.StatusCode != stdhttp.StatusBadRequest { + t.Errorf("status: %d", res.StatusCode) + } +} + +func TestLoginAndLogout(t *testing.T) { + t.Parallel() + _, url := newTestServer(t, true) + + // Bootstrap the admin first. + bs, _ := json.Marshal(bootstrapRequest{ + Token: "test-token", Username: "alice", Password: "averylongpassword", + }) + stdhttp.Post(url+"/api/bootstrap", "application/json", bytes.NewReader(bs)) //nolint:errcheck + + // Login. + body, _ := json.Marshal(loginRequest{Username: "alice", Password: "averylongpassword"}) + res, err := stdhttp.Post(url+"/api/auth/login", "application/json", bytes.NewReader(body)) + if err != nil { + t.Fatalf("login: %v", err) + } + defer res.Body.Close() + if res.StatusCode != stdhttp.StatusOK { + got, _ := io.ReadAll(res.Body) + t.Fatalf("login status %d: %s", res.StatusCode, got) + } + cookies := res.Cookies() + var sess *stdhttp.Cookie + for _, c := range cookies { + if c.Name == sessionCookieName { + sess = c + break + } + } + if sess == nil { + t.Fatal("no session cookie set") + } + if !sess.HttpOnly { + t.Error("session cookie should be HttpOnly") + } + + // Bad password → 401. + bad, _ := json.Marshal(loginRequest{Username: "alice", Password: "wrong"}) + res2, _ := stdhttp.Post(url+"/api/auth/login", "application/json", bytes.NewReader(bad)) + defer res2.Body.Close() + if res2.StatusCode != stdhttp.StatusUnauthorized { + t.Errorf("bad pass: want 401, got %d", res2.StatusCode) + } + + // Logout deletes the cookie + the server-side session. + logoutReq, _ := stdhttp.NewRequest(stdhttp.MethodPost, url+"/api/auth/logout", nil) + logoutReq.AddCookie(sess) + res3, err := stdhttp.DefaultClient.Do(logoutReq) + if err != nil { + t.Fatalf("logout: %v", err) + } + defer res3.Body.Close() + if res3.StatusCode != stdhttp.StatusNoContent { + t.Errorf("logout status: %d", res3.StatusCode) + } +} + +func TestLoginUnknownUserSameAsBadPassword(t *testing.T) { + t.Parallel() + _, url := newTestServer(t, false) + + body, _ := json.Marshal(loginRequest{Username: "ghost", Password: "anything12345"}) + res, _ := stdhttp.Post(url+"/api/auth/login", "application/json", bytes.NewReader(body)) + defer res.Body.Close() + // Both unknown-user and bad-password must return 401 with the same + // code so a probe can't enumerate usernames. + if res.StatusCode != stdhttp.StatusUnauthorized { + t.Errorf("unknown user: want 401, got %d", res.StatusCode) + } +} diff --git a/internal/server/http/doc.go b/internal/server/http/doc.go deleted file mode 100644 index 066fc91..0000000 --- a/internal/server/http/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package http hosts the chi-based REST handlers for the control plane. -package http diff --git a/internal/server/http/middleware.go b/internal/server/http/middleware.go new file mode 100644 index 0000000..f50e6a6 --- /dev/null +++ b/internal/server/http/middleware.go @@ -0,0 +1,28 @@ +package http + +import ( + "log/slog" + stdhttp "net/http" + "time" + + "github.com/go-chi/chi/v5/middleware" +) + +// requestLogger emits one structured slog line per HTTP request. +// Body sizes are best-effort (handlers that stream don't update them). +func requestLogger(next stdhttp.Handler) stdhttp.Handler { + return stdhttp.HandlerFunc(func(w stdhttp.ResponseWriter, r *stdhttp.Request) { + start := time.Now() + ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor) + next.ServeHTTP(ww, r) + slog.Info("http", + "method", r.Method, + "path", r.URL.Path, + "status", ww.Status(), + "bytes", ww.BytesWritten(), + "dur_ms", time.Since(start).Milliseconds(), + "req_id", middleware.GetReqID(r.Context()), + "remote", r.RemoteAddr, + ) + }) +} diff --git a/internal/server/http/server.go b/internal/server/http/server.go new file mode 100644 index 0000000..2494a03 --- /dev/null +++ b/internal/server/http/server.go @@ -0,0 +1,110 @@ +// Package http hosts the chi-based REST handlers for the control +// plane. The Server type owns the router, the handlers, and the +// graceful-shutdown lifecycle. +package http + +import ( + "context" + "errors" + "fmt" + stdhttp "net/http" + "time" + + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + + "gitea.dcglab.co.uk/steve/restic-manager/internal/crypto" + "gitea.dcglab.co.uk/steve/restic-manager/internal/server/config" + "gitea.dcglab.co.uk/steve/restic-manager/internal/store" +) + +// Deps bundles every collaborator the HTTP server depends on. Wired up +// in cmd/server; tests pass a pared-down Deps with fakes. +type Deps struct { + Cfg config.Config + Store *store.Store + AEAD *crypto.AEAD + // BootstrapToken (optional, populated only on first run) is the raw + // admin-bootstrap token printed in the server logs. While set, the + // /bootstrap endpoint accepts it to create the first admin user. + BootstrapToken string +} + +// Server is the running HTTP server. +type Server struct { + srv *stdhttp.Server + deps Deps +} + +// New builds a configured but not-yet-started server. +func New(deps Deps) *Server { + r := chi.NewRouter() + + // Built-in middleware: request ID for log correlation, recovery + // (don't crash the process on a panic in a handler), realIP iff a + // trusted proxy is configured. + r.Use(middleware.RequestID) + r.Use(middleware.Recoverer) + r.Use(requestLogger) + + // Health endpoint — unauthenticated, no audit, deliberately cheap. + r.Get("/healthz", func(w stdhttp.ResponseWriter, _ *stdhttp.Request) { + w.WriteHeader(stdhttp.StatusNoContent) + }) + + s := &Server{deps: deps} + s.routes(r) + + s.srv = &stdhttp.Server{ + Addr: deps.Cfg.Listen, + Handler: r, + ReadHeaderTimeout: 10 * time.Second, + IdleTimeout: 60 * time.Second, + // Long write timeout — WS upgrades and live log streams need it. + WriteTimeout: 0, + } + return s +} + +// routes wires the API tree. Subtrees live in this file by area so a +// reader can scan one place and see the surface. +func (s *Server) routes(r chi.Router) { + r.Route("/api", func(r chi.Router) { + r.Post("/auth/login", s.handleLogin) + r.Post("/auth/logout", s.handleLogout) + r.Post("/bootstrap", s.handleBootstrap) + }) + + // UI handlers will hang off / — Phase 1 will add them. + r.Get("/", func(w stdhttp.ResponseWriter, _ *stdhttp.Request) { + _, _ = fmt.Fprint(w, "restic-manager — UI not yet implemented") + }) +} + +// Start begins listening. Blocks until ListenAndServe returns +// (typically only on Shutdown). Pass the result to errgroup.Group.Go. +func (s *Server) Start() error { + cfg := s.deps.Cfg + if cfg.TLSEnabled() { + err := s.srv.ListenAndServeTLS(cfg.TLSCert, cfg.TLSKey) + if errors.Is(err, stdhttp.ErrServerClosed) { + return nil + } + return err + } + err := s.srv.ListenAndServe() + if errors.Is(err, stdhttp.ErrServerClosed) { + return nil + } + return err +} + +// Shutdown stops accepting new connections and waits up to ctx.Deadline +// for in-flight handlers to finish. +func (s *Server) Shutdown(ctx context.Context) error { + return s.srv.Shutdown(ctx) +} + +// Addr returns the configured listen address. Useful in tests when +// the caller passes :0 to get a random port. +func (s *Server) Addr() string { return s.srv.Addr }