diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 6a6391fe7..188509e58 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -37,6 +37,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/eda/playbook" "github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/domain/presence" "github.com/samcharles93/archie-core/internal/domain/scheduling" "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/workflow" @@ -265,7 +266,7 @@ func (b *boot) openStateStoreAdapter(ctx context.Context) error { if target == "" { return fmt.Errorf("services.state.target is required: archied/archie-gateway no longer own archie.db; the standalone archie-state-store process owns it (docs/prds/state-store-contract.md §12 step 7)") } - client, cleanup, err := servicekit.StateStoreClient(b.cfg.Services, b.secrets) + client, cleanup, err := servicekit.StateStoreClient(presence.Daemon, b.cfg.Services, b.secrets) if err != nil { b.log.Error("state store adapter", "err", err) return err diff --git a/internal/app/archied/status.go b/internal/app/archied/status.go index cb0f77e16..5ebd14b1c 100644 --- a/internal/app/archied/status.go +++ b/internal/app/archied/status.go @@ -31,7 +31,7 @@ func RunStatus(args []string, stdout, stderr io.Writer) int { fmt.Fprintf(stderr, "archied status: %v\n", err) return 1 } - client, cleanup, err := servicekit.StateStoreClient(doc.Config.Services, secret.NewRegistry()) + client, cleanup, err := servicekit.StateStoreClient(presence.Daemon, doc.Config.Services, secret.NewRegistry()) if err != nil { fmt.Fprintf(stderr, "archied status: %v\n", err) return 1 diff --git a/internal/app/archiegateway/server.go b/internal/app/archiegateway/server.go index c8e0c3586..219235eb1 100644 --- a/internal/app/archiegateway/server.go +++ b/internal/app/archiegateway/server.go @@ -170,7 +170,7 @@ func (b *server) openState(ctx context.Context) error { if err := b.claimGatewayOwnership(ctx); err != nil { return err } - client, cleanup, err := servicekit.StateStoreClient(b.cfg.Services, b.secrets) + client, cleanup, err := servicekit.StateStoreClient(presence.Gateway, b.cfg.Services, b.secrets) if err != nil { return fmt.Errorf("state store client: %w", err) } diff --git a/internal/app/archiemessaging/run.go b/internal/app/archiemessaging/run.go index 468404507..c934465ea 100644 --- a/internal/app/archiemessaging/run.go +++ b/internal/app/archiemessaging/run.go @@ -49,7 +49,7 @@ func Run(ctx context.Context, o Options) error { var applyReporter *applystatus.Reporter var appliedVersion int64 if cfg.Options.StateStore.Target != "" { - stateStore, closeClient, dialErr := staterpc.Dial(cfg.Options.StateStore.Target, cfg.Options.StateStore.Token, staterpc.WaitForPeer) + stateStore, closeClient, dialErr := staterpc.Dial(cfg.Options.StateStore.Target, presence.Messaging, cfg.Options.StateStore.Token, staterpc.WaitForPeer) if dialErr != nil { return fmt.Errorf("dial state store control plane (%s): %w", cfg.Options.StateStore.Target, dialErr) } diff --git a/internal/app/archieui/run.go b/internal/app/archieui/run.go index 27c299846..eeeaefc4d 100644 --- a/internal/app/archieui/run.go +++ b/internal/app/archieui/run.go @@ -56,7 +56,7 @@ func Run(ctx context.Context, options Options) error { } }() - tasks, closeState, err := staterpc.Dial(opts.State.Target, opts.State.Token) + tasks, closeState, err := staterpc.Dial(opts.State.Target, presence.UI, opts.State.Token) if err != nil { return err } diff --git a/internal/app/servicekit/statestore.go b/internal/app/servicekit/statestore.go index b663f2c21..8a2bcb210 100644 --- a/internal/app/servicekit/statestore.go +++ b/internal/app/servicekit/statestore.go @@ -6,16 +6,16 @@ import ( "github.com/samcharles93/archie-core/internal/secret" ) -// StateStoreClient dials the State Store gRPC service the daemon's own -// capture/mapping/binding consumers call. Token resolution is the daemon's +// StateStoreClient dials the State Store gRPC service as the caller service. +// 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 staterpc.Dial. Calls wait for the State Store rather than fail while it // is down, so boot order between services does not matter. -func StateStoreClient(services config.Services, secrets *secret.Registry) (*staterpc.Client, func(), error) { +func StateStoreClient(caller string, services config.Services, secrets *secret.Registry) (*staterpc.Client, func(), error) { target, err := services.RequireTarget(config.ServiceNameState) if err != nil { return nil, nil, err } - return staterpc.Dial(target, services.ResolvedToken(config.ServiceNameState, secrets.Getenv), staterpc.WaitForPeer) + return staterpc.Dial(target, caller, services.ResolvedToken(config.ServiceNameState, secrets.Getenv), staterpc.WaitForPeer) } diff --git a/internal/app/statestore/server.go b/internal/app/statestore/server.go index 19e14ff81..37e276c40 100644 --- a/internal/app/statestore/server.go +++ b/internal/app/statestore/server.go @@ -477,7 +477,7 @@ func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants) (op } keepalive := staterpc.ServerKeepaliveOption() if loopback { - return []grpc.ServerOption{keepalive}, true, nil + return []grpc.ServerOption{keepalive, grpc.ChainUnaryInterceptor(staterpc.UnaryActorInterceptor())}, true, nil } if token == "" { return nil, false, fmt.Errorf( @@ -491,7 +491,9 @@ func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants) (op // than the single all-or-nothing token check this replaced. return []grpc.ServerOption{ keepalive, - grpc.ChainUnaryInterceptor(grants.UnaryInterceptor(token)), + // The actor interceptor runs first so a task grant's own attribution + // replaces whatever service name the container claimed. + grpc.ChainUnaryInterceptor(staterpc.UnaryActorInterceptor(), grants.UnaryInterceptor(token)), grpc.ChainStreamInterceptor(grants.StreamInterceptor(token)), }, false, nil } diff --git a/internal/domain/access/actor.go b/internal/domain/access/actor.go new file mode 100644 index 000000000..288e2eb15 --- /dev/null +++ b/internal/domain/access/actor.go @@ -0,0 +1,19 @@ +package access + +import "context" + +type actorContextKey struct{} + +// WithActor attaches who a State Store call is made by, so an audit row +// records the caller the server authenticated rather than a constant. +func WithActor(ctx context.Context, actor string) context.Context { + return context.WithValue(ctx, actorContextKey{}, actor) +} + +// ActorFromContext returns the caller WithActor attached, or "unknown". +func ActorFromContext(ctx context.Context) string { + if actor, ok := ctx.Value(actorContextKey{}).(string); ok && actor != "" { + return actor + } + return "unknown" +} diff --git a/internal/infrastructure/agenttransport/nats/transport.go b/internal/infrastructure/agenttransport/nats/transport.go index 8036828c5..ae464a467 100644 --- a/internal/infrastructure/agenttransport/nats/transport.go +++ b/internal/infrastructure/agenttransport/nats/transport.go @@ -85,7 +85,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)") } - state, closeState, err := staterpc.Dial(config.StateStoreURL, config.StateStoreToken) + state, closeState, err := staterpc.Dial(config.StateStoreURL, "archie-agent", config.StateStoreToken) if err != nil { conn.Close() return nil, fmt.Errorf("connect state store: %w", err) diff --git a/internal/infrastructure/postgres/access.go b/internal/infrastructure/postgres/access.go index 62ac6aa86..3811c92de 100644 --- a/internal/infrastructure/postgres/access.go +++ b/internal/infrastructure/postgres/access.go @@ -107,8 +107,8 @@ func (s *Store) PutPolicy(ctx context.Context, p access.Policy) (int64, error) { RecordKey: auditKey(p), NewValue: textJSON(p.Text), RecordVersion: version, - Actor: "archied", - Source: "archied", + Actor: access.ActorFromContext(ctx), + Source: access.ActorFromContext(ctx), RequestID: "", }) }) diff --git a/internal/infrastructure/staterpc/auth.go b/internal/infrastructure/staterpc/auth.go index 5a9bdc411..8a3fc2464 100644 --- a/internal/infrastructure/staterpc/auth.go +++ b/internal/infrastructure/staterpc/auth.go @@ -5,22 +5,51 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/metadata" + + "github.com/samcharles93/archie-core/internal/domain/access" ) // tokenMetadataKey is the gRPC metadata key the bearer token travels in. // Metadata, never a URL. const tokenMetadataKey = "state-store-token" -// UnaryClientTokenInterceptor attaches token to every outgoing call. -func UnaryClientTokenInterceptor(token string) grpc.UnaryClientInterceptor { +// callerMetadataKey names the service making the call. +const callerMetadataKey = "state-store-caller" + +// outgoing stamps the caller's service name and, when set, its token. +func outgoing(ctx context.Context, caller, token string) context.Context { + ctx = metadata.AppendToOutgoingContext(ctx, callerMetadataKey, caller) + if token != "" { + ctx = metadata.AppendToOutgoingContext(ctx, tokenMetadataKey, token) + } + return ctx +} + +// UnaryClientCredentialInterceptor attaches caller and token to every +// outgoing call. +func UnaryClientCredentialInterceptor(caller, 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...) + return invoker(outgoing(ctx, caller, token), method, req, reply, cc, opts...) } } -// StreamClientTokenInterceptor attaches token to every outgoing stream. -func StreamClientTokenInterceptor(token string) grpc.StreamClientInterceptor { +// StreamClientCredentialInterceptor attaches caller and token to every +// outgoing stream. +func StreamClientCredentialInterceptor(caller, 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...) + return streamer(outgoing(ctx, caller, token), desc, cc, method, opts...) + } +} + +// UnaryActorInterceptor puts the calling service on the request context for +// audit. It runs after authentication, which is what makes the name +// trustworthy: only holders of the instance credential reach a write. +func UnaryActorInterceptor() grpc.UnaryServerInterceptor { + return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + md, _ := metadata.FromIncomingContext(ctx) + if callers := md.Get(callerMetadataKey); len(callers) > 0 { + ctx = access.WithActor(ctx, callers[0]) + } + return handler(ctx, req) } } diff --git a/internal/infrastructure/staterpc/dial.go b/internal/infrastructure/staterpc/dial.go index a0be8e7ff..48234a24c 100644 --- a/internal/infrastructure/staterpc/dial.go +++ b/internal/infrastructure/staterpc/dial.go @@ -11,10 +11,10 @@ import ( "google.golang.org/grpc/keepalive" ) -// Dial returns a State Store client for target. A loopback target dials -// insecure; any other target requires a token. The cleanup closes the -// connection. -func Dial(target, token string, options ...grpc.DialOption) (*Client, func(), error) { +// Dial returns a State Store client for target, attributed to the caller +// service. A loopback target dials insecure; any other target requires a +// token. The cleanup closes the connection. +func Dial(target, caller, token string, options ...grpc.DialOption) (*Client, func(), error) { target = strings.TrimSpace(target) if target == "" { return nil, nil, fmt.Errorf("state store target is required") @@ -36,16 +36,11 @@ func Dial(target, token string, options ...grpc.DialOption) (*Client, func(), er // GetInstalledPackage returns the whole layer, which for an extension is // a plugin binary well past gRPC's default 4 MiB receive limit. grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxPackageResponseBytes)), - } - if 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)), - ) + grpc.WithUnaryInterceptor(UnaryClientCredentialInterceptor(caller, token)), + grpc.WithStreamInterceptor(StreamClientCredentialInterceptor(caller, token)), } conn, err := grpc.NewClient(target, append(opts, options...)...) if err != nil { diff --git a/internal/infrastructure/staterpc/task_grants.go b/internal/infrastructure/staterpc/task_grants.go index d1a77b634..bb9491577 100644 --- a/internal/infrastructure/staterpc/task_grants.go +++ b/internal/infrastructure/staterpc/task_grants.go @@ -6,6 +6,7 @@ import ( "crypto/sha256" "crypto/subtle" "encoding/hex" + "fmt" "sync" "time" @@ -15,6 +16,7 @@ import ( "google.golang.org/grpc/status" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" + "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/workflow/task" ) @@ -170,7 +172,7 @@ func (g *TaskGrants) UnaryInterceptor(adminToken string) grpc.UnaryServerInterce if !authorizesTaskScopedCall(info.FullMethod, req, taskID) { return nil, status.Error(codes.PermissionDenied, "task grant does not authorize this operation") } - return handler(ctx, req) + return handler(access.WithActor(ctx, fmt.Sprintf("task/%d", taskID)), req) } }