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
10 changes: 5 additions & 5 deletions app/controlplane/internal/service/apitoken.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func (s *APITokenService) List(ctx context.Context, req *pb.APITokenServiceListR
// Org-level API tokens can only see project-scoped tokens
scope := mapTokenScope(req.Scope)
if token := entities.CurrentAPIToken(ctx); token != nil && token.ProjectID == nil {
scope = biz.APITokenScopeProject
scope = authz.ResourceTypeProject
}

tokens, err := s.APITokenUseCase.List(ctx, currentOrg.ID, biz.WithAPITokenStatusFilter(mapTokenStatusFilter(req.GetStatusFilter())), biz.WithAPITokenProjectFilter(defaultProjectFilter), biz.WithAPITokenScope(scope))
Expand All @@ -127,12 +127,12 @@ func (s *APITokenService) List(ctx context.Context, req *pb.APITokenServiceListR
return &pb.APITokenServiceListResponse{Result: result}, nil
}

func mapTokenScope(scope pb.APITokenServiceListRequest_Scope) biz.APITokenScope {
func mapTokenScope(scope pb.APITokenServiceListRequest_Scope) authz.ResourceType {
switch scope {
case pb.APITokenServiceListRequest_SCOPE_PROJECT:
return biz.APITokenScopeProject
return authz.ResourceTypeProject
case pb.APITokenServiceListRequest_SCOPE_GLOBAL:
return biz.APITokenScopeGlobal
return authz.ResourceTypeOrganization
}

return ""
Expand Down Expand Up @@ -215,7 +215,7 @@ func apiTokenBizToPb(in *biz.APIToken) *pb.APITokenItem {

if in.ProjectID != nil {
res.ScopedEntity = &pb.ScopedEntity{
Type: string(biz.ContractScopeProject),
Type: string(authz.ResourceTypeProject),
Id: in.ProjectID.String(),
Name: *in.ProjectName,
}
Expand Down
174 changes: 156 additions & 18 deletions app/controlplane/internal/service/apitoken_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,18 @@ package service
import (
"context"
"testing"
"time"

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/pkg/authz"
"github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz"
bizMocks "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz/mocks"
"github.com/chainloop-dev/chainloop/app/controlplane/pkg/usercontext/entities"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)

func TestAPITokenService_Create_OrgTokenWithoutProjectIsRejected(t *testing.T) {
Expand All @@ -42,37 +48,75 @@ func TestAPITokenService_Create_OrgTokenWithoutProjectIsRejected(t *testing.T) {
assert.Contains(t, err.Error(), "org-level API tokens must specify a project")
}

func TestAPITokenService_List_OrgTokenForcesProjectScope(t *testing.T) {
// An organization-wide token may only list project tokens, whatever scope it asks for; every
// other caller gets the scope it asked for. Driven through List itself, down to the filters the
// repository receives, so the override cannot drift away from what is asserted here.
func TestAPITokenServiceListForcesProjectScopeForOrgTokens(t *testing.T) {
t.Parallel()

tests := []struct {
name string
token *entities.APIToken
wantScope biz.APITokenScope
orgID, projectID := uuid.New(), uuid.New()

testCases := []struct {
name string
// caller is the API token making the request; nil means a user
caller *entities.APIToken
requested pb.APITokenServiceListRequest_Scope
wantScope authz.ResourceType
wantProjects []uuid.UUID
}{
{
name: "org-level token forces project scope",
token: &entities.APIToken{ID: uuid.NewString(), ProjectID: nil},
wantScope: biz.APITokenScopeProject,
name: "an organization token is forced to project tokens",
caller: &entities.APIToken{ID: uuid.NewString()},
wantScope: authz.ResourceTypeProject,
},
{
name: "an organization token asking for global tokens is still forced",
caller: &entities.APIToken{ID: uuid.NewString()},
requested: pb.APITokenServiceListRequest_SCOPE_GLOBAL,
wantScope: authz.ResourceTypeProject,
},
{
name: "project-scoped token does not override scope",
token: &entities.APIToken{ID: uuid.NewString(), ProjectID: toUUIDPtr(uuid.New())},
wantScope: "", // mapTokenScope returns "" for SCOPE_UNSPECIFIED
name: "a project token keeps the scope it asks for",
caller: &entities.APIToken{ID: uuid.NewString(), ProjectID: &projectID},
requested: pb.APITokenServiceListRequest_SCOPE_GLOBAL,
wantScope: authz.ResourceTypeOrganization,
wantProjects: []uuid.UUID{projectID},
},
{
name: "a user keeps the scope it asks for",
requested: pb.APITokenServiceListRequest_SCOPE_GLOBAL,
wantScope: authz.ResourceTypeOrganization,
},
{
name: "a user asking for no scope gets none",
wantScope: "",
},
}

for _, tc := range tests {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
ctx = entities.WithCurrentAPIToken(ctx, tc.token)
t.Parallel()

scope := mapTokenScope(pb.APITokenServiceListRequest_SCOPE_UNSPECIFIED)
if token := entities.CurrentAPIToken(ctx); token != nil && token.ProjectID == nil {
scope = biz.APITokenScopeProject
var got *biz.APITokenListFilters
repo := bizMocks.NewAPITokenRepo(t)
repo.On("List", mock.Anything, mock.Anything, mock.Anything).Once().
Run(func(args mock.Arguments) { got = args.Get(2).(*biz.APITokenListFilters) }).
Return([]*biz.APIToken{}, nil)
uc, err := biz.NewAPITokenUseCase(repo, &biz.APITokenJWTConfig{SymmetricHmacKey: "test"}, nil, nil, nil, nil)
require.NoError(t, err)

ctx := entities.WithCurrentOrg(context.Background(), &entities.Org{ID: orgID.String(), Name: "acme"})
if tc.caller != nil {
ctx = entities.WithCurrentAPIToken(ctx, tc.caller)
} else {
ctx = usercontext.WithAuthzSubject(ctx, string(authz.RoleAdmin))
}

assert.Equal(t, tc.wantScope, scope)
_, err = NewAPITokenService(uc).List(ctx, &pb.APITokenServiceListRequest{Scope: tc.requested})
require.NoError(t, err)
require.NotNil(t, got)
assert.Equal(t, tc.wantScope, got.FilterByScope)
assert.Equal(t, tc.wantProjects, got.FilterByProjects)
})
}
}
Expand Down Expand Up @@ -130,3 +174,97 @@ func TestAPITokenService_Revoke_OrgTokenCannotRevokeOrgTokens(t *testing.T) {
func toUUIDPtr(id uuid.UUID) *uuid.UUID {
return &id
}

// A listing reports the project a token is confined to, and the scope columns change nothing
// about it: every new token records a scope, yet each one lists exactly as it did before.
func TestAPITokenBizToPbScopedEntity(t *testing.T) {
t.Parallel()

projectID, productID, orgID := uuid.New(), uuid.New(), uuid.New()
createdAt := time.Now()

testCases := []struct {
name string
token *biz.APIToken
want *pb.ScopedEntity
}{
{
name: "a project-scoped token reports its project",
token: &biz.APIToken{
ID: uuid.New(), CreatedAt: &createdAt,
ProjectID: &projectID, ProjectName: biz.ToPtr("billing"),
},
want: &pb.ScopedEntity{Type: string(authz.ResourceTypeProject), Id: projectID.String(), Name: "billing"},
},
{
name: "a scope id without a kind is not reported",
token: &biz.APIToken{
ID: uuid.New(), CreatedAt: &createdAt,
ScopeID: &productID,
},
want: nil,
},
{
// New tokens record their scope for every kind, but only a product is reported
// from it: an organization token lists exactly as it did before.
name: "an organization-scoped token reports none",
token: &biz.APIToken{
ID: uuid.New(), CreatedAt: &createdAt,
Scope: biz.ToPtr(authz.ResourceTypeOrganization), ScopeID: &orgID,
},
want: nil,
},
{
name: "a project-scoped token still reports its project from project_id",
token: &biz.APIToken{
ID: uuid.New(), CreatedAt: &createdAt,
ProjectID: &projectID, ProjectName: biz.ToPtr("billing"),
Scope: biz.ToPtr(authz.ResourceTypeProject), ScopeID: &projectID,
},
want: &pb.ScopedEntity{Type: string(authz.ResourceTypeProject), Id: projectID.String(), Name: "billing"},
},
{
name: "an organization-level token reports none",
token: &biz.APIToken{ID: uuid.New(), CreatedAt: &createdAt},
want: nil,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()

got := apiTokenBizToPb(tc.token).GetScopedEntity()
if tc.want == nil {
assert.Nil(t, got)
return
}

require.NotNil(t, got)
assert.Equal(t, tc.want.GetType(), got.GetType())
assert.Equal(t, tc.want.GetId(), got.GetId())
assert.Equal(t, tc.want.GetName(), got.GetName())
})
}
}

// The public listing scopes map onto resource kinds; "global" is the organization's own tokens.
func TestMapTokenScope(t *testing.T) {
t.Parallel()

testCases := []struct {
in pb.APITokenServiceListRequest_Scope
want authz.ResourceType
}{
{in: pb.APITokenServiceListRequest_SCOPE_UNSPECIFIED, want: ""},
{in: pb.APITokenServiceListRequest_SCOPE_PROJECT, want: authz.ResourceTypeProject},
{in: pb.APITokenServiceListRequest_SCOPE_GLOBAL, want: authz.ResourceTypeOrganization},
}

for _, tc := range testCases {
t.Run(tc.in.String(), func(t *testing.T) {
t.Parallel()
assert.Equal(t, tc.want, mapTokenScope(tc.in))
})
}
}
Loading
Loading