Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 41 additions & 3 deletions app/controlplane/internal/service/attestation.go
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,12 @@ func (s *AttestationService) GetUploadCreds(ctx context.Context, req *cpAPI.Atte
return nil, errors.NotFound("not found", "workflow run not found")
}

// Workflow-scoped API tokens and legacy robot accounts may only get credentials for runs of
// their own workflow.
if err := checkCallerWorkflowScope(ctx, wRun.Workflow); err != nil {
return nil, err
}

// Apply RBAC on the project
if _, err = s.userHasPermissionOnProject(ctx, robotAccount.OrgID, &cpAPI.IdentityReference{Name: &wRun.Workflow.Project}, authz.PolicyWorkflowRunCreate); err != nil {
return nil, err
Expand Down Expand Up @@ -791,10 +797,22 @@ func (s *AttestationService) findWorkflowFromTokenOrNameOrRunID(ctx context.Cont
return nil, biz.NewErrValidationStr("workflowName or workflowRunId must be provided")
}

if err := checkCallerWorkflowScope(ctx, wf); err != nil {
return nil, err
}

return wf, nil
}

// checkCallerWorkflowScope rejects callers pinned to a different workflow than wf. Every
// AttestationService handler that resolves a workflow from the request must call it, because the
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
// attestation endpoints skip the authz middleware and project-level RBAC can't tell apart two
// workflows of the same project.
func checkCallerWorkflowScope(ctx context.Context, wf *biz.Workflow) error {
// Workflow-scoped API tokens may only operate on their own workflow.
if apiToken := entities.CurrentAPIToken(ctx); apiToken != nil && apiToken.WorkflowID != nil {
if wf.ID != *apiToken.WorkflowID {
return nil, errors.Forbidden("forbidden", "API token is scoped to a different workflow")
return errors.Forbidden("forbidden", "API token is scoped to a different workflow")
}
}

Expand All @@ -803,11 +821,15 @@ func (s *AttestationService) findWorkflowFromTokenOrNameOrRunID(ctx context.Cont
// only a populated one identifies a robot account and constrains the caller.
if robotAccount := usercontext.CurrentRobotAccount(ctx); robotAccount != nil && robotAccount.WorkflowID != "" {
if wf.ID.String() != robotAccount.WorkflowID {
return nil, errors.Forbidden("forbidden", "robot account is scoped to a different workflow")
return errRobotAccountOtherWorkflow()
}
}

return wf, nil
return nil
}

func errRobotAccountOtherWorkflow() error {
return errors.Forbidden("forbidden", "robot account is scoped to a different workflow")
}

func checkAuthRequirements(attToken *usercontext.RobotAccount, workflowName string) error {
Expand All @@ -834,6 +856,22 @@ func (s *AttestationService) FindOrCreateWorkflow(ctx context.Context, req *cpAP
return nil, errors.Forbidden("forbidden", "API token is workflow-scoped and cannot create or look up other workflows")
}

// Legacy robot accounts are pinned to an existing workflow: they may only look it up or update
// its contract, never reach or create another one.
if apiToken.WorkflowID != "" {
wf, err := s.workflowUseCase.FindByNameInOrg(ctx, apiToken.OrgID, req.GetProjectName(), req.GetWorkflowName())
if err != nil {
if biz.IsNotFound(err) {
return nil, errRobotAccountOtherWorkflow()
}
return nil, handleUseCaseErr(ctx, err, s.log)
}

if err := checkCallerWorkflowScope(ctx, wf); err != nil {
return nil, err
}
}

// try to load project and apply RBAC if needed
if _, err := s.userHasPermissionOnProject(ctx, apiToken.OrgID, &cpAPI.IdentityReference{Name: &req.ProjectName}, authz.PolicyWorkflowCreate); err != nil {
// if the project is not found, check if user can create projects
Expand Down
213 changes: 209 additions & 4 deletions app/controlplane/internal/service/attestation_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,12 @@ func TestGetContractRBACIntegration(t *testing.T) {
suite.Run(t, new(getContractRBACIntegrationSuite))
}

// Names of the binding cases that every handler test repeats.
const (
caseOrgTokenUnaffected = "org-scoped API token is unaffected by the binding"
caseFederatedUnaffected = "federated credential is unaffected by the binding"
)

// Regression tests for the legacy robot-account credential: a robot account is scoped to a single
// workflow, but findWorkflowFromTokenOrNameOrRunID resolved the workflow purely from the request,
// so any robot account could reach every workflow in its organization. Robot accounts can no longer
Expand All @@ -273,8 +279,11 @@ type robotAccountWorkflowBindingIntegrationSuite struct {
org *biz.Organization
projectA, projectB *biz.Project
workflowA, workflowB *biz.Workflow
orgToken *biz.APIToken
svc *AttestationService
// workflowA2 shares project A with workflowA, so project-level RBAC alone cannot tell them apart.
workflowA2 *biz.Workflow
runA, runA2, runB *biz.WorkflowRun
orgToken, workflowTokenA *biz.APIToken
svc *AttestationService
}

func (s *robotAccountWorkflowBindingIntegrationSuite) SetupTest() {
Expand All @@ -296,8 +305,21 @@ func (s *robotAccountWorkflowBindingIntegrationSuite) SetupTest() {
s.workflowB, err = s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{Name: "workflow-b", OrgID: s.org.ID, Project: "project-b"})
s.Require().NoError(err)

s.workflowA2, err = s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{Name: "workflow-a2", OrgID: s.org.ID, Project: "project-a"})
s.Require().NoError(err)

s.orgToken, err = s.APIToken.Create(ctx, "token-org", nil, nil, &s.org.ID)
s.Require().NoError(err)
s.workflowTokenA, err = s.APIToken.Create(ctx, "token-workflow-a", nil, nil, &s.org.ID, biz.APITokenWithProject(s.projectA), biz.APITokenWithWorkflow(s.workflowA))
s.Require().NoError(err)

// An inline backend is valid by default and has no secret, so GetUploadCreds can answer
// without a CAS credentials use case.
backend, err := s.CASBackend.CreateInlineBackend(ctx, s.org.ID)
s.Require().NoError(err)
s.runA = s.createRun(ctx, s.workflowA, backend)
s.runA2 = s.createRun(ctx, s.workflowA2, backend)
s.runB = s.createRun(ctx, s.workflowB, backend)

authzUC := biz.NewAuthzUseCase(&biz.AuthzUseCaseConfig{
CasbinEnforcer: s.Enforcer,
Expand All @@ -316,6 +338,167 @@ func (s *robotAccountWorkflowBindingIntegrationSuite) SetupTest() {
})
}

func (s *robotAccountWorkflowBindingIntegrationSuite) createRun(ctx context.Context, wf *biz.Workflow, backend *biz.CASBackend) *biz.WorkflowRun {
contractVersion, 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: contractVersion, CASBackendID: backend.ID,
RunnerType: "runnerType", RunnerRunURL: "runURL",
})
s.Require().NoError(err)

return run
}

// GetUploadCreds resolves the workflow from the run ID, so it must apply the same workflow binding
// as the other attestation handlers. Before the fix it only checked project-level RBAC, which a
// workflow-scoped token passes for every workflow in its project and a legacy robot account skips.
func (s *robotAccountWorkflowBindingIntegrationSuite) TestGetUploadCredsWorkflowBinding() {
testCases := []struct {
name string
ctx func() context.Context
run func() *biz.WorkflowRun
wantForbidden bool
}{
{
name: "workflow-scoped API token reaches a run of its own workflow",
ctx: func() context.Context { return s.ctxForWorkflowAPIToken() },
run: func() *biz.WorkflowRun { return s.runA },
},
{
name: "workflow-scoped API token cannot reach a run of another workflow in the same project",
ctx: func() context.Context { return s.ctxForWorkflowAPIToken() },
run: func() *biz.WorkflowRun { return s.runA2 },
wantForbidden: true,
},
{
name: "workflow-scoped API token cannot reach a run of a workflow in another project",
ctx: func() context.Context { return s.ctxForWorkflowAPIToken() },
run: func() *biz.WorkflowRun { return s.runB },
wantForbidden: true,
},
{
name: "legacy robot account reaches a run of the workflow it is bound to",
ctx: func() context.Context { return s.ctxForRobotAccount(s.workflowA) },
run: func() *biz.WorkflowRun { return s.runA },
},
{
name: "legacy robot account cannot reach a run of another workflow in the same project",
ctx: func() context.Context { return s.ctxForRobotAccount(s.workflowA) },
run: func() *biz.WorkflowRun { return s.runA2 },
wantForbidden: true,
},
{
name: "legacy robot account cannot reach a run of a workflow in another project",
ctx: func() context.Context { return s.ctxForRobotAccount(s.workflowA) },
run: func() *biz.WorkflowRun { return s.runB },
wantForbidden: true,
},
{
name: caseOrgTokenUnaffected,
ctx: func() context.Context { return s.ctxForOrgAPIToken() },
run: func() *biz.WorkflowRun { return s.runB },
},
{
name: caseFederatedUnaffected,
ctx: func() context.Context { return s.ctxForFederated() },
run: func() *biz.WorkflowRun { return s.runB },
},
}

for _, tc := range testCases {
s.Run(tc.name, func() {
resp, err := s.svc.GetUploadCreds(tc.ctx(), &pb.AttestationServiceGetUploadCredsRequest{
WorkflowRunId: tc.run().ID.String(),
})

if tc.wantForbidden {
s.Require().Error(err)
s.True(kerrors.IsForbidden(err), "expected forbidden, got %v", err)
s.Nil(resp)
return
}

s.Require().NoError(err)
s.NotNil(resp.GetResult().GetBackend())
})
}
}

// FindOrCreateWorkflow resolves the workflow from the request name and can update its contract or
// create a new workflow. A legacy robot account skips project-level RBAC, so the handler must bind
// it to its own workflow.
func (s *robotAccountWorkflowBindingIntegrationSuite) TestFindOrCreateWorkflowWorkflowBinding() {
testCases := []struct {
name string
ctx func() context.Context
project string
workflow string
wantForbidden bool
}{
{
name: "legacy robot account reaches the workflow it is bound to",
ctx: func() context.Context { return s.ctxForRobotAccount(s.workflowA) },
project: s.workflowA.Project,
workflow: s.workflowA.Name,
},
{
name: "legacy robot account cannot reach another workflow in the same project",
ctx: func() context.Context { return s.ctxForRobotAccount(s.workflowA) },
project: s.workflowA2.Project,
workflow: s.workflowA2.Name,
wantForbidden: true,
},
{
name: "legacy robot account cannot reach a workflow in another project",
ctx: func() context.Context { return s.ctxForRobotAccount(s.workflowA) },
project: s.workflowB.Project,
workflow: s.workflowB.Name,
wantForbidden: true,
},
{
name: "legacy robot account cannot create a new workflow",
ctx: func() context.Context { return s.ctxForRobotAccount(s.workflowA) },
project: s.projectA.Name,
workflow: "new-workflow",
wantForbidden: true,
},
{
name: caseOrgTokenUnaffected,
ctx: func() context.Context { return s.ctxForOrgAPIToken() },
project: s.workflowB.Project,
workflow: s.workflowB.Name,
},
{
name: caseFederatedUnaffected,
ctx: func() context.Context { return s.ctxForFederated() },
project: s.workflowB.Project,
workflow: s.workflowB.Name,
},
}

for _, tc := range testCases {
s.Run(tc.name, func() {
_, err := s.svc.FindOrCreateWorkflow(tc.ctx(), &pb.FindOrCreateWorkflowRequest{
ProjectName: tc.project,
WorkflowName: tc.workflow,
ContractBytes: []byte("schemaVersion: v1"),
})

s.Require().Error(err)
if tc.wantForbidden {
s.True(kerrors.IsForbidden(err), "expected forbidden, got %v", err)
return
}

// The request carries no transport, so an allowed caller stops later, when the
// handler reads the raw bearer token. Reaching that point means the binding passed.
s.False(kerrors.IsForbidden(err), "expected the binding to pass, got %v", err)
})
}
}

func (s *robotAccountWorkflowBindingIntegrationSuite) TestGetContractWorkflowBinding() {
testCases := []struct {
name string
Expand All @@ -337,12 +520,12 @@ func (s *robotAccountWorkflowBindingIntegrationSuite) TestGetContractWorkflowBin
wantForbidden: true,
},
{
name: "org-scoped API token is unaffected by the binding",
name: caseOrgTokenUnaffected,
ctx: func() context.Context { return s.ctxForOrgAPIToken() },
wantWorkflow: s.workflowB,
},
{
name: "federated credential is unaffected by the binding",
name: caseFederatedUnaffected,
ctx: func() context.Context { return s.ctxForFederated() },
wantWorkflow: s.workflowB,
},
Expand Down Expand Up @@ -399,6 +582,28 @@ func (s *robotAccountWorkflowBindingIntegrationSuite) ctxForOrgAPIToken() contex
})
}

