Repository navigation
fix(attestation): check contract access before rewriting it on workflow lookup #3870
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
225 changes: 225 additions & 0 deletions
225
app/controlplane/internal/service/findorcreateworkflow_integration_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,225 @@ | ||
| // | ||
| // 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" | ||
| kerrors "github.com/go-kratos/kratos/v2/errors" | ||
| "github.com/go-kratos/kratos/v2/transport" | ||
| "github.com/google/uuid" | ||
| "github.com/stretchr/testify/suite" | ||
| ) | ||
|
|
||
| // Regression tests for SEC-612: FindOrCreateWorkflow must not let a caller confined to projects | ||
| // rewrite, through the contract bytes of attestation init, a contract it can not manage through | ||
| // WorkflowContractService/Update. Attestation endpoints are skipped by the authz middleware, so | ||
| // the handler is the only authorization point. | ||
| type findOrCreateWorkflowContractIntegrationSuite struct { | ||
| testhelpers.UseCasesEachTestSuite | ||
| org *biz.Organization | ||
| projectA *biz.Project | ||
| svc *AttestationService | ||
| } | ||
|
|
||
| func TestFindOrCreateWorkflowContractAuthz(t *testing.T) { | ||
| suite.Run(t, new(findOrCreateWorkflowContractIntegrationSuite)) | ||
| } | ||
|
|
||
| func (s *findOrCreateWorkflowContractIntegrationSuite) SetupTest() { | ||
| s.TestingUseCases = testhelpers.NewTestingUseCases(s.T()) | ||
|
|
||
| ctx := context.Background() | ||
| var err error | ||
|
|
||
| s.org, err = s.Organization.CreateWithRandomName(ctx) | ||
| s.Require().NoError(err) | ||
| s.projectA, err = s.Project.Create(ctx, s.org.ID, "project-a") | ||
| s.Require().NoError(err) | ||
|
|
||
| authzUC := biz.NewAuthzUseCase(&biz.AuthzUseCaseConfig{ | ||
| CasbinEnforcer: s.Enforcer, | ||
| APITokenRepo: s.Repos.APITokenRepo, | ||
| Logger: s.L, | ||
| }) | ||
|
|
||
| s.svc = NewAttestationService(&NewAttestationServiceOpts{ | ||
| WorkflowRunUC: s.WorkflowRun, | ||
| WorkflowUC: s.Workflow, | ||
| WorkflowContractUC: s.WorkflowContract, | ||
| OrgUC: s.Organization, | ||
| ProjectUC: s.Project, | ||
| ProjectVersionUC: s.ProjectVersion, | ||
| Opts: []NewOpt{WithProjectUseCase(s.Project), WithEnforcer(authzUC)}, | ||
| }) | ||
| } | ||
|
|
||
| // findOrCreateCaller builds a caller's context for a call on a workflow of project A. It takes the | ||
| // workflow because a workflow token may only target its own. | ||
| type findOrCreateCaller struct { | ||
| name string | ||
| ctx func(wf *biz.Workflow) context.Context | ||
| } | ||
|
|
||
| // confinedCallers are the callers that reach project A only: the tokens confined to it and an org | ||
| // member who administers it. | ||
| func (s *findOrCreateWorkflowContractIntegrationSuite) confinedCallers() []findOrCreateCaller { | ||
| productID := uuid.New() | ||
| projectToken := func(t *entities.APIToken) { | ||
| t.ScopeID, t.ProjectID, t.ProjectName = &s.projectA.ID, &s.projectA.ID, &s.projectA.Name | ||
| } | ||
|
|
||
| return []findOrCreateCaller{ | ||
| {name: "project token", ctx: func(_ *biz.Workflow) context.Context { | ||
| return s.tokenCtx(authz.ResourceTypeProject, projectToken) | ||
| }}, | ||
| {name: "workflow token", ctx: func(wf *biz.Workflow) context.Context { | ||
| return s.tokenCtx(authz.ResourceTypeProject, func(t *entities.APIToken) { | ||
| projectToken(t) | ||
| t.WorkflowID, t.WorkflowName = &wf.ID, &wf.Name | ||
| }) | ||
| }}, | ||
| {name: "product token", ctx: func(_ *biz.Workflow) context.Context { | ||
| return s.tokenCtx(authz.ResourceTypeProduct, func(t *entities.APIToken) { | ||
| t.ScopeID, t.ProjectIDs = &productID, []uuid.UUID{s.projectA.ID} | ||
| }) | ||
| }}, | ||
| {name: "org member, project admin", ctx: func(_ *biz.Workflow) context.Context { | ||
| ctx := usercontext.WithAuthzSubject(s.baseCtx(), string(authz.RoleOrgMember)) | ||
| ctx = entities.WithMembership(ctx, &entities.Membership{ | ||
| UserID: uuid.New(), | ||
| Resources: []*entities.ResourceMembership{ | ||
| {Role: authz.RoleProjectAdmin, ResourceType: authz.ResourceTypeProject, ResourceID: s.projectA.ID}, | ||
| }, | ||
| }) | ||
| return s.robotCtx(ctx) | ||
| }}, | ||
| } | ||
| } | ||
|
|
||
| // unconfinedCallers are the callers that manage organization-level contracts. | ||
| func (s *findOrCreateWorkflowContractIntegrationSuite) unconfinedCallers() []findOrCreateCaller { | ||
| orgID := uuid.MustParse(s.org.ID) | ||
|
|
||
| return []findOrCreateCaller{ | ||
| {name: "org token", ctx: func(_ *biz.Workflow) context.Context { | ||
| return s.tokenCtx(authz.ResourceTypeOrganization, func(t *entities.APIToken) { t.ScopeID = &orgID }) | ||
| }}, | ||
| {name: "org admin", ctx: func(_ *biz.Workflow) context.Context { | ||
| return s.robotCtx(usercontext.WithAuthzSubject(s.baseCtx(), string(authz.RoleAdmin))) | ||
| }}, | ||
| } | ||
| } | ||
|
|
||
| // baseCtx carries the current org and the bearer token the handler forwards to the policy provider. | ||
| func (s *findOrCreateWorkflowContractIntegrationSuite) 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{"Authorization": "Bearer test-token"}}) | ||
| } | ||
|
|
||
| // robotCtx adds the robot account the attestation handlers read the organization from. | ||
| func (s *findOrCreateWorkflowContractIntegrationSuite) robotCtx(ctx context.Context) context.Context { | ||
| return usercontext.WithRobotAccount(ctx, &usercontext.RobotAccount{OrgID: s.org.ID, ProviderKey: attjwtmiddleware.APITokenProviderKey}) | ||
| } | ||
|
|
||
| // tokenCtx acts as an API token with the given scope, as the attestation middlewares set it up. | ||
| func (s *findOrCreateWorkflowContractIntegrationSuite) tokenCtx(scope authz.ResourceType, configure func(*entities.APIToken)) context.Context { | ||
| token := &entities.APIToken{ID: uuid.NewString(), Name: "ci", Scope: biz.ToPtr(scope)} | ||
| configure(token) | ||
|
|
||
| ctx := entities.WithCurrentAPIToken(s.baseCtx(), token) | ||
| ctx = usercontext.WithAuthzSubject(ctx, (&authz.SubjectAPIToken{ID: token.ID}).String()) | ||
| return s.robotCtx(ctx) | ||
| } | ||
|
|
||
| // workflowWithContract creates a workflow in project A attached to a new contract, scoped to the | ||
| // given project or, when nil, to the organization. | ||
| func (s *findOrCreateWorkflowContractIntegrationSuite) workflowWithContract(name string, contractProject *biz.Project) (*biz.Workflow, *biz.WorkflowContract) { | ||
| opts := &biz.WorkflowContractCreateOpts{OrgID: s.org.ID, Name: name, RawSchema: namedContract(name)} | ||
| if contractProject != nil { | ||
| opts.ProjectID = &contractProject.ID | ||
| } | ||
|
|
||
| contract, err := s.WorkflowContract.Create(context.Background(), opts) | ||
| s.Require().NoError(err) | ||
|
|
||
| wf, err := s.Workflow.Create(context.Background(), &biz.WorkflowCreateOpts{ | ||
| OrgID: s.org.ID, Name: name, Project: s.projectA.Name, ContractName: contract.Name, | ||
| }) | ||
| s.Require().NoError(err) | ||
|
|
||
| return wf, contract | ||
| } | ||
|
|
||
| // findOrCreate calls attestation init on the workflow with new contract bytes for its contract. | ||
| func (s *findOrCreateWorkflowContractIntegrationSuite) findOrCreate(ctx context.Context, wf *biz.Workflow) error { | ||
| _, err := s.svc.FindOrCreateWorkflow(ctx, &pb.FindOrCreateWorkflowRequest{ | ||
| ProjectName: s.projectA.Name, | ||
| WorkflowName: wf.Name, | ||
| ContractBytes: namedContract(wf.ContractName, "injected-artifact"), | ||
| }) | ||
| return err | ||
| } | ||
|
|
||
| func (s *findOrCreateWorkflowContractIntegrationSuite) revisionOf(contract *biz.WorkflowContract) int { | ||
| got, err := s.WorkflowContract.FindByIDInOrg(context.Background(), s.org.ID, contract.ID.String()) | ||
| s.Require().NoError(err) | ||
| return got.LatestRevision | ||
| } | ||
|
|
||
| func (s *findOrCreateWorkflowContractIntegrationSuite) TestConfinedCallerCannotRewriteAnOrgContract() { | ||
| for _, tc := range s.confinedCallers() { | ||
| s.Run(tc.name, func() { | ||
| wf, contract := s.workflowWithContract("org-"+uuid.NewString()[:8], nil) | ||
|
|
||
| err := s.findOrCreate(tc.ctx(wf), wf) | ||
| s.Require().Error(err) | ||
| s.True(kerrors.IsBadRequest(err), "got %v", err) | ||
| s.ErrorContains(err, "you can not manage a global contract") | ||
| s.Equal(1, s.revisionOf(contract), "the contract is unchanged") | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func (s *findOrCreateWorkflowContractIntegrationSuite) TestConfinedCallerUpdatesItsProjectContract() { | ||
| for _, tc := range s.confinedCallers() { | ||
| s.Run(tc.name, func() { | ||
| wf, contract := s.workflowWithContract("own-"+uuid.NewString()[:8], s.projectA) | ||
|
|
||
| s.Require().NoError(s.findOrCreate(tc.ctx(wf), wf)) | ||
| s.Equal(2, s.revisionOf(contract)) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func (s *findOrCreateWorkflowContractIntegrationSuite) TestUnconfinedCallerUpdatesAnOrgContract() { | ||
| for _, tc := range s.unconfinedCallers() { | ||
| s.Run(tc.name, func() { | ||
| wf, contract := s.workflowWithContract("unconfined-"+uuid.NewString()[:8], nil) | ||
|
|
||
| s.Require().NoError(s.findOrCreate(tc.ctx(wf), wf)) | ||
| s.Equal(2, s.revisionOf(contract)) | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.