diff --git a/app/controlplane/pkg/biz/apitoken.go b/app/controlplane/pkg/biz/apitoken.go index 2075a76f9..6e024e03c 100644 --- a/app/controlplane/pkg/biz/apitoken.go +++ b/app/controlplane/pkg/biz/apitoken.go @@ -497,9 +497,11 @@ func (uc *APITokenUseCase) Create(ctx context.Context, name string, description return nil, err } - // Use provided policies if present, otherwise use defaults + // Explicit policies are stored as given, whatever the scope. Only a token created without + // them gets the defaults, plus the organization-level policies when it is organization-wide. policies := options.policies - if policies == nil { + explicitPolicies := policies != nil + if !explicitPolicies { policies = uc.DefaultAuthzPolicies } @@ -522,7 +524,7 @@ func (uc *APITokenUseCase) Create(ctx context.Context, name string, description } // Concat, not append: policies may alias the shared defaultAuthzPolicies slice. - if *scope == authz.ResourceTypeOrganization { + if *scope == authz.ResourceTypeOrganization && !explicitPolicies { policies = slices.Concat(policies, orgLevelTokenPolicies) } diff --git a/app/controlplane/pkg/biz/apitoken_integration_test.go b/app/controlplane/pkg/biz/apitoken_integration_test.go index bf4331d34..d36ddb9c9 100644 --- a/app/controlplane/pkg/biz/apitoken_integration_test.go +++ b/app/controlplane/pkg/biz/apitoken_integration_test.go @@ -1192,11 +1192,29 @@ func (s *apiTokenTestSuite) TestExplicitPoliciesAreNotWidenedForScopedTokens() { ctx := context.Background() explicit := []*authz.Policy{authz.PolicyWorkflowRunRead} - scoped, err := s.APIToken.Create(ctx, randomName(), nil, nil, &s.org.ID, - biz.APITokenWithPolicies(explicit), - biz.APITokenWithScope(authz.ResourceTypeProduct, biz.ToPtr(uuid.New())), biz.APITokenWithProjectIDs(nil)) - s.Require().NoError(err) - s.ElementsMatch(explicit, scoped.Policies) + testCases := []struct { + name string + opts []biz.APITokenCreateOpt + }{ + {name: "organization-scoped token"}, + {name: "project-scoped token", opts: []biz.APITokenCreateOpt{biz.APITokenWithProject(s.p1)}}, + { + name: "product-scoped token", + opts: []biz.APITokenCreateOpt{ + biz.APITokenWithScope(authz.ResourceTypeProduct, biz.ToPtr(uuid.New())), + biz.APITokenWithProjectIDs(nil), + }, + }, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + opts := append([]biz.APITokenCreateOpt{biz.APITokenWithPolicies(explicit)}, tc.opts...) + token, err := s.APIToken.Create(ctx, randomName(), nil, nil, &s.org.ID, opts...) + s.Require().NoError(err) + s.ElementsMatch(explicit, token.Policies) + }) + } } // A product token is created with the projects it reaches, stored deduplicated and sorted.