From d7178250aef8e892ab64d66cc76a6d869420067f Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Wed, 30 Sep 2026 04:01:52 +1000 Subject: [PATCH 1/2] feat(controlplane): carry the caller org from the request principal The storage and wire contract already key resources by (org, kind), but no caller sent an org, so every request acted in the default org. The org now travels on the request context: webui's authorize middleware attaches the verified principal's org, and one request-constructor per wire shape (controlplanerpc's Query/History/Watch/CommandRequest) stamps it back, so a call site cannot send the wrong org and a new one cannot forget it. No behaviour change today: the shared token's principal is the default org's owner, no production path creates another org, and a context with no principal yields DefaultOrgID (what the server already derived from an empty org_id). --- internal/app/archied/state_store_recovery.go | 5 +- internal/app/archiemessaging/settings.go | 5 +- internal/app/controlplane/client.go | 20 ++--- internal/app/controlplane/client_org_test.go | 85 +++++++++++++++++++ .../app/controlplane/workflow_enablement.go | 3 +- internal/domain/org/context.go | 24 ++++++ internal/domain/org/context_test.go | 49 +++++++++++ .../infrastructure/controlplanerpc/client.go | 2 +- .../infrastructure/controlplanerpc/request.go | 37 ++++++++ internal/webui/api_control_plane.go | 9 +- internal/webui/api_workflow_enablement.go | 7 +- internal/webui/authorize.go | 5 +- internal/webui/authorize_test.go | 52 ++++++++++++ internal/webui/live_hub.go | 3 +- 14 files changed, 280 insertions(+), 26 deletions(-) create mode 100644 internal/app/controlplane/client_org_test.go create mode 100644 internal/domain/org/context.go create mode 100644 internal/domain/org/context_test.go create mode 100644 internal/infrastructure/controlplanerpc/request.go diff --git a/internal/app/archied/state_store_recovery.go b/internal/app/archied/state_store_recovery.go index a4d448a3e..f13393b6b 100644 --- a/internal/app/archied/state_store_recovery.go +++ b/internal/app/archied/state_store_recovery.go @@ -30,6 +30,7 @@ import ( pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" + "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" ) // The audit identity every offline rollback records. A rollback is one more @@ -146,7 +147,7 @@ func replayRevision(ctx context.Context, resources controlplane.ResourceStore, o if err != nil { return "", err } - replaced, err := server.Command(ctx, &pb.CommandRequest{ + replaced, err := server.Command(ctx, controlplanerpc.CommandRequest(ctx, &pb.CommandRequest{ Kind: options.Kind, Command: "replace", ValueJson: revision.Value, @@ -154,7 +155,7 @@ func replayRevision(ctx context.Context, resources controlplane.ResourceStore, o Actor: OfflineRollbackActor, Source: OfflineRollbackSource, RequestId: fmt.Sprintf("recovery-rollback-%s-%d", options.Kind, time.Now().UTC().UnixNano()), - }) + })) if err != nil { return "", fmt.Errorf("replay %s at revision %d: %w", options.Kind, revision.Version, err) } diff --git a/internal/app/archiemessaging/settings.go b/internal/app/archiemessaging/settings.go index 689c1141f..806d44ebf 100644 --- a/internal/app/archiemessaging/settings.go +++ b/internal/app/archiemessaging/settings.go @@ -11,6 +11,7 @@ import ( pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" "github.com/samcharles93/archie-core/internal/domain/messaging" + "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" ) type messagingControlPlane struct{ client pb.ControlPlaneServiceClient } @@ -46,7 +47,7 @@ func (c messagingControlPlane) Catalog(ctx context.Context) ([]messaging.Setting } func (c messagingControlPlane) Query(ctx context.Context, kind string) (messaging.SettingResource, error) { - response, err := c.client.Query(ctx, &pb.QueryRequest{Kind: kind}) + response, err := c.client.Query(ctx, controlplanerpc.QueryRequest(ctx, kind)) if err != nil { return messaging.SettingResource{}, settingsRPCError(err) } @@ -62,7 +63,7 @@ func (c messagingControlPlane) Command(ctx context.Context, command messaging.Se if err != nil { return messaging.SettingResource{}, errors.Join(messaging.ErrSettingsValidation, err) } - response, err := c.client.Command(ctx, &pb.CommandRequest{Kind: command.Kind, Command: "replace", ValueJson: value, ExpectedVersion: command.ExpectedVersion, RequestId: command.RequestID, Actor: command.Actor, Source: command.Source}) + response, err := c.client.Command(ctx, controlplanerpc.CommandRequest(ctx, &pb.CommandRequest{Kind: command.Kind, Command: "replace", ValueJson: value, ExpectedVersion: command.ExpectedVersion, RequestId: command.RequestID, Actor: command.Actor, Source: command.Source})) if err != nil { return messaging.SettingResource{}, settingsRPCError(err) } diff --git a/internal/app/controlplane/client.go b/internal/app/controlplane/client.go index 0d650114c..8547fe245 100644 --- a/internal/app/controlplane/client.go +++ b/internal/app/controlplane/client.go @@ -70,7 +70,7 @@ func (c *Client) Catalog(ctx context.Context) ([]*pb.ResourceDescriptor, error) } func (c *WorkflowDefinitionsClient) WorkflowDefinitions(ctx context.Context) (workflow.WorkflowDefinitionCollection, int64, error) { - response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: WorkflowDefinitionsKind}) + response, err := c.rpc.Query(ctx, controlplanerpc.QueryRequest(ctx, WorkflowDefinitionsKind)) if err != nil { return workflow.WorkflowDefinitionCollection{}, 0, controlplanerpc.ClientError(err) } @@ -90,7 +90,7 @@ func (c *WorkflowDefinitionsClient) ReplaceWorkflowDefinitions(ctx context.Conte if err != nil { return 0, err } - response, err := c.rpc.Command(ctx, &pb.CommandRequest{Kind: WorkflowDefinitionsKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID}) + response, err := c.rpc.Command(ctx, controlplanerpc.CommandRequest(ctx, &pb.CommandRequest{Kind: WorkflowDefinitionsKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID})) if err != nil { return 0, controlplanerpc.ClientError(err) } @@ -98,7 +98,7 @@ func (c *WorkflowDefinitionsClient) ReplaceWorkflowDefinitions(ctx context.Conte } func (c *Client) WorkflowExecutionSettings(ctx context.Context) (workflow.ExecutionSettings, int64, error) { - response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: WorkflowExecutionSettingsKind}) + response, err := c.rpc.Query(ctx, controlplanerpc.QueryRequest(ctx, WorkflowExecutionSettingsKind)) if err != nil { return workflow.ExecutionSettings{}, 0, controlplanerpc.ClientError(err) } @@ -114,7 +114,7 @@ func (c *Client) ReplaceWorkflowExecutionSettings(ctx context.Context, settings if err != nil { return 0, err } - response, err := c.rpc.Command(ctx, &pb.CommandRequest{Kind: WorkflowExecutionSettingsKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID}) + response, err := c.rpc.Command(ctx, controlplanerpc.CommandRequest(ctx, &pb.CommandRequest{Kind: WorkflowExecutionSettingsKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID})) if err != nil { return 0, controlplanerpc.ClientError(err) } @@ -122,7 +122,7 @@ func (c *Client) ReplaceWorkflowExecutionSettings(ctx context.Context, settings } func (c *Client) WatchWorkflowExecutionSettings(ctx context.Context, afterVersion int64) (<-chan AppliedSettings, error) { - stream, err := c.rpc.Watch(ctx, &pb.WatchRequest{Kind: WorkflowExecutionSettingsKind, AfterVersion: afterVersion}) + stream, err := c.rpc.Watch(ctx, controlplanerpc.WatchRequest(ctx, WorkflowExecutionSettingsKind, afterVersion)) if err != nil { return nil, controlplanerpc.ClientError(err) } @@ -152,7 +152,7 @@ type AppliedResource struct { // refused to decode -- the store answered with that version, and resuming // before it would re-offer it on every reconnect. func (c *Client) WatchResource(ctx context.Context, kind string, afterVersion int64) (<-chan AppliedResource, error) { - stream, err := c.rpc.Watch(ctx, &pb.WatchRequest{Kind: kind, AfterVersion: afterVersion}) + stream, err := c.rpc.Watch(ctx, controlplanerpc.WatchRequest(ctx, kind, afterVersion)) if err != nil { return nil, controlplanerpc.ClientError(err) } @@ -168,7 +168,7 @@ type AppliedSettings struct { } func (c *Client) Personas(ctx context.Context) (agent.PersonaCollection, int64, error) { - response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: PersonasKind}) + response, err := c.rpc.Query(ctx, controlplanerpc.QueryRequest(ctx, PersonasKind)) if err != nil { return agent.PersonaCollection{}, 0, controlplanerpc.ClientError(err) } @@ -183,7 +183,7 @@ type AppliedPersonas struct { } func (c *Client) WatchPersonas(ctx context.Context, afterVersion int64) (<-chan AppliedPersonas, error) { - stream, err := c.rpc.Watch(ctx, &pb.WatchRequest{Kind: PersonasKind, AfterVersion: afterVersion}) + stream, err := c.rpc.Watch(ctx, controlplanerpc.WatchRequest(ctx, PersonasKind, afterVersion)) if err != nil { return nil, controlplanerpc.ClientError(err) } @@ -241,7 +241,7 @@ func sendUpdate[T any](ctx context.Context, out chan<- T, update T) bool { } func (c *Client) Schedules(ctx context.Context) ([]scheduling.JobSpec, int64, error) { - response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: SchedulesKind}) + response, err := c.rpc.Query(ctx, controlplanerpc.QueryRequest(ctx, SchedulesKind)) if err != nil { return nil, 0, controlplanerpc.ClientError(err) } @@ -257,7 +257,7 @@ func (c *Client) ReplaceSchedules(ctx context.Context, jobs []scheduling.JobSpec if err != nil { return 0, err } - response, err := c.rpc.Command(ctx, &pb.CommandRequest{Kind: SchedulesKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID}) + response, err := c.rpc.Command(ctx, controlplanerpc.CommandRequest(ctx, &pb.CommandRequest{Kind: SchedulesKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID})) if err != nil { return 0, controlplanerpc.ClientError(err) } diff --git a/internal/app/controlplane/client_org_test.go b/internal/app/controlplane/client_org_test.go new file mode 100644 index 000000000..1c964b92f --- /dev/null +++ b/internal/app/controlplane/client_org_test.go @@ -0,0 +1,85 @@ +package controlplane + +import ( + "context" + "io" + "testing" + + "google.golang.org/grpc" + + pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" + "github.com/samcharles93/archie-core/internal/domain/org" +) + +// orgRecordingClient is the rpc end that records the org of every request it +// is handed, so a test can read back what the client put on the wire. +type orgRecordingClient struct { + queryOrg string + commandOrg string + watchOrg string +} + +func (*orgRecordingClient) Catalog(context.Context, *pb.CatalogRequest, ...grpc.CallOption) (*pb.CatalogResponse, error) { + panic("Catalog is not part of the org-stamping path") +} + +func (c *orgRecordingClient) Query(_ context.Context, in *pb.QueryRequest, _ ...grpc.CallOption) (*pb.QueryResponse, error) { + c.queryOrg = in.GetOrgId() + return &pb.QueryResponse{Resource: &pb.Resource{Kind: in.GetKind()}}, nil +} + +func (*orgRecordingClient) History(context.Context, *pb.HistoryRequest, ...grpc.CallOption) (*pb.HistoryResponse, error) { + panic("History is not part of the org-stamping path") +} + +func (*orgRecordingClient) Audit(context.Context, *pb.AuditRequest, ...grpc.CallOption) (*pb.AuditResponse, error) { + return &pb.AuditResponse{}, nil +} + +func (c *orgRecordingClient) Command(_ context.Context, in *pb.CommandRequest, _ ...grpc.CallOption) (*pb.CommandResponse, error) { + c.commandOrg = in.GetOrgId() + return &pb.CommandResponse{Resource: &pb.Resource{Version: 1}}, nil +} + +func (c *orgRecordingClient) Watch(_ context.Context, in *pb.WatchRequest, _ ...grpc.CallOption) (grpc.ServerStreamingClient[pb.WatchResponse], error) { + c.watchOrg = in.GetOrgId() + return eofWatchStream{}, nil +} + +// eofWatchStream is the client end of a stream that ends before it carries +// anything: the watch under test only builds the request. +type eofWatchStream struct{ grpc.ClientStream } + +func (eofWatchStream) Recv() (*pb.WatchResponse, error) { return nil, io.EOF } + +func TestClientStampsCallerOrgOnEveryRequestShape(t *testing.T) { + tests := []struct { + name string + ctx context.Context + want string + }{ + {name: "no org on the context is the default org", ctx: context.Background(), want: string(org.DefaultOrgID)}, + {name: "org on the context travels on the wire", ctx: org.WithOrg(context.Background(), "acme"), want: "acme"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rpc := &orgRecordingClient{} + client := NewRPCClient(rpc) + + if _, _, err := client.Query(tt.ctx, ChannelSettingsKind, func([]byte) error { return nil }); err != nil { + t.Fatalf("Query: %v", err) + } + if _, err := client.ReplaceSchedules(tt.ctx, nil, 0, "actor", "source", "request"); err != nil { + t.Fatalf("ReplaceSchedules: %v", err) + } + if _, err := client.WatchResource(tt.ctx, WorkflowExecutionSettingsKind, 0); err != nil { + t.Fatalf("WatchResource: %v", err) + } + + if rpc.queryOrg != tt.want || rpc.commandOrg != tt.want || rpc.watchOrg != tt.want { + t.Fatalf("wire orgs = query %q command %q watch %q, want %q each", + rpc.queryOrg, rpc.commandOrg, rpc.watchOrg, tt.want) + } + }) + } +} diff --git a/internal/app/controlplane/workflow_enablement.go b/internal/app/controlplane/workflow_enablement.go index cdedee6cb..fe9978efd 100644 --- a/internal/app/controlplane/workflow_enablement.go +++ b/internal/app/controlplane/workflow_enablement.go @@ -5,7 +5,6 @@ import ( "encoding/json" "github.com/samcharles93/archie-core/internal/config" - 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/workflow/task" "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" @@ -28,7 +27,7 @@ func workflowEnablementDefinition() Definition { // WorkflowEnablement returns which workflows each org has disabled. func (c *Client) WorkflowEnablement(ctx context.Context) (task.WorkflowEnablement, error) { - response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: WorkflowEnablementKind}) + response, err := c.rpc.Query(ctx, controlplanerpc.QueryRequest(ctx, WorkflowEnablementKind)) if err != nil { return task.WorkflowEnablement{}, controlplanerpc.ClientError(err) } diff --git a/internal/domain/org/context.go b/internal/domain/org/context.go new file mode 100644 index 000000000..97e83744d --- /dev/null +++ b/internal/domain/org/context.go @@ -0,0 +1,24 @@ +package org + +import "context" + +// orgContextKey is the unexported key the acting org travels under. A named +// struct type, not a string, so no other package can collide with it. +type orgContextKey struct{} + +// WithOrg attaches the org a request acts in. Every control-plane request +// reads it back with OrgFromContext, so the org reaches the wire from one +// place: the context the caller's principal put it on. +func WithOrg(ctx context.Context, id OrgID) context.Context { + return context.WithValue(ctx, orgContextKey{}, id) +} + +// OrgFromContext returns the org a request acts in, or DefaultOrgID when the +// context carries none. DefaultOrgID is the single-operator install's org and +// the org every record written before orgs existed belongs to. +func OrgFromContext(ctx context.Context) OrgID { + if id, ok := ctx.Value(orgContextKey{}).(OrgID); ok && id != "" { + return id + } + return DefaultOrgID +} diff --git a/internal/domain/org/context_test.go b/internal/domain/org/context_test.go new file mode 100644 index 000000000..955b210a9 --- /dev/null +++ b/internal/domain/org/context_test.go @@ -0,0 +1,49 @@ +package org + +import ( + "context" + "testing" +) + +// foreignContextKey stands in for another package's key: a value stored under +// it must never be read back as the org. +type foreignContextKey struct{} + +func TestOrgFromContext(t *testing.T) { + tests := []struct { + name string + ctx context.Context + want OrgID + }{ + {name: "unset is the default org", ctx: context.Background(), want: DefaultOrgID}, + {name: "set org", ctx: WithOrg(context.Background(), "acme"), want: "acme"}, + { + name: "inner org overrides an outer one", + ctx: WithOrg(WithOrg(context.Background(), "outer"), "inner"), + want: "inner", + }, + { + name: "nil stored value is the default org", + ctx: context.WithValue(context.Background(), orgContextKey{}, nil), + want: DefaultOrgID, + }, + { + name: "a value of a foreign type is the default org", + ctx: context.WithValue(context.Background(), orgContextKey{}, "acme"), + want: DefaultOrgID, + }, + { + name: "a value under a foreign key is the default org", + ctx: context.WithValue(context.Background(), foreignContextKey{}, OrgID("acme")), + want: DefaultOrgID, + }, + {name: "empty org is the default org", ctx: WithOrg(context.Background(), ""), want: DefaultOrgID}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := OrgFromContext(tt.ctx); got != tt.want { + t.Fatalf("OrgFromContext() = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/internal/infrastructure/controlplanerpc/client.go b/internal/infrastructure/controlplanerpc/client.go index 96da28943..91a307279 100644 --- a/internal/infrastructure/controlplanerpc/client.go +++ b/internal/infrastructure/controlplanerpc/client.go @@ -60,7 +60,7 @@ type ResourceReader interface { } func (c *Client) Query(ctx context.Context, kind string, decode func([]byte) error) (int64, bool, error) { - response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: kind}) + response, err := c.rpc.Query(ctx, QueryRequest(ctx, kind)) if err != nil { mapped := ClientError(err) if errors.Is(mapped, ErrNotFound) { diff --git a/internal/infrastructure/controlplanerpc/request.go b/internal/infrastructure/controlplanerpc/request.go new file mode 100644 index 000000000..3c8c492bb --- /dev/null +++ b/internal/infrastructure/controlplanerpc/request.go @@ -0,0 +1,37 @@ +package controlplanerpc + +import ( + "context" + + pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" + "github.com/samcharles93/archie-core/internal/domain/org" +) + +// Every control-plane request acts in one org's copy of a resource. The org +// travels on the request context (org.WithOrg), attached once by whatever +// established the caller's principal, and these constructors are the one place +// it is read back: a call site cannot send the wrong org, and a new call site +// cannot forget it. org.OrgFromContext yields the default org when the context +// carries none, so a process with no principal still acts where it always did. + +// QueryRequest builds a resource query for the caller's org. +func QueryRequest(ctx context.Context, kind string) *pb.QueryRequest { + return &pb.QueryRequest{Kind: kind, OrgId: string(org.OrgFromContext(ctx))} +} + +// HistoryRequest builds an audit-history request for the caller's org. +func HistoryRequest(ctx context.Context, kind string) *pb.HistoryRequest { + return &pb.HistoryRequest{Kind: kind, OrgId: string(org.OrgFromContext(ctx))} +} + +// WatchRequest builds a resource watch for the caller's org. +func WatchRequest(ctx context.Context, kind string, afterVersion int64) *pb.WatchRequest { + return &pb.WatchRequest{Kind: kind, AfterVersion: afterVersion, OrgId: string(org.OrgFromContext(ctx))} +} + +// CommandRequest stamps the caller's org onto a command request the caller +// assembled, whose remaining fields differ per command. +func CommandRequest(ctx context.Context, request *pb.CommandRequest) *pb.CommandRequest { + request.OrgId = string(org.OrgFromContext(ctx)) + return request +} diff --git a/internal/webui/api_control_plane.go b/internal/webui/api_control_plane.go index a7687628d..02c42a5cd 100644 --- a/internal/webui/api_control_plane.go +++ b/internal/webui/api_control_plane.go @@ -11,6 +11,7 @@ import ( "google.golang.org/grpc/status" controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" + "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" ) type controlPlaneCommandRequest struct { @@ -63,7 +64,7 @@ func (s *Server) handleControlPlaneQuery(w http.ResponseWriter, r *http.Request) http.Error(w, "control plane unavailable", http.StatusServiceUnavailable) return } - response, err := s.ControlPlane.Query(r.Context(), &controlpb.QueryRequest{Kind: r.PathValue("kind")}) + response, err := s.ControlPlane.Query(r.Context(), controlplanerpc.QueryRequest(r.Context(), r.PathValue("kind"))) if err != nil { writeControlPlaneError(w, err) return @@ -76,7 +77,7 @@ func (s *Server) handleControlPlaneHistory(w http.ResponseWriter, r *http.Reques http.Error(w, "control plane unavailable", http.StatusServiceUnavailable) return } - response, err := s.ControlPlane.History(r.Context(), &controlpb.HistoryRequest{Kind: r.PathValue("kind")}) + response, err := s.ControlPlane.History(r.Context(), controlplanerpc.HistoryRequest(r.Context(), r.PathValue("kind"))) if err != nil { writeControlPlaneError(w, err) return @@ -111,11 +112,11 @@ func (s *Server) handleControlPlaneCommand(w http.ResponseWriter, r *http.Reques http.Error(w, "cannot create request ID", http.StatusInternalServerError) return } - response, err := s.ControlPlane.Command(r.Context(), &controlpb.CommandRequest{ + response, err := s.ControlPlane.Command(r.Context(), controlplanerpc.CommandRequest(r.Context(), &controlpb.CommandRequest{ Kind: r.PathValue("kind"), Command: r.PathValue("command"), ValueJson: request.Value, ExpectedVersion: request.ExpectedVersion, Actor: string(audit.ActorID), Source: audit.Source, RequestId: audit.RequestID, - }) + })) if err != nil { writeControlPlaneError(w, err) return diff --git a/internal/webui/api_workflow_enablement.go b/internal/webui/api_workflow_enablement.go index dab001e98..3001e5121 100644 --- a/internal/webui/api_workflow_enablement.go +++ b/internal/webui/api_workflow_enablement.go @@ -9,6 +9,7 @@ import ( controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" "github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/workflow/task" + "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" ) const workflowEnablementKind = "workflow-enablement" @@ -19,7 +20,7 @@ func (s *Server) workflowEnablement(ctx context.Context) (task.WorkflowEnablemen if s.ControlPlane == nil { return task.WorkflowEnablement{}, 0, nil } - response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: workflowEnablementKind}) + response, err := s.ControlPlane.Query(ctx, controlplanerpc.QueryRequest(ctx, workflowEnablementKind)) if err != nil { return task.WorkflowEnablement{}, 0, err } @@ -78,11 +79,11 @@ func (s *Server) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) { http.Error(w, "cannot create request ID", http.StatusInternalServerError) return } - if _, err := s.ControlPlane.Command(r.Context(), &controlpb.CommandRequest{ + if _, err := s.ControlPlane.Command(r.Context(), controlplanerpc.CommandRequest(r.Context(), &controlpb.CommandRequest{ Kind: workflowEnablementKind, Command: "replace", ValueJson: value, ExpectedVersion: version, Actor: string(audit.ActorID), Source: audit.Source, RequestId: audit.RequestID, - }); err != nil { + })); err != nil { writeControlPlaneError(w, err) return } diff --git a/internal/webui/authorize.go b/internal/webui/authorize.go index d3fabe915..0365cc59c 100644 --- a/internal/webui/authorize.go +++ b/internal/webui/authorize.go @@ -84,7 +84,10 @@ func (s *Server) authorize(h http.Handler) http.Handler { http.Error(w, "forbidden", http.StatusForbidden) return } - h.ServeHTTP(w, r.WithContext(WithPrincipal(r.Context(), principal))) + // 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))) }) } diff --git a/internal/webui/authorize_test.go b/internal/webui/authorize_test.go index a3f9e96c2..f51ac2b01 100644 --- a/internal/webui/authorize_test.go +++ b/internal/webui/authorize_test.go @@ -49,6 +49,58 @@ func newAccessServer(t *testing.T, engine access.Authorizer, denials access.Deni return &Server{Access: engine, Principals: nil, Denials: denials, Token: ""} } +// stubPrincipalSource answers with one fixed principal: the middleware test +// only needs to see that principal's org reach the request context. +type stubPrincipalSource struct{ principal access.Principal } + +func (s stubPrincipalSource) PrincipalFor(context.Context, identity.IdentityID) (access.Principal, error) { + return s.principal, nil +} + +func orgEcho(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(org.OrgFromContext(r.Context()))) +} + +// TestAuthorizeAttachesPrincipalOrgToRequestContext: the org a control-plane +// call acts in is the principal's, and it travels on the context the handler +// receives -- so every downstream request inherits it without naming it. +func TestAuthorizeAttachesPrincipalOrgToRequestContext(t *testing.T) { + namedOrg := access.Principal{ + IdentityID: testActingIdentity.ID, + Kind: identity.KindUser, + Org: "acme", + Memberships: []org.Membership{{IdentityID: testActingIdentity.ID, OrgID: "acme", Role: org.RoleOwner}}, + } + tests := []struct { + name string + principal access.Principal + acting bool + want org.OrgID + }{ + {name: "shared token acts in the default org", principal: TokenOwnerPrincipal(), want: org.DefaultOrgID}, + {name: "an identity acts in its own org", principal: namedOrg, acting: true, want: "acme"}, + {name: "an identity in the default org yields the default", principal: TokenOwnerPrincipal(), acting: true, want: org.DefaultOrgID}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := &Server{Access: &fakeAuthorizer{decision: access.Allowed()}, Principals: stubPrincipalSource{tt.principal}} + h := s.authorize(http.HandlerFunc(orgEcho)) + ctx := t.Context() + if tt.acting { + ctx = WithActingIdentity(ctx, testActingIdentity) + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("authorized request served %d, want 200", rec.Code) + } + if got := rec.Body.String(); got != string(tt.want) { + t.Fatalf("request org = %q, want %q", got, tt.want) + } + }) + } +} + func TestAuthorizeNilEngineServesEverything(t *testing.T) { s := &Server{} h := s.authorize(http.HandlerFunc(handlerEcho)) diff --git a/internal/webui/live_hub.go b/internal/webui/live_hub.go index 37aea4728..119c14b77 100644 --- a/internal/webui/live_hub.go +++ b/internal/webui/live_hub.go @@ -10,6 +10,7 @@ import ( controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" ) // liveUpdate is one topic's payload. Only durable tasks and the bounded log @@ -116,7 +117,7 @@ func (s *Server) watchResource(ctx context.Context, kind string) { for ctx.Err() == nil { started := time.Now() progressed := false - stream, err := s.ControlPlane.Watch(ctx, &controlpb.WatchRequest{Kind: kind, AfterVersion: version}) + stream, err := s.ControlPlane.Watch(ctx, controlplanerpc.WatchRequest(ctx, kind, version)) if err == nil { for ctx.Err() == nil { response, recvErr := stream.Recv() From fb0424b72931c727b6b9346f19cc3a277f33ace4 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Wed, 30 Sep 2026 07:24:09 +1000 Subject: [PATCH 2/2] fix(test): a table case holds the org, not a context containedctx rejects a struct field of type context.Context, and both new table tests stored one. Each case now carries what the caller put on the context -- a builder in the org test, the org id in the client test -- and builds the context inside the subtest. --- internal/app/controlplane/client_org_test.go | 23 ++++++++---- internal/domain/org/context_test.go | 39 +++++++++++--------- 2 files changed, 37 insertions(+), 25 deletions(-) diff --git a/internal/app/controlplane/client_org_test.go b/internal/app/controlplane/client_org_test.go index 1c964b92f..660d5544b 100644 --- a/internal/app/controlplane/client_org_test.go +++ b/internal/app/controlplane/client_org_test.go @@ -53,26 +53,33 @@ type eofWatchStream struct{ grpc.ClientStream } func (eofWatchStream) Recv() (*pb.WatchResponse, error) { return nil, io.EOF } func TestClientStampsCallerOrgOnEveryRequestShape(t *testing.T) { + // The table holds the org, not a context: a stored context.Context field is + // what containedctx rejects, and each case only needs to say what the caller + // put on its context. tests := []struct { - name string - ctx context.Context - want string + name string + orgID string + want string }{ - {name: "no org on the context is the default org", ctx: context.Background(), want: string(org.DefaultOrgID)}, - {name: "org on the context travels on the wire", ctx: org.WithOrg(context.Background(), "acme"), want: "acme"}, + {name: "no org on the context is the default org", want: string(org.DefaultOrgID)}, + {name: "org on the context travels on the wire", orgID: "acme", want: "acme"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctx := context.Background() + if tt.orgID != "" { + ctx = org.WithOrg(ctx, org.OrgID(tt.orgID)) + } rpc := &orgRecordingClient{} client := NewRPCClient(rpc) - if _, _, err := client.Query(tt.ctx, ChannelSettingsKind, func([]byte) error { return nil }); err != nil { + if _, _, err := client.Query(ctx, ChannelSettingsKind, func([]byte) error { return nil }); err != nil { t.Fatalf("Query: %v", err) } - if _, err := client.ReplaceSchedules(tt.ctx, nil, 0, "actor", "source", "request"); err != nil { + if _, err := client.ReplaceSchedules(ctx, nil, 0, "actor", "source", "request"); err != nil { t.Fatalf("ReplaceSchedules: %v", err) } - if _, err := client.WatchResource(tt.ctx, WorkflowExecutionSettingsKind, 0); err != nil { + if _, err := client.WatchResource(ctx, WorkflowExecutionSettingsKind, 0); err != nil { t.Fatalf("WatchResource: %v", err) } diff --git a/internal/domain/org/context_test.go b/internal/domain/org/context_test.go index 955b210a9..32f4f3fc8 100644 --- a/internal/domain/org/context_test.go +++ b/internal/domain/org/context_test.go @@ -10,38 +10,43 @@ import ( type foreignContextKey struct{} func TestOrgFromContext(t *testing.T) { + // build derives each case's context from a fresh background one. The table + // holds no context.Context field on purpose: a stored context is what + // containedctx rejects, and a builder keeps every case readable without one. tests := []struct { - name string - ctx context.Context - want OrgID + name string + build func(context.Context) context.Context + want OrgID }{ - {name: "unset is the default org", ctx: context.Background(), want: DefaultOrgID}, - {name: "set org", ctx: WithOrg(context.Background(), "acme"), want: "acme"}, + {name: "unset is the default org", build: func(ctx context.Context) context.Context { return ctx }, want: DefaultOrgID}, + {name: "set org", build: func(ctx context.Context) context.Context { return WithOrg(ctx, "acme") }, want: "acme"}, { - name: "inner org overrides an outer one", - ctx: WithOrg(WithOrg(context.Background(), "outer"), "inner"), - want: "inner", + name: "inner org overrides an outer one", + build: func(ctx context.Context) context.Context { return WithOrg(WithOrg(ctx, "outer"), "inner") }, + want: "inner", }, { - name: "nil stored value is the default org", - ctx: context.WithValue(context.Background(), orgContextKey{}, nil), - want: DefaultOrgID, + name: "nil stored value is the default org", + build: func(ctx context.Context) context.Context { return context.WithValue(ctx, orgContextKey{}, nil) }, + want: DefaultOrgID, }, { - name: "a value of a foreign type is the default org", - ctx: context.WithValue(context.Background(), orgContextKey{}, "acme"), - want: DefaultOrgID, + name: "a value of a foreign type is the default org", + build: func(ctx context.Context) context.Context { return context.WithValue(ctx, orgContextKey{}, "acme") }, + want: DefaultOrgID, }, { name: "a value under a foreign key is the default org", - ctx: context.WithValue(context.Background(), foreignContextKey{}, OrgID("acme")), + build: func(ctx context.Context) context.Context { + return context.WithValue(ctx, foreignContextKey{}, OrgID("acme")) + }, want: DefaultOrgID, }, - {name: "empty org is the default org", ctx: WithOrg(context.Background(), ""), want: DefaultOrgID}, + {name: "empty org is the default org", build: func(ctx context.Context) context.Context { return WithOrg(ctx, "") }, want: DefaultOrgID}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := OrgFromContext(tt.ctx); got != tt.want { + if got := OrgFromContext(tt.build(context.Background())); got != tt.want { t.Fatalf("OrgFromContext() = %q, want %q", got, tt.want) } })