Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions app/cli/cmd/attestation_add.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 <material-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 <material-name> --value <material-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

Expand Down Expand Up @@ -115,6 +120,7 @@ func newAttestationAddCmd() *cobra.Command {
SkipSecretRedaction: skipSecretRedaction,
MaxExtractEntries: maxExtractEntries,
MaxExtractSize: int64(maxExtractSizeBytes),
Replace: replace,
},
)
if err != nil {
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions app/cli/documentation/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,10 @@ chainloop attestation add --kind <material-kind> --value <material-value>
Add a material to the attestation without specifying neither kind nor name enables automatic detection
chainloop attestation add --value <material-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 <material-name> --value <material-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

Expand Down Expand Up @@ -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
```
Expand Down
48 changes: 32 additions & 16 deletions app/cli/pkg/action/attestation_add.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -67,6 +70,7 @@ type AttestationAdd struct {
localStatePath string
maxExtractEntries int
maxExtractSize int64
replace bool
*newCrafterOpts
}

Expand Down Expand Up @@ -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...)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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...)
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Comment thread
migmartri marked this conversation as resolved.
Resolved
return fmt.Errorf("adding evidence material %q: %w", names[i], withMaterialExistsHint(err))
}
}

Expand Down
2 changes: 2 additions & 0 deletions app/cli/pkg/action/trace_attestation.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pkg/attestation/crafter/collector_aiagentconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/attestation/crafter/collector_prmetadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
35 changes: 28 additions & 7 deletions pkg/attestation/crafter/crafter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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...)
}

Expand Down Expand Up @@ -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
}

Expand All @@ -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,
Expand Down
104 changes: 104 additions & 0 deletions pkg/attestation/crafter/crafter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
})
}
}
Loading