Skip to content
Closed
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
28 changes: 27 additions & 1 deletion app/controlplane/internal/service/cascredential.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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()
}

Expand All @@ -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
}
44 changes: 44 additions & 0 deletions app/controlplane/internal/service/cascredential_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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)
})
}
}
8 changes: 7 additions & 1 deletion app/controlplane/internal/service/casredirect.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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()
}

Expand Down
83 changes: 83 additions & 0 deletions app/controlplane/internal/service/casredirect_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"net/url"
"os"
"path/filepath"
Expand All @@ -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"
)
Expand Down Expand Up @@ -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{}
Expand All @@ -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())
Expand Down
31 changes: 16 additions & 15 deletions app/controlplane/internal/usercontext/apitoken_middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions app/controlplane/internal/usercontext/apitoken_middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}{
Expand All @@ -338,13 +340,22 @@ 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 {
t.Run(tc.name, func(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)
Expand Down Expand Up @@ -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)
})
}
}
Expand Down
Loading
Loading