From 73eb044a633dc34705e3fdde1aff55913c7b3169 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Tue, 17 Nov 2026 13:16:01 +0100 Subject: [PATCH] fix(cli): fail attestation add on a duplicate material name Adding a material with a name that is already in the attestation silently overwrote the previous one. It now fails and tells the user to use a different --name, or to pass the new --replace flag to overwrite it. Closes #3824 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: c0141405-13fa-4976-8c09-9cbdb55cdc07 --- app/cli/cmd/attestation_add.go | 7 ++ app/cli/documentation/cli-reference.md | 5 + app/cli/pkg/action/attestation_add.go | 48 +++++--- app/cli/pkg/action/trace_attestation.go | 2 + .../crafter/collector_aiagentconfig.go | 2 +- .../crafter/collector_prmetadata.go | 2 +- pkg/attestation/crafter/crafter.go | 35 ++++-- pkg/attestation/crafter/crafter_test.go | 104 ++++++++++++++++++ 8 files changed, 180 insertions(+), 25 deletions(-) diff --git a/app/cli/cmd/attestation_add.go b/app/cli/cmd/attestation_add.go index 55ef9e243..c0c26a296 100644 --- a/app/cli/cmd/attestation_add.go +++ b/app/cli/cmd/attestation_add.go @@ -47,6 +47,7 @@ func newAttestationAddCmd() *cobra.Command { var appendFlag bool var maxExtractEntries int var maxExtractSize string + var replace bool // OCI registry credentials can be passed as flags or environment variables var registryServer, registryUsername, registryPassword string @@ -73,6 +74,10 @@ func newAttestationAddCmd() *cobra.Command { # Add a material to the attestation without specifying neither kind nor name enables automatic detection chainloop attestation add --value + # Replace a material that was already added to the attestation with the same name. + # Without --replace, adding a material with a name that already exists fails. + chainloop attestation add --name --value --replace + # Add a material by also providing a URL pointing to the material. It will be downloaded to a temporary folder first chainloop attestation add --value https://example.com/sbom.json @@ -115,6 +120,7 @@ func newAttestationAddCmd() *cobra.Command { SkipSecretRedaction: skipSecretRedaction, MaxExtractEntries: maxExtractEntries, MaxExtractSize: int64(maxExtractSizeBytes), + Replace: replace, }, ) if err != nil { @@ -195,6 +201,7 @@ func newAttestationAddCmd() *cobra.Command { } cmd.Flags().StringVar(&name, "name", "", "name of the material as shown in the contract") + cmd.Flags().BoolVar(&replace, "replace", false, "replace a material with the same name that is already in the attestation, instead of failing") cmd.Flags().StringVar(&value, "value", "", "value to be recorded") err := cmd.MarkFlagRequired("value") cobra.CheckErr(err) diff --git a/app/cli/documentation/cli-reference.md b/app/cli/documentation/cli-reference.md index 01ec5e823..1c909387b 100644 --- a/app/cli/documentation/cli-reference.md +++ b/app/cli/documentation/cli-reference.md @@ -238,6 +238,10 @@ chainloop attestation add --kind --value Add a material to the attestation without specifying neither kind nor name enables automatic detection chainloop attestation add --value +Replace a material that was already added to the attestation with the same name. +Without --replace, adding a material with a name that already exists fails. +chainloop attestation add --name --value --replace + Add a material by also providing a URL pointing to the material. It will be downloaded to a temporary folder first chainloop attestation add --value https://example.com/sbom.json @@ -274,6 +278,7 @@ Options --registry-password string registry password, ($CHAINLOOP_REGISTRY_PASSWORD) --registry-server string OCI repository server, ($CHAINLOOP_REGISTRY_SERVER) --registry-username string registry username, ($CHAINLOOP_REGISTRY_USERNAME) +--replace[=true|false] replace a material with the same name that is already in the attestation, instead of failing --skip-secret-redaction[=true|false] store evidence exactly as captured, without redacting detected secrets first (CHAINLOOP_AI_CODING_SESSION). Recorded in the attestation so policies can reject it --value string value to be recorded ``` diff --git a/app/cli/pkg/action/attestation_add.go b/app/cli/pkg/action/attestation_add.go index e6b36634b..a17976559 100644 --- a/app/cli/pkg/action/attestation_add.go +++ b/app/cli/pkg/action/attestation_add.go @@ -51,6 +51,9 @@ type AttestationAddOpts struct { // MaxExtractSize limits the total uncompressed bytes extracted from an archive. // Zero defaults to materials.DefaultArchiveLimits().MaxTotalSize. MaxExtractSize int64 + // Replace overwrites a material that already exists in the attestation + // with the same name. Without it, adding such a material fails. + Replace bool } type newCrafterOpts struct { @@ -67,6 +70,7 @@ type AttestationAdd struct { localStatePath string maxExtractEntries int maxExtractSize int64 + replace bool *newCrafterOpts } @@ -103,11 +107,21 @@ func NewAttestationAdd(cfg *AttestationAddOpts) (*AttestationAdd, error) { localStatePath: cfg.LocalStatePath, maxExtractEntries: maxEntries, maxExtractSize: maxSize, + replace: cfg.Replace, }, nil } var ErrAttestationNotInitialized = errors.New("attestation not yet initialized") +// withMaterialExistsHint tells the user how to solve a duplicate material name. +func withMaterialExistsHint(err error) error { + if errors.Is(err, crafter.ErrMaterialAlreadyExists) { + return fmt.Errorf("%w: use a different --name, or pass --replace to overwrite it", err) + } + + return err +} + func (action *AttestationAdd) Run(ctx context.Context, attestationID, materialName, materialValue, materialType string, annotations map[string]string, policyInputFiles []*PolicyInputFromFile, policyInputs []*PolicyInput) ([]*AttestationStatusMaterial, error) { // initialize the crafter. If attestation-id is provided we assume the attestation is performed using remote state crafter, err := newCrafter(&newCrafterStateOpts{enableRemoteState: (attestationID != ""), localStatePath: action.localStatePath}, action.CPConnection, action.opts...) @@ -158,7 +172,7 @@ func (action *AttestationAdd) Run(ctx context.Context, attestationID, materialNa // 2. If materialName is not empty, check if the material is in the contract. If it is, add material from contract // 2.1. If materialType is empty, try to guess the material kind with auto-detected kind and materialName // 3. If materialType is not empty, add material contract free with materialType and materialName - addOpts := runtimeInputAddOpts(runtimeInputs) + addOpts := materialAddOpts(runtimeInputs, action.replace) // Explode path: --kind set, value is a (non-archive-native) archive. format, err := shouldExplode(materialType, materialValue) @@ -196,10 +210,9 @@ func (action *AttestationAdd) Run(ctx context.Context, attestationID, materialNa switch { case materialName == "" && materialType == "": mt, err = crafter.AddMaterialContactFreeWithAutoDetectedKind(ctx, attestationID, "", materialValue, casBackend, annotations, addOpts...) - if err != nil { - return nil, fmt.Errorf("adding material: %w", err) + if err == nil { + action.Logger.Info().Str("kind", mt.MaterialType.String()).Msg("material kind detected") } - action.Logger.Info().Str("kind", mt.MaterialType.String()).Msg("material kind detected") case materialName != "": switch { // If the material is in the contract, add it from the contract @@ -208,10 +221,9 @@ func (action *AttestationAdd) Run(ctx context.Context, attestationID, materialNa // If the material is not in the contract and the materialType is not provided, add material contract free with auto-detected kind, guessing the kind case materialType == "": mt, err = crafter.AddMaterialContactFreeWithAutoDetectedKind(ctx, attestationID, materialName, materialValue, casBackend, annotations, addOpts...) - if err != nil { - return nil, fmt.Errorf("adding material: %w", err) + if err == nil { + action.Logger.Info().Str("kind", mt.MaterialType.String()).Msg("material kind detected") } - action.Logger.Info().Str("kind", mt.MaterialType.String()).Msg("material kind detected") // If the material is not in the contract and has a materialType, add material contract free with the provided materialType default: mt, err = crafter.AddMaterialContractFree(ctx, attestationID, materialType, materialName, materialValue, casBackend, annotations, addOpts...) @@ -221,7 +233,7 @@ func (action *AttestationAdd) Run(ctx context.Context, attestationID, materialNa } if err != nil { - return nil, fmt.Errorf("adding material: %w", err) + return nil, fmt.Errorf("adding material: %w", withMaterialExistsHint(err)) } // Record each source file as an EVIDENCE material, cross-linked to the @@ -252,15 +264,18 @@ func shouldExplode(materialType, value string) (materials.ArchiveFormat, error) return materials.DetectArchive(value) } -// runtimeInputAddOpts wraps the runtime inputs as crafter add options, or -// returns nil when there are none. Defined at package scope so it can name the -// crafter package type (the Run method shadows it with a local variable). -func runtimeInputAddOpts(runtimeInputs *policies.RuntimeInputs) []crafter.AddOpt { +// materialAddOpts builds the crafter add options: whether a material with the +// same name can be replaced, plus the runtime inputs when there are any. +// Defined at package scope so it can name the crafter package (the Run method +// shadows it with a local variable). +func materialAddOpts(runtimeInputs *policies.RuntimeInputs, replace bool) []crafter.AddOpt { + opts := make([]crafter.AddOpt, 0, 2) + opts = append(opts, crafter.WithReplace(replace)) if runtimeInputs == nil || (len(runtimeInputs.Global) == 0 && len(runtimeInputs.Scoped) == 0 && len(runtimeInputs.GlobalOverride) == 0 && len(runtimeInputs.ScopedOverride) == 0) { - return nil + return opts } - return []crafter.AddOpt{crafter.WithRuntimeInputs(runtimeInputs)} + return append(opts, crafter.WithRuntimeInputs(runtimeInputs)) } // withSourceArchiveEvidence extends opts so an archive explode also records the @@ -355,8 +370,9 @@ func (action *AttestationAdd) addPolicyInputEvidence(ctx context.Context, c *cra materials.AnnotationPolicyInput: pif.Input, } - if _, err := c.AddMaterialContractFree(ctx, attestationID, schemaapi.CraftingSchema_Material_EVIDENCE.String(), names[i], pif.File, casBackend, annotations); err != nil { - return fmt.Errorf("adding evidence material %q: %w", names[i], err) + // The evidence of a replaced material replaces its previous evidence too. + if _, err := c.AddMaterialContractFree(ctx, attestationID, schemaapi.CraftingSchema_Material_EVIDENCE.String(), names[i], pif.File, casBackend, annotations, crafter.WithReplace(action.replace)); err != nil { + return fmt.Errorf("adding evidence material %q: %w", names[i], withMaterialExistsHint(err)) } } diff --git a/app/cli/pkg/action/trace_attestation.go b/app/cli/pkg/action/trace_attestation.go index 739e657e0..dbc3d754a 100644 --- a/app/cli/pkg/action/trace_attestation.go +++ b/app/cli/pkg/action/trace_attestation.go @@ -223,6 +223,8 @@ func (e *AttestationExecutor) AddMaterial(ctx context.Context, name, filePath, k CASURI: casURI(), CASCAPath: casCAPath(), ConnectionInsecure: casInsecure(), + // Trace evidence is generated by the CLI, keep overwriting by name + Replace: true, }) if err != nil { return "", fmt.Errorf("create attestation add action: %w", err) diff --git a/pkg/attestation/crafter/collector_aiagentconfig.go b/pkg/attestation/crafter/collector_aiagentconfig.go index dd1d2ee64..db3137e28 100644 --- a/pkg/attestation/crafter/collector_aiagentconfig.go +++ b/pkg/attestation/crafter/collector_aiagentconfig.go @@ -109,7 +109,7 @@ func (c *AIAgentConfigCollector) uploadAgentConfig( } defer os.Remove(tmpPath) - if _, err := cr.AddMaterialContractFree(ctx, attestationID, schemaapi.CraftingSchema_Material_CHAINLOOP_AI_AGENT_CONFIG.String(), materialName, tmpPath, casBackend, nil); err != nil { + if _, err := cr.AddMaterialContractFree(ctx, attestationID, schemaapi.CraftingSchema_Material_CHAINLOOP_AI_AGENT_CONFIG.String(), materialName, tmpPath, casBackend, nil, WithReplace(true)); err != nil { return fmt.Errorf("adding AI agent config material for %s: %w", agentName, err) } diff --git a/pkg/attestation/crafter/collector_prmetadata.go b/pkg/attestation/crafter/collector_prmetadata.go index 2df29b677..29dfabaa0 100644 --- a/pkg/attestation/crafter/collector_prmetadata.go +++ b/pkg/attestation/crafter/collector_prmetadata.go @@ -75,7 +75,7 @@ func (c *PRMetadataCollector) Collect(ctx context.Context, cr *Crafter, attestat } defer os.Remove(tmpFile) - if _, err := cr.AddMaterialContractFree(ctx, attestationID, schemaapi.CraftingSchema_Material_CHAINLOOP_PR_INFO.String(), materialName, tmpFile, casBackend, nil); err != nil { + if _, err := cr.AddMaterialContractFree(ctx, attestationID, schemaapi.CraftingSchema_Material_CHAINLOOP_PR_INFO.String(), materialName, tmpFile, casBackend, nil, WithReplace(true)); err != nil { return fmt.Errorf("adding PR/MR metadata material: %w", err) } diff --git a/pkg/attestation/crafter/crafter.go b/pkg/attestation/crafter/crafter.go index f86f34702..7e0d63db7 100644 --- a/pkg/attestation/crafter/crafter.go +++ b/pkg/attestation/crafter/crafter.go @@ -651,6 +651,21 @@ type addOpts struct { // source archive as an EVIDENCE material cross-linked with the exploded // materials, within the same atomic add. recordSourceArchive bool + // replace allows overwriting a material that already exists in the + // attestation with the same name. Without it, such an add fails. + replace bool +} + +// ErrMaterialAlreadyExists is returned when a material is added with a name +// that is already present in the attestation and WithReplace is not set. +var ErrMaterialAlreadyExists = errors.New("material already exists in the attestation") + +// WithReplace sets whether the add can overwrite a material that already +// exists in the attestation with the same name. +func WithReplace(replace bool) AddOpt { + return func(o *addOpts) { + o.replace = replace + } } // WithSourceArchiveEvidence makes an archive explode also record the source @@ -717,12 +732,7 @@ func (c *Crafter) AddMaterialFromContract(ctx context.Context, attestationID, ke return nil, fmt.Errorf("material with id %q not found in the schema", key) } - // 2 - Check that it has not been set yet and warn of override - if _, found := c.CraftingState.Attestation.Materials[key]; found { - c.Logger.Info().Str("key", key).Str("value", value).Msg("material already set, overriding it") - } - - // 3 - Craft resulting material + // 2 - Craft resulting material. addMaterial rejects it if it has already been set. return c.addMaterial(ctx, m, attestationID, value, casBackend, runtimeAnnotations, opts...) } @@ -757,7 +767,7 @@ func (c *Crafter) AddMaterialContactFreeWithAutoDetectedKind(ctx context.Context return nil, err } - if v1.IsAttestationStateErrorConflict(err) { + if v1.IsAttestationStateErrorConflict(err) || errors.Is(err, ErrMaterialAlreadyExists) { return nil, err } @@ -776,12 +786,23 @@ func (c *Crafter) AddMaterialContactFreeWithAutoDetectedKind(ctx context.Context // stageMaterial crafts a material into the in-memory crafting state WITHOUT // persisting it. Callers must call stateManager.Write to commit. Splitting the // write out lets the archive explode path craft many entries and commit once. +// It fails with ErrMaterialAlreadyExists if a material with the same name is +// already in the attestation, unless WithReplace is set. func (c *Crafter) stageMaterial(ctx context.Context, m *schemaapi.CraftingSchema_Material, value string, casBackend *casclient.CASBackend, runtimeAnnotations map[string]string, opts ...AddOpt) (*api.Attestation_Material, error) { addOptions := &addOpts{} for _, opt := range opts { opt(addOptions) } + // Check before crafting so that nothing is uploaded for a rejected material. + if _, found := c.CraftingState.GetAttestation().GetMaterials()[m.Name]; found { + if !addOptions.replace { + return nil, fmt.Errorf("%w: %q", ErrMaterialAlreadyExists, m.Name) + } + + c.Logger.Info().Str("name", m.Name).Msg("material already set, replacing it") + } + // 3- Craft resulting material crafted, err := materials.Craft(context.Background(), m, value, casBackend, c.ociRegistryAuth, c.Logger, &materials.CraftingOpts{ NoStrictValidation: c.noStrictValidation, diff --git a/pkg/attestation/crafter/crafter_test.go b/pkg/attestation/crafter/crafter_test.go index c2836adc1..fdf43aef3 100644 --- a/pkg/attestation/crafter/crafter_test.go +++ b/pkg/attestation/crafter/crafter_test.go @@ -1434,3 +1434,107 @@ func loadSchemaV2(path string) (*schemaapi.CraftingSchemaV2, error) { return schema, nil } + +func (s *crafterSuite) TestAddMaterialDuplicateName() { + const ( + contractFree = "contract-free" + fromContract = "from-contract" + autoDetected = "auto-detected" + duplicateName = "non-functional-test" + ) + + testCases := []struct { + name string + contract string + // method selects the crafter add method to use + method string + materialName string + replace bool + wantErr bool + }{ + { + name: "contract free, duplicate name fails", + contract: "testdata/contracts/empty_generic.yaml", + method: contractFree, + materialName: duplicateName, + wantErr: true, + }, + { + name: "contract free, duplicate name with replace overwrites", + contract: "testdata/contracts/empty_generic.yaml", + method: contractFree, + materialName: duplicateName, + replace: true, + }, + { + name: "auto detected, duplicate name fails", + contract: "testdata/contracts/empty_generic.yaml", + method: autoDetected, + materialName: duplicateName, + wantErr: true, + }, + { + name: "auto detected, duplicate name with replace overwrites", + contract: "testdata/contracts/empty_generic.yaml", + method: autoDetected, + materialName: duplicateName, + replace: true, + }, + { + name: "from contract, duplicate name fails", + contract: "testdata/contracts/with_material_annotations.yaml", + method: fromContract, + materialName: "string", + wantErr: true, + }, + { + name: "from contract, duplicate name with replace overwrites", + contract: "testdata/contracts/with_material_annotations.yaml", + method: fromContract, + materialName: "string", + replace: true, + }, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + ctx := context.Background() + // STRING materials are stored inline, so nothing is uploaded + backend := &casclient.CASBackend{Uploader: mUploader.NewUploader(s.T())} + + c, err := newInitializedCrafter(s.T(), tc.contract, &v1.WorkflowMetadata{}, false, "", runners.NewGeneric()) + require.NoError(s.T(), err) + + add := func(value string, opts ...crafter.AddOpt) (*v1.Attestation_Material, error) { + switch tc.method { + case fromContract: + return c.AddMaterialFromContract(ctx, "", tc.materialName, value, backend, nil, opts...) + case autoDetected: + return c.AddMaterialContactFreeWithAutoDetectedKind(ctx, "", tc.materialName, value, backend, nil, opts...) + default: + return c.AddMaterialContractFree(ctx, "", schemaapi.CraftingSchema_Material_STRING.String(), tc.materialName, value, backend, nil, opts...) + } + } + + _, err = add("first-value") + require.NoError(s.T(), err) + + _, err = add("second-value", crafter.WithReplace(tc.replace)) + + got := c.CraftingState.Attestation.Materials[tc.materialName] + require.NotNil(s.T(), got) + + if tc.wantErr { + require.Error(s.T(), err) + assert.ErrorIs(s.T(), err, crafter.ErrMaterialAlreadyExists) + assert.Contains(s.T(), err.Error(), tc.materialName) + // the first material is kept + assert.Equal(s.T(), "first-value", got.GetString_().GetValue()) + return + } + + require.NoError(s.T(), err) + assert.Equal(s.T(), "second-value", got.GetString_().GetValue()) + }) + } +}