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
40 changes: 28 additions & 12 deletions app/controlplane/internal/service/attestation.go
Original file line number Diff line number Diff line change
Expand Up @@ -846,25 +846,41 @@ func (s *AttestationService) FindOrCreateWorkflow(ctx context.Context, req *cpAP
}
}

// we need this token to forward it to the provider service next
token, err := entities.GetRawToken(ctx)
if err != nil {
return nil, err
// Check if the workflow already exists, if it does we might just need to update the contract
wf, err := s.workflowUseCase.FindByNameInOrg(ctx, apiToken.OrgID, req.GetProjectName(), req.GetWorkflowName())
if err != nil && !biz.IsNotFound(err) {
return nil, handleUseCaseErr(ctx, err, s.log)
}

// contract validation
if req.GetContractBytes() != nil {
// Updating the contract of an existing workflow needs the same access to the contract as
// WorkflowContractService/Update. This endpoint is skipped by the authz middleware, and a
// caller confined to projects must not rewrite an organization-level contract (SEC-612).
if wf != nil {
contract, err := s.workflowContractUseCase.FindByNameInOrg(ctx, apiToken.OrgID, wf.ContractName, biz.WithoutReferences())
if err != nil {
return nil, handleUseCaseErr(ctx, err, s.log)
} else if contract == nil {
return nil, errors.NotFound("not found", "contract not found")
}

if err := s.checkContractAccess(ctx, contract, authz.PolicyWorkflowContractUpdate, false); err != nil {
Comment thread
migmartri marked this conversation as resolved.
Resolved
return nil, err
}
}

// we need this token to forward it to the provider service next
token, err := entities.GetRawToken(ctx)
if err != nil {
return nil, err
}

if err = s.workflowContractUseCase.ValidateContractPolicies(ctx, req.GetContractBytes(), token, nil, nil, nil); err != nil {
return nil, handleUseCaseErr(ctx, err, s.log)
}
}

// Check if the workflow already exists, if it does we might just need to update the contract
if wf, err := s.workflowUseCase.FindByNameInOrg(ctx, apiToken.OrgID, req.GetProjectName(), req.GetWorkflowName()); err != nil {
if !biz.IsNotFound(err) {
return nil, handleUseCaseErr(ctx, err, s.log)
}
} else if wf != nil {
if wf != nil {
// We might need to update the contract
if req.GetContractBytes() != nil {
if _, err := s.workflowContractUseCase.Update(ctx, apiToken.OrgID, wf.ContractName, &biz.WorkflowContractUpdateOpts{
Expand Down Expand Up @@ -910,7 +926,7 @@ func (s *AttestationService) FindOrCreateWorkflow(ctx context.Context, req *cpAP
createOpts.UserIsOrgAdmin = isUserOrgAdmin(ctx)
}

wf, err := s.workflowUseCase.Create(ctx, createOpts)
wf, err = s.workflowUseCase.Create(ctx, createOpts)
if err != nil {
if errors.Is(err, biz.ErrImplicitWorkflowCreationDisabled) {
return nil, errors.Forbidden("forbidden", "creating workflows during the attestation process is disabled for this organization. Please create them in advance or contact your administrator")
Expand Down
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))
})
}
}
19 changes: 19 additions & 0 deletions app/controlplane/internal/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,25 @@ func withForceRBAC() AuthorizeResourceOpt {
// For a user, it goes through all the memberships of the user, direct memberships and indirect memberships (Groups)
// and checks if the user has any role that allows the operation on the resourceType and resourceID.
// An API token has no role: it passes only for a project it reaches.
// checkContractAccess checks if the current user can manage a contract
// if the contract is global it makes sure that the user is an admin
// if the contract is scoped to a project it makes sure that the user has permission in the project
func (s *service) checkContractAccess(ctx context.Context, contract *biz.WorkflowContract, policy *authz.Policy, allowGlobalAccess bool) error {
// 1 - Only admins can manage global contracts unless allowGlobalAccess is true
if contract.IsGlobalScoped() && rbacEnabled(ctx) && !allowGlobalAccess {
return errors.BadRequest("invalid", "you can not manage a global contract")
}

// 2 - If the contract is scoped to a project, make sure the user has permission to read it
if contract.IsProjectScoped() {
if err := s.authorizeResource(ctx, policy, authz.ResourceTypeProject, contract.ScopedEntity.ID); err != nil {
Comment thread
migmartri marked this conversation as resolved.
Resolved
return err
}
}

return nil
}

func (s *service) authorizeResource(ctx context.Context, op *authz.Policy, resourceType authz.ResourceType, resourceID uuid.UUID, opts ...AuthorizeResourceOpt) error {
options := &authorizeResourceOpts{}
for _, opt := range opts {
Expand Down
19 changes: 0 additions & 19 deletions app/controlplane/internal/service/workflowcontract.go
Original file line number Diff line number Diff line change
Expand Up @@ -523,25 +523,6 @@ func bizWorkFlowContractVersionToPb(schema *biz.WorkflowContractVersion, contrac
return item
}

// checkContractAccess checks if the current user can manage a contract
// if the contract is global it makes sure that the user is an admin
// if the contract is scoped to a project it makes sure that the user has permission in the project
func (s *WorkflowContractService) checkContractAccess(ctx context.Context, contract *biz.WorkflowContract, policy *authz.Policy, allowGlobalAccess bool) error {
// 1 - Only admins can manage global contracts unless allowGlobalAccess is true
if contract.IsGlobalScoped() && rbacEnabled(ctx) && !allowGlobalAccess {
return errors.BadRequest("invalid", "you can not manage a global contract")
}

// 2 - If the contract is scoped to a project, make sure the user has permission to read it
if contract.IsProjectScoped() {
if err := s.authorizeResource(ctx, policy, authz.ResourceTypeProject, contract.ScopedEntity.ID); err != nil {
return err
}
}

return nil
}

// validateAndExtractName validates and extracts a name from either
// an explicit name parameter OR from metadata.name in the v2 contract.
// Returns error when:
Expand Down
Loading