diff --git a/Dockerfile.archie b/Dockerfile.archie new file mode 100644 index 000000000..b7ea61498 --- /dev/null +++ b/Dockerfile.archie @@ -0,0 +1,39 @@ +# Production single-binary image for cmd/archie. +# Build: docker build -f Dockerfile.archie --build-arg VERSION=v1.0.0 -t archie:v1.0.0 . + +# ── dashboard ── +FROM node:24-trixie-slim AS ui +WORKDIR /src/ui +RUN npm install -g pnpm@10 +COPY ui/package.json ui/pnpm-lock.yaml ./ +RUN --mount=type=cache,target=/root/.local/share/pnpm/store \ + pnpm install --frozen-lockfile +COPY ui/ ./ +RUN pnpm run build + +# ── builder ── +FROM golang:1.27-trixie AS builder +ARG VERSION=dev +WORKDIR /src +COPY go.mod go.sum ./ +RUN --mount=type=cache,target=/go/pkg/mod go mod download +COPY . . +COPY --from=ui /src/ui/dist ./ui/dist +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/root/.cache/go-build \ + CGO_ENABLED=0 go build -trimpath \ + -ldflags "-s -w -X github.com/samcharles93/archie-core/internal/buildinfo.Version=${VERSION}" \ + -o /usr/local/bin/archie ./cmd/archie + +# ── runtime ── +FROM gcr.io/distroless/static-debian12:nonroot +ARG VERSION=dev +ARG REVISION=unknown +LABEL org.opencontainers.image.title="archie" \ + org.opencontainers.image.description="Event-driven agentic automation" \ + org.opencontainers.image.version="${VERSION}" \ + org.opencontainers.image.revision="${REVISION}" + +COPY --from=builder /usr/local/bin/archie /archie +EXPOSE 8080 +ENTRYPOINT ["/archie"] diff --git a/cmd/archie/main.go b/cmd/archie/main.go index 396a85379..a537570f2 100644 --- a/cmd/archie/main.go +++ b/cmd/archie/main.go @@ -26,7 +26,7 @@ func run() error { newIdentity := flag.Bool("new-age-identity", false, "print a new age identity for age_identity and exit") showVersion := buildinfo.RegisterVersionFlag("archie") flag.Usage = func() { - _, _ = fmt.Fprintln(flag.CommandLine.Output(), "usage: archie [flags]\n archie openapi print the API's OpenAPI document") + _, _ = fmt.Fprintln(flag.CommandLine.Output(), "usage: archie [flags]\n archie migrate apply database migrations and runtime grants\n archie openapi print the API's OpenAPI document") flag.PrintDefaults() } flag.Parse() @@ -36,6 +36,10 @@ func run() error { } switch flag.Arg(0) { case "": + case "migrate": + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + return archie.Migrate(ctx, *configPath) case "openapi": doc, err := archie.Document() if err != nil { diff --git a/internal/app/archie/config.go b/internal/app/archie/config.go index 6a562fb2e..a03a2eae8 100644 --- a/internal/app/archie/config.go +++ b/internal/app/archie/config.go @@ -9,6 +9,7 @@ import ( "path/filepath" "regexp" "strings" + "time" "filippo.io/age" "github.com/BurntSushi/toml" @@ -16,6 +17,8 @@ import ( "github.com/samcharles93/archie-core/internal/platform/deletions" ) +const defaultShutdownGrace = 30 * time.Second + // Config is the bootstrap configuration: only what the binary needs before it // can reach its database. Everything else is a setting in the control plane. type Config struct { @@ -37,10 +40,14 @@ type Config struct { // directory, and a relative path is refused: the restore that reads this // directory runs as another process. StateDir string `toml:"state_dir"` + // ShutdownGraceRaw sets how long SIGTERM waits for active requests to finish. + ShutdownGraceRaw string `toml:"shutdown_grace"` + ShutdownGrace time.Duration `toml:"-"` } // DatabaseConfig holds the two connection URLs. The owner runs migrations at -// boot and nothing else; the runtime URL never holds DDL rights. +// boot (or via `archie migrate`) and nothing else; the runtime URL never holds +// DDL rights. type DatabaseConfig struct { URL string `toml:"url"` OwnerURL string `toml:"owner_url"` @@ -54,6 +61,9 @@ var adminLine = regexp.MustCompile(`(?m)^\s*admin_token_sha256\s*=.*$`) // every other line. The hash is the only value written: the old token and the // old hash are never read back or logged. func WriteAdminHash(path, hash string) error { + if path == "" { + return errors.New("admin token cannot be rotated in place without a config file path") + } if !adminHash.MatchString(hash) { return errors.New("an admin token hash is a hex SHA-256") } @@ -145,23 +155,118 @@ func NewAgeIdentity(w io.Writer) error { return err } -// LoadConfig reads and validates the bootstrap config at path. +// LoadConfig reads and validates the bootstrap config at path (when non-empty) +// and applies ARCHIE_* and ARCHIE_*_FILE environment overrides. func LoadConfig(path string) (Config, error) { - cfg := Config{Listen: "127.0.0.1:8080", StateDir: DefaultStateDir()} - if _, err := toml.DecodeFile(path, &cfg); err != nil { - return Config{}, fmt.Errorf("read config %s: %w", path, err) + cfg := Config{ + Listen: "127.0.0.1:8080", + StateDir: DefaultStateDir(), + ShutdownGrace: defaultShutdownGrace, + } + if err := decodeConfig(path, &cfg); err != nil { + return Config{}, err + } + if cfg.ShutdownGraceRaw != "" { + d, err := time.ParseDuration(cfg.ShutdownGraceRaw) + if err != nil || d <= 0 { + return Config{}, fmt.Errorf("config %s: shutdown_grace must be a positive duration", configLabel(path)) + } + cfg.ShutdownGrace = d } dir, err := deletions.Dir(cfg.StateDir) if err != nil { - return Config{}, fmt.Errorf("config %s: %w", path, err) + return Config{}, fmt.Errorf("config %s: %w", configLabel(path), err) } cfg.StateDir = dir if err := cfg.validate(); err != nil { - return Config{}, fmt.Errorf("config %s: %w", path, err) + return Config{}, fmt.Errorf("config %s: %w", configLabel(path), err) } return cfg, nil } +// LoadMigrateConfig loads only the database configuration required by `archie +// migrate`, so migration jobs never need runtime sealing keys or admin hashes. +func LoadMigrateConfig(path string) (DatabaseConfig, error) { + var cfg Config + if err := decodeConfig(path, &cfg); err != nil { + return DatabaseConfig{}, err + } + if err := cfg.Database.validateMigrate(); err != nil { + return DatabaseConfig{}, fmt.Errorf("config %s: %w", configLabel(path), err) + } + return cfg.Database, nil +} + +func decodeConfig(path string, cfg *Config) error { + if path != "" { + if _, err := toml.DecodeFile(path, cfg); err != nil { + return fmt.Errorf("read config %s: %w", path, err) + } + } + if err := applyEnv(cfg); err != nil { + return fmt.Errorf("config %s: %w", configLabel(path), err) + } + return nil +} + +func applyEnv(cfg *Config) error { + overrides := []struct { + envKey string + fileKey string + target *string + }{ + {envKey: "ARCHIE_LISTEN", target: &cfg.Listen}, + {envKey: "ARCHIE_STATE_DIR", target: &cfg.StateDir}, + {envKey: "ARCHIE_DATABASE_URL", fileKey: "ARCHIE_DATABASE_URL_FILE", target: &cfg.Database.URL}, + {envKey: "ARCHIE_DATABASE_OWNER_URL", fileKey: "ARCHIE_DATABASE_OWNER_URL_FILE", target: &cfg.Database.OwnerURL}, + {envKey: "ARCHIE_AGE_IDENTITY", fileKey: "ARCHIE_AGE_IDENTITY_FILE", target: &cfg.AgeIdentity}, + {envKey: "ARCHIE_ADMIN_TOKEN_SHA256", fileKey: "ARCHIE_ADMIN_TOKEN_SHA256_FILE", target: &cfg.AdminTokenSHA256}, + {envKey: "ARCHIE_SHUTDOWN_GRACE", target: &cfg.ShutdownGraceRaw}, + } + for _, o := range overrides { + val, ok, err := envOrFile(o.envKey, o.fileKey) + if err != nil { + return err + } + if ok { + *o.target = val + } + } + return nil +} + +func envOrFile(envKey, fileKey string) (string, bool, error) { + val, hasEnv := os.LookupEnv(envKey) + val = strings.TrimSpace(val) + var filePath string + var hasFile bool + if fileKey != "" { + filePath, hasFile = os.LookupEnv(fileKey) + filePath = strings.TrimSpace(filePath) + } + if hasEnv && val != "" && hasFile && filePath != "" { + return "", false, fmt.Errorf("set either %s or %s, not both", envKey, fileKey) + } + if hasFile && filePath != "" { + raw, err := os.ReadFile(filePath) //nolint:gosec // operator-configured *_FILE secret path + if err != nil { + return "", false, fmt.Errorf("read %s (%s): %w", fileKey, filePath, err) + } + return strings.TrimSpace(string(raw)), true, nil + } + if hasEnv && val != "" { + return val, true, nil + } + return "", false, nil +} + +func configLabel(path string) string { + if path == "" { + return "env" + } + return path +} + func (c Config) validate() error { var errs []error if c.Listen == "" { @@ -170,10 +275,10 @@ func (c Config) validate() error { if c.Database.URL == "" { errs = append(errs, errors.New("database.url is required")) } - // The owner URL has no fallback to the runtime URL: a runtime connection - // that can run DDL defeats the role split. - if c.Database.OwnerURL == "" { - errs = append(errs, errors.New("database.owner_url is required")) + // OwnerURL is optional in serving mode (migrations run out-of-band via + // `archie migrate`). When set, it must still name a distinct DDL role. + if c.Database.URL != "" && c.Database.OwnerURL != "" && c.Database.URL == c.Database.OwnerURL { + errs = append(errs, errors.New("database.url and database.owner_url must name different roles")) } if c.AgeIdentity == "" { errs = append(errs, errors.New("age_identity is required")) @@ -181,7 +286,18 @@ func (c Config) validate() error { if !adminHash.MatchString(c.AdminTokenSHA256) { errs = append(errs, errors.New("admin_token_sha256 must be a hex SHA-256")) } - if c.Database.URL != "" && c.Database.URL == c.Database.OwnerURL { + return errors.Join(errs...) +} + +func (d DatabaseConfig) validateMigrate() error { + var errs []error + if d.URL == "" { + errs = append(errs, errors.New("database.url is required")) + } + if d.OwnerURL == "" { + errs = append(errs, errors.New("database.owner_url is required")) + } + if d.URL != "" && d.OwnerURL != "" && d.URL == d.OwnerURL { errs = append(errs, errors.New("database.url and database.owner_url must name different roles")) } return errors.Join(errs...) diff --git a/internal/app/archie/config_test.go b/internal/app/archie/config_test.go index c8c2df344..17cd5e992 100644 --- a/internal/app/archie/config_test.go +++ b/internal/app/archie/config_test.go @@ -5,6 +5,9 @@ import ( "path/filepath" "strings" "testing" + "time" + + "filippo.io/age" ) // TestWriteAdminHashReplacesOnlyTheHash guards token rotation: the config keeps @@ -63,3 +66,72 @@ func TestWriteAdminHashAddsAMissingLine(t *testing.T) { t.Fatal("the hash was not added") } } + +// TestLoadConfigRuntimeAndEnvFiles guards containerised secret injection and +// DML-only serving mode where owner_url is omitted from the runtime pod. +func TestLoadConfigRuntimeAndEnvFiles(t *testing.T) { + id, err := age.GenerateX25519Identity() + if err != nil { + t.Fatal(err) + } + const adminSHA = "4444444444444444444444444444444444444444444444444444444444444444" + const wantDBURL = "postgres://archie_app:pass@db:5432/archie?sslmode=verify-full" //nolint:gosec // test fixture DSN without real credentials + dir := t.TempDir() + dbFile := filepath.Join(dir, "db_url") + ageFile := filepath.Join(dir, "age_key") + stateDir := filepath.Join(dir, "state") + + if err := os.WriteFile(dbFile, []byte(wantDBURL+"\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(ageFile, []byte(id.String()+"\n"), 0o600); err != nil { + t.Fatal(err) + } + + t.Setenv("ARCHIE_LISTEN", "0.0.0.0:8080") + t.Setenv("ARCHIE_STATE_DIR", stateDir) + t.Setenv("ARCHIE_DATABASE_URL_FILE", dbFile) + t.Setenv("ARCHIE_AGE_IDENTITY_FILE", ageFile) + t.Setenv("ARCHIE_ADMIN_TOKEN_SHA256", adminSHA) + t.Setenv("ARCHIE_SHUTDOWN_GRACE", "45s") + + cfg, err := LoadConfig("") + if err != nil { + t.Fatalf("LoadConfig from env: %v", err) + } + if cfg.Database.OwnerURL != "" { + t.Fatalf("OwnerURL = %q, want empty in runtime-only mode", cfg.Database.OwnerURL) + } + if cfg.Database.URL != wantDBURL { + t.Fatalf("Database.URL = %q", cfg.Database.URL) + } + if cfg.ShutdownGrace != 45*time.Second { + t.Fatalf("ShutdownGrace = %s, want 45s", cfg.ShutdownGrace) + } + + // Setting both ENV and ENV_FILE must fail loudly rather than picking one silently. + t.Setenv("ARCHIE_DATABASE_URL", "postgres://other@db:5432/archie") + if _, err := LoadConfig(""); err == nil || !strings.Contains(err.Error(), "not both") { + t.Fatalf("expected ambiguity error, got %v", err) + } +} + +// TestLoadMigrateConfigRequiresOnlyDatabaseRoles guards migration jobs running +// without runtime sealing keys or bootstrap admin hashes. +func TestLoadMigrateConfigRequiresOnlyDatabaseRoles(t *testing.T) { + t.Setenv("ARCHIE_DATABASE_URL", "postgres://archie_app:pass@db:5432/archie") + t.Setenv("ARCHIE_DATABASE_OWNER_URL", "postgres://archie_owner:pass@db:5432/archie") + + dbCfg, err := LoadMigrateConfig("") + if err != nil { + t.Fatalf("LoadMigrateConfig: %v", err) + } + if dbCfg.OwnerURL == "" || dbCfg.URL == "" { + t.Fatalf("unexpected empty DB config: %+v", dbCfg) + } + + t.Setenv("ARCHIE_DATABASE_OWNER_URL", dbCfg.URL) + if _, err := LoadMigrateConfig(""); err == nil { + t.Fatal("expected error when owner_url matches url") + } +} diff --git a/internal/app/archie/gate.go b/internal/app/archie/gate.go index 955aec5ae..b77dc252a 100644 --- a/internal/app/archie/gate.go +++ b/internal/app/archie/gate.go @@ -24,9 +24,10 @@ const ( // What stopped operations from starting. Readiness reports the stage; the error // text stays in the log, since it can name hosts, roles and tables. const ( - stageSetupRead = "cannot read whether owner setup is required" - stageStartup = "starting operations failed" - stageMigrate = "migrating the database failed" + stageSetupRead = "cannot read whether owner setup is required" + stageStartup = "starting operations failed" + stageMigrate = "migrating the database failed" + stageSchemaVerify = "verifying the database schema failed" ) // How long a failed boot step waits before it runs again. The delay doubles up diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index e5d9693eb..54f592873 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -14,6 +14,7 @@ import ( "os" "path/filepath" "strconv" + "sync/atomic" "time" "github.com/google/uuid" @@ -42,12 +43,21 @@ import ( "github.com/samcharles93/archie-core/ui" ) -const shutdownGrace = 10 * time.Second - // deletionRecordRetry is how often an incomplete record of a committed deletion // is retried. const deletionRecordRetry = 30 * time.Second +// Migrate applies embedded database migrations and grants runtime DML privileges +// using database.owner_url, then exits. +func Migrate(ctx context.Context, configPath string) error { + log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "archie", "version", buildinfo.Version) + dbCfg, err := LoadMigrateConfig(configPath) + if err != nil { + return err + } + return pg.Migrate(ctx, log, dbCfg.OwnerURL, dbCfg.URL, schemas) +} + // Run boots the binary from the config at configPath and blocks until ctx ends // or the server fails. // @@ -78,10 +88,17 @@ func Run(ctx context.Context, configPath string) error { } defer holdServe() // Nothing is served yet, so there is no readiness to report while this retries. - migrate := func(ctx context.Context) error { - return pg.Migrate(ctx, log, cfg.Database.OwnerURL, cfg.Database.URL, schemas) + stage := stageMigrate + if cfg.Database.OwnerURL == "" { + stage = stageSchemaVerify } - if err := retryStartup(ctx, log, func(string) {}, stageMigrate, migrate); err != nil { + migrateOrVerify := func(ctx context.Context) error { + if cfg.Database.OwnerURL != "" { + return pg.Migrate(ctx, log, cfg.Database.OwnerURL, cfg.Database.URL, schemas) + } + return pg.VerifySchema(ctx, db) + } + if err := retryStartup(ctx, log, func(string) {}, stage, migrateOrVerify); err != nil { _ = db.Close() return err } @@ -104,7 +121,8 @@ func Run(ctx context.Context, configPath string) error { } else if applied > 0 { log.WarnContext(ctx, "applied the record of deletions", "notes", applied) } - b, err := wire(log, configPath, cfg, db) //nolint:contextcheck // the API's guard derives its context from each request + var draining atomic.Bool + b, err := wire(log, configPath, cfg, db, &draining) //nolint:contextcheck // the API's guard derives its context from each request if err != nil { _ = db.Close() return err @@ -121,7 +139,7 @@ func Run(ctx context.Context, configPath string) error { close(started) }() - serveErr := serve(work, log, cfg.Listen, b.served) + serveErr := serve(work, log, cfg.Listen, cfg.ShutdownGrace, &draining, b.served) stop() <-started // Every loop activation began has returned before the caller closes the @@ -145,9 +163,8 @@ type binary struct { // wire builds every module and registers its routes. Nothing operational // starts here: the routes are wired on a mux the gate holds back, and Start // brings them up once owner setup has committed. -func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary, error) { - checks := health.NewRegistry() - checks.Register("database", db.PingContext) +func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB, draining *atomic.Bool) (*binary, error) { + checks := newHealthChecks(db, draining) runtime.RegisterBuiltinClasses() settings := governance.NewModule(db, log.With("module", "governance"), orgID) @@ -215,12 +232,14 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary return nil, fmt.Errorf("prepare the deletion record: %w", err) } remember := memory.NewModule(db, orgID, log.With("module", "memory"), ledger) - checks.Register("deletion record", func(context.Context) error { + deletionCheck := func(context.Context) error { if remember.RecordPending() { return errors.New("a deletion is committed and its record is still being written") } return nil - }) + } + checks.RegisterStartup("deletion record", deletionCheck) + checks.Register("deletion record", deletionCheck) proposed := proposals.NewModule(db, log.With("module", "proposals"), orgID, hear, engine, policies, judge) // A cause that keeps recurring becomes a root-cause proposal. remember.UseProposals(proposed) @@ -247,6 +266,19 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary }, nil } +func newHealthChecks(db *sqlx.DB, draining *atomic.Bool) *health.Registry { + checks := health.NewRegistry() + checks.RegisterStartup("database", db.PingContext) + checks.Register("database", db.PingContext) + checks.Register("shutdown", func(context.Context) error { + if draining != nil && draining.Load() { + return errors.New("shutting down") + } + return nil + }) + return checks +} + // close stops the connectors and then the database. func (b *binary) close() { b.conns.Close() @@ -319,7 +351,7 @@ func owner() string { return host + ":" + strconv.Itoa(os.Getpid()) } -func serve(ctx context.Context, log *slog.Logger, addr string, handler http.Handler) error { +func serve(ctx context.Context, log *slog.Logger, addr string, grace time.Duration, draining *atomic.Bool, handler http.Handler) error { var lc net.ListenConfig listener, err := lc.Listen(ctx, "tcp", addr) if err != nil { @@ -339,7 +371,10 @@ func serve(ctx context.Context, log *slog.Logger, addr string, handler http.Hand return fmt.Errorf("serve: %w", err) case <-ctx.Done(): } - shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownGrace) + if draining != nil { + draining.Store(true) + } + shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), grace) defer cancel() if err := server.Shutdown(shutdownCtx); err != nil && !errors.Is(err, http.ErrServerClosed) { return fmt.Errorf("shut down: %w", err) diff --git a/internal/platform/health/health.go b/internal/platform/health/health.go index 3e065306e..f0fe5866a 100644 --- a/internal/platform/health/health.go +++ b/internal/platform/health/health.go @@ -1,5 +1,5 @@ -// Package health serves liveness and readiness. Each module registers the -// check that says whether it can do its work. +// Package health serves liveness, startup, and readiness. Each module +// registers the check that says whether it can do its work. package health import ( @@ -14,47 +14,74 @@ import ( // Check reports whether one part of the binary is ready. type Check func(context.Context) error -// Registry holds the named readiness checks. +// Registry holds the named startup and readiness checks. type Registry struct { - mu sync.RWMutex - checks map[string]Check + mu sync.RWMutex + checks map[string]Check + startup map[string]Check } // NewRegistry returns an empty registry. func NewRegistry() *Registry { - return &Registry{checks: map[string]Check{}} + return &Registry{ + checks: map[string]Check{}, + startup: map[string]Check{}, + } } -// Register adds or replaces the check for name. +// Register adds or replaces the readiness check for name. func (r *Registry) Register(name string, check Check) { r.mu.Lock() defer r.mu.Unlock() r.checks[name] = check } -// Routes adds /healthz and /readyz to mux. +// RegisterStartup adds or replaces the startup check for name. Startup checks +// run on /startupz independently of operational readiness checks such as owner +// setup. +func (r *Registry) RegisterStartup(name string, check Check) { + r.mu.Lock() + defer r.mu.Unlock() + r.startup[name] = check +} + +// Routes adds /healthz, /startupz, and /readyz to mux. func (r *Registry) Routes(mux *http.ServeMux) { mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte("ok\n")) }) - mux.HandleFunc("GET /readyz", r.ready) + mux.HandleFunc("GET /startupz", func(w http.ResponseWriter, req *http.Request) { + writeProbe(w, req, r.StartupResults) + }) + mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, req *http.Request) { + writeProbe(w, req, r.Results) + }) } -// Result is the outcome of one readiness check; Error is empty when it passed. +// Result is the outcome of one check; Error is empty when it passed. type Result struct { Name string `json:"name"` Error string `json:"error,omitzero"` } -// Results runs every check and returns the outcomes in name order. A failing -// check does not stop the others. +// Results runs every readiness check and returns the outcomes in name order. A +// failing check does not stop the others. func (r *Registry) Results(ctx context.Context) []Result { - names := r.names() + return r.run(ctx, false) +} + +// StartupResults runs every startup check and returns the outcomes in name order. +func (r *Registry) StartupResults(ctx context.Context) []Result { + return r.run(ctx, true) +} + +func (r *Registry) run(ctx context.Context, startup bool) []Result { + names := r.names(startup) out := make([]Result, 0, len(names)) for _, name := range names { res := Result{Name: name} - if err := r.check(name)(ctx); err != nil { + if err := r.check(name, startup)(ctx); err != nil { res.Error = err.Error() } out = append(out, res) @@ -62,12 +89,12 @@ func (r *Registry) Results(ctx context.Context) []Result { return out } -func (r *Registry) ready(w http.ResponseWriter, req *http.Request) { +func writeProbe(w http.ResponseWriter, req *http.Request, run func(context.Context) []Result) { ctx, cancel := context.WithTimeout(req.Context(), 5*time.Second) defer cancel() failures := map[string]string{} - for _, res := range r.Results(ctx) { + for _, res := range run(ctx) { if res.Error != "" { failures[res.Name] = res.Error } @@ -79,19 +106,26 @@ func (r *Registry) ready(w http.ResponseWriter, req *http.Request) { _ = json.MarshalWrite(w, map[string]any{"ready": len(failures) == 0, "failures": failures}) } -func (r *Registry) names() []string { +func (r *Registry) names(startup bool) []string { r.mu.RLock() defer r.mu.RUnlock() - names := make([]string, 0, len(r.checks)) - for name := range r.checks { + src := r.checks + if startup { + src = r.startup + } + names := make([]string, 0, len(src)) + for name := range src { names = append(names, name) } sort.Strings(names) return names } -func (r *Registry) check(name string) Check { +func (r *Registry) check(name string, startup bool) Check { r.mu.RLock() defer r.mu.RUnlock() + if startup { + return r.startup[name] + } return r.checks[name] } diff --git a/internal/platform/health/health_test.go b/internal/platform/health/health_test.go new file mode 100644 index 000000000..86e96b4b5 --- /dev/null +++ b/internal/platform/health/health_test.go @@ -0,0 +1,51 @@ +package health + +import ( + "context" + json "encoding/json/v2" + "errors" + "net/http" + "net/http/httptest" + "testing" +) + +// TestProbesSeparateStartupFromReadiness guards /startupz returning 200 once +// core boot checks pass even while /readyz waits on owner setup or drains. +func TestProbesSeparateStartupFromReadiness(t *testing.T) { + reg := NewRegistry() + reg.RegisterStartup("database", func(context.Context) error { return nil }) + reg.Register("database", func(context.Context) error { return nil }) + reg.Register("setup", func(context.Context) error { return errors.New("owner setup is incomplete") }) + + mux := http.NewServeMux() + reg.Routes(mux) + + for _, tc := range []struct { + path string + status int + ready bool + }{ + {path: "/healthz", status: http.StatusOK}, + {path: "/startupz", status: http.StatusOK, ready: true}, + {path: "/readyz", status: http.StatusServiceUnavailable, ready: false}, + } { + req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, tc.path, nil) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + if rec.Code != tc.status { + t.Fatalf("%s: status = %d, want %d", tc.path, rec.Code, tc.status) + } + if tc.path == "/healthz" { + continue + } + var body struct { + Ready bool `json:"ready"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("%s: decode body: %v", tc.path, err) + } + if body.Ready != tc.ready { + t.Fatalf("%s: ready = %v, want %v", tc.path, body.Ready, tc.ready) + } + } +} diff --git a/internal/platform/pg/pg.go b/internal/platform/pg/pg.go index a37f7d6ce..9db99ec50 100644 --- a/internal/platform/pg/pg.go +++ b/internal/platform/pg/pg.go @@ -9,6 +9,9 @@ import ( "fmt" "io/fs" "log/slog" + "slices" + "strconv" + "strings" "github.com/jackc/pgx/v5" // Registers the "pgx" database/sql driver that sqlx and goose use. @@ -121,9 +124,69 @@ func grantRuntime(ctx context.Context, db *sqlx.DB, runtimeURL string, schemas [ } } } + if _, err := db.ExecContext(ctx, "GRANT SELECT ON TABLE public.goose_db_version TO "+role); err != nil { + return fmt.Errorf("grant runtime role on goose_db_version: %w", err) + } return nil } +// VerifySchema checks that every embedded migration has been applied to db. +// Serving processes without DDL credentials call this at boot and refuse to +// serve if migrations are pending. +func VerifySchema(ctx context.Context, db *sqlx.DB) error { + embedded, err := embeddedMigrationVersions() + if err != nil { + return err + } + var applied []int64 + if err := db.SelectContext(ctx, &applied, "SELECT version_id FROM public.goose_db_version WHERE is_applied"); err != nil { + return fmt.Errorf("read schema version (has 'archie migrate' run?): %w", err) + } + missing := missingMigrations(embedded, applied) + if len(missing) > 0 { + return fmt.Errorf("database schema is behind by %d migration(s) (next missing: %d); run 'archie migrate'", len(missing), missing[0]) + } + return nil +} + +func embeddedMigrationVersions() ([]int64, error) { + entries, err := fs.ReadDir(migrationFiles, "migrations") + if err != nil { + return nil, fmt.Errorf("read embedded migrations: %w", err) + } + var versions []int64 + for _, entry := range entries { + if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") { + continue + } + prefix, _, ok := strings.Cut(entry.Name(), "_") + if !ok { + return nil, fmt.Errorf("migration %q has no version prefix", entry.Name()) + } + v, err := strconv.ParseInt(prefix, 10, 64) + if err != nil { + return nil, fmt.Errorf("parse migration %q version: %w", entry.Name(), err) + } + versions = append(versions, v) + } + slices.Sort(versions) + return versions, nil +} + +func missingMigrations(embedded, applied []int64) []int64 { + seen := make(map[int64]struct{}, len(applied)) + for _, v := range applied { + seen[v] = struct{}{} + } + var missing []int64 + for _, v := range embedded { + if _, ok := seen[v]; !ok { + missing = append(missing, v) + } + } + return missing +} + // ServeLockKey is the advisory-lock key the serving processes hold in its shared // form and a restore takes exclusively: several processes may serve at once, and // none may serve while a restore runs. The other archie binaries lock the same diff --git a/internal/platform/pg/pg_test.go b/internal/platform/pg/pg_test.go new file mode 100644 index 000000000..225916398 --- /dev/null +++ b/internal/platform/pg/pg_test.go @@ -0,0 +1,43 @@ +package pg + +import ( + "slices" + "testing" +) + +func TestEmbeddedMigrationVersions(t *testing.T) { + versions, err := embeddedMigrationVersions() + if err != nil { + t.Fatalf("embeddedMigrationVersions: %v", err) + } + if len(versions) == 0 { + t.Fatal("expected at least one embedded migration") + } + if !slices.IsSorted(versions) { + t.Fatalf("versions not sorted: %v", versions) + } +} + +// TestMissingMigrations guards schema verification for DML-only serving pods. +func TestMissingMigrations(t *testing.T) { + embedded := []int64{1, 2, 3} + tests := []struct { + name string + applied []int64 + want []int64 + }{ + {name: "up to date", applied: []int64{1, 2, 3}, want: nil}, + {name: "ahead with extra history", applied: []int64{1, 2, 3, 4}, want: nil}, + {name: "pending tail migration", applied: []int64{1, 2}, want: []int64{3}}, + {name: "missing middle migration", applied: []int64{1, 3}, want: []int64{2}}, + {name: "empty database", applied: nil, want: []int64{1, 2, 3}}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got := missingMigrations(embedded, tc.applied) + if !slices.Equal(got, tc.want) { + t.Fatalf("missingMigrations(%v, %v) = %v, want %v", embedded, tc.applied, got, tc.want) + } + }) + } +} diff --git a/modules/connectors/internal/egress/tunnel.go b/modules/connectors/internal/egress/tunnel.go index 4ca7d4b37..08a3408cd 100644 --- a/modules/connectors/internal/egress/tunnel.go +++ b/modules/connectors/internal/egress/tunnel.go @@ -3,13 +3,18 @@ package egress import ( + "bufio" "context" + "crypto/tls" + "encoding/base64" "fmt" "io" "net" "net/http" "net/http/httputil" + "net/url" "strconv" + "strings" "sync" ) @@ -18,8 +23,9 @@ import ( // are forwarded. Extensions get it rather than Proxy because they carry their // own credentials and never trust the daemon CA. type Tunnel struct { - rules rules - dial func(ctx context.Context, network, addr string) (net.Conn, error) + rules rules + dial func(ctx context.Context, network, addr string) (net.Conn, error) + proxyFunc func(*http.Request) (*url.URL, error) } // NewTunnel admits the hosts allow names, in network-policy@1 form. A host @@ -27,19 +33,23 @@ type Tunnel struct { // it (a LAN forge); a wildcard match may not. Loopback is refused whatever // is named: it would reach archie's own services. func NewTunnel(allow []string) *Tunnel { - t := &Tunnel{rules: rules{allow: compilePatterns(allow)}} + t := &Tunnel{ + rules: rules{allow: compilePatterns(allow)}, + proxyFunc: http.ProxyFromEnvironment, + } t.dial = t.dialGuarded return t } func (t *Tunnel) ServeHTTP(w http.ResponseWriter, r *http.Request) { defaultPort, hostport := 443, r.Host + scheme := "https" if r.Method != http.MethodConnect { if !r.URL.IsAbs() || r.URL.Scheme != "http" { http.Error(w, "only CONNECT and absolute-form http requests are proxied", http.StatusBadRequest) return } - defaultPort, hostport = 80, r.URL.Host + defaultPort, hostport, scheme = 80, r.URL.Host, r.URL.Scheme } host, port, err := splitTarget(hostport, defaultPort) if err != nil { @@ -51,12 +61,31 @@ func (t *Tunnel) ServeHTTP(w http.ResponseWriter, r *http.Request) { deny(w, r, "egress to "+target+" is not allowed") return } - if r.Method == http.MethodConnect { - t.splice(w, r, target) + proxyURL, err := t.proxyFor(scheme, target) + if err != nil { + http.Error(w, "proxy lookup: "+err.Error(), http.StatusBadGateway) return } + if proxyURL != nil && isLocalTarget(host) { + deny(w, r, "egress to "+target+" is not allowed") + return + } + if r.Method == http.MethodConnect { + dialFn := t.dial + if proxyURL != nil { + dialFn = func(ctx context.Context, _, addr string) (net.Conn, error) { + return dialViaProxy(ctx, addr, proxyURL) + } + } + t.splice(w, r, target, dialFn) + return + } + transport := &http.Transport{DialContext: t.dial} + if proxyURL != nil { + transport = &http.Transport{Proxy: http.ProxyURL(proxyURL)} + } rp := &httputil.ReverseProxy{ - Transport: &http.Transport{DialContext: t.dial}, + Transport: transport, FlushInterval: -1, Rewrite: func(pr *httputil.ProxyRequest) { pr.Out.URL.Host = target @@ -69,8 +98,93 @@ func (t *Tunnel) ServeHTTP(w http.ResponseWriter, r *http.Request) { rp.ServeHTTP(w, r) } -func (t *Tunnel) splice(w http.ResponseWriter, r *http.Request, target string) { - upstream, err := t.dial(r.Context(), "tcp", target) +func (t *Tunnel) proxyFor(scheme, target string) (*url.URL, error) { + if t.proxyFunc == nil { + return nil, nil + } + return t.proxyFunc(&http.Request{URL: &url.URL{Scheme: scheme, Host: target}}) +} + +func isLocalTarget(host string) bool { + norm := normalizeHost(host) + if norm == "localhost" || strings.HasSuffix(norm, ".localhost") { + return true + } + ip := net.ParseIP(norm) + return ip != nil && (ip.IsLoopback() || ip.IsUnspecified()) +} + +func dialViaProxy(ctx context.Context, target string, proxyURL *url.URL) (net.Conn, error) { + if proxyURL.Scheme != "http" && proxyURL.Scheme != "https" { + return nil, fmt.Errorf("unsupported proxy scheme %q", proxyURL.Scheme) + } + defaultPort := 80 + if proxyURL.Scheme == "https" { + defaultPort = 443 + } + host, port, err := splitTarget(proxyURL.Host, defaultPort) + if err != nil { + return nil, fmt.Errorf("proxy host: %w", err) + } + proxyAddr := net.JoinHostPort(host, strconv.Itoa(port)) + dialer := &net.Dialer{Timeout: handshakeTimeout} + conn, err := dialer.DialContext(ctx, "tcp", proxyAddr) + if err != nil { + return nil, fmt.Errorf("dial proxy %s: %w", proxyAddr, err) + } + if proxyURL.Scheme == "https" { + tlsConn := tls.Client(conn, &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}) + if err := tlsConn.HandshakeContext(ctx); err != nil { + _ = conn.Close() + return nil, fmt.Errorf("proxy tls handshake: %w", err) + } + conn = tlsConn + } + + req := &http.Request{ + Method: http.MethodConnect, + URL: &url.URL{Opaque: target}, + Host: target, + Header: make(http.Header), + } + if proxyURL.User != nil { + creds := proxyURL.User.String() + req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(creds))) + } + if err := req.Write(conn); err != nil { + _ = conn.Close() + return nil, fmt.Errorf("write proxy CONNECT: %w", err) + } + br := bufio.NewReader(conn) + resp, err := http.ReadResponse(br, req) + if resp != nil { + _ = resp.Body.Close() + } + if err != nil { + _ = conn.Close() + return nil, fmt.Errorf("read proxy CONNECT response: %w", err) + } + if resp.StatusCode != http.StatusOK { + _ = conn.Close() + return nil, fmt.Errorf("proxy CONNECT %s returned %s", target, resp.Status) + } + if br.Buffered() > 0 { + return &bufferedConn{Conn: conn, r: io.MultiReader(br, conn)}, nil + } + return conn, nil +} + +type bufferedConn struct { + net.Conn + r io.Reader +} + +func (b *bufferedConn) Read(p []byte) (int, error) { + return b.r.Read(p) +} + +func (t *Tunnel) splice(w http.ResponseWriter, r *http.Request, target string, dialFn func(context.Context, string, string) (net.Conn, error)) { + upstream, err := dialFn(r.Context(), "tcp", target) if err != nil { http.Error(w, "upstream "+target+": "+err.Error(), http.StatusBadGateway) return diff --git a/modules/connectors/internal/egress/tunnel_test.go b/modules/connectors/internal/egress/tunnel_test.go new file mode 100644 index 000000000..e63c51b74 --- /dev/null +++ b/modules/connectors/internal/egress/tunnel_test.go @@ -0,0 +1,164 @@ +package egress + +import ( + "context" + "encoding/base64" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + "time" +) + +// TestTunnelEnforcesAllowListBeforeCorporateProxy guards that disallowed hosts +// and loopback targets are denied before dialing any corporate proxy, while +// allowed hosts chain CONNECT with Proxy-Authorization end-to-end. +func TestTunnelEnforcesAllowListBeforeCorporateProxy(t *testing.T) { + var proxyHits atomic.Int32 + var seenAuth atomic.Value + var seenTarget atomic.Value + + // Upstream echo server connected to by the corporate proxy. + var lc net.ListenConfig + echoLn, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer func() { _ = echoLn.Close() }() + go func() { + for { + c, err := echoLn.Accept() + if err != nil { + return + } + go func(conn net.Conn) { + defer func() { _ = conn.Close() }() + _, _ = io.Copy(conn, conn) + }(c) + } + }() + + // Local test corporate HTTP CONNECT proxy. + corpProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + proxyHits.Add(1) + seenAuth.Store(r.Header.Get("Proxy-Authorization")) + seenTarget.Store(r.Host) + if r.Method != http.MethodConnect { + http.Error(w, "want CONNECT", http.StatusMethodNotAllowed) + return + } + up, err := (&net.Dialer{Timeout: time.Second}).DialContext(r.Context(), "tcp", echoLn.Addr().String()) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + hj, ok := w.(http.Hijacker) + if !ok { + _ = up.Close() + return + } + cli, brw, err := hj.Hijack() + if err != nil { + _ = up.Close() + return + } + defer func() { _ = cli.Close(); _ = up.Close() }() + _, _ = cli.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n")) + go func() { _, _ = io.Copy(up, brw); closeWrite(up) }() + _, _ = io.Copy(cli, up) + })) + defer corpProxy.Close() + + proxyURL, err := url.Parse(corpProxy.URL) + if err != nil { + t.Fatal(err) + } + proxyURL.User = url.UserPassword("svc", "s3cr3t") //nolint:gosec // test fixture for Proxy-Authorization header + + tun := NewTunnel([]string{"api.example.com:443", "127.0.0.1:443"}) + tun.proxyFunc = func(req *http.Request) (*url.URL, error) { + if strings.HasPrefix(req.URL.Host, "direct.example.com:") { + return nil, nil + } + return proxyURL, nil + } + srv := httptest.NewServer(tun) + defer srv.Close() + srvURL, _ := url.Parse(srv.URL) + + // 1. Disallowed host must fail with 403 and never touch the corporate proxy. + res, err := sendConnect(srvURL.Host, "blocked.example.com:443") + if err != nil { + t.Fatalf("blocked CONNECT: %v", err) + } + if !strings.HasPrefix(res, "HTTP/1.1 403 ") { + t.Fatalf("blocked CONNECT status = %q, want 403", res) + } + if proxyHits.Load() != 0 { + t.Fatalf("corporate proxy was contacted %d times for disallowed host", proxyHits.Load()) + } + + // 2. Loopback host must fail with 403 even if named in allow-list. + res, err = sendConnect(srvURL.Host, "127.0.0.1:443") + if err != nil { + t.Fatalf("loopback CONNECT: %v", err) + } + if !strings.HasPrefix(res, "HTTP/1.1 403 ") { + t.Fatalf("loopback CONNECT status = %q, want 403", res) + } + if proxyHits.Load() != 0 { + t.Fatalf("corporate proxy was contacted %d times for loopback host", proxyHits.Load()) + } + + // 3. Allowed host chains CONNECT through the corporate proxy with Basic auth. + conn, err := (&net.Dialer{Timeout: time.Second}).DialContext(context.Background(), "tcp", srvURL.Host) + if err != nil { + t.Fatal(err) + } + defer func() { _ = conn.Close() }() + _, _ = io.WriteString(conn, "CONNECT api.example.com:443 HTTP/1.1\r\nHost: api.example.com:443\r\n\r\n") + buf := make([]byte, 128) + n, err := conn.Read(buf) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(string(buf[:n]), "HTTP/1.1 200 ") { + t.Fatalf("allowed CONNECT = %q, want 200", string(buf[:n])) + } + _, _ = io.WriteString(conn, "ping") + n, err = conn.Read(buf) + if err != nil { + t.Fatal(err) + } + if string(buf[:n]) != "ping" { + t.Fatalf("echoed = %q, want ping", string(buf[:n])) + } + wantAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte("svc:s3cr3t")) + if got, _ := seenAuth.Load().(string); got != wantAuth { + t.Fatalf("Proxy-Authorization = %q, want %q", got, wantAuth) + } + if got, _ := seenTarget.Load().(string); got != "api.example.com:443" { + t.Fatalf("proxied target = %q, want api.example.com:443", got) + } +} + +func sendConnect(proxyAddr, target string) (string, error) { + conn, err := (&net.Dialer{Timeout: time.Second}).DialContext(context.Background(), "tcp", proxyAddr) + if err != nil { + return "", err + } + defer func() { _ = conn.Close() }() + if _, err := io.WriteString(conn, "CONNECT "+target+" HTTP/1.1\r\nHost: "+target+"\r\n\r\n"); err != nil { + return "", err + } + buf := make([]byte, 256) + n, err := conn.Read(buf) + if err != nil && n == 0 { + return "", err + } + return string(buf[:n]), nil +} diff --git a/modules/connectors/internal/host/host.go b/modules/connectors/internal/host/host.go index ec302848d..832441a0c 100644 --- a/modules/connectors/internal/host/host.go +++ b/modules/connectors/internal/host/host.go @@ -193,8 +193,14 @@ func openVerified(path string, sum []byte) (*os.File, error) { } func passEnv(names []string) []string { - env := make([]string, 0, len(names)+2) - for _, name := range append([]string{"PATH", "HOME"}, names...) { + defaults := []string{"PATH", "HOME", "SSL_CERT_FILE", "SSL_CERT_DIR"} + env := make([]string, 0, len(names)+len(defaults)) + seen := make(map[string]struct{}, len(names)+len(defaults)) + for _, name := range append(defaults, names...) { + if _, dup := seen[name]; dup { + continue + } + seen[name] = struct{}{} if value, ok := os.LookupEnv(name); ok { env = append(env, name+"="+value) }