diff --git a/app/controlplane/internal/service/cascredential.go b/app/controlplane/internal/service/cascredential.go index 5b6889669..4402a0eb2 100644 --- a/app/controlplane/internal/service/cascredential.go +++ b/app/controlplane/internal/service/cascredential.go @@ -17,6 +17,8 @@ package service import ( "context" + stderrors "errors" + "slices" pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/authz" @@ -82,6 +84,11 @@ func (s *CASCredentialsService) Get(ctx context.Context, req *pb.CASCredentialsS policyToCheck = authz.PolicyArtifactUpload } + restricted, err := restrictToAllowedDigest(currentAPIToken, req.GetDigest(), role) + if err != nil { + return nil, errors.Forbidden("forbidden", "not allowed to perform this operation") + } + // Without a digest the scoped request would silently mint an unscoped token if req.GetScopeToDigest() && req.GetDigest() == "" { return nil, errors.BadRequest("invalid argument", "a digest is required to scope the credentials") @@ -154,7 +161,7 @@ func (s *CASCredentialsService) Get(ctx context.Context, req *pb.CASCredentialsS } ref := &biz.CASCredsOpts{BackendType: string(backend.Provider), SecretPath: backend.SecretName, Role: role, MaxBytes: backend.Limits.MaxBytes, OrgID: backend.OrganizationID, SourceInternal: sourceInternal} - if req.GetScopeToDigest() { + if req.GetScopeToDigest() || restricted { ref.Digest = req.GetDigest() } @@ -177,3 +184,22 @@ func (s *CASCredentialsService) Get(ctx context.Context, req *pb.CASCredentialsS func resolveSourceInternal(requested bool, token *entities.APIToken) bool { return requested && token != nil && token.IsSystem } + +// errDigestNotAllowed refuses a CAS credential that is outside the artifacts an API token is +// restricted to. Each RPC answers it with the error it uses for other artifacts out of reach. +var errDigestNotAllowed = stderrors.New("the API token is not allowed to access this artifact") + +// restrictToAllowedDigest applies the artifact restriction of an API token to a request for a CAS +// credential. It reports whether the token has the restriction: the credential must then be +// scoped to the digest. Such a token only downloads, and only a digest in its list. +func restrictToAllowedDigest(token *entities.APIToken, digest string, role casJWT.Role) (bool, error) { + if token == nil || len(token.AllowedDigests) == 0 { + return false, nil + } + + if role != casJWT.Downloader || digest == "" || !slices.Contains(token.AllowedDigests, digest) { + return true, errDigestNotAllowed + } + + return true, nil +} diff --git a/app/controlplane/internal/service/cascredential_test.go b/app/controlplane/internal/service/cascredential_test.go index 4fc491daf..e8349e8a4 100644 --- a/app/controlplane/internal/service/cascredential_test.go +++ b/app/controlplane/internal/service/cascredential_test.go @@ -16,9 +16,11 @@ package service import ( + "strings" "testing" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/usercontext/entities" + casJWT "github.com/chainloop-dev/chainloop/internal/robotaccount/cas" "github.com/stretchr/testify/assert" ) @@ -76,3 +78,45 @@ func TestResolveSourceInternal(t *testing.T) { }) } } + +// A token restricted to artifacts only downloads, and only the digests in its list. A token +// without the restriction, and a user, are left alone. +func TestRestrictToAllowedDigest(t *testing.T) { + const ( + allowed = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + other = "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ) + + restricted := &entities.APIToken{AllowedDigests: []string{allowed}} + + testCases := []struct { + name string + token *entities.APIToken + digest string + role casJWT.Role + wantRestricted bool + wantErr bool + }{ + {name: "a user", digest: other, role: casJWT.Uploader}, + {name: "a token without the restriction", token: &entities.APIToken{}, digest: other, role: casJWT.Uploader}, + {name: "a token without the restriction and no digest", token: &entities.APIToken{}, role: casJWT.Downloader}, + {name: "an allowed digest", token: restricted, digest: allowed, role: casJWT.Downloader, wantRestricted: true}, + {name: "another digest", token: restricted, digest: other, role: casJWT.Downloader, wantRestricted: true, wantErr: true}, + {name: "no digest", token: restricted, role: casJWT.Downloader, wantRestricted: true, wantErr: true}, + {name: "an upload of an allowed digest", token: restricted, digest: allowed, role: casJWT.Uploader, wantRestricted: true, wantErr: true}, + {name: "no role", token: restricted, digest: allowed, wantRestricted: true, wantErr: true}, + {name: "a digest that differs in case", token: restricted, digest: strings.ToUpper(allowed), role: casJWT.Downloader, wantRestricted: true, wantErr: true}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + gotRestricted, err := restrictToAllowedDigest(tc.token, tc.digest, tc.role) + assert.Equal(t, tc.wantRestricted, gotRestricted) + if tc.wantErr { + assert.ErrorIs(t, err, errDigestNotAllowed) + return + } + assert.NoError(t, err) + }) + } +} diff --git a/app/controlplane/internal/service/casredirect.go b/app/controlplane/internal/service/casredirect.go index e003052cb..806607ff3 100644 --- a/app/controlplane/internal/service/casredirect.go +++ b/app/controlplane/internal/service/casredirect.go @@ -89,6 +89,12 @@ func (s *CASRedirectService) GetDownloadURL(ctx context.Context, req *pb.GetDown return nil, err } + restricted, err := restrictToAllowedDigest(currentAPIToken, req.GetDigest(), casJWT.Downloader) + if err != nil { + // The same answer as for any other artifact out of reach + return nil, kerrors.NotFound("not found", "artifact not found") + } + var mapping *biz.CASMapping if currentUser != nil { mapping, err = s.casMappingUC.FindCASMappingForDownloadByUser(ctx, req.Digest, currentUser.ID) @@ -137,7 +143,7 @@ func (s *CASRedirectService) GetDownloadURL(ctx context.Context, req *pb.GetDown // 2- add authentication token to the query params ?t=[token] if backend.SecretName != "" { ref := &biz.CASCredsOpts{BackendType: string(backend.Provider), SecretPath: backend.SecretName, Role: casJWT.Downloader, MaxBytes: backend.Limits.MaxBytes, OrgID: backend.OrganizationID} - if req.GetScopeToDigest() { + if req.GetScopeToDigest() || restricted { ref.Digest = req.GetDigest() } diff --git a/app/controlplane/internal/service/casredirect_integration_test.go b/app/controlplane/internal/service/casredirect_integration_test.go index afc7b8c4a..d10f64a88 100644 --- a/app/controlplane/internal/service/casredirect_integration_test.go +++ b/app/controlplane/internal/service/casredirect_integration_test.go @@ -22,6 +22,7 @@ import ( "crypto/rand" "crypto/x509" "encoding/pem" + "fmt" "net/url" "os" "path/filepath" @@ -39,6 +40,7 @@ import ( creds "github.com/chainloop-dev/chainloop/pkg/credentials/mocks" kerrors "github.com/go-kratos/kratos/v2/errors" "github.com/golang-jwt/jwt/v5" + "github.com/google/uuid" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/suite" ) @@ -239,6 +241,85 @@ func (s *casDownloadRBACIntegrationSuite) TestDigestScopedTokens() { }) } +// A token restricted to artifacts gets download credentials for the digests in its list only, and +// they are always scoped to the requested digest. A token without the restriction is unchanged. +func (s *casDownloadRBACIntegrationSuite) TestTokenRestrictedToDigests() { + ctx := context.Background() + restricted, err := s.APIToken.Create(ctx, "token-restricted", nil, nil, &s.org.ID, + biz.APITokenWithPolicies([]*authz.Policy{authz.PolicyArtifactDownload}), + biz.APITokenWithAllowedDigests(digestProjectA), + ) + s.Require().NoError(err) + + testCases := []struct { + name string + token *biz.APIToken + digest string + scopeToDigest bool + // wantDigest is the digest the CAS credential is scoped to, empty when it is not scoped + wantDigest string + wantErr bool + }{ + {name: "an allowed digest is scoped without asking", token: restricted, digest: digestProjectA, wantDigest: digestProjectA}, + {name: "an allowed digest asked to be scoped", token: restricted, digest: digestProjectA, scopeToDigest: true, wantDigest: digestProjectA}, + {name: "a digest outside the list", token: restricted, digest: digestProjectB, wantErr: true}, + {name: "a digest outside the list asked to be scoped", token: restricted, digest: digestOrgWide, scopeToDigest: true, wantErr: true}, + {name: "no digest", token: restricted, wantErr: true}, + {name: "a token without the restriction is not scoped", token: s.orgToken, digest: digestProjectB}, + } + + for _, tc := range testCases { + s.Run("GetDownloadURL: "+tc.name, func() { + resp, err := s.redirectSvc.GetDownloadURL(s.ctxForToken(tc.token), &pb.GetDownloadURLRequest{Digest: tc.digest, ScopeToDigest: tc.scopeToDigest}) + if tc.wantErr { + s.True(kerrors.IsNotFound(err), "expected not found, got %v", err) + return + } + s.Require().NoError(err) + + u, err := url.Parse(resp.GetResult().GetUrl()) + s.Require().NoError(err) + s.Equal(tc.wantDigest, s.casClaims(u.Query().Get("t")).Digest) + }) + + s.Run("CASCredentialsService.Get: "+tc.name, func() { + resp, err := s.credentialsSvc.Get(s.ctxForToken(tc.token), &pb.CASCredentialsServiceGetRequest{ + Digest: tc.digest, + Role: pb.CASCredentialsServiceGetRequest_ROLE_DOWNLOADER, + ScopeToDigest: tc.scopeToDigest, + }) + if tc.wantErr { + s.True(kerrors.IsForbidden(err), "expected forbidden, got %v", err) + return + } + s.Require().NoError(err) + s.Equal(tc.wantDigest, s.casClaims(resp.GetResult().GetToken()).Digest) + }) + } + + // Create refuses this row. Written straight to the repository, it shows that the upload + // refusal does not depend on the policies. + orgID := uuid.MustParse(s.org.ID) + canUpload, err := s.Repos.APITokenRepo.Create(ctx, &biz.APITokenCreateOpts{ + Name: "token-restricted-upload", OrganizationID: &orgID, + Scope: biz.ToPtr(authz.ResourceTypeOrganization), ScopeID: &orgID, + Policies: []*authz.Policy{authz.PolicyArtifactDownload, authz.PolicyArtifactUpload}, + AllowedDigests: []string{digestProjectA}, + }) + s.Require().NoError(err) + + for _, scopeToDigest := range []bool{false, true} { + s.Run(fmt.Sprintf("CASCredentialsService.Get: no upload of an allowed digest, scope_to_digest=%t", scopeToDigest), func() { + _, err := s.credentialsSvc.Get(s.ctxForToken(canUpload), &pb.CASCredentialsServiceGetRequest{ + Digest: digestProjectA, + Role: pb.CASCredentialsServiceGetRequest_ROLE_UPLOADER, + ScopeToDigest: scopeToDigest, + }) + s.True(kerrors.IsForbidden(err), "expected forbidden, got %v", err) + }) + } +} + // casClaims decodes the claims of a CAS token without verifying its signature func (s *casDownloadRBACIntegrationSuite) casClaims(token string) *casJWT.Claims { claims := &casJWT.Claims{} @@ -259,6 +340,8 @@ func (s *casDownloadRBACIntegrationSuite) ctxForToken(token *biz.APIToken) conte Scope: token.Scope, ScopeID: token.ScopeID, ProjectIDs: token.ProjectIDs, + // The middleware loads the restriction from the row + AllowedDigests: token.AllowedDigests, }) return usercontext.WithAuthzSubject(ctx, (&authz.SubjectAPIToken{ID: token.ID.String()}).String()) diff --git a/app/controlplane/internal/usercontext/apitoken_middleware.go b/app/controlplane/internal/usercontext/apitoken_middleware.go index 1a809bb9d..8897f220c 100644 --- a/app/controlplane/internal/usercontext/apitoken_middleware.go +++ b/app/controlplane/internal/usercontext/apitoken_middleware.go @@ -213,22 +213,23 @@ func setCurrentOrgAndAPIToken(ctx context.Context, apiTokenUC *biz.APITokenUseCa } // Every value here comes from the row. VerifyClaims checked the scope, project and workflow - // against the signed claims. The policies, the project list and the system flag come only from - // the row. + // against the signed claims. The policies, the project list, the allowed digests and the + // system flag come only from the row. ctx = entities.WithCurrentAPIToken(ctx, &entities.APIToken{ - ID: token.ID.String(), - Name: token.Name, - CreatedAt: token.CreatedAt, - Token: token.JWT, - ProjectID: token.ProjectID, - ProjectName: token.ProjectName, - WorkflowID: token.WorkflowID, - WorkflowName: token.WorkflowName, - Scope: token.Scope, - ScopeID: token.ScopeID, - ProjectIDs: token.ProjectIDs, - Policies: token.Policies, - IsSystem: token.IsSystem, + ID: token.ID.String(), + Name: token.Name, + CreatedAt: token.CreatedAt, + Token: token.JWT, + ProjectID: token.ProjectID, + ProjectName: token.ProjectName, + WorkflowID: token.WorkflowID, + WorkflowName: token.WorkflowName, + Scope: token.Scope, + ScopeID: token.ScopeID, + ProjectIDs: token.ProjectIDs, + Policies: token.Policies, + IsSystem: token.IsSystem, + AllowedDigests: token.AllowedDigests, }) // Set the authorization subject that will be used to check the policies diff --git a/app/controlplane/internal/usercontext/apitoken_middleware_test.go b/app/controlplane/internal/usercontext/apitoken_middleware_test.go index 7c966be58..70e8cb9b5 100644 --- a/app/controlplane/internal/usercontext/apitoken_middleware_test.go +++ b/app/controlplane/internal/usercontext/apitoken_middleware_test.go @@ -315,6 +315,8 @@ func TestWithCurrentAPITokenAndOrgMiddlewareCarriesScope(t *testing.T) { rowScope *authz.ResourceType rowScopeID *uuid.UUID rowProjectIDs []uuid.UUID + // the only artifacts the row allows, if any + rowAllowedDigests []string // claims are the signed claims other than aud and jti. claims jwt.MapClaims }{ @@ -338,6 +340,14 @@ func TestWithCurrentAPITokenAndOrgMiddlewareCarriesScope(t *testing.T) { rowScope: biz.ToPtr(authz.ResourceTypeInstance), claims: jwt.MapClaims{claimOrgID: "", claimScope: string(authz.ResourceTypeInstance)}, }, + { + name: "an organization token restricted to artifacts", + rowOrg: orgID, + rowScope: biz.ToPtr(authz.ResourceTypeOrganization), + rowScopeID: &orgID, + rowAllowedDigests: []string{"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, + claims: jwt.MapClaims{claimOrgID: orgID.String(), claimScope: string(authz.ResourceTypeOrganization), claimScopeID: orgID.String()}, + }, } for _, tc := range testCases { @@ -345,6 +355,7 @@ func TestWithCurrentAPITokenAndOrgMiddlewareCarriesScope(t *testing.T) { token := &biz.APIToken{ ID: uuid.New(), Name: "ci", OrganizationID: tc.rowOrg, Scope: tc.rowScope, ScopeID: tc.rowScopeID, ProjectIDs: tc.rowProjectIDs, + AllowedDigests: tc.rowAllowedDigests, } apiTokenRepo := mocks.NewAPITokenRepo(t) @@ -374,6 +385,7 @@ func TestWithCurrentAPITokenAndOrgMiddlewareCarriesScope(t *testing.T) { assert.Equal(t, tc.rowScope, got.Scope) assert.Equal(t, tc.rowScopeID, got.ScopeID) assert.Equal(t, tc.rowProjectIDs, got.ProjectIDs) + assert.Equal(t, tc.rowAllowedDigests, got.AllowedDigests) }) } } diff --git a/app/controlplane/pkg/biz/apitoken.go b/app/controlplane/pkg/biz/apitoken.go index 6e024e03c..566cc37c9 100644 --- a/app/controlplane/pkg/biz/apitoken.go +++ b/app/controlplane/pkg/biz/apitoken.go @@ -32,6 +32,7 @@ import ( "github.com/chainloop-dev/chainloop/pkg/servicelogger" "github.com/go-kratos/kratos/v2/log" + cr_v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/uuid" ) @@ -59,6 +60,11 @@ var orgLevelTokenPolicies = []*authz.Policy{ authz.PolicyRegisteredIntegrationRead, } +// isArtifactUploadPolicy reports whether a policy allows an artifact upload to the CAS. +func isArtifactUploadPolicy(p *authz.Policy) bool { + return p != nil && p.Resource == authz.PolicyArtifactUpload.Resource && p.Action == authz.PolicyArtifactUpload.Action +} + // IsOrgLevelTokenPolicy reports whether a policy is one only an organization-wide token holds. // A token confined to a project or to a product never carries one. func IsOrgLevelTokenPolicy(p *authz.Policy) bool { @@ -129,6 +135,9 @@ type APIToken struct { Policies []*authz.Policy // IsSystem marks tokens minted by internal code paths; these are hidden from the public API. IsSystem bool + // AllowedDigests are the only artifacts the token can download from the CAS. Nil means no + // restriction. + AllowedDigests []string } // scopeView is the token's scope as the request context carries it, so that a token read here and @@ -248,6 +257,8 @@ type APITokenCreateOpts struct { ProjectIDs []uuid.UUID Policies []*authz.Policy IsSystem bool + // AllowedDigests restricts the token to these artifacts. Nil means no restriction. + AllowedDigests []string } type APITokenRepo interface { @@ -307,6 +318,8 @@ type apiTokenOptions struct { projectIDs []uuid.UUID policies []*authz.Policy isSystem bool + // allowedDigests is nil when the option is not used, and never nil when it is + allowedDigests []string } type APITokenCreateOpt func(*apiTokenOptions) @@ -357,6 +370,39 @@ func APITokenWithProjectIDs(ids []uuid.UUID) APITokenCreateOpt { } } +// APITokenWithAllowedDigests restricts the token to download only these artifacts from the CAS. +// Create refuses an empty list, a digest that is not a sha256 digest, and a token whose policies +// allow an upload. +func APITokenWithAllowedDigests(digests ...string) APITokenCreateOpt { + return func(o *apiTokenOptions) { + o.allowedDigests = append(make([]string, 0, len(digests)), digests...) + } +} + +// canonicalAllowedDigests checks that every digest is a sha256 digest, and returns them +// deduplicated and sorted. +func canonicalAllowedDigests(digests []string) ([]string, error) { + if len(digests) == 0 { + return nil, NewErrValidationStr("a token restricted to artifacts needs at least one digest") + } + + for _, d := range digests { + h, err := cr_v1.NewHash(d) + if err != nil { + return nil, NewErrValidation(fmt.Errorf("invalid digest format: %w", err)) + } + + if h.Algorithm != "sha256" { + return nil, NewErrValidationStr(fmt.Sprintf("invalid digest %q: only sha256 digests are supported", d)) + } + } + + out := slices.Clone(digests) + slices.Sort(out) + + return slices.Compact(out), nil +} + // CanonicalProjectIDs returns ids deduplicated and sorted, never nil, so that equal sets are // stored as equal lists and compare equal. func CanonicalProjectIDs(ids []uuid.UUID) []uuid.UUID { @@ -497,6 +543,14 @@ func (uc *APITokenUseCase) Create(ctx context.Context, name string, description return nil, err } + var allowedDigests []string + if options.allowedDigests != nil { + var err error + if allowedDigests, err = canonicalAllowedDigests(options.allowedDigests); err != nil { + return nil, err + } + } + // 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 @@ -528,6 +582,12 @@ func (uc *APITokenUseCase) Create(ctx context.Context, name string, description policies = slices.Concat(policies, orgLevelTokenPolicies) } + // A token restricted to artifacts only downloads them. The defaults allow an upload, so such + // a token needs explicit policies. + if allowedDigests != nil && slices.ContainsFunc(policies, isArtifactUploadPolicy) { + return nil, NewErrValidationStr("a token restricted to artifacts cannot carry the artifact upload policy") + } + // NOTE: the expiration time is stored just for reference, it's also encoded in the JWT // We store it since Chainloop will not have access to the JWT to check the expiration once created token, err := uc.apiTokenRepo.Create(ctx, &APITokenCreateOpts{ @@ -542,6 +602,7 @@ func (uc *APITokenUseCase) Create(ctx context.Context, name string, description ProjectIDs: options.projectIDs, Policies: policies, IsSystem: options.isSystem, + AllowedDigests: allowedDigests, }) if err != nil { if IsErrAlreadyExists(err) { diff --git a/app/controlplane/pkg/biz/apitoken_allowed_digests_test.go b/app/controlplane/pkg/biz/apitoken_allowed_digests_test.go new file mode 100644 index 000000000..06129e9b1 --- /dev/null +++ b/app/controlplane/pkg/biz/apitoken_allowed_digests_test.go @@ -0,0 +1,120 @@ +// +// 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 biz + +import ( + "context" + "testing" + + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/authz" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// allowedDigestsTokenRepo records the options of the token it creates; the embedded interface +// panics on anything else. +type allowedDigestsTokenRepo struct { + APITokenRepo + created *APITokenCreateOpts +} + +func (r *allowedDigestsTokenRepo) Create(_ context.Context, opts *APITokenCreateOpts) (*APIToken, error) { + r.created = opts + t := &APIToken{ID: uuid.New(), Name: opts.Name, Scope: opts.Scope, ScopeID: opts.ScopeID, Policies: opts.Policies, AllowedDigests: opts.AllowedDigests} + if opts.OrganizationID != nil { + t.OrganizationID = *opts.OrganizationID + } + + return t, nil +} + +// A token can be restricted to a list of sha256 digests. The list is stored deduplicated and +// sorted. Create refuses an empty list, a digest that is not sha256, and a token that can upload. +func TestCreateAPITokenWithAllowedDigests(t *testing.T) { + const ( + digestA = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + digestB = "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + // the refusal of a digest that does not parse + errInvalidDigest = "invalid digest" + ) + + orgID := uuid.New() + org := &Organization{ID: orgID.String(), Name: "acme"} + downloadOnly := APITokenWithPolicies([]*authz.Policy{authz.PolicyArtifactDownload}) + + testCases := []struct { + name string + opts []APITokenCreateOpt + // want is the stored list; nil means no restriction + want []string + wantErr string + }{ + {name: "no restriction", opts: []APITokenCreateOpt{downloadOnly}}, + {name: "one digest", opts: []APITokenCreateOpt{downloadOnly, APITokenWithAllowedDigests(digestA)}, want: []string{digestA}}, + { + name: "digests are deduplicated and sorted", + opts: []APITokenCreateOpt{downloadOnly, APITokenWithAllowedDigests(digestB, digestA, digestB)}, + want: []string{digestA, digestB}, + }, + {name: "an empty list", opts: []APITokenCreateOpt{downloadOnly, APITokenWithAllowedDigests()}, wantErr: "at least one digest"}, + {name: "an empty digest", opts: []APITokenCreateOpt{downloadOnly, APITokenWithAllowedDigests(digestA, "")}, wantErr: errInvalidDigest}, + {name: "a digest that is not one", opts: []APITokenCreateOpt{downloadOnly, APITokenWithAllowedDigests("sha256:nothex")}, wantErr: errInvalidDigest}, + {name: "a digest without its algorithm", opts: []APITokenCreateOpt{downloadOnly, APITokenWithAllowedDigests(digestA[len("sha256:"):])}, wantErr: errInvalidDigest}, + { + name: "a sha512 digest", + opts: []APITokenCreateOpt{downloadOnly, APITokenWithAllowedDigests("sha512:" + digestA[len("sha256:"):] + digestA[len("sha256:"):])}, + wantErr: "only sha256", + }, + { + name: "the default policies allow an upload", + opts: []APITokenCreateOpt{APITokenWithAllowedDigests(digestA)}, + wantErr: "upload", + }, + { + name: "explicit policies with the upload policy", + opts: []APITokenCreateOpt{ + APITokenWithPolicies([]*authz.Policy{authz.PolicyArtifactDownload, {Resource: authz.ResourceCASArtifact, Action: authz.ActionCreate}}), + APITokenWithAllowedDigests(digestA), + }, + wantErr: "upload", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + repo := &allowedDigestsTokenRepo{} + auditorUC, _ := newRecordingAuditor() + uc, err := NewAPITokenUseCase(repo, &APITokenJWTConfig{SymmetricHmacKey: "allowed-digests-hmac-key"}, nil, + &OrganizationUseCase{orgRepo: &auditOrgRepo{org: org}}, auditorUC, nil) + require.NoError(t, err) + + orgIDStr := orgID.String() + token, err := uc.Create(ctxWithAPITokenActor(context.Background()), "ci", nil, nil, &orgIDStr, tc.opts...) + if tc.wantErr != "" { + require.Error(t, err) + assert.True(t, IsErrValidation(err), "got %v", err) + assert.ErrorContains(t, err, tc.wantErr) + assert.Nil(t, repo.created, "a refused token is not stored") + return + } + + require.NoError(t, err) + assert.Equal(t, tc.want, repo.created.AllowedDigests) + assert.Equal(t, tc.want, token.AllowedDigests) + }) + } +} diff --git a/app/controlplane/pkg/biz/apitoken_integration_test.go b/app/controlplane/pkg/biz/apitoken_integration_test.go index d36ddb9c9..bb47e695a 100644 --- a/app/controlplane/pkg/biz/apitoken_integration_test.go +++ b/app/controlplane/pkg/biz/apitoken_integration_test.go @@ -18,6 +18,7 @@ package biz_test import ( "context" "fmt" + "slices" "testing" "time" @@ -1394,3 +1395,47 @@ func (s *apiTokenTestSuite) TestListProjectFilterDistinguishesEmptyFromNil() { } }) } + +// The allowed digests survive a round trip through the repository, from every read. A token +// created without them stores NULL, as every row from before the column does. +func (s *apiTokenTestSuite) TestRepoStoresTheAllowedDigests() { + ctx := context.Background() + const digest = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + downloadOnly := biz.APITokenWithPolicies([]*authz.Policy{authz.PolicyArtifactDownload}) + + testCases := []struct { + name string + opts []biz.APITokenCreateOpt + want []string + }{ + {name: "a restricted token", opts: []biz.APITokenCreateOpt{downloadOnly, biz.APITokenWithAllowedDigests(digest)}, want: []string{digest}}, + {name: "a restricted project token", opts: []biz.APITokenCreateOpt{downloadOnly, biz.APITokenWithProject(s.p1), biz.APITokenWithAllowedDigests(digest)}, want: []string{digest}}, + {name: "a token without the restriction", opts: []biz.APITokenCreateOpt{downloadOnly}}, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + token, err := s.APIToken.Create(ctx, randomName(), nil, nil, &s.org.ID, tc.opts...) + s.Require().NoError(err) + s.Equal(tc.want, token.AllowedDigests) + + byID, err := s.APIToken.FindByID(ctx, token.ID.String()) + s.Require().NoError(err) + s.Equal(tc.want, byID.AllowedDigests) + + inOrg, err := s.APIToken.FindByIDInOrg(ctx, s.org.ID, token.ID.String()) + s.Require().NoError(err) + s.Equal(tc.want, inOrg.AllowedDigests) + + listed, err := s.APIToken.List(ctx, s.org.ID) + s.Require().NoError(err) + idx := slices.IndexFunc(listed, func(t *biz.APIToken) bool { return t.ID == token.ID }) + s.Require().NotEqual(-1, idx) + s.Equal(tc.want, listed[idx].AllowedDigests) + + var isNull bool + s.Require().NoError(s.Data.SQLDB.QueryRowContext(ctx, "SELECT allowed_digests IS NULL FROM api_tokens WHERE id = $1", token.ID).Scan(&isNull)) + s.Equal(tc.want == nil, isNull) + }) + } +} diff --git a/app/controlplane/pkg/data/apitoken.go b/app/controlplane/pkg/data/apitoken.go index c2b0b7469..b62fb97bb 100644 --- a/app/controlplane/pkg/data/apitoken.go +++ b/app/controlplane/pkg/data/apitoken.go @@ -75,6 +75,10 @@ func (r *APITokenRepo) Create(ctx context.Context, opts *biz.APITokenCreateOpts) create = create.SetProjectIds(ids) } + if opts.AllowedDigests != nil { + create = create.SetAllowedDigests(opts.AllowedDigests) + } + token, err := create.Save(ctx) if err != nil { if ent.IsConstraintError(err) { @@ -320,6 +324,7 @@ func entAPITokenToBiz(t *ent.APIToken) *biz.APIToken { Scope: t.Scope, ScopeID: t.ScopeID, ProjectIDs: t.ProjectIds, + AllowedDigests: t.AllowedDigests, } // Add organization name if present diff --git a/app/controlplane/pkg/data/ent/apitoken.go b/app/controlplane/pkg/data/ent/apitoken.go index d721bcb3d..2962d0397 100644 --- a/app/controlplane/pkg/data/ent/apitoken.go +++ b/app/controlplane/pkg/data/ent/apitoken.go @@ -51,6 +51,8 @@ type APIToken struct { Policies []*authz.Policy `json:"policies,omitempty"` // IsSystem holds the value of the "is_system" field. IsSystem bool `json:"is_system,omitempty"` + // AllowedDigests holds the value of the "allowed_digests" field. + AllowedDigests []string `json:"allowed_digests,omitempty"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the APITokenQuery when eager-loading is set. Edges APITokenEdges `json:"edges"` @@ -110,7 +112,7 @@ func (*APIToken) scanValues(columns []string) ([]any, error) { switch columns[i] { case apitoken.FieldScopeID: values[i] = &sql.NullScanner{S: new(uuid.UUID)} - case apitoken.FieldProjectIds, apitoken.FieldPolicies: + case apitoken.FieldProjectIds, apitoken.FieldPolicies, apitoken.FieldAllowedDigests: values[i] = new([]byte) case apitoken.FieldIsSystem: values[i] = new(sql.NullBool) @@ -231,6 +233,14 @@ func (_m *APIToken) assignValues(columns []string, values []any) error { } else if value.Valid { _m.IsSystem = value.Bool } + case apitoken.FieldAllowedDigests: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field allowed_digests", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.AllowedDigests); err != nil { + return fmt.Errorf("unmarshal field allowed_digests: %w", err) + } + } default: _m.selectValues.Set(columns[i], values[i]) } @@ -327,6 +337,9 @@ func (_m *APIToken) String() string { builder.WriteString(", ") builder.WriteString("is_system=") builder.WriteString(fmt.Sprintf("%v", _m.IsSystem)) + builder.WriteString(", ") + builder.WriteString("allowed_digests=") + builder.WriteString(fmt.Sprintf("%v", _m.AllowedDigests)) builder.WriteByte(')') return builder.String() } diff --git a/app/controlplane/pkg/data/ent/apitoken/apitoken.go b/app/controlplane/pkg/data/ent/apitoken/apitoken.go index 863c3fc4c..3590b1f94 100644 --- a/app/controlplane/pkg/data/ent/apitoken/apitoken.go +++ b/app/controlplane/pkg/data/ent/apitoken/apitoken.go @@ -45,6 +45,8 @@ const ( FieldPolicies = "policies" // FieldIsSystem holds the string denoting the is_system field in the database. FieldIsSystem = "is_system" + // FieldAllowedDigests holds the string denoting the allowed_digests field in the database. + FieldAllowedDigests = "allowed_digests" // EdgeOrganization holds the string denoting the organization edge name in mutations. EdgeOrganization = "organization" // EdgeProject holds the string denoting the project edge name in mutations. @@ -93,6 +95,7 @@ var Columns = []string{ FieldProjectIds, FieldPolicies, FieldIsSystem, + FieldAllowedDigests, } // ValidColumn reports if the column name is valid (part of the table columns). diff --git a/app/controlplane/pkg/data/ent/apitoken/where.go b/app/controlplane/pkg/data/ent/apitoken/where.go index 9cf26d7ae..908bae842 100644 --- a/app/controlplane/pkg/data/ent/apitoken/where.go +++ b/app/controlplane/pkg/data/ent/apitoken/where.go @@ -652,6 +652,16 @@ func IsSystemNEQ(v bool) predicate.APIToken { return predicate.APIToken(sql.FieldNEQ(FieldIsSystem, v)) } +// AllowedDigestsIsNil applies the IsNil predicate on the "allowed_digests" field. +func AllowedDigestsIsNil() predicate.APIToken { + return predicate.APIToken(sql.FieldIsNull(FieldAllowedDigests)) +} + +// AllowedDigestsNotNil applies the NotNil predicate on the "allowed_digests" field. +func AllowedDigestsNotNil() predicate.APIToken { + return predicate.APIToken(sql.FieldNotNull(FieldAllowedDigests)) +} + // HasOrganization applies the HasEdge predicate on the "organization" edge. func HasOrganization() predicate.APIToken { return predicate.APIToken(func(s *sql.Selector) { diff --git a/app/controlplane/pkg/data/ent/apitoken_create.go b/app/controlplane/pkg/data/ent/apitoken_create.go index 98a839bca..ed8f0e9d8 100644 --- a/app/controlplane/pkg/data/ent/apitoken_create.go +++ b/app/controlplane/pkg/data/ent/apitoken_create.go @@ -200,6 +200,12 @@ func (_c *APITokenCreate) SetNillableIsSystem(v *bool) *APITokenCreate { return _c } +// SetAllowedDigests sets the "allowed_digests" field. +func (_c *APITokenCreate) SetAllowedDigests(v []string) *APITokenCreate { + _c.mutation.SetAllowedDigests(v) + return _c +} + // SetID sets the "id" field. func (_c *APITokenCreate) SetID(v uuid.UUID) *APITokenCreate { _c.mutation.SetID(v) @@ -374,6 +380,10 @@ func (_c *APITokenCreate) createSpec() (*APIToken, *sqlgraph.CreateSpec) { _spec.SetField(apitoken.FieldIsSystem, field.TypeBool, value) _node.IsSystem = value } + if value, ok := _c.mutation.AllowedDigests(); ok { + _spec.SetField(apitoken.FieldAllowedDigests, field.TypeJSON, value) + _node.AllowedDigests = value + } if nodes := _c.mutation.OrganizationIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -675,6 +685,24 @@ func (u *APITokenUpsert) ClearPolicies() *APITokenUpsert { return u } +// SetAllowedDigests sets the "allowed_digests" field. +func (u *APITokenUpsert) SetAllowedDigests(v []string) *APITokenUpsert { + u.Set(apitoken.FieldAllowedDigests, v) + return u +} + +// UpdateAllowedDigests sets the "allowed_digests" field to the value that was provided on create. +func (u *APITokenUpsert) UpdateAllowedDigests() *APITokenUpsert { + u.SetExcluded(apitoken.FieldAllowedDigests) + return u +} + +// ClearAllowedDigests clears the value of the "allowed_digests" field. +func (u *APITokenUpsert) ClearAllowedDigests() *APITokenUpsert { + u.SetNull(apitoken.FieldAllowedDigests) + return u +} + // UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. // Using this option is equivalent to using: // @@ -963,6 +991,27 @@ func (u *APITokenUpsertOne) ClearPolicies() *APITokenUpsertOne { }) } +// SetAllowedDigests sets the "allowed_digests" field. +func (u *APITokenUpsertOne) SetAllowedDigests(v []string) *APITokenUpsertOne { + return u.Update(func(s *APITokenUpsert) { + s.SetAllowedDigests(v) + }) +} + +// UpdateAllowedDigests sets the "allowed_digests" field to the value that was provided on create. +func (u *APITokenUpsertOne) UpdateAllowedDigests() *APITokenUpsertOne { + return u.Update(func(s *APITokenUpsert) { + s.UpdateAllowedDigests() + }) +} + +// ClearAllowedDigests clears the value of the "allowed_digests" field. +func (u *APITokenUpsertOne) ClearAllowedDigests() *APITokenUpsertOne { + return u.Update(func(s *APITokenUpsert) { + s.ClearAllowedDigests() + }) +} + // Exec executes the query. func (u *APITokenUpsertOne) Exec(ctx context.Context) error { if len(u.create.conflict) == 0 { @@ -1418,6 +1467,27 @@ func (u *APITokenUpsertBulk) ClearPolicies() *APITokenUpsertBulk { }) } +// SetAllowedDigests sets the "allowed_digests" field. +func (u *APITokenUpsertBulk) SetAllowedDigests(v []string) *APITokenUpsertBulk { + return u.Update(func(s *APITokenUpsert) { + s.SetAllowedDigests(v) + }) +} + +// UpdateAllowedDigests sets the "allowed_digests" field to the value that was provided on create. +func (u *APITokenUpsertBulk) UpdateAllowedDigests() *APITokenUpsertBulk { + return u.Update(func(s *APITokenUpsert) { + s.UpdateAllowedDigests() + }) +} + +// ClearAllowedDigests clears the value of the "allowed_digests" field. +func (u *APITokenUpsertBulk) ClearAllowedDigests() *APITokenUpsertBulk { + return u.Update(func(s *APITokenUpsert) { + s.ClearAllowedDigests() + }) +} + // Exec executes the query. func (u *APITokenUpsertBulk) Exec(ctx context.Context) error { if u.create.err != nil { diff --git a/app/controlplane/pkg/data/ent/apitoken_update.go b/app/controlplane/pkg/data/ent/apitoken_update.go index af3a89d1f..8133d28fb 100644 --- a/app/controlplane/pkg/data/ent/apitoken_update.go +++ b/app/controlplane/pkg/data/ent/apitoken_update.go @@ -251,6 +251,24 @@ func (_u *APITokenUpdate) ClearPolicies() *APITokenUpdate { return _u } +// SetAllowedDigests sets the "allowed_digests" field. +func (_u *APITokenUpdate) SetAllowedDigests(v []string) *APITokenUpdate { + _u.mutation.SetAllowedDigests(v) + return _u +} + +// AppendAllowedDigests appends value to the "allowed_digests" field. +func (_u *APITokenUpdate) AppendAllowedDigests(v []string) *APITokenUpdate { + _u.mutation.AppendAllowedDigests(v) + return _u +} + +// ClearAllowedDigests clears the value of the "allowed_digests" field. +func (_u *APITokenUpdate) ClearAllowedDigests() *APITokenUpdate { + _u.mutation.ClearAllowedDigests() + return _u +} + // SetOrganization sets the "organization" edge to the Organization entity. func (_u *APITokenUpdate) SetOrganization(v *Organization) *APITokenUpdate { return _u.SetOrganizationID(v.ID) @@ -402,6 +420,17 @@ func (_u *APITokenUpdate) sqlSave(ctx context.Context) (_node int, err error) { if _u.mutation.PoliciesCleared() { _spec.ClearField(apitoken.FieldPolicies, field.TypeJSON) } + if value, ok := _u.mutation.AllowedDigests(); ok { + _spec.SetField(apitoken.FieldAllowedDigests, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedAllowedDigests(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, apitoken.FieldAllowedDigests, value) + }) + } + if _u.mutation.AllowedDigestsCleared() { + _spec.ClearField(apitoken.FieldAllowedDigests, field.TypeJSON) + } if _u.mutation.OrganizationCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -727,6 +756,24 @@ func (_u *APITokenUpdateOne) ClearPolicies() *APITokenUpdateOne { return _u } +// SetAllowedDigests sets the "allowed_digests" field. +func (_u *APITokenUpdateOne) SetAllowedDigests(v []string) *APITokenUpdateOne { + _u.mutation.SetAllowedDigests(v) + return _u +} + +// AppendAllowedDigests appends value to the "allowed_digests" field. +func (_u *APITokenUpdateOne) AppendAllowedDigests(v []string) *APITokenUpdateOne { + _u.mutation.AppendAllowedDigests(v) + return _u +} + +// ClearAllowedDigests clears the value of the "allowed_digests" field. +func (_u *APITokenUpdateOne) ClearAllowedDigests() *APITokenUpdateOne { + _u.mutation.ClearAllowedDigests() + return _u +} + // SetOrganization sets the "organization" edge to the Organization entity. func (_u *APITokenUpdateOne) SetOrganization(v *Organization) *APITokenUpdateOne { return _u.SetOrganizationID(v.ID) @@ -908,6 +955,17 @@ func (_u *APITokenUpdateOne) sqlSave(ctx context.Context) (_node *APIToken, err if _u.mutation.PoliciesCleared() { _spec.ClearField(apitoken.FieldPolicies, field.TypeJSON) } + if value, ok := _u.mutation.AllowedDigests(); ok { + _spec.SetField(apitoken.FieldAllowedDigests, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedAllowedDigests(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, apitoken.FieldAllowedDigests, value) + }) + } + if _u.mutation.AllowedDigestsCleared() { + _spec.ClearField(apitoken.FieldAllowedDigests, field.TypeJSON) + } if _u.mutation.OrganizationCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, diff --git a/app/controlplane/pkg/data/ent/migrate/migrations/20261123100107.sql b/app/controlplane/pkg/data/ent/migrate/migrations/20261123100107.sql new file mode 100644 index 000000000..a7ea0854b --- /dev/null +++ b/app/controlplane/pkg/data/ent/migrate/migrations/20261123100107.sql @@ -0,0 +1,2 @@ +-- Modify "api_tokens" table +ALTER TABLE "api_tokens" ADD COLUMN "allowed_digests" jsonb NULL; diff --git a/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum b/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum index a7e2c006b..a36b10cee 100644 --- a/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum +++ b/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum @@ -1,4 +1,4 @@ -h1:4KMWUuBSeBXXhOyu1wmPspCWeaT/kyYJdwYewEOc6JU= +h1:SppLKAK6TS5ez9HgwBcC+QB7QjPnjcbuLadz7XtQnLg= 20230706165452_init-schema.sql h1:VvqbNFEQnCvUVyj2iDYVQQxDM0+sSXqocpt/5H64k8M= 20230710111950-cas-backend.sql h1:A8iBuSzZIEbdsv9ipBtscZQuaBp3V5/VMw7eZH6GX+g= 20230712094107-cas-backends-workflow-runs.sql h1:a5rzxpVGyd56nLRSsKrmCFc9sebg65RWzLghKHh5xvI= @@ -147,3 +147,4 @@ h1:4KMWUuBSeBXXhOyu1wmPspCWeaT/kyYJdwYewEOc6JU= 20261116124542.sql h1:PNFvP+qcO1URsP9QsKGpAwaAL9m7yP7bzi/8SHk6yNs= 20261116124543.sql h1:r+8IOuLFQ3iMrQjYN8hPGxItVJu/bidc0/yeEUe6RFQ= 20261117162118.sql h1:kihy12JzE5ELo0Jy79LjMs8X4BBgmCjsh8Q1kpFp60c= +20261123100107.sql h1:cF7R2gZuArdEgrMSYTuthqo2ZsXFdf7FEqrNNimNCN0= diff --git a/app/controlplane/pkg/data/ent/migrate/schema.go b/app/controlplane/pkg/data/ent/migrate/schema.go index 9fe082722..685048d03 100644 --- a/app/controlplane/pkg/data/ent/migrate/schema.go +++ b/app/controlplane/pkg/data/ent/migrate/schema.go @@ -23,6 +23,7 @@ var ( {Name: "project_ids", Type: field.TypeJSON, Nullable: true}, {Name: "policies", Type: field.TypeJSON, Nullable: true}, {Name: "is_system", Type: field.TypeBool, Default: false}, + {Name: "allowed_digests", Type: field.TypeJSON, Nullable: true}, {Name: "project_id", Type: field.TypeUUID, Nullable: true}, {Name: "workflow_id", Type: field.TypeUUID, Nullable: true}, {Name: "organization_id", Type: field.TypeUUID, Nullable: true}, @@ -35,19 +36,19 @@ var ( ForeignKeys: []*schema.ForeignKey{ { Symbol: "api_tokens_projects_project", - Columns: []*schema.Column{APITokensColumns[12]}, + Columns: []*schema.Column{APITokensColumns[13]}, RefColumns: []*schema.Column{ProjectsColumns[0]}, OnDelete: schema.SetNull, }, { Symbol: "api_tokens_workflows_workflow", - Columns: []*schema.Column{APITokensColumns[13]}, + Columns: []*schema.Column{APITokensColumns[14]}, RefColumns: []*schema.Column{WorkflowsColumns[0]}, OnDelete: schema.SetNull, }, { Symbol: "api_tokens_organizations_api_tokens", - Columns: []*schema.Column{APITokensColumns[14]}, + Columns: []*schema.Column{APITokensColumns[15]}, RefColumns: []*schema.Column{OrganizationsColumns[0]}, OnDelete: schema.Cascade, }, @@ -56,7 +57,7 @@ var ( { Name: "apitoken_name_organization_id", Unique: true, - Columns: []*schema.Column{APITokensColumns[1], APITokensColumns[14]}, + Columns: []*schema.Column{APITokensColumns[1], APITokensColumns[15]}, Annotation: &entsql.IndexAnnotation{ Where: "revoked_at IS NULL AND project_id IS NULL AND (scope IS NULL OR scope <> 'product')", }, @@ -72,7 +73,7 @@ var ( { Name: "apitoken_name_project_id", Unique: true, - Columns: []*schema.Column{APITokensColumns[1], APITokensColumns[12]}, + Columns: []*schema.Column{APITokensColumns[1], APITokensColumns[13]}, Annotation: &entsql.IndexAnnotation{ Where: "revoked_at IS NULL AND project_id IS NOT NULL", }, diff --git a/app/controlplane/pkg/data/ent/mutation.go b/app/controlplane/pkg/data/ent/mutation.go index 494a7c000..244898714 100644 --- a/app/controlplane/pkg/data/ent/mutation.go +++ b/app/controlplane/pkg/data/ent/mutation.go @@ -77,32 +77,34 @@ const ( // APITokenMutation represents an operation that mutates the APIToken nodes in the graph. type APITokenMutation struct { config - op Op - typ string - id *uuid.UUID - name *string - description *string - created_at *time.Time - expires_at *time.Time - revoked_at *time.Time - last_used_at *time.Time - scope *authz.ResourceType - scope_id *uuid.UUID - project_ids *[]uuid.UUID - appendproject_ids []uuid.UUID - policies *[]*authz.Policy - appendpolicies []*authz.Policy - is_system *bool - clearedFields map[string]struct{} - organization *uuid.UUID - clearedorganization bool - project *uuid.UUID - clearedproject bool - workflow *uuid.UUID - clearedworkflow bool - done bool - oldValue func(context.Context) (*APIToken, error) - predicates []predicate.APIToken + op Op + typ string + id *uuid.UUID + name *string + description *string + created_at *time.Time + expires_at *time.Time + revoked_at *time.Time + last_used_at *time.Time + scope *authz.ResourceType + scope_id *uuid.UUID + project_ids *[]uuid.UUID + appendproject_ids []uuid.UUID + policies *[]*authz.Policy + appendpolicies []*authz.Policy + is_system *bool + allowed_digests *[]string + appendallowed_digests []string + clearedFields map[string]struct{} + organization *uuid.UUID + clearedorganization bool + project *uuid.UUID + clearedproject bool + workflow *uuid.UUID + clearedworkflow bool + done bool + oldValue func(context.Context) (*APIToken, error) + predicates []predicate.APIToken } var _ ent.Mutation = (*APITokenMutation)(nil) @@ -888,6 +890,71 @@ func (m *APITokenMutation) ResetIsSystem() { m.is_system = nil } +// SetAllowedDigests sets the "allowed_digests" field. +func (m *APITokenMutation) SetAllowedDigests(s []string) { + m.allowed_digests = &s + m.appendallowed_digests = nil +} + +// AllowedDigests returns the value of the "allowed_digests" field in the mutation. +func (m *APITokenMutation) AllowedDigests() (r []string, exists bool) { + v := m.allowed_digests + if v == nil { + return + } + return *v, true +} + +// OldAllowedDigests returns the old "allowed_digests" field's value of the APIToken entity. +// If the APIToken object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *APITokenMutation) OldAllowedDigests(ctx context.Context) (v []string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAllowedDigests is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAllowedDigests requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAllowedDigests: %w", err) + } + return oldValue.AllowedDigests, nil +} + +// AppendAllowedDigests adds s to the "allowed_digests" field. +func (m *APITokenMutation) AppendAllowedDigests(s []string) { + m.appendallowed_digests = append(m.appendallowed_digests, s...) +} + +// AppendedAllowedDigests returns the list of values that were appended to the "allowed_digests" field in this mutation. +func (m *APITokenMutation) AppendedAllowedDigests() ([]string, bool) { + if len(m.appendallowed_digests) == 0 { + return nil, false + } + return m.appendallowed_digests, true +} + +// ClearAllowedDigests clears the value of the "allowed_digests" field. +func (m *APITokenMutation) ClearAllowedDigests() { + m.allowed_digests = nil + m.appendallowed_digests = nil + m.clearedFields[apitoken.FieldAllowedDigests] = struct{}{} +} + +// AllowedDigestsCleared returns if the "allowed_digests" field was cleared in this mutation. +func (m *APITokenMutation) AllowedDigestsCleared() bool { + _, ok := m.clearedFields[apitoken.FieldAllowedDigests] + return ok +} + +// ResetAllowedDigests resets all changes to the "allowed_digests" field. +func (m *APITokenMutation) ResetAllowedDigests() { + m.allowed_digests = nil + m.appendallowed_digests = nil + delete(m.clearedFields, apitoken.FieldAllowedDigests) +} + // ClearOrganization clears the "organization" edge to the Organization entity. func (m *APITokenMutation) ClearOrganization() { m.clearedorganization = true @@ -1003,7 +1070,7 @@ func (m *APITokenMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *APITokenMutation) Fields() []string { - fields := make([]string, 0, 14) + fields := make([]string, 0, 15) if m.name != nil { fields = append(fields, apitoken.FieldName) } @@ -1046,6 +1113,9 @@ func (m *APITokenMutation) Fields() []string { if m.is_system != nil { fields = append(fields, apitoken.FieldIsSystem) } + if m.allowed_digests != nil { + fields = append(fields, apitoken.FieldAllowedDigests) + } return fields } @@ -1082,6 +1152,8 @@ func (m *APITokenMutation) Field(name string) (ent.Value, bool) { return m.Policies() case apitoken.FieldIsSystem: return m.IsSystem() + case apitoken.FieldAllowedDigests: + return m.AllowedDigests() } return nil, false } @@ -1119,6 +1191,8 @@ func (m *APITokenMutation) OldField(ctx context.Context, name string) (ent.Value return m.OldPolicies(ctx) case apitoken.FieldIsSystem: return m.OldIsSystem(ctx) + case apitoken.FieldAllowedDigests: + return m.OldAllowedDigests(ctx) } return nil, fmt.Errorf("unknown APIToken field %s", name) } @@ -1226,6 +1300,13 @@ func (m *APITokenMutation) SetField(name string, value ent.Value) error { } m.SetIsSystem(v) return nil + case apitoken.FieldAllowedDigests: + v, ok := value.([]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAllowedDigests(v) + return nil } return fmt.Errorf("unknown APIToken field %s", name) } @@ -1289,6 +1370,9 @@ func (m *APITokenMutation) ClearedFields() []string { if m.FieldCleared(apitoken.FieldPolicies) { fields = append(fields, apitoken.FieldPolicies) } + if m.FieldCleared(apitoken.FieldAllowedDigests) { + fields = append(fields, apitoken.FieldAllowedDigests) + } return fields } @@ -1336,6 +1420,9 @@ func (m *APITokenMutation) ClearField(name string) error { case apitoken.FieldPolicies: m.ClearPolicies() return nil + case apitoken.FieldAllowedDigests: + m.ClearAllowedDigests() + return nil } return fmt.Errorf("unknown APIToken nullable field %s", name) } @@ -1386,6 +1473,9 @@ func (m *APITokenMutation) ResetField(name string) error { case apitoken.FieldIsSystem: m.ResetIsSystem() return nil + case apitoken.FieldAllowedDigests: + m.ResetAllowedDigests() + return nil } return fmt.Errorf("unknown APIToken field %s", name) } diff --git a/app/controlplane/pkg/data/ent/schema/apitoken.go b/app/controlplane/pkg/data/ent/schema/apitoken.go index 073f5ff08..838482003 100644 --- a/app/controlplane/pkg/data/ent/schema/apitoken.go +++ b/app/controlplane/pkg/data/ent/schema/apitoken.go @@ -67,6 +67,9 @@ func (APIToken) Fields() []ent.Field { field.JSON("policies", []*authz.Policy{}).Optional(), // System tokens are minted by internal code paths and hidden from the public API. field.Bool("is_system").Default(false).Immutable(), + // The artifact digests the token can download from the CAS. NULL means no restriction. + // When set, the CAS credentials it gets are always scoped to one of these digests. + field.JSON("allowed_digests", []string{}).Optional(), } } diff --git a/app/controlplane/pkg/usercontext/entities/apitoken.go b/app/controlplane/pkg/usercontext/entities/apitoken.go index 93ac5471a..ae96e2272 100644 --- a/app/controlplane/pkg/usercontext/entities/apitoken.go +++ b/app/controlplane/pkg/usercontext/entities/apitoken.go @@ -44,6 +44,9 @@ type APIToken struct { ProjectIDs []uuid.UUID // IsSystem marks tokens minted by internal code paths; these are hidden from the public API. IsSystem bool + // AllowedDigests are the only artifacts the token can download from the CAS, loaded from the + // row. Nil means no restriction. + AllowedDigests []string } // IsProductScoped reports whether the token is confined to a product: it reaches the projects in