From dde38264724b9a5974bb8d08209d6a70b040eb9f Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 4 Oct 2026 15:54:22 +1100 Subject: [PATCH] feat(staterpc): the State Store derives org and actor from the principal archie-ui forwards --- internal/app/controlplane/controlplane.go | 20 ++--- internal/app/statestore/server.go | 25 ++++-- internal/domain/access/actor.go | 30 ++++++- internal/infrastructure/postgres/access.go | 2 +- internal/infrastructure/staterpc/access.go | 2 +- internal/infrastructure/staterpc/auth.go | 88 ++++++++++++++++--- .../infrastructure/staterpc/callers_test.go | 66 ++++++++++++++ internal/infrastructure/staterpc/packages.go | 11 +-- .../infrastructure/staterpc/task_grants.go | 3 + internal/webui/api_access_policies.go | 4 +- internal/webui/authorize.go | 21 +---- 11 files changed, 214 insertions(+), 58 deletions(-) create mode 100644 internal/infrastructure/staterpc/callers_test.go diff --git a/internal/app/controlplane/controlplane.go b/internal/app/controlplane/controlplane.go index f76b70296..89b5ed307 100644 --- a/internal/app/controlplane/controlplane.go +++ b/internal/app/controlplane/controlplane.go @@ -11,6 +11,7 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" + "github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" @@ -78,7 +79,7 @@ func (s *Server) Query(ctx context.Context, request *pb.QueryRequest) (*pb.Query if _, ok := s.definitions[request.GetKind()]; !ok { return nil, status.Error(codes.NotFound, "resource not found") } - resource, err := s.store.Resource(ctx, requestOrg(request.GetOrgId()), request.Kind) + resource, err := s.store.Resource(ctx, requestOrg(ctx), request.Kind) if err != nil { return nil, mapError(err) } @@ -96,7 +97,7 @@ func (s *Server) History(ctx context.Context, request *pb.HistoryRequest) (*pb.H if limit <= 0 || limit > defaultHistoryLimit { limit = defaultHistoryLimit } - revisions, err := s.store.ResourceHistory(ctx, requestOrg(request.GetOrgId()), request.Kind, limit) + revisions, err := s.store.ResourceHistory(ctx, requestOrg(ctx), request.Kind, limit) if err != nil { return nil, mapError(err) } @@ -149,7 +150,7 @@ func (s *Server) Command(ctx context.Context, request *pb.CommandRequest) (*pb.C if err != nil { return nil, mapError(err) } - resource, err := s.store.PutResource(ctx, storecontract.ResourceWrite{OrgID: requestOrg(request.GetOrgId()), Kind: request.Kind, Value: value, Actor: request.Actor, Source: request.Source, RequestID: request.RequestId, ExpectedVersion: request.ExpectedVersion, At: time.Now().UTC()}) + resource, err := s.store.PutResource(ctx, storecontract.ResourceWrite{OrgID: requestOrg(ctx), Kind: request.Kind, Value: value, Actor: request.Actor, Source: request.Source, RequestID: request.RequestId, ExpectedVersion: request.ExpectedVersion, At: time.Now().UTC()}) if err != nil { return nil, mapError(err) } @@ -164,7 +165,7 @@ func (s *Server) Watch(request *pb.WatchRequest, stream pb.ControlPlaneService_W ticker := time.NewTicker(250 * time.Millisecond) defer ticker.Stop() for { - resource, err := s.store.Resource(stream.Context(), requestOrg(request.GetOrgId()), request.Kind) + resource, err := s.store.Resource(stream.Context(), requestOrg(stream.Context()), request.Kind) if err == nil && resource.Version > version { if err := stream.Send(&pb.WatchResponse{Resource: resourceProto(resource)}); err != nil { return err @@ -185,13 +186,10 @@ func resourceProto(resource storecontract.Resource) *pb.Resource { return &pb.Resource{OrgId: resource.OrgID, Kind: resource.Kind, Version: resource.Version, ValueJson: resource.Value, UpdatedAt: timestamp(resource.At)} } -// requestOrg is the org a request acts in. Until the caller's org is derived -// server-side (access), a request that names none acts in the default org. -func requestOrg(orgID string) string { - if orgID == "" { - return storecontract.DefaultOrgID - } - return orgID +// requestOrg is the org a request acts in, derived from the caller's +// principal when the call carried one (staterpc.Callers). +func requestOrg(ctx context.Context) string { + return string(org.OrgFromContext(ctx)) } func timestamp(value time.Time) *timestamppb.Timestamp { diff --git a/internal/app/statestore/server.go b/internal/app/statestore/server.go index 4debfaa4d..15dd64934 100644 --- a/internal/app/statestore/server.go +++ b/internal/app/statestore/server.go @@ -117,7 +117,7 @@ func Run(ctx context.Context, options Options) error { //nolint:cyclop // the co } grants := &staterpc.TaskGrants{} //nolint:contextcheck // grpc.StreamServerInterceptor has no context.Context parameter; TaskGrants.StreamInterceptor derives its context from stream.Context() instead - opts, loopback, err := stateStoreServerOpts(listen, token, grants) + opts, loopback, err := stateStoreServerOpts(listen, token, grants, b.callers()) if err != nil { return err } @@ -370,6 +370,13 @@ func (b *server) executionDeps(deps *staterpc.Deps) { } } +// callers resolves the service and principal of each call against this +// store's principals. +func (b *server) callers() staterpc.Callers { + ps, _ := b.st.(access.PrincipalSource) + return staterpc.Callers{Principals: ps} +} + // accessDeps wires the policy chain and its denial records from the same // store. A store without them -- one that owns // no tenant boundary yet -- degrades the access RPCs rather than failing the @@ -470,14 +477,18 @@ func (b *server) startOptionalSurfaces(ctx context.Context, options Options) err // as a remote one (staterpc.Dial installs the client keepalive on every target, // loopback included), and grpc's default policy would answer their idle // watches with GOAWAY too_many_pings. See staterpc.ServerKeepaliveOption. -func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants) (opts []grpc.ServerOption, loopback bool, err error) { +func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants, callers staterpc.Callers) (opts []grpc.ServerOption, loopback bool, err error) { loopback, err = staterpc.TargetIsLoopback(listen) if err != nil { return nil, false, err } keepalive := staterpc.ServerKeepaliveOption() if loopback { - return []grpc.ServerOption{keepalive, grpc.ChainUnaryInterceptor(staterpc.UnaryActorInterceptor())}, true, nil + return []grpc.ServerOption{ + keepalive, + grpc.ChainUnaryInterceptor(callers.Unary()), + grpc.ChainStreamInterceptor(callers.Stream()), + }, true, nil } if token == "" { return nil, false, fmt.Errorf( @@ -491,10 +502,10 @@ func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants) (op // than the single all-or-nothing token check this replaced. return []grpc.ServerOption{ keepalive, - // 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)), + // Authentication runs before attribution: callers trusts the metadata + // only of a call the grants check admitted as the instance. + grpc.ChainUnaryInterceptor(grants.UnaryInterceptor(token), callers.Unary()), + grpc.ChainStreamInterceptor(grants.StreamInterceptor(token), callers.Stream()), }, false, nil } diff --git a/internal/domain/access/actor.go b/internal/domain/access/actor.go index 288e2eb15..8527710ca 100644 --- a/internal/domain/access/actor.go +++ b/internal/domain/access/actor.go @@ -2,7 +2,11 @@ package access import "context" -type actorContextKey struct{} +type ( + actorContextKey struct{} + sourceContextKey struct{} + principalContextKey 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. @@ -17,3 +21,27 @@ func ActorFromContext(ctx context.Context) string { } return "unknown" } + +// WithSource attaches the service a call came through. +func WithSource(ctx context.Context, source string) context.Context { + return context.WithValue(ctx, sourceContextKey{}, source) +} + +// SourceFromContext returns the service WithSource attached, or "unknown". +func SourceFromContext(ctx context.Context) string { + if source, ok := ctx.Value(sourceContextKey{}).(string); ok && source != "" { + return source + } + return "unknown" +} + +// WithPrincipal attaches the principal a request acts as. +func WithPrincipal(ctx context.Context, p Principal) context.Context { + return context.WithValue(ctx, principalContextKey{}, p) +} + +// PrincipalFromContext returns the principal WithPrincipal attached. +func PrincipalFromContext(ctx context.Context) (Principal, bool) { + p, ok := ctx.Value(principalContextKey{}).(Principal) + return p, ok +} diff --git a/internal/infrastructure/postgres/access.go b/internal/infrastructure/postgres/access.go index 3811c92de..7c7171e54 100644 --- a/internal/infrastructure/postgres/access.go +++ b/internal/infrastructure/postgres/access.go @@ -108,7 +108,7 @@ func (s *Store) PutPolicy(ctx context.Context, p access.Policy) (int64, error) { NewValue: textJSON(p.Text), RecordVersion: version, Actor: access.ActorFromContext(ctx), - Source: access.ActorFromContext(ctx), + Source: access.SourceFromContext(ctx), RequestID: "", }) }) diff --git a/internal/infrastructure/staterpc/access.go b/internal/infrastructure/staterpc/access.go index e2642af14..fa8d05a40 100644 --- a/internal/infrastructure/staterpc/access.go +++ b/internal/infrastructure/staterpc/access.go @@ -154,7 +154,7 @@ func (s *server) ListDenials(ctx context.Context, request *pb.ListDenialsRequest if limit <= 0 || limit > 1000 { limit = 100 } - values, err := s.deps.Denials.ListDenials(ctx, org.OrgID(request.OrgId), limit) + values, err := s.deps.Denials.ListDenials(ctx, org.OrgFromContext(ctx), limit) if err != nil { return nil, accessStatus(err) } diff --git a/internal/infrastructure/staterpc/auth.go b/internal/infrastructure/staterpc/auth.go index 8a3fc2464..71ef629b7 100644 --- a/internal/infrastructure/staterpc/auth.go +++ b/internal/infrastructure/staterpc/auth.go @@ -4,9 +4,13 @@ import ( "context" "google.golang.org/grpc" + "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" "github.com/samcharles93/archie-core/internal/domain/access" + "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/domain/org" ) // tokenMetadataKey is the gRPC metadata key the bearer token travels in. @@ -16,13 +20,21 @@ const tokenMetadataKey = "state-store-token" // callerMetadataKey names the service making the call. const callerMetadataKey = "state-store-caller" -// outgoing stamps the caller's service name and, when set, its token. +// principalMetadataKey carries the identity a service acts for, when it acts +// for one. +const principalMetadataKey = "state-store-principal" + +// outgoing stamps the caller's service name, the principal on ctx when there +// is one, and the token when set. func outgoing(ctx context.Context, caller, token string) context.Context { - ctx = metadata.AppendToOutgoingContext(ctx, callerMetadataKey, caller) - if token != "" { - ctx = metadata.AppendToOutgoingContext(ctx, tokenMetadataKey, token) + pairs := []string{callerMetadataKey, caller} + if p, ok := access.PrincipalFromContext(ctx); ok { + pairs = append(pairs, principalMetadataKey, string(p.IdentityID)) } - return ctx + if token != "" { + pairs = append(pairs, tokenMetadataKey, token) + } + return metadata.AppendToOutgoingContext(ctx, pairs...) } // UnaryClientCredentialInterceptor attaches caller and token to every @@ -41,15 +53,67 @@ func StreamClientCredentialInterceptor(caller, token string) grpc.StreamClientIn } } -// 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 { +// Callers resolves who a call is made by. It runs after authentication, +// which is what makes the metadata trustworthy: only holders of the instance +// credential reach it with their metadata intact (a task grant's is +// stripped). A call naming a principal acts in that principal's org; any +// other acts in the default org. +type Callers struct { + Principals access.PrincipalSource +} + +func (c Callers) resolve(ctx context.Context) (context.Context, error) { + md, _ := metadata.FromIncomingContext(ctx) + caller := first(md, callerMetadataKey) + if caller != "" { + ctx = access.WithActor(access.WithSource(ctx, caller), caller) + } + id := first(md, principalMetadataKey) + if id == "" { + return ctx, nil + } + if c.Principals == nil { + return nil, status.Error(codes.Unavailable, "principals unavailable") + } + p, err := c.Principals.PrincipalFor(ctx, identity.IdentityID(id)) + if err != nil { + return nil, status.Errorf(codes.Unavailable, "resolve principal: %v", err) + } + return org.WithOrg(access.WithActor(access.WithPrincipal(ctx, p), id), p.Org), nil +} + +// Unary attributes unary calls. +func (c Callers) Unary() 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]) + ctx, err := c.resolve(ctx) + if err != nil { + return nil, err } return handler(ctx, req) } } + +// Stream attributes streams. +func (c Callers) Stream() grpc.StreamServerInterceptor { + return func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + ctx, err := c.resolve(stream.Context()) + if err != nil { + return err + } + return handler(srv, attributedStream{ServerStream: stream, ctx: ctx}) + } +} + +type attributedStream struct { + grpc.ServerStream + ctx context.Context //nolint:containedctx // grpc.ServerStream exposes its context only through Context() +} + +func (s attributedStream) Context() context.Context { return s.ctx } + +func first(md metadata.MD, key string) string { + if values := md.Get(key); len(values) > 0 { + return values[0] + } + return "" +} diff --git a/internal/infrastructure/staterpc/callers_test.go b/internal/infrastructure/staterpc/callers_test.go new file mode 100644 index 000000000..1385110f3 --- /dev/null +++ b/internal/infrastructure/staterpc/callers_test.go @@ -0,0 +1,66 @@ +package staterpc + +import ( + "context" + "strings" + "testing" + + "google.golang.org/grpc" + "google.golang.org/grpc/metadata" + + 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/identity" + "github.com/samcharles93/archie-core/internal/domain/org" +) + +type principalsByID map[identity.IdentityID]org.OrgID + +func (p principalsByID) PrincipalFor(_ context.Context, id identity.IdentityID) (access.Principal, error) { + return access.Principal{IdentityID: id, Org: p[id]}, nil +} + +// TestCallerAttribution pins who a call acts as: the instance credential's +// metadata is trusted, a task grant's is not. +func TestCallerAttribution(t *testing.T) { + const admin = "admin-token" + taskToken := strings.Repeat("ab", 32) + grants := &TaskGrants{} + if err := grants.register(7, taskToken, 3600e9); err != nil { + t.Fatal(err) + } + callers := Callers{Principals: principalsByID{"alice": "acme"}} + update := &grpc.UnaryServerInfo{FullMethod: pb.StateStoreService_Update_FullMethodName} + + tests := []struct { + name string + md []string + wantActor string + wantOrg org.OrgID + }{ + {"service alone acts in the default org", []string{tokenMetadataKey, admin, callerMetadataKey, "archied"}, "archied", org.DefaultOrgID}, + {"forwarded principal sets actor and org", []string{tokenMetadataKey, admin, callerMetadataKey, "archie-ui", principalMetadataKey, "alice"}, "alice", "acme"}, + {"task grant cannot claim a principal", []string{tokenMetadataKey, taskToken, callerMetadataKey, "archie-ui", principalMetadataKey, "alice"}, "task/7", org.DefaultOrgID}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(tt.md...)) + var gotActor string + var gotOrg org.OrgID + handler := func(ctx context.Context, _ any) (any, error) { + gotActor, gotOrg = access.ActorFromContext(ctx), org.OrgFromContext(ctx) + return nil, nil + } + chained := func(ctx context.Context, req any) (any, error) { + return callers.Unary()(ctx, req, update, handler) + } + req := &pb.UpdateRequest{Task: &pb.Task{Id: 7}} + if _, err := grants.UnaryInterceptor(admin)(ctx, req, update, chained); err != nil { + t.Fatal(err) + } + if gotActor != tt.wantActor || gotOrg != tt.wantOrg { + t.Fatalf("got actor %q org %q, want %q %q", gotActor, gotOrg, tt.wantActor, tt.wantOrg) + } + }) + } +} diff --git a/internal/infrastructure/staterpc/packages.go b/internal/infrastructure/staterpc/packages.go index b0b394d99..9a166efef 100644 --- a/internal/infrastructure/staterpc/packages.go +++ b/internal/infrastructure/staterpc/packages.go @@ -8,6 +8,7 @@ import ( "google.golang.org/grpc/status" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" + "github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/storepkg" ) @@ -15,7 +16,7 @@ func (s *server) InstallPackage(ctx context.Context, request *pb.InstallPackageR if s.deps.Packages == nil { return nil, status.Error(codes.Unavailable, "package store unavailable") } - p, err := s.deps.Packages.InstallPackage(ctx, request.GetOrgId(), request.GetName(), request.GetReference(), request.GetDigest()) + p, err := s.deps.Packages.InstallPackage(ctx, string(org.OrgFromContext(ctx)), request.GetName(), request.GetReference(), request.GetDigest()) if err != nil { return nil, s.logErr("InstallPackage", err) } @@ -26,7 +27,7 @@ func (s *server) GetInstalledPackage(ctx context.Context, request *pb.GetInstall if s.deps.Packages == nil { return nil, status.Error(codes.Unavailable, "package store unavailable") } - p, err := s.deps.Packages.GetInstalled(ctx, request.GetOrgId(), request.GetName()) + p, err := s.deps.Packages.GetInstalled(ctx, string(org.OrgFromContext(ctx)), request.GetName()) if err != nil { return nil, s.logErr("GetInstalledPackage", err) } @@ -37,7 +38,7 @@ func (s *server) ListInstalledPackages(ctx context.Context, request *pb.ListInst if s.deps.Packages == nil { return nil, status.Error(codes.Unavailable, "package store unavailable") } - packages, err := s.deps.Packages.ListInstalled(ctx, request.GetOrgId()) + packages, err := s.deps.Packages.ListInstalled(ctx, string(org.OrgFromContext(ctx))) if err != nil { return nil, s.logErr("ListInstalledPackages", err) } @@ -52,7 +53,7 @@ func (s *server) AcceptPackageAuthority(ctx context.Context, request *pb.AcceptP if s.deps.Packages == nil { return nil, status.Error(codes.Unavailable, "package store unavailable") } - p, err := s.deps.Packages.AcceptPackageAuthority(ctx, request.GetOrgId(), request.GetName(), authorityValue(request.GetAccepted())) + p, err := s.deps.Packages.AcceptPackageAuthority(ctx, string(org.OrgFromContext(ctx)), request.GetName(), authorityValue(request.GetAccepted())) if err != nil { return nil, s.logErr("AcceptPackageAuthority", err) } @@ -63,7 +64,7 @@ func (s *server) RemoveInstalledPackage(ctx context.Context, request *pb.RemoveI if s.deps.Packages == nil { return nil, status.Error(codes.Unavailable, "package store unavailable") } - if err := s.deps.Packages.RemoveInstalled(ctx, request.GetOrgId(), request.GetName()); err != nil { + if err := s.deps.Packages.RemoveInstalled(ctx, string(org.OrgFromContext(ctx)), request.GetName()); err != nil { return nil, s.logErr("RemoveInstalledPackage", err) } return &pb.RemoveInstalledPackageResponse{}, nil diff --git a/internal/infrastructure/staterpc/task_grants.go b/internal/infrastructure/staterpc/task_grants.go index bb9491577..99029ec22 100644 --- a/internal/infrastructure/staterpc/task_grants.go +++ b/internal/infrastructure/staterpc/task_grants.go @@ -172,6 +172,9 @@ 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") } + // A container's metadata is its own claim: drop it so no later + // interceptor attributes the call to a service or principal. + ctx = metadata.NewIncomingContext(ctx, metadata.MD{}) return handler(access.WithActor(ctx, fmt.Sprintf("task/%d", taskID)), req) } } diff --git a/internal/webui/api_access_policies.go b/internal/webui/api_access_policies.go index 49b18d126..9ad4a8040 100644 --- a/internal/webui/api_access_policies.go +++ b/internal/webui/api_access_policies.go @@ -11,7 +11,7 @@ import ( // policyOrg is the org a policy request acts in: the caller's. func policyOrg(r *http.Request) org.OrgID { - if principal, ok := RequestPrincipal(r.Context()); ok { + if principal, ok := access.PrincipalFromContext(r.Context()); ok { return principal.Org } return access.SharedTokenOwner().Org @@ -115,7 +115,7 @@ func shippedPolicyIDs() []string { // instanceOwner reports whether the request acts as the instance owner: the // shared-token principal of a single-operator install. func instanceOwner(r *http.Request) bool { - principal, ok := RequestPrincipal(r.Context()) + principal, ok := access.PrincipalFromContext(r.Context()) if !ok { principal = access.SharedTokenOwner() } diff --git a/internal/webui/authorize.go b/internal/webui/authorize.go index 667a6d02a..8ba4cf7d6 100644 --- a/internal/webui/authorize.go +++ b/internal/webui/authorize.go @@ -10,20 +10,6 @@ import ( "github.com/samcharles93/archie-core/internal/domain/org" ) -// principalContextKey carries the assembled principal of a request. -type principalContextKey struct{} - -// WithRequestPrincipal attaches the principal a request was authorized for. -func WithPrincipal(ctx context.Context, p access.Principal) context.Context { - return context.WithValue(ctx, principalContextKey{}, p) -} - -// RequestPrincipal returns the principal a request was authorized as. -func RequestPrincipal(ctx context.Context) (access.Principal, bool) { - value, ok := ctx.Value(principalContextKey{}).(access.Principal) - return value, ok -} - // authorize wraps h with the policy chain. Optional: a server with no // Authorizer keeps the credential check as the whole gate, which is the // documented behaviour of an install that has not built the chain. @@ -60,10 +46,9 @@ func (s *Server) authorize(h http.Handler) http.Handler { http.Error(w, "forbidden", http.StatusForbidden) return } - // The org the request acts in is the principal's, attached on the same - // context the handler receives so every control-plane call downstream - // inherits it (org.OrgFromContext). - h.ServeHTTP(w, r.WithContext(org.WithOrg(WithPrincipal(r.Context(), principal), principal.Org))) + // The principal rides the context into every State Store call, which + // derives the org it acts in from it. + h.ServeHTTP(w, r.WithContext(org.WithOrg(access.WithPrincipal(r.Context(), principal), principal.Org))) }) }