From dd38d93a292b55b819698a673674f141b91baca2 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Fri, 27 Nov 2026 21:20:33 +1100 Subject: [PATCH] feat(archie): wire enterprise rekey, OIDC/SoD, audit, telemetry, and bundles (#2153, #2154, #2155, #2156, #2157, #2158) --- api/openapi.yaml | 545 +++++++++++++++++++++++++++++ cmd/archie/main.go | 51 ++- internal/app/archie/access_test.go | 2 +- internal/app/archie/api.go | 12 +- internal/app/archie/config.go | 8 +- internal/app/archie/run.go | 110 ++++-- 6 files changed, 687 insertions(+), 41 deletions(-) diff --git a/api/openapi.yaml b/api/openapi.yaml index 3e50a028e..aecc9521d 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -89,6 +89,8 @@ components: type: string id: type: string + initiator_id: + type: string kind: type: string level: @@ -96,6 +98,8 @@ components: requested_at: format: date-time type: string + require_sod: + type: boolean run_id: type: string state: @@ -136,6 +140,209 @@ components: assertion: $ref: "#/components/schemas/ApprovalsAssertion" type: object + ArchieAccessPolicyChange: + additionalProperties: false + properties: + id: + type: string + op: + type: string + required: + - op + - id + type: object + ArchieActionTypeChange: + additionalProperties: false + properties: + action: + type: string + connector: + type: string + details: + items: + type: string + type: + - array + - "null" + environment: + type: string + op: + type: string + target_kind: + type: string + required: + - op + - connector + - action + - target_kind + - environment + type: object + ArchieBundleApplyReply: + additionalProperties: false + properties: + applied: + type: boolean + diff: + $ref: "#/components/schemas/ArchieBundleDiff" + digest: + type: string + dry_run: + type: boolean + empty: + type: boolean + formatted: + type: string + required: + - digest + - dry_run + - applied + - empty + - formatted + - diff + type: object + ArchieBundleDiff: + additionalProperties: false + properties: + access_policies: + items: + $ref: "#/components/schemas/ArchieAccessPolicyChange" + type: + - array + - "null" + action_types: + items: + $ref: "#/components/schemas/ArchieActionTypeChange" + type: + - array + - "null" + judgement_rules: + items: + $ref: "#/components/schemas/ArchieRuleChange" + type: + - array + - "null" + workflows: + items: + $ref: "#/components/schemas/ArchieWorkflowChange" + type: + - array + - "null" + type: object + ArchieBundleDiffReply: + additionalProperties: false + properties: + diff: + $ref: "#/components/schemas/ArchieBundleDiff" + digest: + type: string + empty: + type: boolean + formatted: + type: string + required: + - digest + - empty + - formatted + - diff + type: object + ArchieBundleExportReply: + additionalProperties: false + properties: + bundle_yaml: + type: string + digest: + type: string + exported_at: + format: date-time + type: string + schema_version: + type: string + required: + - schema_version + - exported_at + - digest + - bundle_yaml + type: object + ArchieRuleChange: + additionalProperties: false + properties: + kind: + type: string + op: + type: string + required: + - op + - kind + type: object + ArchieWorkflowChange: + additionalProperties: false + properties: + details: + items: + type: string + type: + - array + - "null" + name: + type: string + op: + type: string + required: + - op + - name + type: object + AuditEvent: + additionalProperties: false + properties: + action: + type: string + actor_id: + type: string + actor_kind: + type: string + at: + format: date-time + type: string + category: + type: string + detail: {} + id: + type: string + org_id: + type: string + outcome: + type: string + resource_id: + type: string + resource_kind: + type: string + trace_id: + type: string + required: + - id + - org_id + - at + - category + - action + - actor_id + - outcome + type: object + AuditEventsBody: + additionalProperties: false + properties: + events: + items: + $ref: "#/components/schemas/AuditEvent" + type: + - array + - "null" + more: + description: Whether older events match beyond this page + type: boolean + required: + - events + - more + type: object AuditjsonPayload: additionalProperties: false properties: @@ -157,10 +364,26 @@ components: type: string oidc_client_id: type: string + oidc_client_secret: + type: string + oidc_groups_claim: + type: string oidc_issuer: type: string + oidc_role_map: + additionalProperties: + type: string + type: object public_url: type: string + session_idle_timeout_s: + format: int64 + type: integer + session_max_lifetime_s: + format: int64 + type: integer + sso_only: + type: boolean trusted_proxies: items: type: string @@ -170,6 +393,33 @@ components: required: - public_url type: object + BundleApplyInputBody: + additionalProperties: false + properties: + bindings_yaml: + description: Optional stage-local bindings YAML + type: string + bundle_yaml: + description: Portable promotion bundle YAML + type: string + dry_run: + description: Validate and compute diff without mutating state + type: boolean + expect_digest: + description: Expected canonical bundle SHA-256 digest + type: string + required: + - bundle_yaml + type: object + BundleDiffInputBody: + additionalProperties: false + properties: + bundle_yaml: + description: Portable promotion bundle YAML + type: string + required: + - bundle_yaml + type: object CaptureInputBody: additionalProperties: false properties: @@ -2140,12 +2390,15 @@ components: type: string setup_required: type: boolean + sso_only: + type: boolean user: $ref: "#/components/schemas/GovernanceIdentity" required: - setup_required - user - oidc + - sso_only - public_url - instance type: object @@ -2156,10 +2409,30 @@ components: type: string oidc_client_id: type: string + oidc_client_secret: + type: string + writeOnly: true + oidc_client_secret_set: + readOnly: true + type: boolean + oidc_groups_claim: + type: string oidc_issuer: type: string + oidc_role_map: + additionalProperties: + type: string + type: object public_url: type: string + session_idle_timeout_s: + format: int64 + type: integer + session_max_lifetime_s: + format: int64 + type: integer + sso_only: + type: boolean trusted_proxies: items: type: string @@ -2171,6 +2444,10 @@ components: - oidc_issuer - oidc_audience - oidc_client_id + - oidc_client_secret_set + - sso_only + - session_idle_timeout_s + - session_max_lifetime_s - trusted_proxies type: object GovernanceBlackout: @@ -5571,6 +5848,176 @@ paths: summary: Start the passkey confirmation that approving an irreversible action needs tags: - Approvals + /api/audit/events: + get: + operationId: list-audit-events + parameters: + - description: Only events in this category + explode: false + in: query + name: category + schema: + description: Only events in this category + type: string + - description: Only events for this action + explode: false + in: query + name: action + schema: + description: Only events for this action + type: string + - description: Only events by this actor ID + explode: false + in: query + name: actor + schema: + description: Only events by this actor ID + type: string + - description: Only events recorded at or after this time + explode: false + in: query + name: since + schema: + description: Only events recorded at or after this time + format: date-time + type: string + - description: Only events recorded before this time + explode: false + in: query + name: until + schema: + description: Only events recorded before this time + format: date-time + type: string + - description: How many events to return + explode: false + in: query + name: limit + schema: + default: 100 + description: How many events to return + format: int64 + maximum: 1000 + minimum: 1 + type: integer + - description: How many of the newest matching events to skip + explode: false + in: query + name: offset + schema: + default: 0 + description: How many of the newest matching events to skip + format: int64 + minimum: 0 + type: integer + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/AuditEventsBody" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: List append-only audit events + tags: + - Audit + /api/audit/events/export: + get: + operationId: export-audit-events + parameters: + - description: Only events in this category + explode: false + in: query + name: category + schema: + description: Only events in this category + type: string + - description: Only events for this action + explode: false + in: query + name: action + schema: + description: Only events for this action + type: string + - description: Only events by this actor ID + explode: false + in: query + name: actor + schema: + description: Only events by this actor ID + type: string + - description: Only events recorded at or after this time + explode: false + in: query + name: since + schema: + description: Only events recorded at or after this time + format: date-time + type: string + - description: Only events recorded before this time + explode: false + in: query + name: until + schema: + description: Only events recorded before this time + format: date-time + type: string + - description: Maximum number of events to export + explode: false + in: query + name: limit + schema: + default: 1000 + description: Maximum number of events to export + format: int64 + maximum: 1000 + minimum: 1 + type: integer + - description: How many of the newest matching events to skip + explode: false + in: query + name: offset + schema: + default: 0 + description: How many of the newest matching events to skip + format: int64 + minimum: 0 + type: integer + - description: "Export format: jsonl or csv" + explode: false + in: query + name: format + schema: + default: jsonl + description: "Export format: jsonl or csv" + enum: + - jsonl + - csv + type: string + responses: + "200": + content: + application/x-ndjson: + schema: + type: string + text/csv: + schema: + type: string + description: Audit events exported as JSON Lines or CSV + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Export append-only audit events as JSONL or CSV + tags: + - Audit /api/auth/login: post: operationId: sign-in @@ -5836,6 +6283,75 @@ paths: summary: Change the authentication settings tags: - Accounts + /api/bundles/apply: + post: + operationId: apply-bundle + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/BundleApplyInputBody" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ArchieBundleApplyReply" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Apply a promotion bundle atomically + tags: + - Bundles + /api/bundles/diff: + post: + operationId: diff-bundle + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/BundleDiffInputBody" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ArchieBundleDiffReply" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Diff a promotion bundle against the active stage + tags: + - Bundles + /api/bundles/export: + get: + operationId: export-bundle + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ArchieBundleExportReply" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Export a deterministic promotion bundle + tags: + - Bundles /api/capabilities: get: operationId: get-capabilities @@ -10222,6 +10738,35 @@ paths: summary: Run a workflow now with an input tags: - Workflows + /oauth2/backchannel-logout: + post: + operationId: oidc-backchannel-logout + requestBody: + content: + application/octet-stream: + schema: + contentMediaType: application/octet-stream + format: binary + type: string + required: true + responses: + "200": + description: OK + headers: + Cache-Control: + schema: + type: string + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + security: + - {} + summary: Handle OIDC back-channel logout notifications + tags: + - Accounts /oauth2/callback: get: operationId: finish-oidc-sign-in diff --git a/cmd/archie/main.go b/cmd/archie/main.go index fe8ae15f7..b831b7928 100644 --- a/cmd/archie/main.go +++ b/cmd/archie/main.go @@ -4,18 +4,27 @@ package main import ( "context" + "errors" "flag" "fmt" "os" "os/signal" + "strings" "syscall" "github.com/samcharles93/archie-core/internal/app/archie" "github.com/samcharles93/archie-core/internal/buildinfo" ) +type exitCodeError int + +func (e exitCodeError) Error() string { return fmt.Sprintf("exit %d", int(e)) } + func main() { if err := run(); err != nil { + if code, ok := errors.AsType[exitCodeError](err); ok { + os.Exit(int(code)) + } fmt.Fprintln(os.Stderr, "archie:", err) os.Exit(1) } @@ -27,7 +36,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 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") + _, _ = 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 rekey rotate age sealing identities in one transaction\n archie bundle validate, export, diff, or apply promotion bundles\n archie openapi print the API's OpenAPI document") flag.PrintDefaults() } flag.Parse() @@ -45,6 +54,17 @@ func run() error { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() return archie.Bootstrap(ctx, *configPath, *specPath) + case "rekey": + return runRekey(*configPath, flag.Args()[1:]) + case "bundle": + code, err := runBundle(*configPath, flag.Args()[1:]) + if err != nil { + return err + } + if code != 0 { + return exitCodeError(code) + } + return nil case "openapi": doc, err := archie.Document() if err != nil { @@ -60,3 +80,32 @@ func run() error { defer stop() return archie.Run(ctx, *configPath) } + +func runRekey(configPath string, args []string) error { + fs := flag.NewFlagSet("rekey", flag.ContinueOnError) + oldIdentity := fs.String("old-identity", "", "current age identity (or ARCHIE_OLD_AGE_IDENTITY[_FILE])") + newIdentity := fs.String("new-identity", "", "replacement age identity (or ARCHIE_NEW_AGE_IDENTITY[_FILE])") + newBackupsRaw := fs.String("new-backups", "", "comma-separated age backup recipients for re-sealed values") + if err := fs.Parse(args); err != nil { + return err + } + var newBackups []string + for r := range strings.SplitSeq(*newBackupsRaw, ",") { + if r = strings.TrimSpace(r); r != "" { + newBackups = append(newBackups, r) + } + } + rcfg, err := archie.LoadRekeyConfig(*oldIdentity, *newIdentity, newBackups) + if err != nil { + return err + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + return archie.Rekey(ctx, configPath, rcfg) +} + +func runBundle(configPath string, args []string) (int, error) { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + return archie.RunBundleCLI(ctx, configPath, args, os.Stdout) +} diff --git a/internal/app/archie/access_test.go b/internal/app/archie/access_test.go index de203bd3c..97e81268f 100644 --- a/internal/app/archie/access_test.go +++ b/internal/app/archie/access_test.go @@ -35,7 +35,7 @@ func (r *refuses) Allow(_ context.Context, action, kind string) error { // credential: sign-in, setup and the auth status the sign-in page reads. var publicOperations = []string{ "begin-oidc-sign-in", "begin-passkey-sign-in", "finish-oidc-sign-in", "finish-passkey-sign-in", - "get-auth-status", "recover-account", "set-up-account", "sign-in", "sign-out", + "get-auth-status", "oidc-backchannel-logout", "recover-account", "set-up-account", "sign-in", "sign-out", } var pathParam = regexp.MustCompile(`\{[^}]+\}`) diff --git a/internal/app/archie/api.go b/internal/app/archie/api.go index a5e60af8c..4db57554f 100644 --- a/internal/app/archie/api.go +++ b/internal/app/archie/api.go @@ -1,14 +1,17 @@ package archie import ( + "log/slog" "net/http" "github.com/danielgtaylor/huma/v2" + "github.com/jmoiron/sqlx" "github.com/samcharles93/archie-core/internal/buildinfo" "github.com/samcharles93/archie-core/internal/platform/httpapi" "github.com/samcharles93/archie-core/internal/platform/hub" "github.com/samcharles93/archie-core/modules/approvals" + "github.com/samcharles93/archie-core/modules/audit" "github.com/samcharles93/archie-core/modules/chat" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/dashboard" @@ -37,6 +40,9 @@ type apiModules struct { chat *chat.Module proposals *proposals.Module notes *memory.Module + auditLog *audit.Module + db *sqlx.DB + bundleLog *slog.Logger live *hub.Hub } @@ -61,6 +67,10 @@ func (m apiModules) register(api huma.API) { if m.notes != nil { m.notes.Register(api) } + if m.auditLog != nil { + m.auditLog.Register(api) + } + RegisterBundleAPI(api, m.db, m.bundleLog) dashboard.Register(api, m.live) } @@ -83,7 +93,7 @@ func emptyAPI(auth httpapi.Authenticator, authz httpapi.Authorizer) (*http.Serve tell: &deliveries.Module{}, allow: &approvals.Module{}, actionTypes: &judgement.ActionTypes{}, policies: &judgement.Policies{}, hear: &events.Module{}, judge: &judgement.Module{}, engine: &runs.Engine{}, chat: &chat.Module{}, proposals: &proposals.Module{}, - notes: &memory.Module{}, live: hub.New(), + notes: &memory.Module{}, auditLog: &audit.Module{}, bundleLog: slog.New(slog.DiscardHandler), live: hub.New(), }.register(api) return mux, api } diff --git a/internal/app/archie/config.go b/internal/app/archie/config.go index 49dc2e9f4..637a1d5c0 100644 --- a/internal/app/archie/config.go +++ b/internal/app/archie/config.go @@ -24,8 +24,11 @@ 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 { - Listen string `toml:"listen"` - Database DatabaseConfig `toml:"database"` + // Listen is the main HTTP server address. + Listen string `toml:"listen"` + // MetricsListen is an optional internal listen address for Prometheus /metrics. + MetricsListen string `toml:"metrics_listen"` + Database DatabaseConfig `toml:"database"` // AdminTokenSHA256 is the hex SHA-256 of the bootstrap admin token that // guards /api/ until identities exist. The token itself is never stored. AdminTokenSHA256 string `toml:"admin_token_sha256"` @@ -250,6 +253,7 @@ func applyEnv(cfg *Config) error { target *string }{ {envKey: "ARCHIE_LISTEN", target: &cfg.Listen}, + {envKey: "ARCHIE_METRICS_LISTEN", target: &cfg.MetricsListen}, {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}, diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index f88c4d2c5..555637db6 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -28,7 +28,9 @@ import ( "github.com/samcharles93/archie-core/internal/platform/hub" "github.com/samcharles93/archie-core/internal/platform/pg" "github.com/samcharles93/archie-core/internal/platform/seal" + "github.com/samcharles93/archie-core/internal/platform/telemetry" "github.com/samcharles93/archie-core/modules/approvals" + "github.com/samcharles93/archie-core/modules/audit" "github.com/samcharles93/archie-core/modules/chat" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/dashboard" @@ -67,7 +69,13 @@ func Migrate(ctx context.Context, configPath string) error { // happened, so a restart reads that state and starts serving operations // immediately. func Run(ctx context.Context, configPath string) error { - log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "archie", "version", buildinfo.Version) + shutdownTelemetry, err := telemetry.Setup(ctx, "archie", buildinfo.Version) + if err != nil { + return err + } + defer func() { _ = shutdownTelemetry(context.WithoutCancel(ctx)) }() + + log := slog.New(telemetry.NewLogHandler(slog.NewJSONHandler(os.Stdout, nil))).With("service", "archie", "version", buildinfo.Version) cfg, err := LoadConfig(configPath) if err != nil { @@ -88,41 +96,13 @@ func Run(ctx context.Context, configPath string) error { } defer holdServe() // Nothing is served yet, so there is no readiness to report while this retries. - stage := stageMigrate - if cfg.Database.OwnerURL == "" { - stage = stageSchemaVerify - } - 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 { + if err := prepareDatabase(ctx, log, cfg, db); err != nil { _ = db.Close() return err } - // A deletion whose record did not land is completed before anything serves: - // the database is the authority on what was deleted, the record outside it on - // what a restore can apply again. - if added, err := memory.Reconcile(ctx, db, cfg.StateDir); err != nil { - _ = db.Close() - return fmt.Errorf("complete the record of deletions: %w", err) - } else if added > 0 { - log.WarnContext(ctx, "completed the record of deletions", "entries", added) - } - // The record is applied to whatever database is here before anything serves. - // A restore that replaced the database and then failed to apply the record - // leaves the notes it recorded behind, and those are the ones nobody may see - // again. - if applied, err := memory.ReapplyDeletions(ctx, db, cfg.StateDir); err != nil { - _ = db.Close() - return fmt.Errorf("apply the record of deletions: %w", err) - } else if applied > 0 { - log.WarnContext(ctx, "applied the record of deletions", "notes", applied) - } var draining atomic.Bool - b, err := wire(log, configPath, cfg, db, &draining) //nolint:contextcheck // the API's guard derives its context from each request + metrics := telemetry.NewMetrics() + b, err := wire(log, configPath, cfg, db, &draining, metrics) //nolint:contextcheck // the API's guard derives its context from each request if err != nil { _ = db.Close() return err @@ -139,15 +119,67 @@ func Run(ctx context.Context, configPath string) error { close(started) }() + metricsErr := startMetricsServer(work, log, cfg.MetricsListen, cfg.ShutdownGrace, metrics) serveErr := serve(work, log, cfg.Listen, cfg.ShutdownGrace, &draining, b.served) stop() <-started + if err := <-metricsErr; err != nil && serveErr == nil { + serveErr = err + } // Every loop activation began has returned before the caller closes the // connectors and the database. b.ops.Wait() return serveErr } +func prepareDatabase(ctx context.Context, log *slog.Logger, cfg Config, db *sqlx.DB) error { + stage := stageMigrate + if cfg.Database.OwnerURL == "" { + stage = stageSchemaVerify + } + 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 { + return err + } + // A deletion whose record did not land is completed before anything serves: + // the database is the authority on what was deleted, the record outside it on + // what a restore can apply again. + if added, err := memory.Reconcile(ctx, db, cfg.StateDir); err != nil { + return fmt.Errorf("complete the record of deletions: %w", err) + } else if added > 0 { + log.WarnContext(ctx, "completed the record of deletions", "entries", added) + } + // The record is applied to whatever database is here before anything serves. + // A restore that replaced the database and then failed to apply the record + // leaves the notes it recorded behind, and those are the ones nobody may see + // again. + if applied, err := memory.ReapplyDeletions(ctx, db, cfg.StateDir); err != nil { + return fmt.Errorf("apply the record of deletions: %w", err) + } else if applied > 0 { + log.WarnContext(ctx, "applied the record of deletions", "notes", applied) + } + return nil +} + +func startMetricsServer(ctx context.Context, log *slog.Logger, addr string, grace time.Duration, metrics *telemetry.Metrics) <-chan error { + ch := make(chan error, 1) + if addr == "" || metrics == nil { + ch <- nil + return ch + } + mux := http.NewServeMux() + mux.Handle("GET /metrics", metrics.MetricsHandler()) + go func() { + ch <- serve(ctx, log.With("component", "metrics"), addr, grace, nil, mux) + }() + return ch +} + // binary is a wired instance: the surface it serves, and what waits for owner // setup before it does any work. type binary struct { @@ -163,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) (*binary, error) { +func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB, draining *atomic.Bool, metrics *telemetry.Metrics) (*binary, error) { checks := newHealthChecks(db, draining) runtime.RegisterBuiltinClasses() @@ -223,6 +255,8 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB, draining if err != nil { return nil, err } + settings.UseSealer(sealer) + auditLog := audit.NewModule(db, log.With("module", "audit"), orgID) hear := events.NewModule(db, log.With("module", "events"), orgID, sealer, conns, engine, allow, settings, tell) hear.Routes(mux) engine.UseReferrers(hear) @@ -240,13 +274,17 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB, draining apiModules{ settings: settings, conns: conns, system: sys, tell: tell, allow: allow, actionTypes: actionTypes, policies: policies, hear: hear, judge: judge, engine: engine, chat: talk, proposals: proposed, - notes: remember, live: live, + notes: remember, auditLog: auditLog, db: db, bundleLog: log.With("module", "bundles"), live: live, }.register(api) dashboard.Routes(mux, ui.DistDirFS) g := newGate(mux, ui.DistDirFS) + served := http.Handler(serveSurface(checks, g)) + if metrics != nil { + served = metrics.Middleware(served) + } return &binary{ - db: db, conns: conns, gate: g, served: serveSurface(checks, g), settings: settings, + db: db, conns: conns, gate: g, served: served, settings: settings, 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, @@ -374,7 +412,7 @@ func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, actio const orgID = "default" // schemas are the module schemas the runtime role is granted DML on. -var schemas = []string{"runs", "connectors", "events", "governance", "deliveries", "judgement", "approvals", "memory", "alerts", "proposals", "chat"} +var schemas = []string{"runs", "connectors", "events", "governance", "deliveries", "judgement", "approvals", "memory", "alerts", "proposals", "chat", "audit"} // owner names this process in run leases. func owner() string {