From 0ec4ececd57b2872a5b90f7e765e8bc268f22645 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Wed, 9 Sep 2026 00:27:03 +1000 Subject: [PATCH] feat(gateway): authenticate the gRPC contract and allow off-loopback listeners The Gateway had no transport boundary: RunGateway refused any non-loopback listen address and serveGateway registered no interceptor, so archie-ui was colocation-only while the State Store already had a token-authenticated equivalent. gatewayrpc gains a gateway-token metadata credential with constant-time comparison and both unary and stream interceptors on each side. Stream coverage is required here and not in staterpc: the Gateway's Stream RPC is server-streaming. Dial fails closed on a non-loopback target with no token, mirroring staterpc.Dial. gatewayServerOpts applies the same rule server-side: loopback stays insecure, non-loopback requires a token, malformed errors. The daemon resolves [services.gateway].target_token then GATEWAY_TOKEN; archie-ui passes the token its config projection already carried, so a distributed dashboard is now possible. Closes: archie-core-juqx --- cmd/archie-gateway/main.go | 1 + config.example.toml | 5 + internal/app/archied/bootstrap.go | 2 +- internal/app/archied/chat_service.go | 23 +++- internal/app/archied/chat_service_test.go | 43 +++++-- internal/app/archied/gateway.go | 48 +++++-- internal/app/archied/gateway_test.go | 38 ++++++ internal/app/archieui/run.go | 2 +- internal/app/archieui/run_test.go | 2 +- internal/infrastructure/gatewayrpc/auth.go | 98 +++++++++++++++ .../infrastructure/gatewayrpc/auth_test.go | 118 ++++++++++++++++++ internal/infrastructure/gatewayrpc/dial.go | 39 ++++-- .../infrastructure/gatewayrpc/dial_test.go | 67 ++++++++++ 13 files changed, 453 insertions(+), 33 deletions(-) create mode 100644 internal/app/archied/gateway_test.go create mode 100644 internal/infrastructure/gatewayrpc/auth.go create mode 100644 internal/infrastructure/gatewayrpc/auth_test.go create mode 100644 internal/infrastructure/gatewayrpc/dial_test.go diff --git a/cmd/archie-gateway/main.go b/cmd/archie-gateway/main.go index 521c26b3a..dfa6bd83c 100644 --- a/cmd/archie-gateway/main.go +++ b/cmd/archie-gateway/main.go @@ -25,6 +25,7 @@ func run() int { flag.StringVar(&options.Config, "config", filepath.Join(base, "archie", "config.toml"), "configuration file or directory") flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory") flag.StringVar(&options.Listen, "listen", "127.0.0.1:8585", "gateway gRPC listen address") + flag.StringVar(&options.Token, "token", "", "Bearer [REDACTED] required for a non-loopback listener (defaults to [services.gateway].target_token)") flag.Parse() ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() diff --git a/config.example.toml b/config.example.toml index 402c3f698..7436cccfc 100644 --- a/config.example.toml +++ b/config.example.toml @@ -265,6 +265,11 @@ gate_max_failures = 5 # docs/prds/state-store-contract.md). # [services.gateway] # target = "127.0.0.1:8585" # archie-gateway's gRPC address (always remote once set) +# target_token = "..." # Bearer [REDACTED] for a NON-loopback listener. A loopback listener +# # (127.0.0.1/::1/localhost) needs no token. A non-loopback +# # listener without a token fails closed, as does a +# # non-loopback dial without one. The same token is +# # presented as GATEWAY_TOKEN by remote consumers. # [services.state] # target = "127.0.0.1:9090" # REQUIRED. The State Store gRPC address archied and diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 6ec743933..a378015bc 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -580,7 +580,7 @@ func (b *boot) setupLLMAndChat() error { b.setupChatRuntime(cfg) b.setupEmbeddings(cfg, log) - contract, cleanup, err := composeChatContract(cfg.Services.Gateway) + contract, cleanup, err := composeChatContract(cfg.Services.Gateway, b.secrets) if err != nil { return err } diff --git a/internal/app/archied/chat_service.go b/internal/app/archied/chat_service.go index 7e949b216..85bb6d2ef 100644 --- a/internal/app/archied/chat_service.go +++ b/internal/app/archied/chat_service.go @@ -9,18 +9,35 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" + "github.com/samcharles93/archie-core/internal/secret" ) +// gatewayResolvedToken returns the Bearer [REDACTED] a Gateway client +// presents: the explicit [services.gateway].target_token key, then the +// GATEWAY_TOKEN secret/env. The server side (RunGateway) resolves the same +// value, so a distributed consumer and the gateway agree without sharing +// any other configuration. +func gatewayResolvedToken(settings config.ServiceConnection, secrets *secret.Registry) string { + token := settings.TargetToken + if token == "" { + token = secrets.Getenv("GATEWAY_TOKEN") + } + return token +} + // composeChatContract dials the standalone archie-gateway, the sole owner of -// ChatContract, from the daemon's own configuration key. -func composeChatContract(settings config.ServiceConnection, options ...grpc.DialOption) (gateway.ChatContract, func(), error) { +// ChatContract, from the daemon's own configuration key. 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 belong to the transport, so +// they come from gatewayrpc.Dial. +func composeChatContract(settings config.ServiceConnection, secrets *secret.Registry, options ...grpc.DialOption) (gateway.ChatContract, func(), error) { if strings.TrimSpace(settings.Target) == "" { return nil, nil, fmt.Errorf("services.gateway.target is required") } // 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...) + client, cleanup, err := gatewayrpc.Dial(settings.Target, gatewayResolvedToken(settings, secrets), options...) if err != nil { return nil, nil, err } diff --git a/internal/app/archied/chat_service_test.go b/internal/app/archied/chat_service_test.go index 8d52dbaa1..d4540341b 100644 --- a/internal/app/archied/chat_service_test.go +++ b/internal/app/archied/chat_service_test.go @@ -8,13 +8,12 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/status" - "google.golang.org/grpc/test/bufconn" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" + "github.com/samcharles93/archie-core/internal/secret" ) func TestComposeChatContractRejectsInvalidSettings(t *testing.T) { @@ -26,7 +25,7 @@ func TestComposeChatContractRejectsInvalidSettings(t *testing.T) { {name: "blank target", settings: config.ServiceConnection{Target: " \t\n"}}, } { t.Run(tt.name, func(t *testing.T) { - chat, cleanup, err := composeChatContract(tt.settings) + chat, cleanup, err := composeChatContract(tt.settings, &secret.Registry{}) if cleanup != nil { t.Cleanup(cleanup) } @@ -40,8 +39,21 @@ func TestComposeChatContractRejectsInvalidSettings(t *testing.T) { } } +func TestComposeChatContractNonLoopbackFailsClosed(t *testing.T) { + _, _, err := composeChatContract( + config.ServiceConnection{Target: "gateway.example.com:8585"}, + &secret.Registry{}, + ) + if err == nil { + t.Fatal("non-loopback target without a token should fail closed") + } +} + func TestComposeChatContractRemoteAndCleanup(t *testing.T) { - listener := bufconn.Listen(1024 * 1024) + listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } server := grpc.NewServer() gatewayrpc.RegisterServer(server, compositionChat{snapshot: gateway.ChatSnapshot{ActiveModel: "remote-model"}}) serveDone := make(chan error, 1) @@ -55,11 +67,8 @@ func TestComposeChatContractRemoteAndCleanup(t *testing.T) { }) chat, cleanup, err := composeChatContract( - config.ServiceConnection{Target: "passthrough:///chat"}, - grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { - return listener.DialContext(ctx) - }), - grpc.WithTransportCredentials(insecure.NewCredentials()), + config.ServiceConnection{Target: listener.Addr().String()}, + &secret.Registry{}, ) if err != nil { t.Fatal(err) @@ -86,6 +95,22 @@ func TestComposeChatContractRemoteAndCleanup(t *testing.T) { } } +func TestGatewayResolvedToken(t *testing.T) { + if got := gatewayResolvedToken(config.ServiceConnection{TargetToken: "file-token"}, &secret.Registry{}); got != "file-token" { + t.Fatalf("resolved token = %q, want file-token", got) + } + t.Setenv("GATEWAY_TOKEN", "environment-token") + if got := gatewayResolvedToken(config.ServiceConnection{}, &secret.Registry{}); got != "environment-token" { + t.Fatalf("resolved token = %q, want environment-token", got) + } + if got := gatewayResolvedToken( + config.ServiceConnection{TargetToken: "file-token"}, + &secret.Registry{}, + ); got != "file-token" { + t.Fatalf("explicit target_token should win over the environment, got %q", got) + } +} + type compositionChat struct { gateway.ChatContract snapshot gateway.ChatSnapshot diff --git a/internal/app/archied/gateway.go b/internal/app/archied/gateway.go index c373aaac6..e21c5aea3 100644 --- a/internal/app/archied/gateway.go +++ b/internal/app/archied/gateway.go @@ -23,6 +23,10 @@ type GatewayOptions struct { Config string Overlay string Listen string + // Token is the Bearer [REDACTED] the Gateway server validates for a + // non-loopback listener. Empty falls back to + // [services.gateway].target_token. + Token string } // RunGateway owns conversation persistence, model runtime and tool-provider @@ -81,17 +85,22 @@ func RunGateway(ctx context.Context, options GatewayOptions) error { if err != nil { return err } - host, _, err := net.SplitHostPort(options.Listen) - if err != nil || !net.ParseIP(host).IsLoopback() { - return fmt.Errorf("gateway listen address must use a loopback IP; use a secured tunnel for remote access") + gatewayToken := options.Token + if gatewayToken == "" { + gatewayToken = gatewayResolvedToken(b.cfg.Services.Gateway, b.secrets) + } + //nolint:contextcheck // grpc.StreamServerInterceptor has no context.Context parameter; gatewayrpc.StreamServerInterceptor derives its context from stream.Context() instead + opts, loopback, err := gatewayServerOpts(options.Listen, gatewayToken) + if err != nil { + return err } listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", options.Listen) if err != nil { return fmt.Errorf("listen for gateway: %w", err) } defer listener.Close() - b.log.Info("archie-gateway running", "addr", listener.Addr().String()) - return serveGateway(ctx, listener, contract, b.chatSessionStore) + b.log.Info("archie-gateway running", "addr", listener.Addr().String(), "token_required", !loopback) + return serveGateway(ctx, listener, contract, b.chatSessionStore, opts) } func (b *boot) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskActor) (gateway.ChatContract, error) { @@ -120,8 +129,33 @@ func (b *boot) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskAc return contract, nil } -func serveGateway(ctx context.Context, listener net.Listener, contract gateway.ChatContract, sessions gateway.SessionStore) error { - server := grpc.NewServer() +// gatewayServerOpts applies the transport security boundary: a loopback +// listener is served insecure with no token; any non-loopback address +// requires a Bearer [REDACTED], else the process fails closed. It mirrors +// stateStoreServerOpts, minus the State Store's task-scoped grants: the +// Gateway has one administrative token for all callers. +func gatewayServerOpts(listen, token string) (opts []grpc.ServerOption, loopback bool, err error) { + loopback, err = gatewayrpc.TargetIsLoopback(listen) + if err != nil { + return nil, false, err + } + if loopback { + return nil, true, nil + } + if token == "" { + return nil, false, fmt.Errorf( + "gateway listen address %q is non-loopback; non-loopback exposure requires a Bearer [REDACTED] (--token / [services.gateway].target_token) or TLS", + listen, + ) + } + return []grpc.ServerOption{ + grpc.ChainUnaryInterceptor(gatewayrpc.UnaryServerInterceptor(token)), + grpc.ChainStreamInterceptor(gatewayrpc.StreamServerInterceptor(token)), + }, false, nil +} + +func serveGateway(ctx context.Context, listener net.Listener, contract gateway.ChatContract, sessions gateway.SessionStore, opts []grpc.ServerOption) error { + server := grpc.NewServer(opts...) gatewayrpc.RegisterServer(server, contract, sessions) serveErr := make(chan error, 1) go func() { serveErr <- server.Serve(listener) }() diff --git a/internal/app/archied/gateway_test.go b/internal/app/archied/gateway_test.go new file mode 100644 index 000000000..a8c4ad1fd --- /dev/null +++ b/internal/app/archied/gateway_test.go @@ -0,0 +1,38 @@ +package archied + +import "testing" + +func TestGatewayServerOptsLoopbackIsInsecure(t *testing.T) { + opts, loopback, err := gatewayServerOpts("127.0.0.1:8585", "") + if err != nil { + t.Fatalf("gatewayServerOpts(loopback, no token) error: %v", err) + } + if !loopback { + t.Fatal("loopback listener should report loopback") + } + if len(opts) != 0 { + t.Fatalf("loopback listener should have no server opts, got %d", len(opts)) + } +} + +func TestGatewayServerOptsNonLoopbackRequiresToken(t *testing.T) { + if _, _, err := gatewayServerOpts("0.0.0.0:8585", ""); err == nil { + t.Fatal("non-loopback listener without a token should fail closed") + } + opts, loopback, err := gatewayServerOpts("0.0.0.0:8585", "secret") + if err != nil { + t.Fatalf("non-loopback listener with a token error: %v", err) + } + if loopback { + t.Fatal("non-loopback listener should not report loopback") + } + if len(opts) != 2 { + t.Fatalf("non-loopback listener should install two server options (unary and stream auth interceptors), got %d", len(opts)) + } +} + +func TestGatewayServerOptsMalformedListen(t *testing.T) { + if _, _, err := gatewayServerOpts("not-an-address", ""); err == nil { + t.Fatal("malformed listen address should error") + } +} diff --git a/internal/app/archieui/run.go b/internal/app/archieui/run.go index 47f856233..30c07cb34 100644 --- a/internal/app/archieui/run.go +++ b/internal/app/archieui/run.go @@ -38,7 +38,7 @@ func Run(ctx context.Context, options Options) error { return err } cleanups = append(cleanups, closeState) - chat, closeGateway, err := gatewayrpc.Dial(opts.Gateway.Target) + chat, closeGateway, err := gatewayrpc.Dial(opts.Gateway.Target, opts.Gateway.Token) if err != nil { return err } diff --git a/internal/app/archieui/run_test.go b/internal/app/archieui/run_test.go index 6e52551a8..aab7e183d 100644 --- a/internal/app/archieui/run_test.go +++ b/internal/app/archieui/run_test.go @@ -114,7 +114,7 @@ func TestUIServesDashboardAgainstRemoteContracts(t *testing.T) { t.Fatalf("dial state store: %v", err) } defer closeState() - chatClient, closeGateway, err := gatewayrpc.Dial(gatewayTarget) + chatClient, closeGateway, err := gatewayrpc.Dial(gatewayTarget, "") if err != nil { t.Fatalf("dial gateway: %v", err) } diff --git a/internal/infrastructure/gatewayrpc/auth.go b/internal/infrastructure/gatewayrpc/auth.go new file mode 100644 index 000000000..4121b64c0 --- /dev/null +++ b/internal/infrastructure/gatewayrpc/auth.go @@ -0,0 +1,98 @@ +package gatewayrpc + +import ( + "context" + "crypto/subtle" + "net" + "strings" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// tokenMetadataKey is the gRPC metadata key the Gateway Bearer [REDACTED] +// travels in. Metadata, never a URL, mirroring the State Store's +// token lifecycle (docs/prds/state-store-contract.md §9). +const tokenMetadataKey = "gateway-token" + +// 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. It mirrors +// staterpc.TargetIsLoopback; the two transports keep their own copy so +// neither adapter imports the other. +func TargetIsLoopback(addr string) (bool, error) { + host, _, err := net.SplitHostPort(addr) + if err != nil { + return false, err + } + if strings.EqualFold(host, "localhost") { + return true, nil + } + ip := net.ParseIP(host) + if ip == nil { + return false, nil + } + return ip.IsLoopback(), nil +} + +// validToken compares candidate against the configured token in constant +// time so a timing side channel cannot leak how many bytes matched. +func validToken(token, candidate string) bool { + if token == "" || candidate == "" { + return false + } + return subtle.ConstantTimeCompare([]byte(token), []byte(candidate)) == 1 +} + +// UnaryServerInterceptor validates the Bearer [REDACTED] carried in each unary +// call's metadata, returning codes.Unauthenticated on a missing or wrong +// token. It is installed only for a non-loopback listener; a loopback +// listener serves with no interceptors. +func UnaryServerInterceptor(token string) grpc.UnaryServerInterceptor { + return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + md, ok := metadata.FromIncomingContext(ctx) + if !ok { + return nil, status.Error(codes.Unauthenticated, "missing gateway token") + } + values := md.Get(tokenMetadataKey) + if len(values) == 0 || !validToken(token, values[0]) { + return nil, status.Error(codes.Unauthenticated, "missing or invalid gateway token") + } + return handler(ctx, req) + } +} + +// StreamServerInterceptor is the streaming counterpart of +// UnaryServerInterceptor: the chat Stream RPC is server-streaming, so its +// credential must be checked on the stream context as well. +func StreamServerInterceptor(token string) grpc.StreamServerInterceptor { + return func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + md, _ := metadata.FromIncomingContext(stream.Context()) + values := md.Get(tokenMetadataKey) + if len(values) == 0 || !validToken(token, values[0]) { + return status.Error(codes.Unauthenticated, "missing or invalid gateway token") + } + return handler(srv, stream) + } +} + +// UnaryClientTokenInterceptor attaches token to every outgoing unary call's +// metadata under tokenMetadataKey. +func UnaryClientTokenInterceptor(token string) grpc.UnaryClientInterceptor { + return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + return invoker(metadata.AppendToOutgoingContext(ctx, tokenMetadataKey, token), method, req, reply, cc, opts...) + } +} + +// StreamClientTokenInterceptor attaches token to the outgoing stream's +// context, covering the chat Stream RPC that the unary interceptor cannot +// see. +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/gatewayrpc/auth_test.go b/internal/infrastructure/gatewayrpc/auth_test.go new file mode 100644 index 000000000..0a97c39d1 --- /dev/null +++ b/internal/infrastructure/gatewayrpc/auth_test.go @@ -0,0 +1,118 @@ +package gatewayrpc + +import ( + "context" + "net" + "testing" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/samcharles93/archie-core/internal/gateway" +) + +// authChat is a minimal ChatContract for the auth boundary: only Snapshot +// and Stream are exercised, the rest fall through to the nil embedded +// contract and are never called. +type authChat struct { + gateway.ChatContract + snapshot gateway.ChatSnapshot +} + +func (f *authChat) Snapshot(context.Context) (gateway.ChatSnapshot, error) { + return f.snapshot, nil +} + +func (f *authChat) Stream(context.Context, gateway.Message) (<-chan gateway.ChatEvent, error) { + ch := make(chan gateway.ChatEvent) + close(ch) + return ch, nil +} + +// serveAuth serves the chat contract on a loopback listener with the token +// interceptors installed when token is non-empty, mirroring the standalone +// gateway composition. It returns the dial target. +func serveAuth(t *testing.T, token string) string { + t.Helper() + listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + var opts []grpc.ServerOption + if token != "" { + opts = []grpc.ServerOption{ + grpc.ChainUnaryInterceptor(UnaryServerInterceptor(token)), + grpc.ChainStreamInterceptor(StreamServerInterceptor(token)), + } + } + server := grpc.NewServer(opts...) + RegisterServer(server, &authChat{}) + go func() { _ = server.Serve(listener) }() + t.Cleanup(server.Stop) + return listener.Addr().String() +} + +func TestGatewayTokenRoundTrip(t *testing.T) { + target := serveAuth(t, "correct-token") + client, cleanup, err := Dial(target, "correct-token") + if err != nil { + t.Fatalf("Dial with the correct token: %v", err) + } + defer cleanup() + if _, err := client.Snapshot(t.Context()); err != nil { + t.Fatalf("Snapshot with the correct token: %v", err) + } + events, err := client.Stream(t.Context(), gateway.Message{}) + if err != nil { + t.Fatalf("Stream with the correct token: %v", err) + } + for range events { + } +} + +func TestGatewayTokenMissingIsRejected(t *testing.T) { + target := serveAuth(t, "correct-token") + // A loopback target dials without a credential, so the dial itself + // succeeds; the server rejects the unauthenticated call. + client, cleanup, err := Dial(target, "") + if err != nil { + t.Fatalf("Dial to a loopback target without a token: %v", err) + } + defer cleanup() + if _, err := client.Snapshot(t.Context()); status.Code(err) != codes.Unauthenticated { + t.Fatalf("Snapshot without a token: code = %v, want Unauthenticated (err = %v)", status.Code(err), err) + } +} + +func TestGatewayTokenWrongIsRejected(t *testing.T) { + target := serveAuth(t, "correct-token") + client, cleanup, err := Dial(target, "wrong-token") + if err != nil { + t.Fatalf("Dial with a token: %v", err) + } + defer cleanup() + if _, err := client.Snapshot(t.Context()); status.Code(err) != codes.Unauthenticated { + t.Fatalf("Snapshot with the wrong token: code = %v, want Unauthenticated (err = %v)", status.Code(err), err) + } +} + +func TestGatewayStreamWithoutTokenIsRejected(t *testing.T) { + target := serveAuth(t, "correct-token") + client, cleanup, err := Dial(target, "") + if err != nil { + t.Fatalf("Dial to a loopback target without a token: %v", err) + } + defer cleanup() + events, err := client.Stream(t.Context(), gateway.Message{}) + if err != nil { + t.Fatalf("Stream without a token: %v", err) + } + event, ok := <-events + if !ok { + t.Fatal("Stream without a token closed with no error event") + } + if event.Kind != "error" { + t.Fatalf("Stream without a token: event kind = %q, want error", event.Kind) + } +} diff --git a/internal/infrastructure/gatewayrpc/dial.go b/internal/infrastructure/gatewayrpc/dial.go index 45f27e8c7..badc070bb 100644 --- a/internal/infrastructure/gatewayrpc/dial.go +++ b/internal/infrastructure/gatewayrpc/dial.go @@ -9,20 +9,37 @@ import ( ) // 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. +// archie-gateway process, applying the transport security boundary: a +// loopback target dials insecure with no credential, while a non-loopback +// target requires a Bearer [REDACTED] and fails closed without one. 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) == "" { +// 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. It mirrors staterpc.Dial. +func Dial(target, token string, options ...grpc.DialOption) (*Client, func(), error) { + target = strings.TrimSpace(target) + if 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...) + loopback, err := TargetIsLoopback(target) + if err != nil { + return nil, nil, fmt.Errorf("gateway target must be host:port: %w", err) + } + if !loopback && token == "" { + return nil, nil, fmt.Errorf( + "gateway target %q is non-loopback; non-loopback exposure requires a Bearer [REDACTED] ([services.gateway].target_token / GATEWAY_TOKEN) or TLS", + target, + ) + } + opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())} + if token != "" { + opts = append(opts, + grpc.WithUnaryInterceptor(UnaryClientTokenInterceptor(token)), + grpc.WithStreamInterceptor(StreamClientTokenInterceptor(token)), + ) + } + conn, err := grpc.NewClient(target, append(opts, options...)...) if err != nil { return nil, nil, fmt.Errorf("create gateway client: %w", err) } diff --git a/internal/infrastructure/gatewayrpc/dial_test.go b/internal/infrastructure/gatewayrpc/dial_test.go new file mode 100644 index 000000000..2fea052e0 --- /dev/null +++ b/internal/infrastructure/gatewayrpc/dial_test.go @@ -0,0 +1,67 @@ +package gatewayrpc + +import "testing" + +func TestTargetIsLoopback(t *testing.T) { + tests := []struct { + name string + addr string + want bool + }{ + {"loopback ipv4", "127.0.0.1:8585", true}, + {"loopback ipv6", "[::1]:8585", true}, + {"localhost hostname", "localhost:8585", true}, + {"localhost uppercase", "LOCALHOST:8585", true}, + {"wildcard", "0.0.0.0:8585", false}, + {"private ip", "192.168.1.10:8585", false}, + {"dns name", "gateway.example.com:8585", false}, + {"empty host", ":8585", 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 +// Gateway security rule: a target reachable from the network must present a +// Bearer [REDACTED], so a missing credential stops the dial rather than opening +// an unauthenticated connection. It mirrors staterpc's §9 dial rule. +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:8585", ""); err == nil { + t.Fatal("Dial to a non-loopback target without a token should fail closed") + } + client, cleanup, err := Dial("0.0.0.0:8585", "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:8585", "") + 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") + } +}