From 3d611f18abce0793a34458df37f908366011d787 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Tue, 8 Sep 2026 22:54:26 +1000 Subject: [PATCH] feat(archieui): standalone UI process over remote Gateway and State Store Add cmd/archie-ui and internal/app/archieui: a second composition root that serves the dashboard and the compiled SPA against the two contracts the daemon already dials, so the UI stops needing the daemon's in-process objects. The composition root lives outside internal/app/archied deliberately. That package pulls 88 internal packages (daemon, forge, containers, NATS, secrets, workflow); reusing its boot the way RunGateway and RunStateStore do would make the PRD's deletion gate unreachable. archieui links 41, and cmd/archie-ui 42. Configuration ownership follows docs/prds/ui-service-boundary.md: the process reads the shared file, but only [services.gateway].{target,target_token}, [services.state].{target,target_token} and [web].{listen, trust_forwarded_headers}, with flags taking precedence. Options has no field for anything else in that file to land in, and no config.Holder. compose() sets only the contract-backed and process-local fields. Every daemon runtime handle stays nil on purpose and its route degrades through the existing 501/503/empty paths. Captures, CaptureLimiter and BindingDispatcher are withheld for the duration of the seam: the daemon's dashboard still serves POST /webhooks/capture/{source}, and two intakes are not permitted. Readiness is the UI's own registry over its two dependencies via a new bounded readiness.ContractProbe. The existing GatewayProbe was unusable here: with no channel manager to inject it reports "no gateway channels configured", i.e. permanently degraded. The State Store's fail-closed non-loopback rule and the two dial paths move to staterpc.Dial/TargetIsLoopback and gatewayrpc.Dial, so the server side and every client share one implementation instead of three copies. The Gateway remains loopback-only with no auth interceptor, so this process is scoped to being colocated with it; filed as archie-core-juqx. Refs: archie-core-8cda.5.2 --- Taskfile.yml | 2 + cmd/archie-ui/main.go | 62 ++++ internal/app/archied/chat_service.go | 16 +- internal/app/archied/state_store.go | 22 +- internal/app/archied/state_store_client.go | 46 +-- internal/app/archied/state_store_test.go | 35 -- internal/app/archieui/compose.go | 59 +++ internal/app/archieui/compose_test.go | 126 +++++++ internal/app/archieui/config.go | 152 ++++++++ internal/app/archieui/config_test.go | 132 +++++++ internal/app/archieui/options.go | 79 ++++ internal/app/archieui/readiness.go | 31 ++ internal/app/archieui/run.go | 88 +++++ internal/app/archieui/run_test.go | 346 ++++++++++++++++++ internal/infrastructure/gatewayrpc/dial.go | 30 ++ internal/infrastructure/readiness/probes.go | 38 ++ internal/infrastructure/staterpc/dial.go | 66 ++++ internal/infrastructure/staterpc/dial_test.go | 67 ++++ 18 files changed, 1296 insertions(+), 101 deletions(-) create mode 100644 cmd/archie-ui/main.go create mode 100644 internal/app/archieui/compose.go create mode 100644 internal/app/archieui/compose_test.go create mode 100644 internal/app/archieui/config.go create mode 100644 internal/app/archieui/config_test.go create mode 100644 internal/app/archieui/options.go create mode 100644 internal/app/archieui/readiness.go create mode 100644 internal/app/archieui/run.go create mode 100644 internal/app/archieui/run_test.go create mode 100644 internal/infrastructure/gatewayrpc/dial.go create mode 100644 internal/infrastructure/staterpc/dial.go create mode 100644 internal/infrastructure/staterpc/dial_test.go diff --git a/Taskfile.yml b/Taskfile.yml index 192fc3b12..bd7768501 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -172,11 +172,13 @@ tasks: - "{{.BIN_DIR}}/archied" - "{{.BIN_DIR}}/archie-gateway" - "{{.BIN_DIR}}/archie-state-store" + - "{{.BIN_DIR}}/archie-ui" - "{{.BIN_DIR}}/archie-agent" cmds: - go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/archied.gatewayVersion={{.GATEWAY_VERSION}} -X github.com/samcharles93/archie-core/internal/app/archied.runtimeVersion={{.RUNTIME_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archied ./cmd/archied - go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/archied.gatewayVersion={{.GATEWAY_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archie-gateway ./cmd/archie-gateway - go build -o {{.BIN_DIR}}/archie-state-store ./cmd/archie-state-store + - go build -o {{.BIN_DIR}}/archie-ui ./cmd/archie-ui - go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/agentworker.version={{.RUNTIME_VERSION}} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o {{.BIN_DIR}}/archie-agent ./cmd/archie-agent test: diff --git a/cmd/archie-ui/main.go b/cmd/archie-ui/main.go new file mode 100644 index 000000000..1f54b8177 --- /dev/null +++ b/cmd/archie-ui/main.go @@ -0,0 +1,62 @@ +// Command archie-ui serves the operator dashboard and the compiled SPA as its +// own process, against a Gateway and a State Store reached over their gRPC +// contracts. It is the .5.2 companion to archie-gateway and +// archie-state-store: a thin main that parses process inputs and hands them +// to archieui.Run. +// +// See docs/prds/ui-service-boundary.md for the ratified boundary. +package main + +import ( + "context" + "flag" + "fmt" + "os" + "os/signal" + "path/filepath" + "strconv" + "syscall" + + "github.com/samcharles93/archie-core/internal/app/archieui" +) + +func main() { os.Exit(run()) } + +func run() int { + base, err := os.UserConfigDir() + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + var options archieui.Options + flag.StringVar(&options.Config, "config", filepath.Join(base, "archie", "config.toml"), "configuration file or directory (only [services.*] targets and [web] are read)") + flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory") + flag.StringVar(&options.Listen, "listen", "", "dashboard HTTP listen address (defaults to [web].listen, else 127.0.0.1:8484)") + flag.StringVar(&options.Token, "token", "", "dashboard token; required for a non-loopback listener") + flag.StringVar(&options.TokenFile, "token-file", "", "file holding the dashboard token, minted on first use") + flag.StringVar(&options.Gateway.Target, "gateway-target", "", "archie-gateway gRPC address (defaults to [services.gateway].target)") + flag.StringVar(&options.Gateway.Token, "gateway-token", "", "bearer token presented to archie-gateway") + flag.StringVar(&options.State.Target, "state-target", "", "archie-state-store gRPC address (defaults to [services.state].target)") + flag.StringVar(&options.State.Token, "state-token", "", "bearer token presented to archie-state-store") + flag.DurationVar(&options.DependencyTimeout, "dependency-timeout", 0, "per-dependency readiness probe timeout (default 5s)") + // BoolFunc rather than BoolVar so an unset flag stays distinguishable + // from an explicit -trust-forwarded-headers=false, which must be able to + // override a configuration file that enables it. + flag.BoolFunc("trust-forwarded-headers", "trust X-Forwarded-Proto/Host when validating Origin (only behind a trusted proxy)", func(v string) error { + parsed, err := strconv.ParseBool(v) + if err != nil { + return err + } + options.TrustForwardedHeaders = &parsed + return nil + }) + flag.Parse() + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := archieui.Run(ctx, options); err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + return 0 +} diff --git a/internal/app/archied/chat_service.go b/internal/app/archied/chat_service.go index 20ca3af5a..7e949b216 100644 --- a/internal/app/archied/chat_service.go +++ b/internal/app/archied/chat_service.go @@ -5,7 +5,6 @@ import ( "strings" "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/gateway" @@ -13,18 +12,17 @@ import ( ) // composeChatContract dials the standalone archie-gateway, the sole owner of -// ChatContract. +// ChatContract, from the daemon's own configuration key. func composeChatContract(settings config.ServiceConnection, options ...grpc.DialOption) (gateway.ChatContract, func(), error) { if strings.TrimSpace(settings.Target) == "" { return nil, nil, fmt.Errorf("services.gateway.target is required") } - // Deployments that put the Gateway on a separate trust boundary supply - // their own transport credentials through options; the default must be - // usable without manufacturing a certificate in the config loader. - opts := append([]grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}, options...) - conn, err := grpc.NewClient(settings.Target, opts...) + // Assigned through a typed variable rather than returned directly: a + // direct forward would hand a failed dial's nil *Client back as a + // non-nil ChatContract interface. + client, cleanup, err := gatewayrpc.Dial(settings.Target, options...) if err != nil { - return nil, nil, fmt.Errorf("create gateway client: %w", err) + return nil, nil, err } - return gatewayrpc.NewClient(conn), func() { _ = conn.Close() }, nil + return client, cleanup, nil } diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index 1928230da..ac3a62957 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -16,7 +16,6 @@ import ( "fmt" "net" "net/http" - "strings" "time" "google.golang.org/grpc" @@ -213,7 +212,7 @@ func (b *boot) startStateStoreReadiness(ctx context.Context, readyAddr string) e // path to token auth -- the same confinement philosophy as the gateway's // loopback-only --listen rule. func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants) (opts []grpc.ServerOption, loopback bool, err error) { - loopback, err = stateStoreListenIsLoopback(listen) + loopback, err = staterpc.TargetIsLoopback(listen) if err != nil { return nil, false, err } @@ -236,25 +235,6 @@ func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants) (op }, false, nil } -// stateStoreListenIsLoopback reports whether listen's host is a loopback -// address. Both literal loopback IPs (127.0.0.1, ::1) and the "localhost" -// hostname count; everything else (including the wildcard 0.0.0.0 and DNS -// names) is treated as network-reachable and therefore non-loopback. -func stateStoreListenIsLoopback(listen string) (bool, error) { - host, _, err := net.SplitHostPort(listen) - if err != nil { - return false, fmt.Errorf("state store listen address must be host:port: %w", err) - } - if strings.EqualFold(host, "localhost") { - return true, nil - } - ip := net.ParseIP(host) - if ip == nil { - return false, nil - } - return ip.IsLoopback(), nil -} - // constantTimeTokenValidator returns a staterpc.TokenValidator that accepts // exactly the configured token, compared in constant time so a timing side // channel cannot leak how many bytes matched (the standalone server's diff --git a/internal/app/archied/state_store_client.go b/internal/app/archied/state_store_client.go index 579eb1514..3e5c31694 100644 --- a/internal/app/archied/state_store_client.go +++ b/internal/app/archied/state_store_client.go @@ -4,28 +4,16 @@ import ( "fmt" "strings" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" - "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/secret" ) -// composeStateStoreClient dials the State Store gRPC service the daemon's own -// capture/mapping/binding consumers will call when [services.state].target is -// set. It mirrors the gateway's composeChatContract (internal/app/archied/ -// chat_service.go), but the fail-closed rule for non-loopback targets (§9) is -// the State Store's own and requires a bearer token. The token comes from -// [services.state].target_token, falling back to the STATE_STORE_TOKEN -// secret/env. The returned cleanup closes the connection; Close() on the -// adapter itself is a no-op, because the store service owns its own DB -// lifecycle (§11). // stateStoreResolvedToken returns the bearer token a State Store client -// presents, matching composeStateStoreClient's resolution order: the explicit -// [services.state].target_token key, then the STATE_STORE_TOKEN secret/env. The -// daemon injects the same token into agent containers as STATE_STORE_TOKEN so -// the agent authenticates to the same remote store the daemon dials. +// presents: the explicit [services.state].target_token key, then the +// STATE_STORE_TOKEN secret/env. The daemon injects the same token into agent +// containers as STATE_STORE_TOKEN so the agent authenticates to the same +// remote store the daemon dials. func stateStoreResolvedToken(settings config.ServiceConnection, secrets *secret.Registry) string { token := settings.TargetToken if token == "" { @@ -34,29 +22,15 @@ func stateStoreResolvedToken(settings config.ServiceConnection, secrets *secret. return token } +// composeStateStoreClient dials the State Store gRPC service the daemon's own +// capture/mapping/binding consumers call. Token resolution is the daemon's +// (it owns the config keys and the secret registry); the dial itself and the +// fail-closed non-loopback rule (§9) belong to the transport, so they come +// from staterpc.Dial. func composeStateStoreClient(settings config.ServiceConnection, secrets *secret.Registry) (*staterpc.Client, func(), error) { target := strings.TrimSpace(settings.Target) if target == "" { return nil, nil, fmt.Errorf("services.state.target is required") } - token := stateStoreResolvedToken(settings, secrets) - loopback, err := stateStoreListenIsLoopback(target) - if err != nil { - return nil, nil, fmt.Errorf("services.state.target must be host:port: %w", err) - } - if !loopback && token == "" { - return nil, nil, fmt.Errorf( - "services.state.target %q is non-loopback; non-loopback exposure requires a bearer token ([services.state].target_token / STATE_STORE_TOKEN) or TLS, mirroring the gateway's --listen confinement (docs/prds/state-store-contract.md §9)", - target, - ) - } - opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())} - if token != "" { - opts = append(opts, grpc.WithUnaryInterceptor(staterpc.UnaryClientTokenInterceptor(token))) - } - conn, err := grpc.NewClient(target, opts...) - if err != nil { - return nil, nil, fmt.Errorf("create state store client: %w", err) - } - return staterpc.NewClient(conn), func() { _ = conn.Close() }, nil + return staterpc.Dial(target, stateStoreResolvedToken(settings, secrets)) } diff --git a/internal/app/archied/state_store_test.go b/internal/app/archied/state_store_test.go index ce03dff49..b743fa333 100644 --- a/internal/app/archied/state_store_test.go +++ b/internal/app/archied/state_store_test.go @@ -15,41 +15,6 @@ import ( "github.com/samcharles93/archie-core/internal/store" ) -func TestStateStoreListenIsLoopback(t *testing.T) { - tests := []struct { - name string - listen string - want bool - }{ - {"loopback ipv4", "127.0.0.1:9090", true}, - {"loopback ipv6", "[::1]:9090", true}, - {"localhost hostname", "localhost:9090", true}, - {"localhost uppercase", "LOCALHOST:9090", true}, - {"wildcard", "0.0.0.0:9090", false}, - {"private ip", "192.168.1.10:9090", false}, - {"dns name", "store.example.com:9090", false}, - {"empty host", ":9090", false}, - {"malformed", "127.0.0.1", false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := stateStoreListenIsLoopback(tt.listen) - if tt.name == "malformed" { - if err == nil { - t.Fatalf("stateStoreListenIsLoopback(%q) = (%v, nil), want error", tt.listen, got) - } - return - } - if err != nil { - t.Fatalf("stateStoreListenIsLoopback(%q): %v", tt.listen, err) - } - if got != tt.want { - t.Fatalf("stateStoreListenIsLoopback(%q) = %v, want %v", tt.listen, got, tt.want) - } - }) - } -} - func TestStateStoreServerOptsLoopbackIsInsecure(t *testing.T) { opts, loopback, err := stateStoreServerOpts("127.0.0.1:9090", "", &staterpc.TaskGrants{}) if err != nil { diff --git a/internal/app/archieui/compose.go b/internal/app/archieui/compose.go new file mode 100644 index 000000000..b2f864038 --- /dev/null +++ b/internal/app/archieui/compose.go @@ -0,0 +1,59 @@ +package archieui + +import ( + "log/slog" + + "github.com/samcharles93/archie-core/internal/domain/health" + "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/store" + "github.com/samcharles93/archie-core/internal/webui" +) + +// deps are the resolved inputs the dashboard is built from: two remote +// contracts, the process's own logger and options, and the readiness registry +// assembled over those same contracts. +type deps struct { + Options Options + Log *slog.Logger + Store store.TaskStore + Chat gateway.ChatContract + Health *health.Registry +} + +// compose builds the dashboard server for the UI process. It sets exactly the +// fields a contract already carries plus this process's own settings, and +// leaves every remaining field at its zero value on purpose: each one is a +// daemon-local runtime handle with no contract behind it, and the handlers +// already degrade to a documented 501/503/empty response rather than panicking +// (docs/prds/ui-service-boundary.md:130-131). +// +// What is deliberately absent, and which bead fills it: +// +// - Cfg, LastReload, UpdateConfig, ConfigOverrides, ResetConfig, +// UpdateRepoField: the configuration owner stays the daemon, reached +// through a narrow admin contract. The shared holder is removed from the +// daemon's own wiring by archie-core-8cda.5.4. +// - LogFeed, TaskLogs, Events, Channels, ReloadChannel, Curators, Memory, +// Issues, TaskStopper, Workflows, WorkRequests, RunningVersions, +// Chat.Updates, UpdateReportPath: no contract exists for these yet. +// Defining one amends the owning service's contract first +// (docs/prds/ui-service-boundary.md:205-207); the route migration is +// archie-core-8cda.5.3. +// - Captures, CaptureLimiter, BindingDispatcher: withheld for the duration +// of the seam. The daemon's in-process dashboard still serves +// POST /webhooks/capture/{source}; wiring it here too would give two +// listeners the same intake authority, which the PRD forbids +// (lines 30-33). Turned on at cutover, once the daemon's listener is gone. +func compose(d deps) *webui.Server { + srv := &webui.Server{ + Store: d.Store, + Log: d.Log, + Token: d.Options.Token, + TrustForwardedHeaders: d.Options.trustForwardedHeaders(), + Health: d.Health, + } + if d.Chat != nil { + srv.Chat = &webui.ChatService{Contract: d.Chat} + } + return srv +} diff --git a/internal/app/archieui/compose_test.go b/internal/app/archieui/compose_test.go new file mode 100644 index 000000000..bbc1797b8 --- /dev/null +++ b/internal/app/archieui/compose_test.go @@ -0,0 +1,126 @@ +package archieui + +import ( + "log/slog" + "reflect" + "testing" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" + "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" + "github.com/samcharles93/archie-core/internal/store" +) + +// isNil reports whether v is nil, including a typed nil func or pointer +// carried inside a non-nil interface -- a plain `v != nil` reports those as +// present. +func isNil(v any) bool { + rv := reflect.ValueOf(v) + if !rv.IsValid() { + return true + } + switch rv.Kind() { + case reflect.Func, reflect.Pointer, reflect.Interface, reflect.Map, reflect.Slice, reflect.Chan: + return rv.IsNil() + default: + return false + } +} + +// TestComposeUIServerHoldsNoDaemonState is the acceptance criterion the parent +// bead names first: the UI process's dashboard "no longer receives the +// daemon's live config.Holder". It pins the whole composition: the two +// contract-backed fields hold remote clients, and every daemon-local runtime +// handle stays nil so the process cannot hold in-process daemon state by +// accident (docs/prds/ui-service-boundary.md, "Boundary and ownership"). +func TestComposeUIServerHoldsNoDaemonState(t *testing.T) { + stateConn, err := grpc.NewClient("passthrough:///127.0.0.1:1", grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("state client: %v", err) + } + defer stateConn.Close() + gatewayConn, err := grpc.NewClient("passthrough:///127.0.0.1:1", grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatalf("gateway client: %v", err) + } + defer gatewayConn.Close() + + srv := compose(deps{ + Options: Options{Listen: "127.0.0.1:8484", Token: "tok"}, + Log: slog.New(slog.DiscardHandler), + Store: staterpc.NewClient(stateConn), + Chat: gatewayrpc.NewClient(gatewayConn), + }) + + if srv.Cfg != nil { + t.Fatal("UI server holds a config.Holder; the UI process must not share the daemon's live configuration (docs/prds/ui-service-boundary.md:95-96)") + } + if _, ok := srv.Store.(*staterpc.Client); !ok { + t.Fatalf("Store = %T, want *staterpc.Client", srv.Store) + } + if _, ok := srv.Store.(*store.Store); ok { + t.Fatal("Store is the concrete *store.Store; the UI process must not open archie.db") + } + if srv.Chat == nil { + t.Fatal("Chat is nil; the UI process must dial the Gateway contract") + } + if _, ok := srv.Chat.Contract.(*gatewayrpc.Client); !ok { + t.Fatalf("Chat.Contract = %T, want *gatewayrpc.Client", srv.Chat.Contract) + } + if srv.Chat.Updates != nil { + t.Error("Chat.Updates is wired; host-local install/restart stays with the daemon") + } + if srv.Token != "tok" { + t.Fatalf("Token = %q, want the UI process's own token", srv.Token) + } + + unwired := map[string]any{ + "UpdateConfig": srv.UpdateConfig, + "ResetConfig": srv.ResetConfig, + "ConfigOverrides": srv.ConfigOverrides, + "UpdateRepoField": srv.UpdateRepoField, + "LastReload": srv.LastReload, + "ReloadChannel": srv.ReloadChannel, + "RunningVersions": srv.RunningVersions, + "TaskStopper": srv.TaskStopper, + "Issues": srv.Issues, + "Events": srv.Events, + "Curators": srv.Curators, + "Memory": srv.Memory, + "Channels": srv.Channels, + "LogFeed": srv.LogFeed, + "TaskLogs": srv.TaskLogs, + "WorkRequests": srv.WorkRequests, + "Mappings": srv.Mappings, + "Bindings": srv.Bindings, + "Captures": srv.Captures, + "BindingDispatcher": srv.BindingDispatcher, + "CaptureLimiter": srv.CaptureLimiter, + } + for name, handle := range unwired { + if !isNil(handle) { + t.Errorf("%s is wired; it is a daemon-owned callback or runtime handle with no contract behind it yet", name) + } + } + if srv.Workflows != nil { + t.Error("Workflows is wired; the definition catalog is a filesystem scan on the daemon host") + } + if srv.UpdateReportPath != "" { + t.Error("UpdateReportPath is set; host-local update relay stays with the daemon") + } +} + +// TestComposeLeavesCaptureIntakeUnset pins the seam rule: while the daemon's +// in-process dashboard is still running (its removal is bead +// archie-core-8cda.5.4), a second process wiring Captures/BindingDispatcher +// would give two listeners the same webhook intake authority, which +// docs/prds/ui-service-boundary.md:30-33 forbids. The route answers 503 +// instead. +func TestComposeLeavesCaptureIntakeUnset(t *testing.T) { + srv := compose(deps{Options: Options{}, Log: slog.New(slog.DiscardHandler)}) + if srv.Captures != nil || srv.BindingDispatcher != nil || srv.CaptureLimiter != nil { + t.Fatal("capture intake is wired in the UI process; it must stay unset until the daemon's dashboard is removed (bead archie-core-8cda.5.4)") + } +} diff --git a/internal/app/archieui/config.go b/internal/app/archieui/config.go new file mode 100644 index 000000000..c248fd1b7 --- /dev/null +++ b/internal/app/archieui/config.go @@ -0,0 +1,152 @@ +package archieui + +import ( + "errors" + "fmt" + "io/fs" + "log/slog" + "os" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" + "github.com/samcharles93/archie-core/internal/webui" +) + +// Resolve produces the effective Options: flag values win, and a field the +// operator left empty falls back to the configuration file's projection, then +// to a process default. It ends with validate, so a caller that gets no error +// holds a startable configuration. +// +// The projection is an allowlist of exactly six values -- +// [services.gateway].{target,target_token}, [services.state].{target, +// target_token} and [web].{listen,trust_forwarded_headers}. The UI reads the +// same file the daemon does because operators already keep the service +// endpoints there, but Options has no field for anything else in it: the +// daemon's forge credentials, model catalog, workflow routing, NATS settings, +// filesystem jail and agent/container settings have nowhere to land +// (docs/prds/ui-service-boundary.md:87-89). +func Resolve(o Options, log *slog.Logger) (Options, error) { + if o.Config != "" { + cfg, found, err := readProjection(o.Config, o.Overlay, log) + if err != nil { + return Options{}, err + } + if found { + o = merge(o, cfg) + } + } + o = withDefaults(o) + token, err := resolveToken(o) + if err != nil { + return Options{}, err + } + o.Token = token + if err := o.validate(); err != nil { + return Options{}, err + } + return o, nil +} + +// readProjection loads the configuration source and returns the six values +// the UI process is allowed to see. An absent source is not an error (the +// process is fully drivable by flags); an unreadable or invalid one is. +func readProjection(path, overlay string, log *slog.Logger) (projection, bool, error) { + if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) { + return projection{}, false, nil + } + doc, err := configuration.New(log).Resolve(path, overlay) + if err != nil { + return projection{}, false, fmt.Errorf("read ui configuration: %w", err) + } + return project(doc.Config), true, nil +} + +// projection is the file's contribution, narrowed at the point of decode so +// no other configuration value is carried past this function. +type projection struct { + listen string + trustForwardedHeaders bool + gateway ServiceTarget + state ServiceTarget +} + +func project(cfg config.Config) projection { + return projection{ + listen: cfg.Web.Listen, + trustForwardedHeaders: cfg.Web.TrustForwardedHeaders, + gateway: ServiceTarget{Target: cfg.Services.Gateway.Target, Token: cfg.Services.Gateway.TargetToken}, + state: ServiceTarget{Target: cfg.Services.State.Target, Token: cfg.Services.State.TargetToken}, + } +} + +// merge fills only the fields the flags left empty. +func merge(o Options, p projection) Options { + if o.Listen == "" { + o.Listen = p.listen + } + if o.TrustForwardedHeaders == nil { + trust := p.trustForwardedHeaders + o.TrustForwardedHeaders = &trust + } + if o.Gateway.Target == "" { + o.Gateway.Target = p.gateway.Target + } + if o.Gateway.Token == "" { + o.Gateway.Token = p.gateway.Token + } + if o.State.Target == "" { + o.State.Target = p.state.Target + } + if o.State.Token == "" { + o.State.Token = p.state.Token + } + return o +} + +func withDefaults(o Options) Options { + if o.Listen == "" || o.Listen == "off" { + o.Listen = defaultListen + } + if o.DependencyTimeout <= 0 { + o.DependencyTimeout = defaultDependencyTimeout + } + if o.ReadHeaderTimeout <= 0 { + o.ReadHeaderTimeout = defaultReadHeaderTimeout + } + if o.ShutdownTimeout <= 0 { + o.ShutdownTimeout = defaultShutdownTimeout + } + return o +} + +// resolveToken returns the dashboard token, minting and persisting one when +// the operator named a token file and gave no token directly. Naming the file +// is how a non-loopback listener opts in to a generated token instead of +// being refused. +func resolveToken(o Options) (string, error) { + if o.Token != "" || o.TokenFile == "" { + return o.Token, nil + } + return webui.LoadOrCreateToken(o.TokenFile) +} + +// validate holds the PRD's security posture (lines 116-118): a loopback +// listener may omit the dashboard token, a non-loopback listener requires one +// and fails closed without it. Unlike the daemon, which mints a token +// silently, this process refuses to start -- an operator who exposed the +// dashboard by accident learns about it here rather than from the log. +func (o Options) validate() error { + if o.Gateway.Target == "" { + return fmt.Errorf("gateway target is required (-gateway-target or [services.gateway].target)") + } + if o.State.Target == "" { + return fmt.Errorf("state store target is required (-state-target or [services.state].target)") + } + if !webui.IsLoopback(o.Listen) && o.Token == "" { + return fmt.Errorf( + "ui listen address %q is non-loopback; a reachable dashboard requires a token (-token) or a token file to mint one (-token-file) (docs/prds/ui-service-boundary.md, listen and authentication)", + o.Listen, + ) + } + return nil +} diff --git a/internal/app/archieui/config_test.go b/internal/app/archieui/config_test.go new file mode 100644 index 000000000..1382dece8 --- /dev/null +++ b/internal/app/archieui/config_test.go @@ -0,0 +1,132 @@ +package archieui + +import ( + "log/slog" + "os" + "path/filepath" + "testing" +) + +// uiConfigFile writes a config.toml carrying both the six fields the UI +// process is allowed to read and a spread of daemon-only settings it must +// ignore. +func uiConfigFile(t *testing.T) string { + t.Helper() + path := filepath.Join(t.TempDir(), "config.toml") + contents := `bot_user = "widget" +work_dir = "/var/lib/archie/work" +skills_dir = "/var/lib/archie/skills" + +[forge] +type = "none" +host = "https://forge.example.com" + +[web] +listen = "127.0.0.1:9999" +trust_forwarded_headers = true + +[log] +file = "/var/log/archie.log" + +[services.gateway] +target = "127.0.0.1:8585" +target_token = "gateway-token" + +[services.state] +target = "127.0.0.1:9090" +target_token = "state-token" +` + if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { + t.Fatal(err) + } + return path +} + +// TestResolveReadsOnlyTheAllowlistedConfigProjection pins the maintainer's +// decision for this bead: the UI process does read config.toml, but only +// Services.Gateway.{Target,TargetToken}, Services.State.{Target,TargetToken} +// and Web.{Listen,TrustForwardedHeaders}. Options has no field that could +// carry anything else, so this asserts the six values arrive and the daemon's +// own settings have nowhere to land. +func TestResolveReadsOnlyTheAllowlistedConfigProjection(t *testing.T) { + resolved, err := Resolve(Options{Config: uiConfigFile(t)}, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("Resolve: %v", err) + } + if resolved.Listen != "127.0.0.1:9999" { + t.Errorf("Listen = %q, want the file's web.listen", resolved.Listen) + } + if !resolved.trustForwardedHeaders() { + t.Error("TrustForwardedHeaders = false, want the file's web.trust_forwarded_headers") + } + if resolved.Gateway != (ServiceTarget{Target: "127.0.0.1:8585", Token: "gateway-token"}) { + t.Errorf("Gateway = %+v, want the file's [services.gateway]", resolved.Gateway) + } + if resolved.State != (ServiceTarget{Target: "127.0.0.1:9090", Token: "state-token"}) { + t.Errorf("State = %+v, want the file's [services.state]", resolved.State) + } +} + +// TestResolveFlagsWinOverConfigFile is the other half of that decision: +// "Flags take precedence over file values." +func TestResolveFlagsWinOverConfigFile(t *testing.T) { + trust := false + resolved, err := Resolve(Options{ + Config: uiConfigFile(t), + Listen: "127.0.0.1:7777", + TrustForwardedHeaders: &trust, + Gateway: ServiceTarget{Target: "127.0.0.1:1111", Token: "flag-gateway"}, + State: ServiceTarget{Target: "127.0.0.1:2222", Token: "flag-state"}, + }, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("Resolve: %v", err) + } + if resolved.Listen != "127.0.0.1:7777" { + t.Errorf("Listen = %q, want the flag value", resolved.Listen) + } + if resolved.trustForwardedHeaders() { + t.Error("TrustForwardedHeaders = true, want the explicit -trust-forwarded-headers=false to override the file") + } + if resolved.Gateway.Target != "127.0.0.1:1111" || resolved.Gateway.Token != "flag-gateway" { + t.Errorf("Gateway = %+v, want the flag values", resolved.Gateway) + } + if resolved.State.Target != "127.0.0.1:2222" || resolved.State.Token != "flag-state" { + t.Errorf("State = %+v, want the flag values", resolved.State) + } +} + +// TestResolveRunsWithoutAConfigFile keeps the process usable in a deployment +// that passes every endpoint as a flag: an absent config path is not an +// error, an unreadable one is. +func TestResolveRunsWithoutAConfigFile(t *testing.T) { + resolved, err := Resolve(Options{ + Config: filepath.Join(t.TempDir(), "absent.toml"), + Gateway: ServiceTarget{Target: "127.0.0.1:8585"}, + State: ServiceTarget{Target: "127.0.0.1:9090"}, + }, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("Resolve with an absent config file: %v", err) + } + if resolved.Listen != defaultListen { + t.Errorf("Listen = %q, want the default %q", resolved.Listen, defaultListen) + } +} + +// TestResolveRequiresBothServiceTargets keeps the UI a client of two real +// services: neither contract has an in-process fallback in this process. +func TestResolveRequiresBothServiceTargets(t *testing.T) { + tests := []struct { + name string + options Options + }{ + {name: "no gateway target", options: Options{State: ServiceTarget{Target: "127.0.0.1:9090"}}}, + {name: "no state target", options: Options{Gateway: ServiceTarget{Target: "127.0.0.1:8585"}}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if _, err := Resolve(tt.options, slog.New(slog.DiscardHandler)); err == nil { + t.Fatal("Resolve succeeded without both service targets") + } + }) + } +} diff --git a/internal/app/archieui/options.go b/internal/app/archieui/options.go new file mode 100644 index 000000000..3b0dbc1ae --- /dev/null +++ b/internal/app/archieui/options.go @@ -0,0 +1,79 @@ +// Package archieui composes the standalone UI Service: the operator-facing +// HTTP surface and the compiled SPA, served against a Gateway and a State +// Store running in other processes. +// +// docs/prds/ui-service-boundary.md is the authority. The two rules that shape +// this package are that the UI owns only process-local settings ("HTTP listen +// address and read/header/shutdown timeouts; UI asset source or build mode; +// UI authentication mode and token reference; Gateway endpoint and credential +// reference; State Store endpoint and credential reference; readiness +// endpoint and dependency timeout policy"), and that it "must never implement +// [configuration] policy by holding or mutating a shared config.Holder". +// +// It deliberately lives outside internal/app/archied: that package's +// dependency graph carries the daemon, forge, container and workflow runtimes +// that the PRD's deletion gate forbids the UI process from linking. +package archieui + +import "time" + +// Process defaults. Listen matches the dashboard's historical bind +// (internal/infrastructure/configuration/defaults.go) so an operator moving +// the dashboard into its own process keeps the same URL. +const ( + defaultListen = "127.0.0.1:8484" + defaultDependencyTimeout = 5 * time.Second + defaultReadHeaderTimeout = 5 * time.Second + defaultShutdownTimeout = 5 * time.Second +) + +// ServiceTarget is one remote contract's endpoint and the service-to-service +// bearer token this process presents to it. It is an endpoint reference, not +// a resolved daemon credential: the UI authenticates each client itself. +type ServiceTarget struct { + Target string + Token string +} + +// Options is the UI-owned input DTO. It carries process-local settings and +// endpoint references only -- there is deliberately no config.Config, +// config.Holder, forge credential, model catalog or workflow routing field +// for daemon configuration to arrive through. +type Options struct { + // Config and Overlay name the configuration source the process reads a + // narrow projection of. Both are optional: a deployment may pass every + // setting as a flag. + Config string + Overlay string + + // Listen is the dashboard HTTP bind address. + Listen string + // Token gates browser access. Empty is permitted only for a loopback + // listener; see Options.validate. + Token string + // TokenFile is where the dashboard token is persisted, minted on first + // use. It is the explicit opt-in to a non-loopback listener: without it + // a reachable bind must be given a token. + TokenFile string + // TrustForwardedHeaders is tri-state so an explicit false on the command + // line can override a configuration file that enables it. Nil means the + // operator did not say, and the file (else false) decides. + TrustForwardedHeaders *bool + + // Gateway and State are the two remote contracts the dashboard consumes. + Gateway ServiceTarget + State ServiceTarget + + // DependencyTimeout bounds each readiness probe's call to a dependency. + DependencyTimeout time.Duration + // ReadHeaderTimeout and ShutdownTimeout bound the HTTP lifecycle. + ReadHeaderTimeout time.Duration + ShutdownTimeout time.Duration +} + +// trustForwardedHeaders reports the resolved value, treating "not specified" +// as off: trusting forwarded headers unconditionally lets an untrusted client +// spoof the Origin scheme check. +func (o Options) trustForwardedHeaders() bool { + return o.TrustForwardedHeaders != nil && *o.TrustForwardedHeaders +} diff --git a/internal/app/archieui/readiness.go b/internal/app/archieui/readiness.go new file mode 100644 index 000000000..de1b7610d --- /dev/null +++ b/internal/app/archieui/readiness.go @@ -0,0 +1,31 @@ +package archieui + +import ( + "context" + + "github.com/samcharles93/archie-core/internal/domain/health" + "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/infrastructure/readiness" + "github.com/samcharles93/archie-core/internal/store" +) + +// newReadinessRegistry builds the registry behind GET /health/detailed. The +// UI is ready when both of its mandatory remote contracts answer within the +// dependency timeout; each probe consumes the dependency's own result over +// the wire and never inspects its manager, registry or database +// (docs/prds/ui-service-boundary.md:126-132). +// +// The component names match the daemon dashboard's, so the readiness view +// reads the same whichever process serves it. +func newReadinessRegistry(o Options, tasks store.TaskStore, chat gateway.ChatContract) *health.Registry { + return health.NewRegistry( + readiness.NewContractProbe("state_db", o.DependencyTimeout, func(ctx context.Context) error { + _, err := tasks.StatusCounts(ctx) + return err + }), + readiness.NewContractProbe("gateway", o.DependencyTimeout, func(ctx context.Context) error { + _, err := chat.Snapshot(ctx) + return err + }), + ) +} diff --git a/internal/app/archieui/run.go b/internal/app/archieui/run.go new file mode 100644 index 000000000..47f856233 --- /dev/null +++ b/internal/app/archieui/run.go @@ -0,0 +1,88 @@ +package archieui + +import ( + "context" + "errors" + "fmt" + "log/slog" + "net" + "net/http" + "os" + "slices" + + "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" + "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" + "github.com/samcharles93/archie-core/internal/webui" +) + +// Run serves the dashboard until ctx is cancelled. It resolves its own +// options, dials the Gateway and State Store contracts itself, composes the +// HTTP surface over them, and unwinds listener then clients in reverse order +// on shutdown. +func Run(ctx context.Context, options Options) error { + log := slog.New(slog.NewJSONHandler(os.Stderr, nil)).With("component", "ui") + opts, err := Resolve(options, log) + if err != nil { + return err + } + + var cleanups []func() + defer func() { + for _, cleanup := range slices.Backward(cleanups) { + cleanup() + } + }() + + tasks, closeState, err := staterpc.Dial(opts.State.Target, opts.State.Token) + if err != nil { + return err + } + cleanups = append(cleanups, closeState) + chat, closeGateway, err := gatewayrpc.Dial(opts.Gateway.Target) + if err != nil { + return err + } + cleanups = append(cleanups, closeGateway) + + srv := compose(deps{ + Options: opts, + Log: log, + Store: tasks, + Chat: chat, + Health: newReadinessRegistry(opts, tasks, chat), + }) + + listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", opts.Listen) + if err != nil { + return fmt.Errorf("listen for ui: %w", err) + } + cleanups = append(cleanups, func() { _ = listener.Close() }) + log.Info("archie-ui running", + "addr", listener.Addr().String(), + "open", webui.DashboardURL(listener.Addr().String(), opts.Token), + "gateway", opts.Gateway.Target, + "state", opts.State.Target, + ) + + return serve(ctx, listener, srv.Handler(), opts) +} + +// serve runs handler on listener until ctx ends, then shuts the HTTP server +// down within ShutdownTimeout so in-flight dashboard requests finish before +// the contract clients close. +func serve(ctx context.Context, listener net.Listener, handler http.Handler, opts Options) error { + server := &http.Server{Handler: handler, ReadHeaderTimeout: opts.ReadHeaderTimeout} + serveErr := make(chan error, 1) + go func() { serveErr <- server.Serve(listener) }() + select { + case <-ctx.Done(): + shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), opts.ShutdownTimeout) + defer cancel() + return server.Shutdown(shutdownCtx) + case err := <-serveErr: + if errors.Is(err, http.ErrServerClosed) { + return nil + } + return err + } +} diff --git a/internal/app/archieui/run_test.go b/internal/app/archieui/run_test.go new file mode 100644 index 000000000..6e52551a8 --- /dev/null +++ b/internal/app/archieui/run_test.go @@ -0,0 +1,346 @@ +package archieui + +import ( + "context" + "encoding/json" + "io" + "log/slog" + "net" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + "google.golang.org/grpc" + + "github.com/samcharles93/archie-core/internal/domain/health" + "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" + "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" + "github.com/samcharles93/archie-core/internal/store" + "github.com/samcharles93/archie-core/internal/taskstate" +) + +// fakeChat is a minimal gateway.ChatContract standing in for the standalone +// archie-gateway process. Only the read path the dashboard exercises here +// returns data; the rest satisfy the interface. +type fakeChat struct{ sessions []gateway.SessionContext } + +func (f *fakeChat) Snapshot(context.Context) (gateway.ChatSnapshot, error) { + return gateway.ChatSnapshot{ + Sessions: f.sessions, + Models: []string{"test/model"}, + ActiveModel: "test/model", + ActivePersonas: map[string]string{}, + }, nil +} + +func (f *fakeChat) GetSession(context.Context, string) (gateway.SessionContext, bool, error) { + return gateway.SessionContext{}, false, nil +} + +func (f *fakeChat) RecentMessages(context.Context, string, int) ([]gateway.Message, error) { + return nil, nil +} + +func (f *fakeChat) RecentTurns(context.Context, string, int) ([]gateway.TurnRecord, error) { + return nil, nil +} + +func (f *fakeChat) Route(context.Context, gateway.Message) (gateway.ChatReply, error) { + return gateway.ChatReply{}, nil +} + +func (f *fakeChat) Stream(context.Context, gateway.Message) (<-chan gateway.ChatEvent, error) { + ch := make(chan gateway.ChatEvent) + close(ch) + return ch, nil +} + +func (f *fakeChat) Cancel(context.Context, string) (gateway.ChatCancellation, error) { + return gateway.ChatCancellation{}, nil +} + +func (f *fakeChat) SetPersona(context.Context, string, string) (bool, error) { return false, nil } + +func (f *fakeChat) ApplyTaskAction(context.Context, string, int64, taskstate.Action) (gateway.TaskActionResult, error) { + return gateway.TaskActionResult{}, nil +} + +// serveGRPC runs register against a fresh loopback listener and returns the +// dial target plus a stop func. Mirrors the harness in +// internal/app/archied/state_store_test.go's TestServeStateStoreServesContract. +func serveGRPC(t *testing.T, register func(grpc.ServiceRegistrar)) (target string, stop func()) { + t.Helper() + listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + server := grpc.NewServer() + register(server) + go func() { _ = server.Serve(listener) }() + return listener.Addr().String(), server.Stop +} + +// TestUIServesDashboardAgainstRemoteContracts is the bead's headline claim: +// the composed UI process serves the whole dashboard with its data coming +// over the wire from a State Store and a Gateway in other processes, and +// every route with no contract behind it degrades exactly as +// docs/prds/ui-service-boundary.md:130-131 permits. +func TestUIServesDashboardAgainstRemoteContracts(t *testing.T) { + st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "tasks.sqlite")) + if err != nil { + t.Fatalf("open temp store: %v", err) + } + defer st.Close() + if _, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "remote summary", "body", "implement", ""); err != nil { + t.Fatalf("seed task: %v", err) + } + + stateTarget, stopState := serveGRPC(t, func(r grpc.ServiceRegistrar) { + staterpc.RegisterServer(r, staterpc.Deps{Tasks: st, Log: slog.New(slog.DiscardHandler)}) + }) + defer stopState() + chat := &fakeChat{sessions: []gateway.SessionContext{ + {SessionID: "s1", Source: gateway.SessionSource{Platform: "web", ChannelID: "dash"}}, + }} + gatewayTarget, stopGateway := serveGRPC(t, func(r grpc.ServiceRegistrar) { + gatewayrpc.RegisterServer(r, chat) + }) + defer stopGateway() + + stateClient, closeState, err := staterpc.Dial(stateTarget, "") + if err != nil { + t.Fatalf("dial state store: %v", err) + } + defer closeState() + chatClient, closeGateway, err := gatewayrpc.Dial(gatewayTarget) + if err != nil { + t.Fatalf("dial gateway: %v", err) + } + defer closeGateway() + + options := Options{Listen: "127.0.0.1:0", DependencyTimeout: defaultDependencyTimeout} + srv := compose(deps{ + Options: options, + Log: slog.New(slog.DiscardHandler), + Store: stateClient, + Chat: chatClient, + Health: newReadinessRegistry(options, stateClient, chatClient), + }) + ts := httptest.NewServer(srv.Handler()) + defer ts.Close() + + get := func(path string) (int, []byte) { + t.Helper() + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, ts.URL+path, nil) + if err != nil { + t.Fatalf("request %s: %v", path, err) + } + resp, err := ts.Client().Do(req) + if err != nil { + t.Fatalf("GET %s: %v", path, err) + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + return resp.StatusCode, body + } + + // Liveness is unauthenticated (PRD lines 119-120). + for _, path := range []string{"/healthz", "/health"} { + if code, _ := get(path); code != http.StatusOK { + t.Errorf("GET %s = %d, want 200", path, code) + } + } + + // The task board's data came over the State Store's gRPC listener. + code, body := get("/api/summary") + if code != http.StatusOK { + t.Fatalf("GET /api/summary = %d (%s), want 200", code, body) + } + var summary struct { + Statuses map[string]int `json:"statuses"` + } + if err := json.Unmarshal(body, &summary); err != nil { + t.Fatalf("decode summary: %v", err) + } + total := 0 + for _, n := range summary.Statuses { + total += n + } + if total != 1 { + t.Fatalf("summary counted %d tasks, want the 1 seeded behind the gRPC listener (%s)", total, body) + } + + // Chat reads come over the Gateway's gRPC listener. + code, body = get("/api/chat/sessions") + if code != http.StatusOK { + t.Fatalf("GET /api/chat/sessions = %d (%s), want 200", code, body) + } + var sessions struct { + Sessions []gateway.SessionContext `json:"sessions"` + } + if err := json.Unmarshal(body, &sessions); err != nil { + t.Fatalf("decode sessions: %v", err) + } + if len(sessions.Sessions) != 1 || sessions.Sessions[0].SessionID != "s1" { + t.Fatalf("chat sessions = %s, want the single web session from the remote contract", body) + } + + // No shared config.Holder: the read is empty and there is no second writer. + if code, body := get("/api/config"); code != http.StatusOK || string(body) != "{}\n" { + t.Errorf("GET /api/config = %d %q, want 200 {}", code, body) + } + req, err := http.NewRequestWithContext(t.Context(), http.MethodPatch, ts.URL+"/api/config", http.NoBody) + if err != nil { + t.Fatalf("patch request: %v", err) + } + resp, err := ts.Client().Do(req) + if err != nil { + t.Fatalf("PATCH /api/config: %v", err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusServiceUnavailable { + t.Errorf("PATCH /api/config = %d, want 503: the daemon stays the configuration writer (PRD lines 95-96)", resp.StatusCode) + } + + // Routes with no contract behind them degrade rather than panic. + code, body = get("/api/logs") + if code != http.StatusOK { + t.Errorf("GET /api/logs = %d, want 200", code) + } + var logs struct { + Disabled bool `json:"disabled"` + } + if err := json.Unmarshal(body, &logs); err != nil { + t.Fatalf("decode logs: %v", err) + } + if !logs.Disabled { + t.Errorf("GET /api/logs reported logging enabled; the UI process has no daemon log feed (%s)", body) + } + if code, _ := get("/api/version"); code != http.StatusNotImplemented { + t.Errorf("GET /api/version = %d, want 501", code) + } + + // Capture intake stays with the daemon until bead archie-core-8cda.5.4. + capReq, err := http.NewRequestWithContext(t.Context(), http.MethodPost, ts.URL+"/webhooks/capture/demo", http.NoBody) + if err != nil { + t.Fatalf("capture request: %v", err) + } + capResp, err := ts.Client().Do(capReq) + if err != nil { + t.Fatalf("POST /webhooks/capture/demo: %v", err) + } + capResp.Body.Close() + if capResp.StatusCode != http.StatusServiceUnavailable { + t.Errorf("POST /webhooks/capture/demo = %d, want 503: two processes must not share webhook intake authority", capResp.StatusCode) + } + + // Readiness aggregates the two remote dependencies, and drops when one dies. + code, body = get("/health/detailed") + if code != http.StatusOK { + t.Fatalf("GET /health/detailed = %d (%s), want 200", code, body) + } + report := decodeReport(t, body) + if report.Status != health.StatusOK { + t.Fatalf("readiness = %s with both dependencies up, want ok (%s)", report.Status, body) + } + stopState() + _, body = get("/health/detailed") + report = decodeReport(t, body) + if report.Status != health.StatusDegraded { + t.Fatalf("readiness = %s with the State Store stopped, want degraded (%s)", report.Status, body) + } + if ready, ok := componentReady(report, "state_db"); !ok || ready { + t.Fatalf("state_db component ready=%v present=%v with the State Store stopped (%s)", ready, ok, body) + } + if ready, ok := componentReady(report, "gateway"); !ok || !ready { + t.Fatalf("gateway component ready=%v present=%v while the Gateway is still up (%s)", ready, ok, body) + } +} + +func decodeReport(t *testing.T, body []byte) health.Report { + t.Helper() + var report health.Report + if err := json.Unmarshal(body, &report); err != nil { + t.Fatalf("decode readiness report: %v (%s)", err, body) + } + return report +} + +func componentReady(report health.Report, name string) (ready, found bool) { + for _, c := range report.Components { + if c.Name == name { + return c.Ready, true + } + } + return false, false +} + +// TestUIRefusesNonLoopbackListenWithoutToken holds the PRD's security +// posture (lines 116-118): "non-loopback listeners require a non-empty token +// and fail closed when it is absent". Unlike the daemon, which mints a token +// silently (webTokenFor), the standalone process refuses to start; -token-file +// is the explicit opt-in to minting one. +func TestUIRefusesNonLoopbackListenWithoutToken(t *testing.T) { + tests := []struct { + name string + options Options + wantErr bool + }{ + {name: "loopback without token", options: Options{Listen: "127.0.0.1:8484"}}, + {name: "localhost without token", options: Options{Listen: "localhost:8484"}}, + {name: "non-loopback without token", options: Options{Listen: "0.0.0.0:8484"}, wantErr: true}, + {name: "routable without token", options: Options{Listen: "192.168.1.10:8484"}, wantErr: true}, + {name: "non-loopback with token", options: Options{Listen: "0.0.0.0:8484", Token: "s3cret"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + options := tt.options + options.Gateway = ServiceTarget{Target: "127.0.0.1:8585"} + options.State = ServiceTarget{Target: "127.0.0.1:9090"} + _, err := Resolve(options, slog.New(slog.DiscardHandler)) + if tt.wantErr && err == nil { + t.Fatalf("Resolve(%q, token=%q) succeeded; a non-loopback listener without a token must fail closed", options.Listen, options.Token) + } + if !tt.wantErr && err != nil { + t.Fatalf("Resolve(%q, token=%q): %v", options.Listen, options.Token, err) + } + }) + } +} + +// TestUIMintsTokenFromTokenFile is the explicit opt-in the fail-closed rule +// leaves the operator: -token-file names where the dashboard token lives, and +// a non-loopback listener then starts with the minted token rather than +// refusing. +func TestUIMintsTokenFromTokenFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "web-token") + resolved, err := Resolve(Options{ + Listen: "0.0.0.0:8484", + TokenFile: path, + Gateway: ServiceTarget{Target: "127.0.0.1:8585"}, + State: ServiceTarget{Target: "127.0.0.1:9090"}, + }, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("Resolve with -token-file: %v", err) + } + if resolved.Token == "" { + t.Fatal("Resolve did not mint a token from -token-file") + } + again, err := Resolve(Options{ + Listen: "0.0.0.0:8484", + TokenFile: path, + Gateway: ServiceTarget{Target: "127.0.0.1:8585"}, + State: ServiceTarget{Target: "127.0.0.1:9090"}, + }, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("Resolve reusing -token-file: %v", err) + } + if again.Token != resolved.Token { + t.Fatalf("token file minted a second token %q, want the persisted %q", again.Token, resolved.Token) + } +} diff --git a/internal/infrastructure/gatewayrpc/dial.go b/internal/infrastructure/gatewayrpc/dial.go new file mode 100644 index 000000000..45f27e8c7 --- /dev/null +++ b/internal/infrastructure/gatewayrpc/dial.go @@ -0,0 +1,30 @@ +package gatewayrpc + +import ( + "fmt" + "strings" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +// Dial returns a chat contract client for target, the standalone +// archie-gateway process. Deployments that put the Gateway on a separate +// trust boundary supply their own transport credentials through options; the +// default must be usable without manufacturing a certificate in the config +// loader. The returned cleanup closes the connection. +// +// The Gateway listener is loopback-only (internal/app/archied.RunGateway), so +// a caller is colocated with it until a Gateway transport-security amendment +// says otherwise. +func Dial(target string, options ...grpc.DialOption) (*Client, func(), error) { + if strings.TrimSpace(target) == "" { + return nil, nil, fmt.Errorf("gateway target is required") + } + opts := append([]grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}, options...) + conn, err := grpc.NewClient(target, opts...) + if err != nil { + return nil, nil, fmt.Errorf("create gateway client: %w", err) + } + return NewClient(conn), func() { _ = conn.Close() }, nil +} diff --git a/internal/infrastructure/readiness/probes.go b/internal/infrastructure/readiness/probes.go index ca6e5ba6a..0104da2f6 100644 --- a/internal/infrastructure/readiness/probes.go +++ b/internal/infrastructure/readiness/probes.go @@ -14,6 +14,7 @@ import ( "context" "fmt" "syscall" + "time" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/health" @@ -52,6 +53,43 @@ func (p *StoreProbe) Check(ctx context.Context) health.Result { return health.Result{Status: health.StatusOK} } +// --- remote contract --- + +// ContractProbe reports whether a service this process consumes over the wire +// answers a cheap call within a bounded timeout. It is the readiness signal +// available to a process that depends on a service it does not own: the probe +// consumes the dependency's own result and never inspects its manager, +// registry or database (docs/prds/ui-service-boundary.md, "Listen, +// authentication, and readiness"). +type ContractProbe struct { + ProbeName string + Timeout time.Duration + Ping func(context.Context) error +} + +// NewContractProbe returns a probe named name that calls ping. A zero or +// negative timeout leaves the caller's context deadline in force. +func NewContractProbe(name string, timeout time.Duration, ping func(context.Context) error) *ContractProbe { + return &ContractProbe{ProbeName: name, Timeout: timeout, Ping: ping} +} + +func (p *ContractProbe) Name() string { return p.ProbeName } + +func (p *ContractProbe) Check(ctx context.Context) health.Result { + if p.Ping == nil { + return health.Result{Status: health.StatusDegraded, Detail: "contract not wired"} + } + if p.Timeout > 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, p.Timeout) + defer cancel() + } + if err := p.Ping(ctx); err != nil { + return health.Result{Status: health.StatusDegraded, Detail: "unreachable: " + err.Error()} + } + return health.Result{Status: health.StatusOK} +} + // --- config --- // ConfigProbe validates the running configuration. It is the same check the diff --git a/internal/infrastructure/staterpc/dial.go b/internal/infrastructure/staterpc/dial.go new file mode 100644 index 000000000..488590088 --- /dev/null +++ b/internal/infrastructure/staterpc/dial.go @@ -0,0 +1,66 @@ +package staterpc + +import ( + "fmt" + "net" + "strings" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +// Dial returns a State Store contract client for target, applying the +// transport security boundary (docs/prds/state-store-contract.md §9): a +// loopback target dials insecure with no credential, while a non-loopback +// target requires a bearer token and fails closed without one. The returned +// cleanup closes the connection; Client.Close is a no-op because the store +// service owns its own DB lifecycle (§11). +// +// The rule lives here rather than in a composition root so the server side +// (which decides whether to install the token interceptors) and every client +// that dials it share one implementation. +func Dial(target, token string, options ...grpc.DialOption) (*Client, func(), error) { + target = strings.TrimSpace(target) + if target == "" { + return nil, nil, fmt.Errorf("state store target is required") + } + loopback, err := TargetIsLoopback(target) + if err != nil { + return nil, nil, fmt.Errorf("state store target must be host:port: %w", err) + } + if !loopback && token == "" { + return nil, nil, fmt.Errorf( + "state store target %q is non-loopback; non-loopback exposure requires a bearer token ([services.state].target_token / STATE_STORE_TOKEN) or TLS, mirroring the gateway's --listen confinement (docs/prds/state-store-contract.md §9)", + target, + ) + } + opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())} + if token != "" { + opts = append(opts, grpc.WithUnaryInterceptor(UnaryClientTokenInterceptor(token))) + } + conn, err := grpc.NewClient(target, append(opts, options...)...) + if err != nil { + return nil, nil, fmt.Errorf("create state store client: %w", err) + } + return NewClient(conn), func() { _ = conn.Close() }, nil +} + +// TargetIsLoopback reports whether addr's host is a loopback address. Both +// literal loopback IPs (127.0.0.1, ::1) and the "localhost" hostname count; +// everything else (including the wildcard 0.0.0.0 and DNS names) is treated +// as network-reachable and therefore non-loopback. It applies to a listen +// address and a dial target alike -- the same host decides both. +func TargetIsLoopback(addr string) (bool, error) { + host, _, err := net.SplitHostPort(addr) + if err != nil { + return false, fmt.Errorf("address must be host:port: %w", err) + } + if strings.EqualFold(host, "localhost") { + return true, nil + } + ip := net.ParseIP(host) + if ip == nil { + return false, nil + } + return ip.IsLoopback(), nil +} diff --git a/internal/infrastructure/staterpc/dial_test.go b/internal/infrastructure/staterpc/dial_test.go new file mode 100644 index 000000000..9badfe351 --- /dev/null +++ b/internal/infrastructure/staterpc/dial_test.go @@ -0,0 +1,67 @@ +package staterpc + +import "testing" + +func TestTargetIsLoopback(t *testing.T) { + tests := []struct { + name string + addr string + want bool + }{ + {"loopback ipv4", "127.0.0.1:9090", true}, + {"loopback ipv6", "[::1]:9090", true}, + {"localhost hostname", "localhost:9090", true}, + {"localhost uppercase", "LOCALHOST:9090", true}, + {"wildcard", "0.0.0.0:9090", false}, + {"private ip", "192.168.1.10:9090", false}, + {"dns name", "store.example.com:9090", false}, + {"empty host", ":9090", false}, + {"malformed", "127.0.0.1", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := TargetIsLoopback(tt.addr) + if tt.name == "malformed" { + if err == nil { + t.Fatalf("TargetIsLoopback(%q) = (%v, nil), want error", tt.addr, got) + } + return + } + if err != nil { + t.Fatalf("TargetIsLoopback(%q): %v", tt.addr, err) + } + if got != tt.want { + t.Fatalf("TargetIsLoopback(%q) = %v, want %v", tt.addr, got, tt.want) + } + }) + } +} + +// TestDialFailsClosedOffLoopbackWithoutToken is the transport half of the §9 +// rule: a target reachable from the network must present a bearer token, so a +// missing credential stops the dial rather than opening an unauthenticated +// connection. +func TestDialFailsClosedOffLoopbackWithoutToken(t *testing.T) { + if _, _, err := Dial("", ""); err == nil { + t.Fatal("Dial with an empty target should fail") + } + if _, _, err := Dial("0.0.0.0:9090", ""); err == nil { + t.Fatal("Dial to a non-loopback target without a token should fail closed") + } + client, cleanup, err := Dial("0.0.0.0:9090", "secret") + if err != nil { + t.Fatalf("Dial to a non-loopback target with a token: %v", err) + } + defer cleanup() + if client == nil { + t.Fatal("Dial returned no client") + } + loopback, cleanupLoopback, err := Dial("127.0.0.1:9090", "") + if err != nil { + t.Fatalf("Dial to a loopback target without a token: %v", err) + } + defer cleanupLoopback() + if loopback == nil { + t.Fatal("Dial returned no client for a loopback target") + } +}