From 5891d581cbe24c03d769a3b17c6af8802984df37 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Wed, 30 Sep 2026 07:33:16 +1000 Subject: [PATCH] fix(webui): the workflow handlers act in the caller's org The definitions query was built by hand, so it carried no org and the server resolved the default one, while the enablement document read beside it and the enablement write went to the default org outright. A caller in a non-default org therefore read one org's definitions beside another org's enablement, and toggled that other org's workflows. workflowCollection now builds its query with controlplanerpc.QueryRequest, and the three enablement reads and the write use org.OrgFromContext, so every one of them names the org the principal put on the request context. --- internal/webui/api_control_plane_test.go | 7 +- internal/webui/api_workflow_enablement.go | 7 +- .../webui/api_workflow_enablement_test.go | 49 +++++++ internal/webui/api_workflows.go | 15 +- internal/webui/api_workflows_test.go | 135 ++++++++++++++++++ 5 files changed, 200 insertions(+), 13 deletions(-) diff --git a/internal/webui/api_control_plane_test.go b/internal/webui/api_control_plane_test.go index 6de1d804b..77982839a 100644 --- a/internal/webui/api_control_plane_test.go +++ b/internal/webui/api_control_plane_test.go @@ -20,8 +20,12 @@ import ( ) type controlPlaneClientStub struct { - command *controlpb.CommandRequest + command *controlpb.CommandRequest + // query is the resource a kind-less Query falls back to; queries is every + // request Query was handed, so a test can read back the org each one + // carried. query *controlpb.Resource + queries []*controlpb.QueryRequest history *controlpb.HistoryRequest revisions []*controlpb.Revision audit *controlpb.AuditRequest @@ -38,6 +42,7 @@ func (f *controlPlaneClientStub) Catalog(context.Context, *controlpb.CatalogRequ } func (f *controlPlaneClientStub) Query(_ context.Context, request *controlpb.QueryRequest, _ ...grpc.CallOption) (*controlpb.QueryResponse, error) { + f.queries = append(f.queries, request) if resource, ok := f.resources[request.Kind]; ok { return &controlpb.QueryResponse{Resource: resource}, f.err } diff --git a/internal/webui/api_workflow_enablement.go b/internal/webui/api_workflow_enablement.go index 3001e5121..c9889206b 100644 --- a/internal/webui/api_workflow_enablement.go +++ b/internal/webui/api_workflow_enablement.go @@ -38,9 +38,8 @@ type workflowEnabledRequest struct { Enabled bool `json:"enabled"` } -// handleWorkflowEnabled enables or disables a workflow for the dashboard's -// org. Every dashboard caller acts in the default org until access resolves a -// caller's own. +// handleWorkflowEnabled enables or disables a workflow for the caller's org +// (org.OrgFromContext). func (s *Server) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) { if !s.authorizeTaskMutation(w, r) { return @@ -69,7 +68,7 @@ func (s *Server) handleWorkflowEnabled(w http.ResponseWriter, r *http.Request) { http.Error(w, "workflow enablement unavailable", http.StatusServiceUnavailable) return } - value, err := json.Marshal(enablement.SetEnabled(org.DefaultOrgID, id, request.Enabled)) + value, err := json.Marshal(enablement.SetEnabled(org.OrgFromContext(r.Context()), id, request.Enabled)) if err != nil { http.Error(w, "encode workflow enablement", http.StatusInternalServerError) return diff --git a/internal/webui/api_workflow_enablement_test.go b/internal/webui/api_workflow_enablement_test.go index adf0166c5..03548d0a0 100644 --- a/internal/webui/api_workflow_enablement_test.go +++ b/internal/webui/api_workflow_enablement_test.go @@ -6,8 +6,57 @@ import ( "testing" 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" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" ) +// TestWorkflowEnabledWritesTheCallersOrg: enabling a workflow writes the +// caller's org's enablement document, and leaves the other org's exactly as it +// found it -- otherwise a caller in one org toggles another org's workflows. +func TestWorkflowEnabledWritesTheCallersOrg(t *testing.T) { + // Both orgs have the workflow disabled, so the write has to name the org it + // turns on rather than the state it happens to leave behind. + const enablement = `{"orgs":{"default":{"disabled":["implement"]},"acme":{"disabled":["implement"]}}}` + tests := []struct { + name string + orgID org.OrgID + want org.OrgID + other org.OrgID + }{ + {name: "a caller resolved into acme", orgID: "acme", want: "acme", other: org.DefaultOrgID}, + {name: "no org on the context is the default org", want: org.DefaultOrgID, other: "acme"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + srv := newTestServer(t) + stub := workflowOrgControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"}}}, enablement) + srv.ControlPlane = stub + + w := doJSONInOrg(t, srv, tt.orgID, http.MethodPut, "/api/workflows/implement/enabled", map[string]any{"enabled": true}) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", w.Code, w.Body) + } + if stub.command == nil { + t.Fatal("the handler wrote no command") + } + if got := stub.command.GetOrgId(); got != string(tt.want) { + t.Errorf("command carried org %q, want %q", got, tt.want) + } + var written task.WorkflowEnablement + if err := json.Unmarshal(stub.command.GetValueJson(), &written); err != nil { + t.Fatalf("decode written enablement: %v", err) + } + if !written.Enabled(tt.want, "implement") { + t.Errorf("the write left implement disabled for %s", tt.want) + } + if written.Enabled(tt.other, "implement") { + t.Errorf("the write enabled implement for %s, want only the caller's org", tt.other) + } + }) + } +} + // Disabling a workflow flags the bindings that target it and refuses new // ones; enabling it again lifts both. func TestWorkflowDisableFlagsAndRefusesBindings(t *testing.T) { diff --git a/internal/webui/api_workflows.go b/internal/webui/api_workflows.go index e82dece81..d8a56d79f 100644 --- a/internal/webui/api_workflows.go +++ b/internal/webui/api_workflows.go @@ -8,11 +8,11 @@ import ( "net/http" "strings" - controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" ) const workflowDefinitionsKind = "workflow-definitions" @@ -118,10 +118,9 @@ func (s *Server) handleWorkRequest(w http.ResponseWriter, r *http.Request) { } // enabledWorkflowInterface returns the interface workflow id declares, and -// whether it is defined and enabled for the default org -- the org every -// dashboard caller acts in until access resolves a caller's own. The interface -// is what the work-request handler checks a request's inputs against, so a task -// whose workflow declaration the request cannot satisfy is refused before it is +// whether it is defined and enabled for the caller's org. The interface is what +// the work-request handler checks a request's inputs against, so a task whose +// workflow declaration the request cannot satisfy is refused before it is // admitted. func (s *Server) enabledWorkflowInterface(ctx context.Context, id string) (task.WorkflowInterface, bool, error) { entry, found, err := s.workflowEntry(ctx, id) @@ -129,7 +128,7 @@ func (s *Server) enabledWorkflowInterface(ctx context.Context, id string) (task. return task.WorkflowInterface{}, false, err } enablement, _, err := s.workflowEnablement(ctx) - if err != nil || !enablement.Enabled(org.DefaultOrgID, id) { + if err != nil || !enablement.Enabled(org.OrgFromContext(ctx), id) { return task.WorkflowInterface{}, false, err } iface, err := task.ParseWorkflowInterface(entry.YAML) @@ -158,7 +157,7 @@ func (s *Server) workflowCollection(ctx context.Context) (task.WorkflowDefinitio if s.ControlPlane == nil { return task.WorkflowDefinitionCollection{}, nil } - response, err := s.ControlPlane.Query(ctx, &controlpb.QueryRequest{Kind: workflowDefinitionsKind}) + response, err := s.ControlPlane.Query(ctx, controlplanerpc.QueryRequest(ctx, workflowDefinitionsKind)) if err != nil { return task.WorkflowDefinitionCollection{}, err } @@ -186,7 +185,7 @@ func (s *Server) workflowDefinitions(ctx context.Context) ([]task.Definition, er } definitions := make([]task.Definition, 0, len(collection.Definitions)) for _, entry := range collection.Definitions { - definition := task.Definition{ID: entry.ID, Name: entry.ID, Origin: "database", Enabled: enablement.Enabled(org.DefaultOrgID, entry.ID), Repository: task.RepositoryRequired} + definition := task.Definition{ID: entry.ID, Name: entry.ID, Origin: "database", Enabled: enablement.Enabled(org.OrgFromContext(ctx), entry.ID), Repository: task.RepositoryRequired} if iface, err := task.ParseWorkflowInterface(entry.YAML); err == nil { definition.Inputs, definition.Repository = iface.Inputs, iface.RepositoryMode() } diff --git a/internal/webui/api_workflows_test.go b/internal/webui/api_workflows_test.go index 7ba32e750..c6861286d 100644 --- a/internal/webui/api_workflows_test.go +++ b/internal/webui/api_workflows_test.go @@ -1,14 +1,17 @@ package webui import ( + "bytes" "context" "encoding/json" + "io" "net/http" "net/http/httptest" "strings" "testing" 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" "github.com/samcharles93/archie-core/internal/gateway" ) @@ -22,6 +25,47 @@ func workflowControlPlane(t *testing.T, definitions workflow.WorkflowDefinitionC return &controlPlaneClientStub{query: &controlpb.Resource{Kind: "workflow-definitions", Version: 1, ValueJson: value}} } +// workflowOrgControlPlane is the control-plane stub holding the two resources +// the workflows handlers read together -- the definition collection and the +// enablement document -- so a test can read back the org each was asked for. +func workflowOrgControlPlane(t *testing.T, definitions workflow.WorkflowDefinitionCollection, enablement string) *controlPlaneClientStub { + t.Helper() + value, err := json.Marshal(definitions) + if err != nil { + t.Fatal(err) + } + return &controlPlaneClientStub{resources: map[string]*controlpb.Resource{ + workflowDefinitionsKind: {Kind: workflowDefinitionsKind, Version: 1, ValueJson: value}, + workflowEnablementKind: {Kind: workflowEnablementKind, Version: 1, ValueJson: []byte(enablement)}, + }} +} + +// doJSONInOrg issues a request acting in orgID, or in no org at all when orgID +// is empty. The org travels on the request context (org.WithOrg) exactly as +// authorize attaches the verified principal's, so a test reads back the org a +// handler acts in the way production puts it there. +func doJSONInOrg(t *testing.T, srv *Server, orgID org.OrgID, method, path string, body any) *httptest.ResponseRecorder { + t.Helper() + var reader io.Reader + if body != nil { + encoded, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal request body: %v", err) + } + reader = bytes.NewReader(encoded) + } + ctx := t.Context() + if orgID != "" { + ctx = org.WithOrg(ctx, orgID) + } + r := httptest.NewRequestWithContext(ctx, method, path, reader) + r.Header.Set("Content-Type", "application/json") + r.Header.Set("X-Archie-CSRF", "1") + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, r) + return w +} + type recordingWorkRequestCreator struct{ request gateway.SpawnRequest } func (c *recordingWorkRequestCreator) CreateTask(_ context.Context, request gateway.SpawnRequest) (int64, error) { @@ -49,6 +93,97 @@ func TestWorkflowsIncludeInstalledZeroRunDefinitions(t *testing.T) { } } +// TestWorkflowDefinitionsPathActsInTheCallersOrg: the definitions listing and +// the enablement read beside it both act in the caller's org. A handler that +// reads the definitions in the caller's org while reading the enablement in the +// default org reports another org's enablement as the caller's own. +func TestWorkflowDefinitionsPathActsInTheCallersOrg(t *testing.T) { + // acme has disabled custom; the default org has not. + const enablement = `{"orgs":{"acme":{"disabled":["custom"]}}}` + tests := []struct { + name string + orgID org.OrgID + want org.OrgID + wantEnabled bool + }{ + {name: "a caller resolved into acme", orgID: "acme", want: "acme"}, + {name: "no org on the context is the default org", want: org.DefaultOrgID, wantEnabled: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + srv := newTestServer(t) + stub := workflowOrgControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "custom", YAML: "id: custom\nsteps:\n - type: implement.prepare\n"}}}, enablement) + srv.ControlPlane = stub + + w := doJSONInOrg(t, srv, tt.orgID, http.MethodGet, "/api/workflows", nil) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", w.Code, w.Body) + } + queried := map[string]bool{} + for _, request := range stub.queries { + queried[request.GetKind()] = true + if got := request.GetOrgId(); got != string(tt.want) { + t.Errorf("%s query carried org %q, want %q", request.GetKind(), got, tt.want) + } + } + if !queried[workflowDefinitionsKind] || !queried[workflowEnablementKind] { + t.Fatalf("definitions path queried %v, want both %s and %s", queried, workflowDefinitionsKind, workflowEnablementKind) + } + var response struct { + Definitions []workflow.Definition `json:"definitions"` + } + if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + if len(response.Definitions) != 1 || response.Definitions[0].Enabled != tt.wantEnabled { + t.Fatalf("definitions = %#v, want custom enabled=%v", response.Definitions, tt.wantEnabled) + } + }) + } +} + +// TestWorkRequestEnablementReadsTheCallersOrg: whether a workflow may run is +// the caller's org's answer, so the org that disabled pr-review cannot run it +// while an org that did not can. +func TestWorkRequestEnablementReadsTheCallersOrg(t *testing.T) { + const enablement = `{"orgs":{"acme":{"disabled":["pr-review"]}}}` + request := map[string]any{ + "identity": "archie", "repository": "acme/widget", "workflow": "pr-review", + "title": "Review 77", "instructions": "Review it.", "inputs": map[string]any{"pr_number": 77}, + } + tests := []struct { + name string + orgID org.OrgID + want org.OrgID + wantCode int + }{ + {name: "a caller in the org that disabled it", orgID: "acme", want: "acme", wantCode: http.StatusConflict}, + {name: "a caller in the org that kept it enabled", want: org.DefaultOrgID, wantCode: http.StatusCreated}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + srv := newTestServer(t) + creator := &recordingWorkRequestCreator{} + srv.WorkRequests = creator + stub := workflowOrgControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "pr-review", YAML: declaredInputsDefinition}}}, enablement) + srv.ControlPlane = stub + + w := doJSONInOrg(t, srv, tt.orgID, http.MethodPost, "/api/work-requests", request) + if w.Code != tt.wantCode { + t.Fatalf("status = %d, body = %s, want %d", w.Code, w.Body, tt.wantCode) + } + for _, query := range stub.queries { + if got := query.GetOrgId(); got != string(tt.want) { + t.Errorf("%s query carried org %q, want %q", query.GetKind(), got, tt.want) + } + } + if admitted := creator.request.Title != ""; admitted != (tt.wantCode == http.StatusCreated) { + t.Errorf("task admitted = %v, want %v", admitted, tt.wantCode == http.StatusCreated) + } + }) + } +} + // declaredInputsDefinition is a pr-review-shaped definition: it declares the // inputs the handler checks a work request against, one of them required, so a // request that does not name a pull request number cannot be admitted.