diff --git a/internal/app/archiegateway/gateway.go b/internal/app/archiegateway/gateway.go index 9a0313b2f..7a2bc336d 100644 --- a/internal/app/archiegateway/gateway.go +++ b/internal/app/archiegateway/gateway.go @@ -9,10 +9,12 @@ import ( "google.golang.org/grpc" "github.com/samcharles93/archie-core/internal/app/controlplane" + "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" + "github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity" "github.com/samcharles93/archie-core/internal/plugin" ) @@ -98,14 +100,15 @@ const inboundMessageHeadroomBytes = 1 << 20 // request carries a channel attachment's bytes: the channel frontend // downloads the file, and this process -- which runs the turn -- holds no // platform credential to fetch it again. -func gatewayServerOpts(listen, token string) (opts []grpc.ServerOption, loopback bool, err error) { +func gatewayServerOpts(listen, token string, principals access.PrincipalSource) (opts []grpc.ServerOption, loopback bool, err error) { + callers := rpcidentity.Callers{Principals: principals} recv := grpc.MaxRecvMsgSize(messaging.MaxInboundAttachmentBytes + inboundMessageHeadroomBytes) loopback, err = gatewayrpc.TargetIsLoopback(listen) if err != nil { return nil, false, err } if loopback { - return []grpc.ServerOption{recv}, true, nil + return []grpc.ServerOption{recv, grpc.ChainUnaryInterceptor(callers.Unary()), grpc.ChainStreamInterceptor(callers.Stream())}, true, nil } if token == "" { return nil, false, fmt.Errorf( @@ -115,8 +118,8 @@ func gatewayServerOpts(listen, token string) (opts []grpc.ServerOption, loopback } return []grpc.ServerOption{ recv, - grpc.ChainUnaryInterceptor(gatewayrpc.UnaryServerInterceptor(token)), - grpc.ChainStreamInterceptor(gatewayrpc.StreamServerInterceptor(token)), + grpc.ChainUnaryInterceptor(gatewayrpc.UnaryServerInterceptor(token), callers.Unary()), + grpc.ChainStreamInterceptor(gatewayrpc.StreamServerInterceptor(token), callers.Stream()), }, false, nil } diff --git a/internal/app/archiegateway/gateway_runtime.go b/internal/app/archiegateway/gateway_runtime.go index 05550a7d7..cba2f0dd0 100644 --- a/internal/app/archiegateway/gateway_runtime.go +++ b/internal/app/archiegateway/gateway_runtime.go @@ -12,8 +12,10 @@ import ( "github.com/samcharles93/archie-core/internal/buildinfo" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/agent" + "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/domain/taskactions" "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" "github.com/samcharles93/archie-core/internal/taskstate" "github.com/samcharles93/archie-core/internal/tools" ) @@ -221,6 +223,7 @@ func (b *server) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskAct } cfg := b.cfg router := gateway.NewRouter(b.stateStore, nil, "web") + router.Settings = messaging.NewSettingsCommand(controlplanerpc.NewSettingsClient(b.stateStore.ControlPlane())).WithIdentities(b.stateStore) router.Limiter = b.rateLimiter router.Version = fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", buildinfo.Version, buildinfo.Runtime) router.Models = b.chatModels diff --git a/internal/app/archiegateway/server.go b/internal/app/archiegateway/server.go index ca62f9080..e2a57367e 100644 --- a/internal/app/archiegateway/server.go +++ b/internal/app/archiegateway/server.go @@ -132,7 +132,7 @@ func Run(ctx context.Context, options Options) error { token = b.cfg.Services.ResolvedToken(config.ServiceNameGateway, b.secrets.Getenv) } //nolint:contextcheck // grpc.StreamServerInterceptor has no context.Context parameter; gatewayrpc.StreamServerInterceptor derives its context from stream.Context() instead - opts, loopback, err := gatewayServerOpts(listen, token) + opts, loopback, err := gatewayServerOpts(listen, token, b.stateStore) if err != nil { return err } diff --git a/internal/app/archiemessaging/run.go b/internal/app/archiemessaging/run.go index a1508fdfa..e236a2e8c 100644 --- a/internal/app/archiemessaging/run.go +++ b/internal/app/archiemessaging/run.go @@ -81,7 +81,7 @@ func Run(ctx context.Context, o Options) error { return fmt.Errorf("resolve database telegram token: %w", settingsErr) } extensionChannels = openExtensionChannels(ctx, extensions, secrets, log) - settings = messaging.NewSettingsCommand(messagingControlPlane{client: stateStore.ControlPlane()}).WithIdentities(stateStore) + settings = messaging.NewSettingsCommand(controlplanerpc.NewSettingsClient(stateStore.ControlPlane())).WithIdentities(stateStore) channelStatusStore, presenceStore = stateStore, stateStore settingsSource, applyReporter, appliedVersion = controlPlaneClient, reporter, channelVersion updates = controlplanerpc.UpdateService(controlPlaneClient, filepath.Join(cfg.WorkDir, "telegram-update-deferrals.json"), cfg.HealthURL) diff --git a/internal/app/controlplane/chat_settings_test.go b/internal/app/controlplane/chat_settings_test.go new file mode 100644 index 000000000..787ab25e0 --- /dev/null +++ b/internal/app/controlplane/chat_settings_test.go @@ -0,0 +1,143 @@ +package controlplane_test + +import ( + "context" + "net" + "strings" + "testing" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + + "github.com/samcharles93/archie-core/internal/app/controlplane" + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/access" + "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/domain/messaging" + "github.com/samcharles93/archie-core/internal/domain/org" + "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" + "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" + "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore" + "github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity" + "github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps" +) + +func TestWebChatSettingsActor(t *testing.T) { + ctx := t.Context() + db := pgstore.Open(t) + if err := db.BootstrapIdentities(ctx, nil); err != nil { + t.Fatal(err) + } + if err := db.UpgradeDefaultOrg(ctx); err != nil { + t.Fatal(err) + } + steps, err := workflowsteps.NewManager() + if err != nil { + t.Fatal(err) + } + cp, err := controlplane.NewServer(db, steps) + if err != nil { + t.Fatal(err) + } + if _, _, err := cp.ImportConfig(ctx, config.Config{}); err != nil { + t.Fatal(err) + } + state := workflowRPC(t, cp, db) + router := gateway.NewRouter(state, nil, "web") + router.Settings = messaging.NewSettingsCommand(controlplanerpc.NewSettingsClient(state.ControlPlane())).WithIdentities(state) + listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + callers := rpcidentity.Callers{Principals: state} + srv := grpc.NewServer(grpc.ChainUnaryInterceptor(gatewayrpc.UnaryServerInterceptor("gateway-secret"), callers.Unary()), grpc.ChainStreamInterceptor(gatewayrpc.StreamServerInterceptor("gateway-secret"), callers.Stream())) + gatewayrpc.RegisterServer(srv, &gateway.LocalChatAdapter{Router: router}, nil, gatewayrpc.Catalog{}) + go func() { _ = srv.Serve(listener) }() + t.Cleanup(srv.Stop) + person, err := db.PrincipalFor(ctx, identity.OperatorID()) + if err != nil { + t.Fatal(err) + } + tests := []struct { + name, token, sender string + person, write, stream bool + code codes.Code + }{ + {name: "streamed signed-in person", stream: true, token: "gateway-secret", person: true, write: true}, + {name: "streamed wrong service credential", stream: true, token: "wrong", person: true, code: codes.Unauthenticated}, + {name: "signed-in person", token: "gateway-secret", person: true, write: true}, + {name: "message cannot spoof actor", token: "gateway-secret", sender: string(identity.SystemID), person: true, write: true}, + {name: "message alone cannot name a person", token: "gateway-secret", sender: string(identity.OperatorID())}, + {name: "wrong service credential cannot forward a principal", token: "wrong", person: true, code: codes.Unauthenticated}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + conn, err := grpc.NewClient(listener.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithUnaryInterceptor(gatewayrpc.UnaryClientTokenInterceptor(tt.token)), grpc.WithStreamInterceptor(gatewayrpc.StreamClientTokenInterceptor(tt.token))) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + requestCtx := ctx + if tt.person { + requestCtx = access.WithPrincipal(ctx, person) + } + before, err := db.Resource(ctx, string(org.DefaultOrgID), controlplane.ReviewSettingsKind) + if err != nil { + t.Fatal(err) + } + in := messaging.Inbound{Platform: "web", Message: messaging.Message{SenderID: tt.sender, Text: "/settings set review-settings precision_gate=true"}} + client := gatewayrpc.NewClient(conn) + reply, err := settingsReply(t, client, requestCtx, in, tt.stream, tt.code) + if status.Code(err) != tt.code { + t.Fatalf("route error = %v, want %s", err, tt.code) + } + after, err := db.Resource(ctx, string(org.DefaultOrgID), controlplane.ReviewSettingsKind) + if err != nil { + t.Fatal(err) + } + if !tt.write { + if after.Version != before.Version { + t.Fatal("unauthenticated command changed settings") + } + return + } + history, err := db.ResourceHistory(ctx, string(org.DefaultOrgID), controlplane.ReviewSettingsKind, 1) + if err != nil { + t.Fatal(err) + } + if len(history) != 1 { + t.Fatal("settings audit missing") + } + if !strings.Contains(reply.Text, "Updated review-settings") || after.Version != before.Version+1 || history[0].Actor != string(person.IdentityID) { + t.Fatalf("reply %q, version %d -> %d, actor %q", reply.Text, before.Version, after.Version, history[0].Actor) + } + }) + } +} + +func settingsReply(t *testing.T, client *gatewayrpc.Client, ctx context.Context, in messaging.Inbound, stream bool, want codes.Code) (messaging.ChatReply, error) { + t.Helper() + if !stream { + return client.Route(ctx, in) + } + events, err := client.Stream(ctx, in) + if err != nil { + return messaging.ChatReply{}, err + } + var reply messaging.ChatReply + for event := range events { + if event.Kind == "error" { + if want == codes.OK || !strings.Contains(event.Text, "code = "+want.String()) { + t.Fatalf("stream: %s", event.Text) + } + return messaging.ChatReply{}, status.Error(want, event.Text) + } + if event.Kind == "done" { + reply.Text = event.Text + } + } + return reply, nil +} diff --git a/internal/app/controlplane/controlplane.go b/internal/app/controlplane/controlplane.go index 405680346..d067a3a93 100644 --- a/internal/app/controlplane/controlplane.go +++ b/internal/app/controlplane/controlplane.go @@ -219,7 +219,7 @@ func resourceProto(resource storecontract.Resource) *pb.Resource { } // requestOrg is the org a request acts in, derived from the caller's -// principal when the call carried one (staterpc.Callers). +// principal when the call carried one (rpcidentity.Callers). func requestOrg(ctx context.Context) string { return string(org.OrgFromContext(ctx)) } diff --git a/internal/app/controlplane/workflow_org_test.go b/internal/app/controlplane/workflow_org_test.go index b00bd2b24..df13237d5 100644 --- a/internal/app/controlplane/workflow_org_test.go +++ b/internal/app/controlplane/workflow_org_test.go @@ -24,6 +24,7 @@ import ( infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access" "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore" "github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest" + "github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps" "github.com/samcharles93/archie-core/internal/webui" @@ -123,7 +124,7 @@ func workflowRPC(t *testing.T, control *controlplane.Server, db *pgstore.TaskDB) } t.Cleanup(func() { _ = listener.Close() }) grants := &staterpc.TaskGrants{} - callers := staterpc.Callers{Principals: db} + callers := rpcidentity.Callers{Principals: db} srv := grpc.NewServer(grpc.ChainUnaryInterceptor(grants.UnaryInterceptor("test-token"), callers.Unary()), grpc.ChainStreamInterceptor(grants.StreamInterceptor("test-token"), callers.Stream())) staterpc.RegisterServer(srv, staterpc.Deps{ControlPlane: control, Tasks: db, Principals: db, Identities: db}) t.Cleanup(srv.Stop) diff --git a/internal/app/statestore/server.go b/internal/app/statestore/server.go index 0cb2a758e..cd46567a5 100644 --- a/internal/app/statestore/server.go +++ b/internal/app/statestore/server.go @@ -29,6 +29,7 @@ import ( infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access" "github.com/samcharles93/archie-core/internal/infrastructure/postgres" "github.com/samcharles93/archie-core/internal/infrastructure/readiness" + "github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" registry "github.com/samcharles93/archie-core/internal/infrastructure/storepkg" "github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps" @@ -403,9 +404,9 @@ func (b *server) runCredentials(ctx context.Context) (*staterpc.TaskGrants, erro // callers resolves the service and principal of each call against this // store's principals. -func (b *server) callers() staterpc.Callers { +func (b *server) callers() rpcidentity.Callers { ps, _ := b.st.(access.PrincipalSource) - return staterpc.Callers{Principals: ps} + return rpcidentity.Callers{Principals: ps} } // accessDeps wires the policy chain and its denial records from the same @@ -511,7 +512,7 @@ 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, callers staterpc.Callers) (opts []grpc.ServerOption, loopback bool, err error) { +func stateStoreServerOpts(listen, token string, grants *staterpc.TaskGrants, callers rpcidentity.Callers) (opts []grpc.ServerOption, loopback bool, err error) { loopback, err = staterpc.TargetIsLoopback(listen) if err != nil { return nil, false, err diff --git a/internal/domain/messaging/settings.go b/internal/domain/messaging/settings.go index 4906c3048..e359ed5d6 100644 --- a/internal/domain/messaging/settings.go +++ b/internal/domain/messaging/settings.go @@ -13,6 +13,7 @@ import ( "strings" "time" + "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/identity" ) @@ -104,6 +105,9 @@ func (c *SettingsCommand) Execute(ctx context.Context, actor, input string) stri // recorded against. A sender that does not resolve cannot run a command: the // audit record names an identity or the command does not happen. func (c *SettingsCommand) resolveActor(ctx context.Context, subject, actor string) (identity.IdentityID, string) { + if p, ok := access.PrincipalFromContext(ctx); ok && p.IdentityID != "" { + return p.IdentityID, "" + } if strings.TrimSpace(actor) == "" { return "", subject + " require an authenticated Archie identity; this channel cannot resolve one." } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index d4a425590..ef9e91b0d 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -14,6 +14,7 @@ import ( "time" "unicode" + "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/ratelimit" "github.com/samcharles93/archie-core/internal/releaseupdate" @@ -344,7 +345,11 @@ func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, platf reply, err := r.handleCancel(ctx, rest) return reply, true, err case "/settings": - return r.Settings.Execute(ctx, "", rest), true, nil + actor := "" + if principal, ok := access.PrincipalFromContext(ctx); ok { + actor = string(principal.IdentityID) + } + return r.Settings.Execute(ctx, actor, rest), true, nil case "/start": reply, err := r.handleStart() return reply, true, err diff --git a/internal/app/archiemessaging/settings.go b/internal/infrastructure/controlplanerpc/settings.go similarity index 81% rename from internal/app/archiemessaging/settings.go rename to internal/infrastructure/controlplanerpc/settings.go index 689c1141f..0dd832595 100644 --- a/internal/app/archiemessaging/settings.go +++ b/internal/infrastructure/controlplanerpc/settings.go @@ -1,4 +1,4 @@ -package archiemessaging +package controlplanerpc import ( "context" @@ -13,9 +13,15 @@ import ( "github.com/samcharles93/archie-core/internal/domain/messaging" ) -type messagingControlPlane struct{ client pb.ControlPlaneServiceClient } +// SettingsClient adapts control-plane resources for channel settings commands. +type SettingsClient struct{ client pb.ControlPlaneServiceClient } -func (c messagingControlPlane) Catalog(ctx context.Context) ([]messaging.SettingDescriptor, error) { +// NewSettingsClient wraps the existing control-plane contract. +func NewSettingsClient(client pb.ControlPlaneServiceClient) SettingsClient { + return SettingsClient{client: client} +} + +func (c SettingsClient) Catalog(ctx context.Context) ([]messaging.SettingDescriptor, error) { response, err := c.client.Catalog(ctx, &pb.CatalogRequest{}) if err != nil { return nil, settingsRPCError(err) @@ -29,7 +35,7 @@ func (c messagingControlPlane) Catalog(ctx context.Context) ([]messaging.Setting WriteOnly bool `json:"writeOnly"` } `json:"properties"` } - if err := json.Unmarshal([]byte(resource.SchemaJson), &schema); err != nil { + if err := json.Unmarshal([]byte(resource.SchemaJson), &schema); strings.TrimSpace(resource.SchemaJson) != "" && err != nil { return nil, errors.Join(messaging.ErrSettingsValidation, err) } fields := make(map[string]messaging.SettingField, len(schema.Properties)) @@ -45,7 +51,7 @@ func (c messagingControlPlane) Catalog(ctx context.Context) ([]messaging.Setting return descriptors, nil } -func (c messagingControlPlane) Query(ctx context.Context, kind string) (messaging.SettingResource, error) { +func (c SettingsClient) Query(ctx context.Context, kind string) (messaging.SettingResource, error) { response, err := c.client.Query(ctx, &pb.QueryRequest{Kind: kind}) if err != nil { return messaging.SettingResource{}, settingsRPCError(err) @@ -53,7 +59,7 @@ func (c messagingControlPlane) Query(ctx context.Context, kind string) (messagin return settingResource(response.Resource) } -func (c messagingControlPlane) Command(ctx context.Context, command messaging.SettingCommand) (messaging.SettingResource, error) { +func (c SettingsClient) Command(ctx context.Context, command messaging.SettingCommand) (messaging.SettingResource, error) { input := any(command.Value) if command.RawValue != nil { input = command.RawValue diff --git a/internal/infrastructure/gatewayrpc/auth.go b/internal/infrastructure/gatewayrpc/auth.go index f6ec9d252..f4ca61195 100644 --- a/internal/infrastructure/gatewayrpc/auth.go +++ b/internal/infrastructure/gatewayrpc/auth.go @@ -10,6 +10,8 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" + + "github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity" ) // tokenMetadataKey is the gRPC metadata key the Gateway Bearer [REDACTED] @@ -79,7 +81,7 @@ func StreamServerInterceptor(token string) grpc.StreamServerInterceptor { // 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...) + return invoker(metadata.AppendToOutgoingContext(rpcidentity.Outgoing(ctx, "gateway-client"), tokenMetadataKey, token), method, req, reply, cc, opts...) } } @@ -88,6 +90,6 @@ func UnaryClientTokenInterceptor(token string) grpc.UnaryClientInterceptor { // 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...) + return streamer(metadata.AppendToOutgoingContext(rpcidentity.Outgoing(ctx, "gateway-client"), tokenMetadataKey, token), desc, cc, method, opts...) } } diff --git a/internal/infrastructure/rpcidentity/identity.go b/internal/infrastructure/rpcidentity/identity.go new file mode 100644 index 000000000..c7e215351 --- /dev/null +++ b/internal/infrastructure/rpcidentity/identity.go @@ -0,0 +1,99 @@ +// Package rpcidentity attributes authenticated service calls to their principal. +package rpcidentity + +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" +) + +// CallerKey names the service making the call. +const CallerKey = "state-store-caller" + +// PrincipalKey carries the identity a service acts for, when it acts +// for one. +const PrincipalKey = "state-store-principal" + +// Outgoing forwards the context's principal, replacing any stale attribution. +func Outgoing(ctx context.Context, caller string) context.Context { + md, _ := metadata.FromOutgoingContext(ctx) + md = md.Copy() + md.Set(CallerKey, caller) + md.Delete(PrincipalKey) + if p, ok := access.PrincipalFromContext(ctx); ok { + md.Set(PrincipalKey, string(p.IdentityID)) + } + return metadata.NewOutgoingContext(ctx, md) +} + +// 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, CallerKey) + if caller != "" { + ctx = access.WithActor(access.WithSource(ctx, caller), caller) + } + id := first(md, PrincipalKey) + 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) { + 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/auth.go b/internal/infrastructure/staterpc/auth.go index 71ef629b7..60f563267 100644 --- a/internal/infrastructure/staterpc/auth.go +++ b/internal/infrastructure/staterpc/auth.go @@ -4,37 +4,21 @@ 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" + "github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity" ) // tokenMetadataKey is the gRPC metadata key the bearer token travels in. // Metadata, never a URL. const tokenMetadataKey = "state-store-token" -// callerMetadataKey names the service making the call. -const callerMetadataKey = "state-store-caller" - -// 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 { - pairs := []string{callerMetadataKey, caller} - if p, ok := access.PrincipalFromContext(ctx); ok { - pairs = append(pairs, principalMetadataKey, string(p.IdentityID)) - } + ctx = rpcidentity.Outgoing(ctx, caller) if token != "" { - pairs = append(pairs, tokenMetadataKey, token) + ctx = metadata.AppendToOutgoingContext(ctx, tokenMetadataKey, token) } - return metadata.AppendToOutgoingContext(ctx, pairs...) + return ctx } // UnaryClientCredentialInterceptor attaches caller and token to every @@ -52,68 +36,3 @@ func StreamClientCredentialInterceptor(caller, token string) grpc.StreamClientIn return streamer(outgoing(ctx, caller, token), desc, cc, method, opts...) } } - -// 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) { - 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 index 74df3b721..9e9d94e18 100644 --- a/internal/infrastructure/staterpc/callers_test.go +++ b/internal/infrastructure/staterpc/callers_test.go @@ -14,6 +14,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/storecontract" + "github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity" ) // credentials is an in-memory RunCredentialStore. @@ -53,7 +54,7 @@ func TestCallerAttribution(t *testing.T) { if err := grants.register(context.Background(), 7, taskToken, time.Hour); err != nil { t.Fatal(err) } - callers := Callers{Principals: principalsByID{"alice": "acme"}} + callers := rpcidentity.Callers{Principals: principalsByID{"alice": "acme"}} update := &grpc.UnaryServerInfo{FullMethod: pb.StateStoreService_Update_FullMethodName} tests := []struct { @@ -62,9 +63,9 @@ func TestCallerAttribution(t *testing.T) { 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}, + {"service alone acts in the default org", []string{tokenMetadataKey, admin, rpcidentity.CallerKey, "archied"}, "archied", org.DefaultOrgID}, + {"forwarded principal sets actor and org", []string{tokenMetadataKey, admin, rpcidentity.CallerKey, "archie-ui", rpcidentity.PrincipalKey, "alice"}, "alice", "acme"}, + {"task grant cannot claim a principal", []string{tokenMetadataKey, taskToken, rpcidentity.CallerKey, "archie-ui", rpcidentity.PrincipalKey, "alice"}, "task/7", org.DefaultOrgID}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) {