// ctxForWorkflowAPIToken mirrors the API-token middleware for a token pinned to workflow A: the
// workflow scope lives on the current API token, not on the RobotAccount carrier.
func (s *robotAccountWorkflowBindingIntegrationSuite) ctxForWorkflowAPIToken() context.Context {
ctx := entities.WithCurrentOrg(context.Background(), &entities.Org{ID: s.org.ID, Name: s.org.Name})
ctx = entities.WithCurrentAPIToken(ctx, &entities.APIToken{
ID: s.workflowTokenA.ID.String(),
Name: s.workflowTokenA.Name,
ProjectID: s.workflowTokenA.ProjectID,
ProjectName: s.workflowTokenA.ProjectName,
WorkflowID: s.workflowTokenA.WorkflowID,
WorkflowName: s.workflowTokenA.WorkflowName,
Scope: s.workflowTokenA.Scope,
ScopeID: s.workflowTokenA.ScopeID,
})
ctx = usercontext.WithAuthzSubject(ctx, (&authz.SubjectAPIToken{ID: s.workflowTokenA.ID.String()}).String())

return usercontext.WithRobotAccount(ctx, &usercontext.RobotAccount{
OrgID: s.org.ID,
ProviderKey: attjwtmiddleware.APITokenProviderKey,
})
}

// ctxForFederated mirrors the federated middleware, which also leaves WorkflowID empty.
func (s *robotAccountWorkflowBindingIntegrationSuite) ctxForFederated() context.Context {
ctx := entities.WithCurrentOrg(context.Background(), &entities.Org{ID: s.org.ID, Name: s.org.Name})
Expand Down
Loading