From 6cbdd7b1078b724889a70613415e82cd9c3d0f3a Mon Sep 17 00:00:00 2001 From: Javier Rodriguez Date: Mon, 23 Nov 2026 12:54:47 +0100 Subject: [PATCH] feat(cli): download an artifact with a ready CAS credential `chainloop artifact download` can use a CAS credential that the client obtained before. Set it with the CHAINLOOP_ARTIFACT_CAS_TOKEN environment variable or with the --artifact-cas-token flag. The command then connects to the CAS API with this credential, and it needs no API token and no control plane call. The CAS credential has precedence over the API token. Without a CAS credential, the command gets one from the control plane as before. When the CAS does not accept the credential, the command now reports that, instead of "artifact not found". Signed-off-by: Javier Rodriguez Assisted-by: Claude Code Chainloop-Trace-Sessions: 5aac1986-3c81-429d-a6e2-ba72c55819b9 --- app/cli/cmd/artifact.go | 34 ++- app/cli/cmd/artifact_download.go | 66 ++++- app/cli/cmd/artifact_download_test.go | 327 ++++++++++++++++++++++++ app/cli/cmd/artifact_upload.go | 2 +- app/cli/documentation/cli-reference.md | 9 +- app/cli/pkg/action/artifact_download.go | 6 + 6 files changed, 417 insertions(+), 27 deletions(-) create mode 100644 app/cli/cmd/artifact_download_test.go diff --git a/app/cli/cmd/artifact.go b/app/cli/cmd/artifact.go index 83a57b14a..41069291c 100644 --- a/app/cli/cmd/artifact.go +++ b/app/cli/cmd/artifact.go @@ -36,15 +36,13 @@ func newArtifactCmd() *cobra.Command { return cmd } -func wrappedArtifactConn(cpConn *grpc.ClientConn, role pb.CASCredentialsServiceGetRequest_Role, digest string) (*grpc.ClientConn, error) { - // Retrieve temporary credentials for the operation - client := pb.NewCASCredentialsServiceClient(cpConn) - resp, err := client.Get(context.Background(), &pb.CASCredentialsServiceGetRequest{ - Role: role, - Digest: digest, - // an upload or a download is for a single digest, so the token can only access that digest - ScopeToDigest: digest != "", - }) +// wrappedArtifactConn connects to the CAS API with casToken or, when casToken is empty, +// with a temporary credential from the control plane +func wrappedArtifactConn(cpConn *grpc.ClientConn, role pb.CASCredentialsServiceGetRequest_Role, digest, casToken string) (*grpc.ClientConn, error) { + var err error + if casToken == "" { + casToken, err = casCredentialFromControlPlane(cpConn, role, digest) + } if err != nil { return nil, err } @@ -70,5 +68,21 @@ func wrappedArtifactConn(cpConn *grpc.ClientConn, role pb.CASCredentialsServiceG } } - return grpcconn.New(viper.GetString(confOptions.CASAPI.viperKey), resp.Result.Token, opts...) + return grpcconn.New(viper.GetString(confOptions.CASAPI.viperKey), casToken, opts...) +} + +// casCredentialFromControlPlane retrieves temporary credentials for the operation +func casCredentialFromControlPlane(cpConn *grpc.ClientConn, role pb.CASCredentialsServiceGetRequest_Role, digest string) (string, error) { + client := pb.NewCASCredentialsServiceClient(cpConn) + resp, err := client.Get(context.Background(), &pb.CASCredentialsServiceGetRequest{ + Role: role, + Digest: digest, + // an upload or a download is for a single digest, so the token can only access that digest + ScopeToDigest: digest != "", + }) + if err != nil { + return "", err + } + + return resp.Result.Token, nil } diff --git a/app/cli/cmd/artifact_download.go b/app/cli/cmd/artifact_download.go index 93f0deb14..2c021e635 100644 --- a/app/cli/cmd/artifact_download.go +++ b/app/cli/cmd/artifact_download.go @@ -1,5 +1,5 @@ // -// Copyright 2024 The Chainloop Authors. +// Copyright 2024-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. @@ -17,6 +17,10 @@ package cmd import ( "errors" + "fmt" + "os" + "slices" + "strings" "github.com/chainloop-dev/chainloop/app/cli/pkg/action" pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" @@ -24,39 +28,56 @@ import ( "google.golang.org/grpc" ) +//nolint:gosec +const artifactCASTokenEnvVarName = "CHAINLOOP_ARTIFACT_CAS_TOKEN" + func newArtifactDownloadCmd() *cobra.Command { - var digest, downloadPath, outputFile string + var digest, downloadPath, outputFile, casTokenFlag string var artifactCASConn *grpc.ClientConn + var actionOpts *action.ActionsOpts cmd := &cobra.Command{ Use: "download", Short: "download an artifact", - PreRunE: func(cmd *cobra.Command, args []string) error { - var err error - + // Root does not build the control plane connection for this command: PreRunE builds it + // only when no CAS credential is set. Telemetry reports the command in both cases. + Annotations: map[string]string{skipActionOptsInit: trueString, reportTelemetryAnyway: trueString}, + PreRunE: func(cmd *cobra.Command, _ []string) error { if err := validateFlags(downloadPath, outputFile); err != nil { return err } - // Retrieve temporary credentials for uploading - artifactCASConn, err = wrappedArtifactConn(ActionOpts.CPConnection, - pb.CASCredentialsServiceGetRequest_ROLE_DOWNLOADER, digest) + casToken, err := artifactCASToken(casTokenFlag) if err != nil { return err } - return nil + // A CAS credential replaces the API token and the control plane + var cpConn *grpc.ClientConn + if casToken == "" { + if err := ensureActionOpts(cmd); err != nil { + return err + } + actionOpts, cpConn = ActionOpts, ActionOpts.CPConnection + } else { + logger.Debug().Msg("using the given CAS credential, the control plane is not contacted") + actionOpts = newActionOpts(logger, nil, "") + } + + artifactCASConn, err = wrappedArtifactConn(cpConn, + pb.CASCredentialsServiceGetRequest_ROLE_DOWNLOADER, digest, casToken) + return err }, - RunE: func(cmd *cobra.Command, args []string) error { + RunE: func(cmd *cobra.Command, _ []string) error { opts := &action.ArtifactDownloadOpts{ - ActionsOpts: ActionOpts, + ActionsOpts: actionOpts, ArtifactsCASConn: artifactCASConn, Stdout: cmd.OutOrStdout(), } return action.NewArtifactDownload(opts).Run(downloadPath, outputFile, digest) }, - PostRunE: func(cmd *cobra.Command, args []string) error { + PostRunE: func(_ *cobra.Command, _ []string) error { if artifactCASConn != nil { return artifactCASConn.Close() } @@ -70,10 +91,31 @@ func newArtifactDownloadCmd() *cobra.Command { cobra.CheckErr(err) cmd.Flags().StringVar(&downloadPath, "path", "", "download path, default to current directory") cmd.Flags().StringVar(&outputFile, "output", "", "The `file` to write a single asset to (use \"-\" to write to standard output") + cmd.Flags().StringVar(&casTokenFlag, "artifact-cas-token", "", fmt.Sprintf("CAS download credential for --digest, used instead of the API token and the control plane. NOTE: Prefer the env variable %s", artifactCASTokenEnvVarName)) return cmd } +// artifactCASToken returns the CAS credential from the flag or, when the flag is empty, +// from the environment. The CAS verifies the credential; this only rejects a non-JWT value. +func artifactCASToken(flagValue string) (string, error) { + token := flagValue + if token == "" { + token = os.Getenv(artifactCASTokenEnvVarName) + } + + token = strings.TrimSpace(token) + if token == "" { + return "", nil + } + + if parts := strings.Split(token, "."); len(parts) != 3 || slices.Contains(parts, "") { + return "", errors.New("the CAS credential is not a JWT") + } + + return token, nil +} + // validateFlags checks if the flags are valid func validateFlags(downloadPath, outputFile string) error { if downloadPath != "" && outputFile != "" { diff --git a/app/cli/cmd/artifact_download_test.go b/app/cli/cmd/artifact_download_test.go new file mode 100644 index 000000000..66efee028 --- /dev/null +++ b/app/cli/cmd/artifact_download_test.go @@ -0,0 +1,327 @@ +// +// 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 cmd + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "net" + "os" + "path/filepath" + "sync" + "testing" + + casv1 "github.com/chainloop-dev/chainloop/app/artifact-cas/api/cas/v1" + pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" + "github.com/rs/zerolog" + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/genproto/googleapis/bytestream" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +const ( + testCASToken = "cas-header.cas-claims.cas-signature" + testMintedToken = "minted-header.minted-claims.minted-signature" + testAPIToken = "api-token" +) + +func TestArtifactDownloadCASCredential(t *testing.T) { + content := []byte("hello world") + sum := sha256.Sum256(content) + digestHex := hex.EncodeToString(sum[:]) + + testCases := []struct { + name string + env map[string]string + args []string + casToken string + // wantCPToken is the API token of the CAS credentials request, empty when the control plane gets no call + wantCPToken string + wantCASToken string + wantErr string + }{ + { + name: "the CAS credential from the environment downloads without the control plane", + env: map[string]string{artifactCASTokenEnvVarName: testCASToken}, + casToken: testCASToken, + wantCASToken: testCASToken, + }, + { + name: "the CAS credential from the flag downloads without the control plane", + args: []string{"--artifact-cas-token", testCASToken}, + casToken: testCASToken, + wantCASToken: testCASToken, + }, + { + name: "the CAS credential has precedence over the API token", + env: map[string]string{artifactCASTokenEnvVarName: testCASToken, tokenEnvVarName: testAPIToken}, + casToken: testCASToken, + wantCASToken: testCASToken, + }, + { + name: "without a CAS credential the control plane gives one for the digest", + env: map[string]string{tokenEnvVarName: testAPIToken}, + casToken: testMintedToken, + wantCPToken: testAPIToken, + wantCASToken: testMintedToken, + }, + { + name: "a value that is not a JWT fails before any request", + env: map[string]string{artifactCASTokenEnvVarName: "not-a-jwt"}, + casToken: testCASToken, + wantErr: "the CAS credential is not a JWT", + }, + { + name: "a credential that the CAS does not accept is reported", + env: map[string]string{artifactCASTokenEnvVarName: testCASToken}, + casToken: "other-header.other-claims.other-signature", + wantCASToken: testCASToken, + wantErr: "the CAS did not accept the credential", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + cp := &fakeCASCredentials{token: testMintedToken} + cpAddr, cpCalls := startFakeGRPCServer(t, func(s *grpc.Server) { + pb.RegisterCASCredentialsServiceServer(s, cp) + }) + + cas := &fakeCAS{token: tc.casToken, digestHex: digestHex, content: content} + casAddr, _ := startFakeGRPCServer(t, func(s *grpc.Server) { + casv1.RegisterResourceServiceServer(s, cas) + bytestream.RegisterByteStreamServer(s, cas) + }) + + // The environment of the test run must not provide credentials + t.Setenv(tokenEnvVarName, "") + t.Setenv(artifactCASTokenEnvVarName, "") + for k, v := range tc.env { + t.Setenv(k, v) + } + + outputFile := filepath.Join(t.TempDir(), "artifact.txt") + args := append([]string{"artifact", "download", "--digest", "sha256:" + digestHex, "--output", outputFile}, tc.args...) + err := runTestCommand(t, cpAddr, casAddr, args...) + + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + } else { + require.NoError(t, err) + got, err := os.ReadFile(outputFile) + require.NoError(t, err) + assert.Equal(t, content, got) + } + + assert.Equal(t, tc.wantCASToken, cas.lastToken()) + + if tc.wantCPToken == "" { + assert.Empty(t, cpCalls(), "the control plane must not get a call") + return + } + + assert.Equal(t, 1, countOf(cpCalls(), pb.CASCredentialsService_Get_FullMethodName)) + req, token := cp.lastRequest() + assert.Equal(t, tc.wantCPToken, token) + assert.True(t, proto.Equal(&pb.CASCredentialsServiceGetRequest{ + Role: pb.CASCredentialsServiceGetRequest_ROLE_DOWNLOADER, + Digest: "sha256:" + digestHex, + ScopeToDigest: true, + }, req), "unexpected request: %v", req) + }) + } +} + +// The command builds its control plane connection itself, and telemetry still reports it +func TestArtifactDownloadIsReported(t *testing.T) { + assert.True(t, shouldReportCommand(newArtifactDownloadCmd())) +} + +// runTestCommand runs the CLI with a temporary config file against the given servers. +// It sets no organization, so the root initialization would ask the control plane for one. +func runTestCommand(t *testing.T, cpAddr, casAddr string, args ...string) error { + t.Helper() + + viper.Reset() + t.Cleanup(viper.Reset) + prevActionOpts, prevLogger := ActionOpts, logger + ActionOpts = nil + t.Cleanup(func() { ActionOpts, logger = prevActionOpts, prevLogger }) + + configFile := filepath.Join(t.TempDir(), "config.toml") + require.NoError(t, os.WriteFile(configFile, nil, 0o600)) + + root := NewRootCmd(zerolog.Nop()) + root.SetArgs(append(args, + "--config", configFile, + "--control-plane", cpAddr, + "--artifact-cas", casAddr, + "-i", // the test servers have no TLS + )) + + return root.Execute() +} + +// startFakeGRPCServer serves the registered services on a local port and records the methods it gets +func startFakeGRPCServer(t *testing.T, register func(*grpc.Server)) (string, func() []string) { + t.Helper() + + var mu sync.Mutex + var calls []string + record := func(method string) { + mu.Lock() + defer mu.Unlock() + calls = append(calls, method) + } + + s := grpc.NewServer( + grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + record(info.FullMethod) + return handler(ctx, req) + }), + grpc.StreamInterceptor(func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + record(info.FullMethod) + return handler(srv, ss) + }), + // The interceptors do not see the methods of services that are not registered + grpc.UnknownServiceHandler(func(_ any, ss grpc.ServerStream) error { + method, _ := grpc.MethodFromServerStream(ss) + record(method) + return status.Error(codes.Unimplemented, "unknown service") + }), + ) + register(s) + + l, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + go func() { _ = s.Serve(l) }() + t.Cleanup(s.Stop) + + return l.Addr().String(), func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), calls...) + } +} + +func countOf(calls []string, method string) int { + n := 0 + for _, c := range calls { + if c == method { + n++ + } + } + + return n +} + +func bearerToken(ctx context.Context) string { + md, _ := metadata.FromIncomingContext(ctx) + if v := md.Get("authorization"); len(v) > 0 && len(v[0]) > len("Bearer ") { + return v[0][len("Bearer "):] + } + + return "" +} + +// fakeCASCredentials returns a fixed CAS credential and records the last request +type fakeCASCredentials struct { + pb.UnimplementedCASCredentialsServiceServer + token string + + mu sync.Mutex + req *pb.CASCredentialsServiceGetRequest + reqAuth string +} + +func (f *fakeCASCredentials) Get(ctx context.Context, req *pb.CASCredentialsServiceGetRequest) (*pb.CASCredentialsServiceGetResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.req, f.reqAuth = req, bearerToken(ctx) + + return &pb.CASCredentialsServiceGetResponse{Result: &pb.CASCredentialsServiceGetResponse_Result{Token: f.token}}, nil +} + +func (f *fakeCASCredentials) lastRequest() (*pb.CASCredentialsServiceGetRequest, string) { + f.mu.Lock() + defer f.mu.Unlock() + return f.req, f.reqAuth +} + +// fakeCAS serves one artifact to requests with the expected credential +type fakeCAS struct { + casv1.UnimplementedResourceServiceServer + bytestream.UnimplementedByteStreamServer + token string + digestHex string + content []byte + + mu sync.Mutex + seen string +} + +func (f *fakeCAS) authorize(ctx context.Context) error { + got := bearerToken(ctx) + + f.mu.Lock() + f.seen = got + f.mu.Unlock() + + if got != f.token { + return status.Error(codes.Unauthenticated, "unexpected credential") + } + + return nil +} + +func (f *fakeCAS) lastToken() string { + f.mu.Lock() + defer f.mu.Unlock() + return f.seen +} + +func (f *fakeCAS) Describe(ctx context.Context, req *casv1.ResourceServiceDescribeRequest) (*casv1.ResourceServiceDescribeResponse, error) { + if err := f.authorize(ctx); err != nil { + return nil, err + } + + if req.GetDigest() != f.digestHex { + return nil, status.Error(codes.NotFound, "artifact not found") + } + + return &casv1.ResourceServiceDescribeResponse{Result: &casv1.CASResource{ + FileName: "artifact.txt", Digest: f.digestHex, Size: int64(len(f.content)), + }}, nil +} + +func (f *fakeCAS) Read(req *bytestream.ReadRequest, stream bytestream.ByteStream_ReadServer) error { + if err := f.authorize(stream.Context()); err != nil { + return err + } + + if req.GetResourceName() != f.digestHex { + return status.Error(codes.NotFound, "artifact not found") + } + + return stream.Send(&bytestream.ReadResponse{Data: f.content}) +} diff --git a/app/cli/cmd/artifact_upload.go b/app/cli/cmd/artifact_upload.go index d8b033502..91d2c2bb7 100644 --- a/app/cli/cmd/artifact_upload.go +++ b/app/cli/cmd/artifact_upload.go @@ -49,7 +49,7 @@ func newArtifactUploadCmd() *cobra.Command { } // Retrieve temporary credentials for uploading, scoped to the file digest - artifactCASConn, err = wrappedArtifactConn(ActionOpts.CPConnection, pb.CASCredentialsServiceGetRequest_ROLE_UPLOADER, digest) + artifactCASConn, err = wrappedArtifactConn(ActionOpts.CPConnection, pb.CASCredentialsServiceGetRequest_ROLE_UPLOADER, digest, "") if err != nil { return err } diff --git a/app/cli/documentation/cli-reference.md b/app/cli/documentation/cli-reference.md index d0f757571..eef7d34aa 100644 --- a/app/cli/documentation/cli-reference.md +++ b/app/cli/documentation/cli-reference.md @@ -93,10 +93,11 @@ chainloop artifact download [flags] Options ``` --d, --digest string digest of the file to download --h, --help[=true|false] help for download ---output file The file to write a single asset to (use "-" to write to standard output ---path string download path, default to current directory +--artifact-cas-token string CAS download credential for --digest, used instead of the API token and the control plane. NOTE: Prefer the env variable CHAINLOOP_ARTIFACT_CAS_TOKEN +-d, --digest string digest of the file to download +-h, --help[=true|false] help for download +--output file The file to write a single asset to (use "-" to write to standard output +--path string download path, default to current directory ``` Options inherited from parent commands diff --git a/app/cli/pkg/action/artifact_download.go b/app/cli/pkg/action/artifact_download.go index d6bce93aa..e07257e39 100644 --- a/app/cli/pkg/action/artifact_download.go +++ b/app/cli/pkg/action/artifact_download.go @@ -31,6 +31,8 @@ import ( "github.com/chainloop-dev/chainloop/pkg/casclient" "github.com/jedib0t/go-pretty/v6/progress" "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" crv1 "github.com/google/go-containerregistry/pkg/v1" ) @@ -61,6 +63,10 @@ func (a *ArtifactDownload) Run(downloadPath, outputFile, digest string) error { ctx := context.Background() info, err := client.Describe(ctx, h.String()) if err != nil { + if code := status.Code(err); code == codes.Unauthenticated || code == codes.PermissionDenied { + return fmt.Errorf("the CAS did not accept the credential for artifact %s: %w", h, err) + } + return fmt.Errorf("artifact with digest %s not found", h) }