refactor(archie,system): remove runtime config writes and finish track 1 (#2153)
This commit is contained in:
8 files changed
+45
-200
No files matched your search
@@ -5017,15 +5017,6 @@ components:
|
||||
required:
|
||||
- label
|
||||
type: object
|
||||
SystemAdminToken:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
token:
|
||||
description: Shown once; only its hash is written to the config
|
||||
type: string
|
||||
required:
|
||||
- token
|
||||
type: object
|
||||
SystemBootstrap:
|
||||
additionalProperties: false
|
||||
properties:
|
||||
@@ -5748,25 +5739,6 @@ paths:
|
||||
summary: Reset an action type to its default level
|
||||
tags:
|
||||
- Controls
|
||||
/api/admin/token:
|
||||
post:
|
||||
operationId: rotate-admin-token
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/SystemAdminToken"
|
||||
description: OK
|
||||
default:
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorModel"
|
||||
description: Error
|
||||
summary: Rotate the admin token; the new one is shown once
|
||||
tags:
|
||||
- System
|
||||
/api/approvals:
|
||||
get:
|
||||
operationId: list-approvals
|
||||
|
||||
+25
-6
@@ -47,13 +47,9 @@ 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)
|
||||
return runMigrate(*configPath, flag.Args()[1:])
|
||||
case "bootstrap":
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
return archie.Bootstrap(ctx, *configPath, *specPath)
|
||||
return runBootstrap(*configPath, *specPath, flag.Args()[1:])
|
||||
case "rekey":
|
||||
return runRekey(*configPath, flag.Args()[1:])
|
||||
case "bundle":
|
||||
@@ -108,6 +104,29 @@ func runRekey(configPath string, args []string) error {
|
||||
return archie.Rekey(ctx, configPath, rcfg)
|
||||
}
|
||||
|
||||
func runMigrate(defaultConfig string, args []string) error {
|
||||
fs := flag.NewFlagSet("migrate", flag.ContinueOnError)
|
||||
configPath := fs.String("config", defaultConfig, "path to the bootstrap config file")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
return archie.Migrate(ctx, *configPath)
|
||||
}
|
||||
|
||||
func runBootstrap(defaultConfig, defaultSpec string, args []string) error {
|
||||
fs := flag.NewFlagSet("bootstrap", flag.ContinueOnError)
|
||||
configPath := fs.String("config", defaultConfig, "path to the bootstrap config file")
|
||||
specPath := fs.String("spec", defaultSpec, "path to the bootstrap spec file")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
return archie.Bootstrap(ctx, *configPath, *specPath)
|
||||
}
|
||||
|
||||
func runBundle(configPath string, args []string) (int, error) {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
@@ -744,7 +744,7 @@ func ExportBundle(ctx context.Context, configPath, outPath string) error {
|
||||
_, err := os.Stdout.Write(raw)
|
||||
return err
|
||||
}
|
||||
return writeConfig(outPath, raw)
|
||||
return writeFileAtomic(outPath, raw)
|
||||
}
|
||||
|
||||
// DiffBundleFile validates the bundle at bundlePath and compares it against the
|
||||
|
||||
@@ -383,7 +383,7 @@ func runBundleExportCLI(ctx context.Context, configPath string, args []string, s
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
if err := writeConfig(*outPath, []byte(reply.BundleYAML)); err != nil {
|
||||
if err := writeFileAtomic(*outPath, []byte(reply.BundleYAML)); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
return 0, nil
|
||||
|
||||
@@ -93,62 +93,33 @@ type DatabaseConfig struct {
|
||||
|
||||
var adminHash = regexp.MustCompile(`^[0-9a-f]{64}$`)
|
||||
|
||||
var adminLine = regexp.MustCompile(`(?m)^\s*admin_token_sha256\s*=.*$`)
|
||||
|
||||
// WriteAdminHash replaces the admin token hash in the config at path, keeping
|
||||
// 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")
|
||||
}
|
||||
raw, err := os.ReadFile(path) //nolint:gosec // the path is the config the binary was started with.
|
||||
if err != nil {
|
||||
return fmt.Errorf("read config %s: %w", path, err)
|
||||
}
|
||||
line := `admin_token_sha256 = "` + hash + `"`
|
||||
next := string(raw)
|
||||
if adminLine.MatchString(next) {
|
||||
next = adminLine.ReplaceAllString(next, line)
|
||||
} else {
|
||||
next = strings.TrimRight(next, "\n") + "\n" + line + "\n"
|
||||
}
|
||||
if !strings.HasSuffix(next, "\n") {
|
||||
next += "\n"
|
||||
}
|
||||
return writeConfig(path, []byte(next))
|
||||
}
|
||||
|
||||
// writeConfig replaces path atomically, so a crash leaves either the old file
|
||||
// writeFileAtomic replaces path atomically, so a crash leaves either the old file
|
||||
// or the new one.
|
||||
func writeConfig(path string, data []byte) error {
|
||||
func writeFileAtomic(path string, data []byte) error {
|
||||
dir := filepath.Dir(path)
|
||||
file, err := os.CreateTemp(dir, ".config-*")
|
||||
file, err := os.CreateTemp(dir, ".tmp-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("write config %s: %w", path, err)
|
||||
return fmt.Errorf("write %s: %w", path, err)
|
||||
}
|
||||
name := file.Name()
|
||||
defer func() { _ = os.Remove(name) }()
|
||||
if err := file.Chmod(0o600); err != nil {
|
||||
_ = file.Close()
|
||||
return fmt.Errorf("write config %s: %w", path, err)
|
||||
return fmt.Errorf("write %s: %w", path, err)
|
||||
}
|
||||
if _, err := file.Write(data); err != nil {
|
||||
_ = file.Close()
|
||||
return fmt.Errorf("write config %s: %w", path, err)
|
||||
return fmt.Errorf("write %s: %w", path, err)
|
||||
}
|
||||
if err := file.Sync(); err != nil {
|
||||
_ = file.Close()
|
||||
return fmt.Errorf("write config %s: %w", path, err)
|
||||
return fmt.Errorf("write %s: %w", path, err)
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
return fmt.Errorf("write config %s: %w", path, err)
|
||||
return fmt.Errorf("write %s: %w", path, err)
|
||||
}
|
||||
if err := os.Rename(name, path); err != nil {
|
||||
return fmt.Errorf("write config %s: %w", path, err)
|
||||
return fmt.Errorf("write %s: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -10,63 +10,6 @@ import (
|
||||
"filippo.io/age"
|
||||
)
|
||||
|
||||
// TestWriteAdminHashReplacesOnlyTheHash guards token rotation: the config keeps
|
||||
// every other value, the old hash is gone, and the file is not left readable.
|
||||
func TestWriteAdminHashReplacesOnlyTheHash(t *testing.T) {
|
||||
const oldHash = "1111111111111111111111111111111111111111111111111111111111111111"
|
||||
const newHash = "2222222222222222222222222222222222222222222222222222222222222222"
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
before := "listen = \":8080\"\nadmin_token_sha256 = \"" + oldHash + "\"\n"
|
||||
if err := os.WriteFile(path, []byte(before), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := WriteAdminHash(path, newHash); err != nil {
|
||||
t.Fatalf("rotate: %v", err)
|
||||
}
|
||||
|
||||
got, err := os.ReadFile(path) //nolint:gosec // a test fixture in t.TempDir.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := string(got)
|
||||
switch {
|
||||
case strings.Contains(text, oldHash):
|
||||
t.Fatal("the old hash is still in the config")
|
||||
case !strings.Contains(text, newHash):
|
||||
t.Fatal("the new hash was not written")
|
||||
case !strings.Contains(text, `listen = ":8080"`):
|
||||
t.Fatal("rotation changed another setting")
|
||||
}
|
||||
info, err := os.Stat(path) //nolint:gosec // a test fixture in t.TempDir.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("config mode is %o, want 600", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteAdminHashAddsAMissingLine guards a config written before the hash
|
||||
// was set.
|
||||
func TestWriteAdminHashAddsAMissingLine(t *testing.T) {
|
||||
const hash = "3333333333333333333333333333333333333333333333333333333333333333"
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte("listen = \":8080\"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := WriteAdminHash(path, hash); err != nil {
|
||||
t.Fatalf("rotate: %v", err)
|
||||
}
|
||||
got, err := os.ReadFile(path) //nolint:gosec // a test fixture in t.TempDir.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(got), hash) {
|
||||
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) {
|
||||
|
||||
@@ -102,7 +102,7 @@ func Run(ctx context.Context, configPath string) error {
|
||||
}
|
||||
var draining atomic.Bool
|
||||
metrics := telemetry.NewMetrics()
|
||||
b, err := wire(log, configPath, cfg, db, &draining, metrics) //nolint:contextcheck // the API's guard derives its context from each request
|
||||
b, err := wire(log, cfg, db, &draining, metrics) //nolint:contextcheck // the API's guard derives its context from each request
|
||||
if err != nil {
|
||||
_ = db.Close()
|
||||
return err
|
||||
@@ -195,7 +195,7 @@ 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, draining *atomic.Bool, metrics *telemetry.Metrics) (*binary, error) {
|
||||
func wire(log *slog.Logger, cfg Config, db *sqlx.DB, draining *atomic.Bool, metrics *telemetry.Metrics) (*binary, error) {
|
||||
checks := newHealthChecks(db, draining)
|
||||
|
||||
runtime.RegisterBuiltinClasses()
|
||||
@@ -225,7 +225,7 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB, draining
|
||||
Listen: cfg.Listen, Database: DatabaseHost(cfg.Database.URL), Schemas: len(schemas),
|
||||
AdminPrefix: cfg.AdminTokenSHA256[:8], AdminSet: cfg.AdminTokenSHA256 != "",
|
||||
Sealing: cfg.AgeIdentity != "",
|
||||
}, func(hash string) error { return WriteAdminHash(configPath, hash) }, log.With("module", "system"))
|
||||
}, log.With("module", "system"))
|
||||
|
||||
live := hub.New()
|
||||
// Messages go to the composer and to every accepted connector that delivers
|
||||
@@ -261,7 +261,7 @@ 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)
|
||||
wireAuditAndChanges(log, auditLog, settings, allow, policies, conns, sys, tell)
|
||||
wireAuditAndChanges(log, auditLog, settings, allow, policies, conns, tell)
|
||||
remember, err := wireMemory(db, log, cfg.StateDir, checks)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -421,7 +421,6 @@ func wireAuditAndChanges(
|
||||
allow *approvals.Module,
|
||||
policies *judgement.Policies,
|
||||
conns *connectors.Module,
|
||||
sys *system.Module,
|
||||
tell *deliveries.Module,
|
||||
) {
|
||||
settings.UseAudit(func(ctx context.Context, e governance.AuditRecord) {
|
||||
@@ -433,7 +432,6 @@ func wireAuditAndChanges(
|
||||
allow.UseAudit(auditLog)
|
||||
policies.UseAudit(auditLog)
|
||||
conns.UseAudit(auditLog)
|
||||
sys.UseAudit(auditLog)
|
||||
allow.UseChangeRequests(changeRequests{tell: tell})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
// Package system serves the bootstrap values the binary reads before the
|
||||
// database is reachable, read-only, and the one change that must survive a
|
||||
// restart: the admin token.
|
||||
// database is reachable, read-only, and instance health.
|
||||
package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
@@ -15,8 +11,6 @@ import (
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
"github.com/samcharles93/archie-core/modules/audit"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
)
|
||||
|
||||
@@ -31,25 +25,19 @@ type Bootstrap struct {
|
||||
Sealing bool `json:"sealing_identity_set"`
|
||||
}
|
||||
|
||||
// Module serves the bootstrap view and rotates the admin token.
|
||||
// Module serves the bootstrap view and instance health.
|
||||
type Module struct {
|
||||
mu sync.RWMutex
|
||||
bootstrap Bootstrap
|
||||
rotate func(hash string) error
|
||||
sources Sources
|
||||
audit audit.Recorder
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// New returns the system module. rotate writes a new admin token hash to the
|
||||
// config the binary loaded.
|
||||
func New(b Bootstrap, rotate func(hash string) error, log *slog.Logger) *Module {
|
||||
return &Module{bootstrap: b, rotate: rotate, log: log}
|
||||
// New returns the system module.
|
||||
func New(b Bootstrap, log *slog.Logger) *Module {
|
||||
return &Module{bootstrap: b, log: log}
|
||||
}
|
||||
|
||||
// UseAudit configures the audit recorder notified on administrative actions.
|
||||
func (m *Module) UseAudit(r audit.Recorder) { m.audit = r }
|
||||
|
||||
// Register adds the system API.
|
||||
func (m *Module) Register(api huma.API) {
|
||||
tags := []string{"System"}
|
||||
@@ -57,57 +45,11 @@ func (m *Module) Register(api huma.API) {
|
||||
OperationID: "get-bootstrap", Method: http.MethodGet, Path: "/api/system/bootstrap",
|
||||
Summary: "Get the bootstrap values, which only the config file sets", Tags: tags,
|
||||
}, m.getBootstrap)
|
||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindInstance), huma.Operation{
|
||||
OperationID: "rotate-admin-token", Method: http.MethodPost, Path: "/api/admin/token",
|
||||
Summary: "Rotate the admin token; the new one is shown once", Tags: tags,
|
||||
}, m.rotateAdminToken)
|
||||
m.registerHealth(api)
|
||||
}
|
||||
|
||||
// adminToken is a new admin token, returned once.
|
||||
type adminToken struct {
|
||||
Token string `json:"token" doc:"Shown once; only its hash is written to the config"`
|
||||
}
|
||||
|
||||
func (m *Module) getBootstrap(_ context.Context, _ *struct{}) (*httpapi.Reply[Bootstrap], error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return httpapi.OK(m.bootstrap), nil
|
||||
}
|
||||
|
||||
// rotateAdminToken generates a new token, writes only its hash to the config,
|
||||
// and returns the token once. The old token and the old hash are never read
|
||||
// back or logged.
|
||||
func (m *Module) rotateAdminToken(ctx context.Context, _ *struct{}) (*httpapi.Reply[adminToken], error) {
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
m.log.ErrorContext(ctx, "generate admin token", "error", err)
|
||||
return nil, huma.NewError(http.StatusInternalServerError, "couldn't generate a token")
|
||||
}
|
||||
hash := httpjson.TokenHash(token)
|
||||
if err := m.rotate(hash); err != nil {
|
||||
m.log.ErrorContext(ctx, "write admin token hash", "error", err)
|
||||
return nil, huma.NewError(http.StatusInternalServerError, "couldn't write the new token hash to the config")
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.bootstrap.AdminPrefix, m.bootstrap.AdminSet = hash[:8], true
|
||||
m.mu.Unlock()
|
||||
m.log.InfoContext(ctx, "admin token rotated", "audit", true, "action", "admin.token.rotate")
|
||||
audit.Emit(ctx, m.audit, m.log, audit.Event{
|
||||
Category: "auth",
|
||||
Action: "admin.token.rotate",
|
||||
ActorID: governance.CallerID(ctx),
|
||||
ResourceKind: "instance",
|
||||
ResourceID: "admin_token",
|
||||
Outcome: "success",
|
||||
})
|
||||
return httpapi.OK(adminToken{Token: token}), nil
|
||||
}
|
||||
|
||||
func newToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("generate token: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
Reference in new issue
Block a user