feat(archie): add headless bootstrap command and remote extension wiring

This commit is contained in:
sam committed 2026-11-27 20:51:52 +11:00
1 parent 6791125aab
commit 47e8db7453
7 files changed
+424 -20

No files matched your search

+6 -1
View File
@@ -23,10 +23,11 @@ func main() {
func run() error {
configPath := flag.String("config", archie.DefaultConfigPath(), "path to the bootstrap config file")
specPath := flag.String("spec", "", "path to the bootstrap spec file (used by 'archie bootstrap')")
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 migrate apply database migrations and runtime grants\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 bootstrap idempotently provision initial owner and SSO settings\n archie openapi print the API's OpenAPI document")
flag.PrintDefaults()
}
flag.Parse()
@@ -40,6 +41,10 @@ func run() error {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
return archie.Migrate(ctx, *configPath)
case "bootstrap":
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
return archie.Bootstrap(ctx, *configPath, *specPath)
case "openapi":
doc, err := archie.Document()
if err != nil {
+170
View File
@@ -0,0 +1,170 @@
package archie
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"strings"
"github.com/BurntSushi/toml"
"github.com/samcharles93/archie-core/internal/buildinfo"
"github.com/samcharles93/archie-core/internal/platform/pg"
"github.com/samcharles93/archie-core/modules/governance"
)
// BootstrapSpec defines headless first-boot provisioning for automated stage
// rollouts, avoiding exposing an unauthenticated setup page.
type BootstrapSpec struct {
PublicURL string `toml:"public_url"`
TrustedProxies []string `toml:"trusted_proxies"`
Owner BootstrapOwnerSpec `toml:"owner"`
OIDC BootstrapOIDCSpec `toml:"oidc"`
}
// BootstrapOwnerSpec creates the initial instance owner when none exists yet.
type BootstrapOwnerSpec struct {
Email string `toml:"email"`
DisplayName string `toml:"display_name"`
Password string `toml:"password"`
}
// BootstrapOIDCSpec configures corporate SSO at bootstrap time.
type BootstrapOIDCSpec struct {
Issuer string `toml:"issuer"`
Audience string `toml:"audience"`
ClientID string `toml:"client_id"`
}
// LoadBootstrapSpec reads specPath (when non-empty) and applies
// ARCHIE_BOOTSTRAP_* and *_FILE environment overrides.
func LoadBootstrapSpec(specPath string) (BootstrapSpec, error) {
var spec BootstrapSpec
if specPath != "" {
if _, err := toml.DecodeFile(specPath, &spec); err != nil {
return BootstrapSpec{}, fmt.Errorf("read bootstrap spec %s: %w", specPath, err)
}
}
if err := applyBootstrapEnv(&spec); err != nil {
return BootstrapSpec{}, err
}
if err := spec.validate(); err != nil {
return BootstrapSpec{}, fmt.Errorf("bootstrap spec: %w", err)
}
return spec, nil
}
func applyBootstrapEnv(spec *BootstrapSpec) error {
overrides := []struct {
envKey string
fileKey string
target *string
}{
{envKey: "ARCHIE_BOOTSTRAP_PUBLIC_URL", target: &spec.PublicURL},
{envKey: "ARCHIE_BOOTSTRAP_OWNER_EMAIL", target: &spec.Owner.Email},
{envKey: "ARCHIE_BOOTSTRAP_OWNER_DISPLAY_NAME", target: &spec.Owner.DisplayName},
{envKey: "ARCHIE_BOOTSTRAP_OWNER_PASSWORD", fileKey: "ARCHIE_BOOTSTRAP_OWNER_PASSWORD_FILE", target: &spec.Owner.Password},
{envKey: "ARCHIE_BOOTSTRAP_OIDC_ISSUER", target: &spec.OIDC.Issuer},
{envKey: "ARCHIE_BOOTSTRAP_OIDC_AUDIENCE", target: &spec.OIDC.Audience},
{envKey: "ARCHIE_BOOTSTRAP_OIDC_CLIENT_ID", target: &spec.OIDC.ClientID},
}
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 (s BootstrapSpec) validate() error {
auth := governance.AuthenticationSettings{
PublicURL: strings.TrimRight(strings.TrimSpace(s.PublicURL), "/"),
OIDCIssuer: strings.TrimSpace(s.OIDC.Issuer),
OIDCAudience: strings.TrimSpace(s.OIDC.Audience),
OIDCClientID: strings.TrimSpace(s.OIDC.ClientID),
TrustedProxies: s.TrustedProxies,
}
if err := auth.Validate(); err != nil {
return err
}
reg := governance.AccountRegistration{
PublicURL: auth.PublicURL,
Email: strings.TrimSpace(s.Owner.Email),
DisplayName: strings.TrimSpace(s.Owner.DisplayName),
Password: s.Owner.Password,
}
return reg.Validate()
}
// Bootstrap idempotently provisions the initial owner account, shipped org
// policies, and OIDC/proxy settings using only the runtime database role.
func Bootstrap(ctx context.Context, configPath, specPath string) error {
log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "archie", "version", buildinfo.Version)
dbURL, err := LoadRuntimeDBConfig(configPath)
if err != nil {
return err
}
spec, err := LoadBootstrapSpec(specPath)
if err != nil {
return err
}
db, err := pg.Open(ctx, dbURL)
if err != nil {
return err
}
defer func() { _ = db.Close() }()
if err := pg.VerifySchema(ctx, db); err != nil {
return err
}
settings := governance.NewModule(db, log.With("module", "governance"), orgID)
required, err := settings.AccountSetupRequired(ctx)
if err != nil {
return fmt.Errorf("check setup state: %w", err)
}
if required {
if _, err := settings.RegisterAccount(ctx, governance.AccountRegistration{
PublicURL: strings.TrimRight(strings.TrimSpace(spec.PublicURL), "/"),
Email: strings.TrimSpace(spec.Owner.Email),
DisplayName: strings.TrimSpace(spec.Owner.DisplayName),
Password: spec.Owner.Password,
}, true); err != nil && !errors.Is(err, governance.ErrInvalidIdentity) {
return fmt.Errorf("register bootstrap owner: %w", err)
}
log.InfoContext(ctx, "bootstrapped initial owner")
} else {
log.InfoContext(ctx, "owner setup already complete; skipping owner creation")
}
if err := settings.EnsureShippedOrgPolicies(ctx, governance.DefaultOrgID); err != nil {
return fmt.Errorf("seed role policies: %w", err)
}
if spec.OIDC.Issuer != "" || len(spec.TrustedProxies) > 0 {
adminCtx := governance.WithPrincipal(ctx, governance.Principal{
IdentityID: governance.SystemID,
Kind: governance.KindSystem,
Org: governance.DefaultOrgID,
Memberships: []governance.Membership{{
IdentityID: governance.SystemID,
OrgID: governance.DefaultOrgID,
Role: governance.RoleOwner,
}},
})
if err := settings.SaveAuthenticationSettings(adminCtx, governance.AuthenticationSettings{
PublicURL: strings.TrimRight(strings.TrimSpace(spec.PublicURL), "/"),
OIDCIssuer: strings.TrimSpace(spec.OIDC.Issuer),
OIDCAudience: strings.TrimSpace(spec.OIDC.Audience),
OIDCClientID: strings.TrimSpace(spec.OIDC.ClientID),
TrustedProxies: spec.TrustedProxies,
}); err != nil {
return fmt.Errorf("save authentication settings: %w", err)
}
log.InfoContext(ctx, "applied bootstrap authentication settings")
}
return nil
}
+71
View File
@@ -0,0 +1,71 @@
package archie
import (
"os"
"path/filepath"
"strings"
"testing"
)
// TestLoadBootstrapSpecAndEnvFiles guards headless bootstrap spec validation
// and *_FILE password injection.
func TestLoadBootstrapSpecAndEnvFiles(t *testing.T) {
dir := t.TempDir()
specPath := filepath.Join(dir, "bootstrap.toml")
pwFile := filepath.Join(dir, "owner_pw")
const testPW = "correct-horse-battery-staple-99" //nolint:gosec // test fixture password for bootstrap validation
if err := os.WriteFile(pwFile, []byte(testPW+"\n"), 0o600); err != nil {
t.Fatal(err)
}
specTOML := `
public_url = "https://archie.staging.example.com"
trusted_proxies = ["10.0.0.0/8"]
[owner]
email = "ops-admin@example.com"
display_name = "Platform Owner"
[oidc]
issuer = "https://idp.example.com"
audience = "archie-staging"
client_id = "archie-web"
`
if err := os.WriteFile(specPath, []byte(specTOML), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("ARCHIE_BOOTSTRAP_OWNER_PASSWORD_FILE", pwFile)
spec, err := LoadBootstrapSpec(specPath)
if err != nil {
t.Fatalf("LoadBootstrapSpec: %v", err)
}
if spec.Owner.Password != testPW {
t.Fatalf("Password mismatch")
}
if spec.OIDC.ClientID != "archie-web" || spec.PublicURL != "https://archie.staging.example.com" {
t.Fatalf("unexpected spec: %+v", spec)
}
// Setting both password env and file must fail loudly.
t.Setenv("ARCHIE_BOOTSTRAP_OWNER_PASSWORD", testPW)
if _, err := LoadBootstrapSpec(specPath); err == nil || !strings.Contains(err.Error(), "not both") {
t.Fatalf("expected ambiguity error, got %v", err)
}
}
func TestLoadBootstrapSpecRejectsInvalidFields(t *testing.T) {
t.Setenv("ARCHIE_BOOTSTRAP_PUBLIC_URL", "not-a-url")
t.Setenv("ARCHIE_BOOTSTRAP_OWNER_EMAIL", "admin@example.com")
t.Setenv("ARCHIE_BOOTSTRAP_OWNER_DISPLAY_NAME", "Owner")
t.Setenv("ARCHIE_BOOTSTRAP_OWNER_PASSWORD", "correct-horse-battery-staple-99")
if _, err := LoadBootstrapSpec(""); err == nil {
t.Fatal("expected invalid public_url error")
}
t.Setenv("ARCHIE_BOOTSTRAP_PUBLIC_URL", "https://archie.example.com")
t.Setenv("ARCHIE_BOOTSTRAP_OIDC_ISSUER", "https://idp.example.com")
if _, err := LoadBootstrapSpec(""); err == nil {
t.Fatal("expected unpaired OIDC fields error")
}
}
+59 -2
View File
@@ -8,6 +8,7 @@ import (
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
@@ -15,6 +16,7 @@ import (
"github.com/BurntSushi/toml"
"github.com/samcharles93/archie-core/internal/platform/deletions"
"github.com/samcharles93/archie-core/modules/connectors"
)
const defaultShutdownGrace = 30 * time.Second
@@ -41,8 +43,28 @@ type Config struct {
// 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:"-"`
ShutdownGraceRaw string `toml:"shutdown_grace"`
ShutdownGrace time.Duration `toml:"-"`
Catalogue CatalogueConfig `toml:"catalogue"`
Extensions ExtensionsConfig `toml:"extensions"`
}
// CatalogueConfig overrides the default extension catalogue source and disables
// periodic update polling in air-gapped environments.
type CatalogueConfig struct {
Location string `toml:"location"`
PublicKey string `toml:"public_key"`
DisableAutoUpdate bool `toml:"disable_auto_update"`
}
// ExtensionsConfig configures remote gRPC+mTLS extension endpoints for
// hardened Kubernetes clusters that disallow local namespace confinement.
type ExtensionsConfig struct {
RequireRemote bool `toml:"require_remote"`
CAFile string `toml:"ca_file"`
CertFile string `toml:"cert_file"`
KeyFile string `toml:"key_file"`
Remote map[string]connectors.RemoteEndpoint `toml:"remote"`
}
// DatabaseConfig holds the two connection URLs. The owner runs migrations at
@@ -197,6 +219,18 @@ func LoadMigrateConfig(path string) (DatabaseConfig, error) {
return cfg.Database, nil
}
// LoadRuntimeDBConfig loads only database.url for `archie bootstrap`.
func LoadRuntimeDBConfig(path string) (string, error) {
var cfg Config
if err := decodeConfig(path, &cfg); err != nil {
return "", err
}
if cfg.Database.URL == "" {
return "", fmt.Errorf("config %s: database.url is required", configLabel(path))
}
return cfg.Database.URL, nil
}
func decodeConfig(path string, cfg *Config) error {
if path != "" {
if _, err := toml.DecodeFile(path, cfg); err != nil {
@@ -222,6 +256,11 @@ func applyEnv(cfg *Config) error {
{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},
{envKey: "ARCHIE_CATALOGUE_LOCATION", target: &cfg.Catalogue.Location},
{envKey: "ARCHIE_CATALOGUE_PUBLIC_KEY", target: &cfg.Catalogue.PublicKey},
{envKey: "ARCHIE_EXTENSIONS_CA_FILE", target: &cfg.Extensions.CAFile},
{envKey: "ARCHIE_EXTENSIONS_CERT_FILE", target: &cfg.Extensions.CertFile},
{envKey: "ARCHIE_EXTENSIONS_KEY_FILE", target: &cfg.Extensions.KeyFile},
}
for _, o := range overrides {
val, ok, err := envOrFile(o.envKey, o.fileKey)
@@ -232,6 +271,21 @@ func applyEnv(cfg *Config) error {
*o.target = val
}
}
for _, b := range []struct {
envKey string
target *bool
}{
{envKey: "ARCHIE_CATALOGUE_DISABLE_AUTO_UPDATE", target: &cfg.Catalogue.DisableAutoUpdate},
{envKey: "ARCHIE_EXTENSIONS_REQUIRE_REMOTE", target: &cfg.Extensions.RequireRemote},
} {
if raw := strings.TrimSpace(os.Getenv(b.envKey)); raw != "" {
v, err := strconv.ParseBool(raw)
if err != nil {
return fmt.Errorf("parse %s: %w", b.envKey, err)
}
*b.target = v
}
}
return nil
}
@@ -286,6 +340,9 @@ 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.Catalogue.Location == "") != (c.Catalogue.PublicKey == "") {
errs = append(errs, errors.New("catalogue.location and catalogue.public_key must be set together"))
}
return errors.Join(errs...)
}
+61
View File
@@ -135,3 +135,64 @@ func TestLoadMigrateConfigRequiresOnlyDatabaseRoles(t *testing.T) {
t.Fatal("expected error when owner_url matches url")
}
}
// TestLoadConfigCatalogueAndExtensions guards air-gapped catalogue overrides
// and remote Kubernetes extension endpoint configuration.
func TestLoadConfigCatalogueAndExtensions(t *testing.T) {
id, err := age.GenerateX25519Identity()
if err != nil {
t.Fatal(err)
}
const adminSHA = "5555555555555555555555555555555555555555555555555555555555555555"
const dsn = "postgres://archie_app:pass@db:5432/archie" //nolint:gosec // test fixture DSN without real credentials
dir := t.TempDir()
path := filepath.Join(dir, "config.toml")
tomlBody := `
listen = "0.0.0.0:8080"
admin_token_sha256 = "` + adminSHA + `"
age_identity = "` + id.String() + `"
state_dir = "` + filepath.Join(dir, "state") + `"
[database]
url = "` + dsn + `"
[catalogue]
location = "oci://registry.internal/archie/catalogue"
public_key = "PLouShOzvRqy1QbYaJplaM41/ulgKFN8ZQ7g1rI02Fc="
disable_auto_update = true
[extensions]
require_remote = true
ca_file = "/etc/archie/tls/ca.crt"
cert_file = "/etc/archie/tls/tls.crt"
key_file = "/etc/archie/tls/tls.key"
[extensions.remote.vault]
address = "vault-ext.archie-prod.svc:9443"
server_name = "vault-ext.archie-prod.svc"
`
if err := os.WriteFile(path, []byte(tomlBody), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := LoadConfig(path)
if err != nil {
t.Fatalf("LoadConfig: %v", err)
}
if !cfg.Catalogue.DisableAutoUpdate || cfg.Catalogue.Location != "oci://registry.internal/archie/catalogue" {
t.Fatalf("unexpected catalogue config: %+v", cfg.Catalogue)
}
if !cfg.Extensions.RequireRemote || cfg.Extensions.Remote["vault"].Address != "vault-ext.archie-prod.svc:9443" {
t.Fatalf("unexpected extensions config: %+v", cfg.Extensions)
}
// Catalogue location without public_key must fail validation.
t.Setenv("ARCHIE_CATALOGUE_PUBLIC_KEY", "")
badPath := filepath.Join(dir, "bad.toml")
badBody := strings.ReplaceAll(tomlBody, `public_key = "PLouShOzvRqy1QbYaJplaM41/ulgKFN8ZQ7g1rI02Fc="`, "")
if err := os.WriteFile(badPath, []byte(badBody), 0o600); err != nil {
t.Fatal(err)
}
if _, err := LoadConfig(badPath); err == nil || !strings.Contains(err.Error(), "must be set together") {
t.Fatalf("expected paired catalogue error, got %v", err)
}
}
+8 -2
View File
@@ -41,6 +41,8 @@ type operations struct {
allow *approvals.Module
remember *memory.Module
proposed *proposals.Module
// disableCatalogueUpdates skips periodic catalogue polling in air-gapped stages.
disableCatalogueUpdates bool
// completeRecord finishes the record of a committed deletion whose entry could
// not be written.
completeRecord func(context.Context) (int, error)
@@ -87,8 +89,12 @@ func (o *operations) Start(ctx context.Context) error {
// Nothing below can fail, so a retry cannot launch a connector or a loop twice.
o.checks.Register("connectors", o.conns.Ready)
// An extension that follows the catalogue checks it for a new version. With
// no catalogue source set it does nothing.
o.workers.Go(func() { o.conns.WatchUpdates(ctx, catalogueUpdateInterval) })
// no catalogue source set (or auto-updates disabled) it does nothing.
if o.disableCatalogueUpdates {
o.log.InfoContext(ctx, "extension catalogue auto-updates disabled")
} else {
o.workers.Go(func() { o.conns.WatchUpdates(ctx, catalogueUpdateInterval) })
}
// Administrative writes, and every API request, are checked against the same
// live policy chain as chat and background work. The webhook intake applies
// each source's delivery policy from it.
+49 -15
View File
@@ -177,6 +177,9 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB, draining
if err != nil {
return nil, err
}
if err := configureConnectors(conns, cfg); err != nil {
return nil, err
}
// A model's key is a credential id resolved through the sealed store in
// organisation scope with no person attached.
settings.UseCredentials(orgCredentials{conns: conns, orgID: string(governance.DefaultOrgID)})
@@ -224,22 +227,10 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB, draining
hear.Routes(mux)
engine.UseReferrers(hear)
judge := newJudgement(db, log, conns, actionTypes, policies, settings, hear)
// The record of deletions outlives this process and its database, so the
// log exists before anything can be deleted: an instance that has run this
// release and lost its log is a different case from one that never deleted.
ledger := deletions.NewLog(deletions.Path(cfg.StateDir))
if err := ledger.Ensure(); err != nil {
return nil, fmt.Errorf("prepare the deletion record: %w", err)
remember, err := wireMemory(db, log, cfg.StateDir, checks)
if err != nil {
return nil, err
}
remember := memory.NewModule(db, orgID, log.With("module", "memory"), ledger)
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)
@@ -259,6 +250,7 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB, draining
ops: &operations{
log: log, checks: checks, settings: settings, conns: conns, engine: engine, hear: hear,
tell: tell, talk: talk, judge: judge, allow: allow, remember: remember, proposed: proposed,
disableCatalogueUpdates: cfg.Catalogue.DisableAutoUpdate,
completeRecord: func(ctx context.Context) (int, error) {
return memory.Reconcile(ctx, db, cfg.StateDir)
},
@@ -266,6 +258,48 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB, draining
}, nil
}
func wireMemory(db *sqlx.DB, log *slog.Logger, stateDir string, checks *health.Registry) (*memory.Module, error) {
// The record of deletions outlives this process and its database, so the
// log exists before anything can be deleted: an instance that has run this
// release and lost its log is a different case from one that never deleted.
ledger := deletions.NewLog(deletions.Path(stateDir))
if err := ledger.Ensure(); err != nil {
return nil, fmt.Errorf("prepare the deletion record: %w", err)
}
remember := memory.NewModule(db, orgID, log.With("module", "memory"), ledger)
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)
return remember, nil
}
func configureConnectors(conns *connectors.Module, cfg Config) error {
if cfg.Catalogue.Location != "" {
if err := conns.UseDefaultCatalogue(cfg.Catalogue.Location, cfg.Catalogue.PublicKey); err != nil {
return fmt.Errorf("default catalogue: %w", err)
}
}
if cfg.Extensions.RequireRemote || len(cfg.Extensions.Remote) > 0 {
if err := conns.UseRemotes(connectors.RemoteConfig{
RequireRemote: cfg.Extensions.RequireRemote,
TLS: connectors.RemoteTLS{
CAFile: cfg.Extensions.CAFile,
CertFile: cfg.Extensions.CertFile,
KeyFile: cfg.Extensions.KeyFile,
},
Endpoints: cfg.Extensions.Remote,
}); err != nil {
return fmt.Errorf("remote extensions: %w", err)
}
}
return nil
}
func newHealthChecks(db *sqlx.DB, draining *atomic.Bool) *health.Registry {
checks := health.NewRegistry()
checks.RegisterStartup("database", db.PingContext)