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
This commit is contained in:
1 parent
73d371614b
commit
0ec4ececd5
13 files changed
+453
-33
No files matched your search
@@ -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...)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user