diff --git a/cmd/archie-state-store/main_test.go b/cmd/archie-state-store/main_test.go index 42137f3d7..5be744ded 100644 --- a/cmd/archie-state-store/main_test.go +++ b/cmd/archie-state-store/main_test.go @@ -20,6 +20,7 @@ import ( "encoding/json" "errors" "fmt" + "net" "net/http" "os" "os/exec" @@ -147,7 +148,24 @@ type stateStoreProcess struct { // configured one) is what a consumer must dial. func startStateStoreProcess(t *testing.T, bin, cfg string) *stateStoreProcess { t.Helper() - cmd := exec.CommandContext(t.Context(), bin, "-config", cfg, "-listen", "127.0.0.1:0", "-ready-addr", "127.0.0.1:0") + return startStateStore(t, bin, cfg, "127.0.0.1:0", "") +} + +// startStateStore is startStateStoreProcess with the listener topology and +// bearer token exposed: the token-protected, non-loopback listener is the +// topology every container-mode deployment profile uses +// (docs/prds/state-store-contract.md §9), where the server installs the +// credential interceptors on both the unary and the streaming surface. +func startStateStore(t *testing.T, bin, cfg, listen, token string) *stateStoreProcess { + t.Helper() + args := []string{"-config", cfg, "-listen", listen, "-ready-addr", "127.0.0.1:0"} + if token != "" { + // An explicit -token wins over [services.state].target_token and the + // STATE_STORE_TOKEN secret, so the process authenticates callers with + // exactly this value. + args = append(args, "-token", token) + } + cmd := exec.CommandContext(t.Context(), bin, args...) cmd.Env = append(os.Environ(), "ARCHIE_GITHUB_TOKEN=test-token") var log syncBuffer cmd.Stderr = &log @@ -419,6 +437,58 @@ func TestStateStoreRealProcessRestartRecovery(t *testing.T) { } } +// TestStateStoreRealProcessTokenProtectedCaptureStream is the capture-batch +// regression against the real binary: the token-protected, non-loopback +// listener topology a container-mode deployment uses, read through the +// production client wiring (staterpc.Dial) the daemon and the dashboard both +// use. The reads the batch needs are server-streaming RPCs, whose metadata +// the unary-only client interceptor never saw -- so before the fix this +// failed with PermissionDenied, and no unary fallback existed to take. 20 x +// 256 KiB is 5 MiB, past gRPC's 4 MiB unary cap, so the batch also proves the +// streams still carry it. +func TestStateStoreRealProcessTokenProtectedCaptureStream(t *testing.T) { + if testing.Short() { + t.Skip("real-process smoke test builds and execs the binary; skip under -short") + } + const token = "operator-secret-token" + dir := t.TempDir() + bin := buildBinary(t, dir) + cfg := writeMinimalConfig(t, dir) + st := startStateStore(t, bin, cfg, "0.0.0.0:0", token) + + // The listener advertises the wildcard address it bound; a consumer dials + // the host address it can reach, which is this host's loopback. + _, port, err := net.SplitHostPort(st.addr) + if err != nil { + t.Fatalf("parse bound address %q: %v", st.addr, err) + } + cl, cleanup, err := staterpc.Dial("127.0.0.1:"+port, token) + if err != nil { + t.Fatalf("dial token-protected state store: %v", err) + } + t.Cleanup(cleanup) + + ctx := t.Context() + body := strings.Repeat("x", 256<<10) + for range 20 { + if _, err := cl.InsertCapture(ctx, capture("large", body), 0, 0); err != nil { + t.Fatalf("InsertCapture: %v", err) + } + } + captures, err := cl.ListCaptures(ctx, 20) + if err != nil { + t.Fatalf("ListCaptures over a token-protected listener: %v", err) + } + if len(captures) != 20 { + t.Fatalf("got %d captures, want 20", len(captures)) + } + for _, c := range captures { + if c.Body != body { + t.Fatal("capture body truncated") + } + } +} + // TestStateStoreRealProcessRemoteSurfaces exercises the capture/mapping/ // binding surfaces the standalone process fronts (the daemon/webui surfaces // swapped to the adapter in .4.4/.4.5), proving one process serves the full diff --git a/internal/infrastructure/agenttransport/nats/transport.go b/internal/infrastructure/agenttransport/nats/transport.go index 497526c32..233e25a6f 100644 --- a/internal/infrastructure/agenttransport/nats/transport.go +++ b/internal/infrastructure/agenttransport/nats/transport.go @@ -7,14 +7,11 @@ import ( "encoding/json" "fmt" "log/slog" - "net" "strconv" "strings" "time" natsio "github.com/nats-io/nats.go" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/domain/workflow" @@ -51,12 +48,13 @@ type sdkSubscription interface { // worker has no JetStream consumer. type Transport struct { conn *natsio.Conn - // stateConn is the long-lived gRPC connection to the State Store. Store() - // dials no per-call connection; it wraps this one connection with the - // per-call timeout each caller supplies. Connect refuses to construct a - // Transport without one (the legacy NATS storerpc path is deleted), so it - // is never nil in a real worker. - stateConn *grpc.ClientConn + // state is the long-lived State Store contract client and closeState its + // connection cleanup. Store() dials nothing per call; it wraps this one + // client with the per-call timeout each caller supplies. Connect refuses + // to construct a Transport without one (the legacy NATS storerpc path is + // deleted), so it is never nil in a real worker. + state *staterpc.Client + closeState func() subscribe func(string, natsio.MsgHandler) (sdkSubscription, error) flush func(time.Duration) error @@ -96,7 +94,7 @@ func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport, conn.Close() return nil, fmt.Errorf("state store target is required: archie-agent no longer supports the legacy NATS storerpc path (docs/prds/state-store-contract.md §12 step 4)") } - stateConn, err := dialStateStore(config.StateStoreURL, config.StateStoreToken) + state, closeState, err := staterpc.Dial(config.StateStoreURL, config.StateStoreToken) if err != nil { conn.Close() return nil, fmt.Errorf("connect state store: %w", err) @@ -104,8 +102,9 @@ func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport, log.Info("worker state store transport connected", "url", config.StateStoreURL) return &Transport{ - conn: conn, - stateConn: stateConn, + conn: conn, + state: state, + closeState: closeState, subscribe: func(subject string, handler natsio.MsgHandler) (sdkSubscription, error) { return conn.Subscribe(subject, handler) }, @@ -113,30 +112,11 @@ func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport, }, nil } -// dialStateStore dials target, failing closed (rather than connecting -// insecurely) when target is not a loopback address and no token was -// configured -- §9's "fail-closed on non-loopback" rule. -func dialStateStore(target, token string) (*grpc.ClientConn, error) { - host, _, err := net.SplitHostPort(target) - if err != nil { - host = target - } - loopback := net.ParseIP(host).IsLoopback() - if !loopback && token == "" { - return nil, fmt.Errorf("state store target %q is not loopback and no token is configured; refusing an unauthenticated remote connection", target) - } - opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())} - if token != "" { - opts = append(opts, grpc.WithUnaryInterceptor(staterpc.UnaryClientTokenInterceptor(token))) - } - return grpc.NewClient(target, opts...) -} - // Close releases all broker resources. func (t *Transport) Close() { t.conn.Close() - if t.stateConn != nil { - _ = t.stateConn.Close() + if t.closeState != nil { + t.closeState() } } @@ -164,14 +144,14 @@ func (t *Transport) Forger(identity string, timeout time.Duration) workflow.Forg return &forgerpc.Client{Conn: t.conn, Timeout: timeout, Identity: identity} } -// Store constructs the workflow store RPC client over the long-lived gRPC -// State Store connection (docs/prds/state-store-contract.md §6). Each call -// is bounded by timeout when the caller's context carries no deadline of its -// own. The legacy NATS storerpc path is deleted (§12 step 4); a transport -// without a stateConn cannot reach Store() because Connect refused to build +// Store constructs the workflow store RPC client over the long-lived State +// Store client (docs/prds/state-store-contract.md §6). Each call is bounded +// by timeout when the caller's context carries no deadline of its own. The +// legacy NATS storerpc path is deleted (§12 step 4); a transport without a +// State Store client cannot reach Store() because Connect refused to build // one. func (t *Transport) Store(timeout time.Duration) workflow.Store { - return deadlineStore{Store: staterpc.NewClient(t.stateConn), timeout: timeout} + return deadlineStore{Store: t.state, timeout: timeout} } // deadlineStore applies a default per-call timeout to workflow.Store calls diff --git a/internal/infrastructure/staterpc/auth.go b/internal/infrastructure/staterpc/auth.go index 813a8366d..fc7084713 100644 --- a/internal/infrastructure/staterpc/auth.go +++ b/internal/infrastructure/staterpc/auth.go @@ -58,3 +58,16 @@ func UnaryClientTokenInterceptor(token string) grpc.UnaryClientInterceptor { return invoker(metadata.AppendToOutgoingContext(ctx, tokenMetadataKey, token), method, req, reply, cc, opts...) } } + +// StreamClientTokenInterceptor attaches token to the outgoing stream's +// context, covering the server-streaming read RPCs (StreamCaptures, +// StreamUndispatchedCaptures) the unary interceptor cannot see. Without it +// those calls reach a token-protected listener with no credential and the +// server's stream interceptor refuses them, leaving the capture batch reads +// -- the ones moved onto streams precisely so a large batch crosses -- with +// no working path. +func StreamClientTokenInterceptor(token string) grpc.StreamClientInterceptor { + return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { + return streamer(metadata.AppendToOutgoingContext(ctx, tokenMetadataKey, token), desc, cc, method, opts...) + } +} diff --git a/internal/infrastructure/staterpc/dial.go b/internal/infrastructure/staterpc/dial.go index 488590088..e5e2dd797 100644 --- a/internal/infrastructure/staterpc/dial.go +++ b/internal/infrastructure/staterpc/dial.go @@ -36,7 +36,13 @@ func Dial(target, token string, options ...grpc.DialOption) (*Client, func(), er } opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())} if token != "" { - opts = append(opts, grpc.WithUnaryInterceptor(UnaryClientTokenInterceptor(token))) + // Both call shapes need the credential: the server's interceptors + // guard unary RPCs and the streaming capture reads separately, so a + // unary-only interceptor leaves the streams unauthenticated. + opts = append(opts, + grpc.WithUnaryInterceptor(UnaryClientTokenInterceptor(token)), + grpc.WithStreamInterceptor(StreamClientTokenInterceptor(token)), + ) } conn, err := grpc.NewClient(target, append(opts, options...)...) if err != nil { diff --git a/internal/infrastructure/staterpc/task_grants_test.go b/internal/infrastructure/staterpc/task_grants_test.go index 39a8e4039..8a4c9b174 100644 --- a/internal/infrastructure/staterpc/task_grants_test.go +++ b/internal/infrastructure/staterpc/task_grants_test.go @@ -3,13 +3,16 @@ package staterpc import ( "context" "net" + "strings" "testing" "time" "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "google.golang.org/grpc/test/bufconn" + "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/store" @@ -28,29 +31,106 @@ func grantsServer(t *testing.T, adminToken string) (grants *TaskGrants, dial fun grpc.ChainUnaryInterceptor(grants.UnaryInterceptor(adminToken)), grpc.ChainStreamInterceptor(grants.StreamInterceptor(adminToken)), ) - RegisterServer(server, Deps{Tasks: local, Grants: grants, ConfigSnapshots: local}) + RegisterServer(server, Deps{Tasks: local, Captures: local, Bindings: local, BindingDispatcher: local, Grants: grants, ConfigSnapshots: local}) go func() { _ = server.Serve(listener) }() t.Cleanup(func() { server.Stop(); _ = listener.Close() }) dial = func(t *testing.T, token string) *Client { t.Helper() - opts := []grpc.DialOption{ - grpc.WithTransportCredentials(insecure.NewCredentials()), - grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }), - } - if token != "" { - opts = append(opts, grpc.WithUnaryInterceptor(UnaryClientTokenInterceptor(token))) - } - conn, err := grpc.NewClient("passthrough:///state", opts...) + // Dial is the production client-side wiring (and the only dial path + // the daemon and the dashboard use), so a credential attached to one + // call shape but not another cannot hide here. The target is the + // non-loopback bridge address every container-mode deployment + // profile uses; the dialer redirects it to the bufconn listener. + client, cleanup, err := Dial("172.17.0.1:9090", token, grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) })) if err != nil { t.Fatal(err) } - t.Cleanup(func() { _ = conn.Close() }) - return NewClient(conn) + t.Cleanup(cleanup) + return client } return grants, dial } +// TestCaptureStreamsCarryTheAdminToken is the capture-batching regression: +// the batch reads moved onto server-streaming RPCs (StreamCaptures / +// StreamUndispatchedCaptures) to get past gRPC's 4 MiB unary cap, but the +// client interceptor suite attached the bearer token to unary calls only -- +// so on the token-protected topology every deployment profile uses, the +// daemon's dispatch loop and the dashboard's inspector got PermissionDenied +// from the stream interceptor, with no unary fallback left to take. 20 x +// 256 KiB is 5 MiB, past that cap, so the batch also proves the streaming +// path still carries it. +func TestCaptureStreamsCarryTheAdminToken(t *testing.T) { + const adminToken = "daemon-admin-token" + _, dial := grantsServer(t, adminToken) + admin := dial(t, adminToken) + ctx := t.Context() + + body := strings.Repeat("x", 256<<10) + for range 20 { + if _, err := admin.InsertCapture(ctx, store.CapturedEvent{Source: "large", Body: body, Authenticated: true}, 0, 0); err != nil { + t.Fatalf("InsertCapture: %v", err) + } + } + // ListUndispatchedCaptures only returns sources with an armed binding + // (internal/store/bindings.go), so "large" needs one taken through the + // public draft -> pending_approval -> armed lifecycle. + id, err := admin.InsertBinding(ctx, binding.Binding{ + Name: "large binding", Matcher: binding.Matcher{Source: "large"}, + MappingID: 1, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef", + }) + if err != nil { + t.Fatal(err) + } + if err := admin.UpdateBinding(ctx, binding.Binding{ + ID: id, Name: "large binding", Matcher: binding.Matcher{Source: "large"}, + MappingID: 1, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef", + }); err != nil { + t.Fatal(err) + } + if err := admin.ApproveBinding(ctx, id); err != nil { + t.Fatal(err) + } + + for _, tc := range []struct { + name string + list func(context.Context) ([]store.CapturedEvent, error) + }{ + {"ListCaptures", func(ctx context.Context) ([]store.CapturedEvent, error) { return admin.ListCaptures(ctx, 20) }}, + {"ListUndispatchedCaptures", func(ctx context.Context) ([]store.CapturedEvent, error) { + return admin.ListUndispatchedCaptures(ctx, []string{"large"}, 20) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + captures, err := tc.list(t.Context()) + if err != nil { + t.Fatalf("%s over a token-protected listener: %v", tc.name, err) + } + if len(captures) != 20 { + t.Fatalf("got %d captures, want 20", len(captures)) + } + for _, capture := range captures { + if capture.Body != body { + t.Fatal("capture body truncated") + } + } + }) + } +} + +// TestUpdateRejectsNilTask is the Update-validation regression: a request +// carrying no Task must be refused at the RPC boundary as InvalidArgument, +// not dereferenced inside the store layer. +func TestUpdateRejectsNilTask(t *testing.T) { + const adminToken = "daemon-admin-token" + _, dial := grantsServer(t, adminToken) + err := dial(t, adminToken).Update(t.Context(), nil) + if status.Code(err) != codes.InvalidArgument { + t.Fatalf("Update(nil) = %v, want InvalidArgument", err) + } +} + // TestTaskGrantScopesWorkerToItsOwnThreeRPCs is the finding #1 regression: // a container's task-scoped credential must authorize only Update/ // Transition/InsertEvent on its own task ID, never the admin-only surface