diff --git a/app/controlplane/cmd/wire_gen.go b/app/controlplane/cmd/wire_gen.go index d7d6c05c3..cbb3c5d06 100644 --- a/app/controlplane/cmd/wire_gen.go +++ b/app/controlplane/cmd/wire_gen.go @@ -313,7 +313,6 @@ func wireApp(contextContext context.Context, bootstrap *conf.Bootstrap, readerWr } newAttestationStateServiceOpt := &service.NewAttestationStateServiceOpt{ AttestationStateUseCase: attestationStateUseCase, - WorkflowUseCase: workflowUseCase, WorkflowRunUseCase: workflowRunUseCase, Opts: v5, } diff --git a/app/controlplane/internal/service/attestationstate.go b/app/controlplane/internal/service/attestationstate.go index ebcffe7b2..1f105d538 100644 --- a/app/controlplane/internal/service/attestationstate.go +++ b/app/controlplane/internal/service/attestationstate.go @@ -37,13 +37,11 @@ type AttestationStateService struct { *service attestationStateUseCase *biz.AttestationStateUseCase - workflowUseCase *biz.WorkflowUseCase wrUseCase *biz.WorkflowRunUseCase } type NewAttestationStateServiceOpt struct { AttestationStateUseCase *biz.AttestationStateUseCase - WorkflowUseCase *biz.WorkflowUseCase WorkflowRunUseCase *biz.WorkflowRunUseCase Opts []NewOpt } @@ -52,7 +50,6 @@ func NewAttestationStateService(opts *NewAttestationStateServiceOpt) *Attestatio return &AttestationStateService{ service: newService(opts.Opts...), attestationStateUseCase: opts.AttestationStateUseCase, - workflowUseCase: opts.WorkflowUseCase, wrUseCase: opts.WorkflowRunUseCase, } } @@ -63,7 +60,7 @@ func (s *AttestationStateService) Initialized(ctx context.Context, req *cpAPI.At return nil, errors.NotFound("not found", "robot account not found") } - wf, err := s.findWorkflowFromTokenOrRunID(ctx, robotAccount.OrgID, robotAccount.WorkflowID, req.GetWorkflowRunId()) + wf, err := s.findWorkflowFromRunID(ctx, robotAccount.OrgID, req.GetWorkflowRunId()) if err != nil { return nil, handleUseCaseErr(ctx, err, s.log) } @@ -90,7 +87,7 @@ func (s *AttestationStateService) Save(ctx context.Context, req *cpAPI.Attestati return nil, errors.NotFound("not found", "robot account not found") } - wf, err := s.findWorkflowFromTokenOrRunID(ctx, robotAccount.OrgID, robotAccount.WorkflowID, req.GetWorkflowRunId()) + wf, err := s.findWorkflowFromRunID(ctx, robotAccount.OrgID, req.GetWorkflowRunId()) if err != nil { return nil, handleUseCaseErr(ctx, err, s.log) } @@ -123,7 +120,7 @@ func (s *AttestationStateService) Read(ctx context.Context, req *cpAPI.Attestati return nil, errors.NotFound("not found", "robot account not found") } - wf, err := s.findWorkflowFromTokenOrRunID(ctx, robotAccount.OrgID, robotAccount.WorkflowID, req.GetWorkflowRunId()) + wf, err := s.findWorkflowFromRunID(ctx, robotAccount.OrgID, req.GetWorkflowRunId()) if err != nil { return nil, handleUseCaseErr(ctx, err, s.log) } @@ -157,7 +154,7 @@ func (s *AttestationStateService) Reset(ctx context.Context, req *cpAPI.Attestat return nil, errors.NotFound("not found", "robot account not found") } - wf, err := s.findWorkflowFromTokenOrRunID(ctx, robotAccount.OrgID, robotAccount.WorkflowID, req.GetWorkflowRunId()) + wf, err := s.findWorkflowFromRunID(ctx, robotAccount.OrgID, req.GetWorkflowRunId()) if err != nil { return nil, handleUseCaseErr(ctx, err, s.log) } @@ -204,26 +201,25 @@ func encryptionPassphrase(ctx context.Context) (string, error) { return hex.EncodeToString(hash[:]), nil } -// Cascade-based way of retrieving the workflow from the robot-account or the run_ID -func (s *AttestationStateService) findWorkflowFromTokenOrRunID(ctx context.Context, orgID string, workflowID, runID string) (*biz.Workflow, error) { +// findWorkflowFromRunID returns the workflow of the run, and denies access when the caller's +// credential is pinned to a different workflow. +func (s *AttestationStateService) findWorkflowFromRunID(ctx context.Context, orgID, runID string) (*biz.Workflow, error) { if orgID == "" { return nil, biz.NewErrValidationStr("orgID must be provided") } - // This is the case of the workflowID encoded in the robot account - if workflowID != "" { - return s.workflowUseCase.FindByIDInOrg(ctx, orgID, workflowID) + if runID == "" { + return nil, biz.NewErrValidationStr("workflowRunId must be provided") } - // This is the case when the workflow is found by its reference to the run - if runID != "" { - run, err := s.wrUseCase.GetByIDInOrg(ctx, orgID, runID) - if err != nil { - return nil, fmt.Errorf("error retrieving the workflow run: %w", err) - } + run, err := s.wrUseCase.GetByIDInOrg(ctx, orgID, runID) + if err != nil { + return nil, fmt.Errorf("error retrieving the workflow run: %w", err) + } - return run.Workflow, nil + if err := checkCallerWorkflowScope(ctx, run.Workflow); err != nil { + return nil, err } - return nil, biz.NewErrValidationStr("workflowRunId must be provided") + return run.Workflow, nil } diff --git a/app/controlplane/internal/service/attestationstate_integration_test.go b/app/controlplane/internal/service/attestationstate_integration_test.go new file mode 100644 index 000000000..98af202dc --- /dev/null +++ b/app/controlplane/internal/service/attestationstate_integration_test.go @@ -0,0 +1,259 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package service + +import ( + "context" + "testing" + + pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" + "github.com/chainloop-dev/chainloop/app/controlplane/internal/usercontext" + "github.com/chainloop-dev/chainloop/app/controlplane/internal/usercontext/attjwtmiddleware" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/authz" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz/testhelpers" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/usercontext/entities" + attestationpb "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/api/attestation/v1" + "github.com/chainloop-dev/chainloop/pkg/blobmanager/oci" + creds "github.com/chainloop-dev/chainloop/pkg/credentials/mocks" + kerrors "github.com/go-kratos/kratos/v2/errors" + "github.com/go-kratos/kratos/v2/transport" + "github.com/google/uuid" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/suite" +) + +// Regression tests for SEC-3114: a credential pinned to one workflow must not reach a run that +// belongs to another workflow in the same project, through the run-ID based attestation RPCs. +// Both workflows share the project, so the project-level RBAC check alone does not stop the caller. +type runWorkflowScopeIntegrationSuite struct { + testhelpers.UseCasesEachTestSuite + org *biz.Organization + workflowA, workflowB *biz.Workflow + runA, runB *biz.WorkflowRun + workflowToken *biz.APIToken + orgToken *biz.APIToken + stateSvc *AttestationStateService + attSvc *AttestationService +} + +func (s *runWorkflowScopeIntegrationSuite) SetupTest() { + credsWriter := creds.NewReaderWriter(s.T()) + credsWriter.On("SaveCredentials", mock.Anything, mock.Anything, mock.Anything).Return("stored-OCI-secret", nil) + + s.TestingUseCases = testhelpers.NewTestingUseCases(s.T(), testhelpers.WithCredsReaderWriter(credsWriter)) + + ctx := context.Background() + var err error + + s.org, err = s.Organization.Create(ctx, "run-workflow-scope-org") + s.Require().NoError(err) + + project, err := s.Project.Create(ctx, s.org.ID, "shared-project") + s.Require().NoError(err) + + // Two workflows in the same project. + s.workflowA, err = s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{Name: "pinned-workflow", OrgID: s.org.ID, Project: project.Name}) + s.Require().NoError(err) + s.workflowB, err = s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{Name: "sibling-workflow", OrgID: s.org.ID, Project: project.Name}) + s.Require().NoError(err) + + backend, err := s.CASBackend.Create(ctx, s.org.ID, "backend", "my-location", "", oci.ProviderID, nil, true, false, nil) + s.Require().NoError(err) + + s.runA = s.createRun(s.workflowA, backend.ID) + s.runB = s.createRun(s.workflowB, backend.ID) + + s.workflowToken, err = s.APIToken.Create(ctx, "token-pinned-workflow", nil, nil, &s.org.ID, biz.APITokenWithProject(project), biz.APITokenWithWorkflow(s.workflowA)) + s.Require().NoError(err) + s.orgToken, err = s.APIToken.Create(ctx, "token-org", nil, nil, &s.org.ID) + s.Require().NoError(err) + + authzUC := biz.NewAuthzUseCase(&biz.AuthzUseCaseConfig{ + CasbinEnforcer: s.Enforcer, + APITokenRepo: s.Repos.APITokenRepo, + Logger: s.L, + }) + opts := []NewOpt{WithProjectUseCase(s.Project), WithEnforcer(authzUC)} + + s.stateSvc = NewAttestationStateService(&NewAttestationStateServiceOpt{ + AttestationStateUseCase: s.AttestationState, + WorkflowRunUseCase: s.WorkflowRun, + Opts: opts, + }) + + s.attSvc = NewAttestationService(&NewAttestationServiceOpts{ + WorkflowRunUC: s.WorkflowRun, + WorkflowUC: s.Workflow, + OrgUC: s.Organization, + ProjectUC: s.Project, + Opts: opts, + }) +} + +func (s *runWorkflowScopeIntegrationSuite) createRun(wf *biz.Workflow, backendID uuid.UUID) *biz.WorkflowRun { + ctx := context.Background() + contract, err := s.WorkflowContract.Describe(ctx, s.org.ID, wf.ContractID.String(), 0) + s.Require().NoError(err) + + run, err := s.WorkflowRun.Create(ctx, &biz.WorkflowRunCreateOpts{ + WorkflowID: wf.ID.String(), ContractRevision: contract, CASBackendID: backendID, + }) + s.Require().NoError(err) + + return run +} + +type runCall struct { + name string + fn func(ctx context.Context, runID string) error + // denyOnly marks a call that is checked only for denial, because its success path needs + // collaborators this suite does not set up. + denyOnly bool +} + +// calls lists the run-ID based RPCs, in an order that works on a run with no state yet: Read +// needs a prior Save, and Reset removes what Save wrote. +func (s *runWorkflowScopeIntegrationSuite) calls() []runCall { + state := &attestationpb.CraftingState{Attestation: &attestationpb.Attestation{Annotations: map[string]string{"key": "value"}}} + + return []runCall{ + {name: "AttestationState.Save", fn: func(ctx context.Context, runID string) error { + _, err := s.stateSvc.Save(ctx, &pb.AttestationStateServiceSaveRequest{WorkflowRunId: runID, AttestationState: state}) + return err + }}, + {name: "AttestationState.Initialized", fn: func(ctx context.Context, runID string) error { + _, err := s.stateSvc.Initialized(ctx, &pb.AttestationStateServiceInitializedRequest{WorkflowRunId: runID}) + return err + }}, + {name: "AttestationState.Read", fn: func(ctx context.Context, runID string) error { + _, err := s.stateSvc.Read(ctx, &pb.AttestationStateServiceReadRequest{WorkflowRunId: runID}) + return err + }}, + {name: "AttestationState.Reset", fn: func(ctx context.Context, runID string) error { + _, err := s.stateSvc.Reset(ctx, &pb.AttestationStateServiceResetRequest{WorkflowRunId: runID}) + return err + }}, + {name: "Attestation.GetUploadCreds", denyOnly: true, fn: func(ctx context.Context, runID string) error { + _, err := s.attSvc.GetUploadCreds(ctx, &pb.AttestationServiceGetUploadCredsRequest{WorkflowRunId: runID}) + return err + }}, + } +} + +func (s *runWorkflowScopeIntegrationSuite) TestWorkflowScope() { + testCases := []struct { + name string + ctx context.Context + run *biz.WorkflowRun + wantForbidden bool + }{ + { + name: "workflow-scoped API token cannot reach another workflow's run", + ctx: s.ctxForAPIToken(s.workflowToken), + run: s.runB, + wantForbidden: true, + }, + { + name: "workflow-scoped API token reaches its own workflow's run", + ctx: s.ctxForAPIToken(s.workflowToken), + run: s.runA, + }, + { + name: "org-scoped API token reaches any run in the organization", + ctx: s.ctxForAPIToken(s.orgToken), + run: s.runB, + }, + { + name: "legacy robot account cannot reach another workflow's run", + ctx: s.ctxForRobotAccount(s.workflowA), + run: s.runB, + wantForbidden: true, + }, + { + name: "legacy robot account reaches its own workflow's run", + ctx: s.ctxForRobotAccount(s.workflowA), + run: s.runA, + }, + } + + for _, tc := range testCases { + for _, call := range s.calls() { + if call.denyOnly && !tc.wantForbidden { + continue + } + + s.Run(tc.name+"/"+call.name, func() { + err := call.fn(tc.ctx, tc.run.ID.String()) + if tc.wantForbidden { + s.Require().Error(err) + s.True(kerrors.IsForbidden(err), "expected forbidden, got %v", err) + // Denied by the workflow check, not by a later step such as decryption. + s.Contains(err.Error(), "scoped to a different workflow") + return + } + + s.NoError(err) + }) + } + } +} + +// baseCtx holds the current org and a bearer token. Save and Read derive the state encryption +// passphrase from the bearer token. +func (s *runWorkflowScopeIntegrationSuite) baseCtx() context.Context { + ctx := entities.WithCurrentOrg(context.Background(), &entities.Org{ID: s.org.ID, Name: s.org.Name}) + + return transport.NewServerContext(ctx, &applyMockTransport{ + header: applyMockHeader{authorizationKey: "Bearer workflow-scope-token"}, + }) +} + +// ctxForAPIToken mirrors the API-token middleware: the workflow scope lives on the API token, +// and the robot account carrier has no WorkflowID. +func (s *runWorkflowScopeIntegrationSuite) ctxForAPIToken(token *biz.APIToken) context.Context { + ctx := entities.WithCurrentAPIToken(s.baseCtx(), &entities.APIToken{ + ID: token.ID.String(), + Name: token.Name, + ProjectID: token.ProjectID, + ProjectName: token.ProjectName, + WorkflowID: token.WorkflowID, + WorkflowName: token.WorkflowName, + Scope: token.Scope, + ScopeID: token.ScopeID, + ProjectIDs: token.ProjectIDs, + }) + ctx = usercontext.WithAuthzSubject(ctx, (&authz.SubjectAPIToken{ID: token.ID.String()}).String()) + + return usercontext.WithRobotAccount(ctx, &usercontext.RobotAccount{ + OrgID: s.org.ID, + ProviderKey: attjwtmiddleware.APITokenProviderKey, + }) +} + +// ctxForRobotAccount mirrors a legacy robot-account token, which is pinned to one workflow. +func (s *runWorkflowScopeIntegrationSuite) ctxForRobotAccount(wf *biz.Workflow) context.Context { + return usercontext.WithRobotAccount(s.baseCtx(), &usercontext.RobotAccount{ + ID: uuid.NewString(), + WorkflowID: wf.ID.String(), + OrgID: s.org.ID, + ProviderKey: attjwtmiddleware.RobotAccountProviderKey, + }) +} + +func TestRunWorkflowScopeIntegration(t *testing.T) { + suite.Run(t, new(runWorkflowScopeIntegrationSuite)) +}