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) <noreply@anthropic.com>
This commit is contained in:
2026-05-01 00:28:18 +01:00
parent f55747a281
commit df2c584b23
11 changed files with 869 additions and 6 deletions
+114
View File
@@ -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 != "" }
+92
View File
@@ -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)
}
@@ -0,0 +1,7 @@
package config
import "os"
func writeFileImpl(path string, body []byte) error {
return os.WriteFile(path, body, 0o600)
}