diff --git a/app/cli/cmd/attestation_add.go b/app/cli/cmd/attestation_add.go index c0c26a296..2583ecf7f 100644 --- a/app/cli/cmd/attestation_add.go +++ b/app/cli/cmd/attestation_add.go @@ -48,6 +48,7 @@ func newAttestationAddCmd() *cobra.Command { var maxExtractEntries int var maxExtractSize string var replace bool + var step string // OCI registry credentials can be passed as flags or environment variables var registryServer, registryUsername, registryPassword string @@ -78,6 +79,10 @@ func newAttestationAddCmd() *cobra.Command { # Without --replace, adding a material with a name that already exists fails. chainloop attestation add --name --value --replace + # Show the material in the custom step that adds it, in the timeline of the run. + # The step is the one of "chainloop attestation event --step". + chainloop attestation add --name sast-report --value report.sarif --step sast-scan + # 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 @@ -121,6 +126,7 @@ func newAttestationAddCmd() *cobra.Command { MaxExtractEntries: maxExtractEntries, MaxExtractSize: int64(maxExtractSizeBytes), Replace: replace, + Step: step, }, ) if err != nil { @@ -202,6 +208,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(&step, "step", "", "custom step that adds the material, as in chainloop attestation event --step. It shows the material in that step of the run timeline") cmd.Flags().StringVar(&value, "value", "", "value to be recorded") err := cmd.MarkFlagRequired("value") cobra.CheckErr(err) diff --git a/app/cli/cmd/attestation_event.go b/app/cli/cmd/attestation_event.go index 0be0e28d2..ba67890a8 100644 --- a/app/cli/cmd/attestation_event.go +++ b/app/cli/cmd/attestation_event.go @@ -24,7 +24,7 @@ import ( ) func newAttestationEventCmd() *cobra.Command { - var name, status, message string + var step, status, message string cmd := &cobra.Command{ Use: "event", @@ -33,14 +33,16 @@ func newAttestationEventCmd() *cobra.Command { The step shows in "chainloop workflow run describe" while the attestation is in progress, and as history after the push. Events are progress information only. They are not part of the signed attestation. -The name uses letters, digits, "_" and "-", up to 64 characters. Events with the same name are one step of the timeline. +The step uses letters, digits, "_" and "-", up to 64 characters. Events with the same step are one step of the timeline. +To show a material in the step that adds it, use the same step in "chainloop attestation add --step". If the event cannot be recorded, the command shows a warning and exits with success, so it never breaks the pipeline.`, Example: ` # Record the start and the end of a step - chainloop attestation event --name sast-scan --status started --message "Semgrep, ruleset p/ci" - chainloop attestation event --name sast-scan --status succeeded + chainloop attestation event --step sast-scan --status started --message "Semgrep, ruleset p/ci" + chainloop attestation add --name sast-report --value report.sarif --step sast-scan + chainloop attestation event --step sast-scan --status succeeded # Record a step that did not run - chainloop attestation event --name dast-scan --status skipped --message "no web target"`, + chainloop attestation event --step dast-scan --status skipped --message "no web target"`, // the arguments are checked in RunE, so that a wrong call is a warning too Args: cobra.ArbitraryArgs, Annotations: map[string]string{ @@ -48,14 +50,16 @@ If the event cannot be recorded, the command shows a warning and exits with succ supportsFederatedAuthAnnotation: trueString, }, RunE: func(cmd *cobra.Command, args []string) error { - // a progress signal never breaks the pipeline (spec R-013), so every - // failure, also a wrong call, is a warning and the command exits with success + // a progress signal never breaks the pipeline (spec issue-3825 R-013), so a failure to + // record the event, and a wrong argument or flag value, is a warning and the command + // exits with success. An unknown flag, as the removed --name, fails in cobra before + // RunE (spec issue-3878 R-003). if len(args) > 0 { - logger.Warn().Msgf("the event was not recorded: unexpected arguments %q, set the step with --name", args) + logger.Warn().Msgf("the event was not recorded: unexpected arguments %q, set the step with --step", args) return nil } - if name == "" { - logger.Warn().Msg("the event was not recorded: --name is required") + if step == "" { + logger.Warn().Msg("the event was not recorded: --step is required") return nil } @@ -66,7 +70,7 @@ If the event cannot be recorded, the command shows a warning and exits with succ } a := action.NewAttestationEvent(&action.AttestationEventOpts{ActionsOpts: ActionOpts, LocalStatePath: attestationLocalStatePath}) - recorded, err := a.Run(cmd.Context(), attestationID, name, st, message) + recorded, err := a.Run(cmd.Context(), attestationID, step, st, message) switch { case err != nil: logger.Warn().Err(err).Msg("the event was not recorded") @@ -80,7 +84,7 @@ If the event cannot be recorded, the command shows a warning and exits with succ }, } - cmd.Flags().StringVar(&name, "name", "", "name of the step (required), with letters, digits, _ and -, up to 64 characters") + cmd.Flags().StringVar(&step, "step", "", "key of the step (required), with letters, digits, _ and -, up to 64 characters") cmd.Flags().StringVar(&status, "status", "", fmt.Sprintf("status of the step (required), valid options are %s", strings.Join(action.RunEventStatuses, ", "))) cmd.Flags().StringVar(&message, "message", "", "message of the event, up to 1 KB") flagAttestationID(cmd) diff --git a/app/cli/cmd/attestation_event_test.go b/app/cli/cmd/attestation_event_test.go index 388213f56..13272ef46 100644 --- a/app/cli/cmd/attestation_event_test.go +++ b/app/cli/cmd/attestation_event_test.go @@ -60,13 +60,13 @@ func (f *eventsControlPlane) received() []*pb.AttestationServiceRecordEventReque return append([]*pb.AttestationServiceRecordEventRequest(nil), f.events...) } -// A progress signal never breaks the pipeline (spec R-009): every failure of -// chainloop attestation event is a warning, and the command exits with success. +// The failures of chainloop attestation event are warnings, and the command exits with success. +// The command has no --name flag, so a call with it fails as an unknown flag (spec issue-3878 R-003). func TestAttestationEventCmd(t *testing.T) { const ( runID = "4f8d2b7e-8c1b-4b1e-9f3a-2a6f1b2c3d4e" invalidStatus = "invalid status" - nameFlag = "--name" + stepFlag = "--step" statusFlag = "--status" started = "started" sastScan = "sast-scan" @@ -82,23 +82,25 @@ func TestAttestationEventCmd(t *testing.T) { wantKey string wantWarn string wantInfo string + wantErr string }{ { - name: "recorded", args: remote(nameFlag, sastScan, statusFlag, started, "--message", "Semgrep"), + name: "recorded", args: remote(stepFlag, sastScan, statusFlag, started, "--message", "Semgrep"), wantSent: true, wantKey: sastScan, wantInfo: "event recorded", }, { - name: "rejected by the control plane", args: remote(nameFlag, "sast.scan", statusFlag, started), + name: "rejected by the control plane", args: remote(stepFlag, "sast.scan", statusFlag, started), cpErr: status.Error(codes.InvalidArgument, "custom event key"), wantSent: true, wantKey: "sast.scan", wantWarn: "custom event key", }, { - name: "control plane without custom events", args: remote(nameFlag, sastScan, statusFlag, started), + name: "control plane without custom events", args: remote(stepFlag, sastScan, statusFlag, started), cpErr: status.Error(codes.Unimplemented, "unknown method"), wantSent: true, wantKey: sastScan, wantWarn: "unknown method", }, - {name: "no attestation in progress", args: []string{nameFlag, sastScan, statusFlag, started}, wantWarn: "not yet initialized"}, - {name: "invalid status", args: remote(nameFlag, sastScan, statusFlag, "done"), wantWarn: invalidStatus}, - {name: "missing status", args: remote(nameFlag, sastScan), wantWarn: invalidStatus}, - {name: "missing name", args: remote(statusFlag, started), wantWarn: "--name is required"}, + {name: "no attestation in progress", args: []string{stepFlag, sastScan, statusFlag, started}, wantWarn: "not yet initialized"}, + {name: "invalid status", args: remote(stepFlag, sastScan, statusFlag, "done"), wantWarn: invalidStatus}, + {name: "missing status", args: remote(stepFlag, sastScan), wantWarn: invalidStatus}, + {name: "missing step", args: remote(statusFlag, started), wantWarn: "--step is required"}, + {name: "the removed --name flag", args: remote("--name", sastScan, statusFlag, started), wantErr: "unknown flag: --name"}, {name: "positional argument", args: remote(sastScan, statusFlag, started), wantWarn: "unexpected arguments"}, } @@ -112,7 +114,12 @@ func TestAttestationEventCmd(t *testing.T) { cmd.SetArgs(tc.args) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) - require.NoError(t, cmd.Execute()) + err := cmd.Execute() + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + } else { + require.NoError(t, err) + } got := fake.received() if !tc.wantSent { diff --git a/app/cli/cmd/workflow_run_timeline.go b/app/cli/cmd/workflow_run_timeline.go index 3fcf3a525..0e6446808 100644 --- a/app/cli/cmd/workflow_run_timeline.go +++ b/app/cli/cmd/workflow_run_timeline.go @@ -77,6 +77,28 @@ func renderRunTimeline(w io.Writer, events []*action.RunEvent, progress *action. } } + // A material whose event names a custom step shows in that step (spec issue-3878 R-002). + // The steps can come first, so the lines of those materials are built before them. + custom := make(map[string]bool) + for _, key := range keys { + custom[key] = groups[key][len(groups[key])-1].Type == timelineTypeCustom + } + nested := make(map[string][]timedNode) + inStep := make(map[string]bool) + for _, key := range keys { + evs := groups[key] + shown := timelineShownEvent(evs) + if shown.Material == nil || !custom[shown.Material.Step] { + continue + } + inStep[key] = true + // the line is the event that names the step, so it shows and sorts at the time of + // that event, not of an earlier attempt that can be before the step started + node := timelineStep(key, evs, shown, materials) + node.at = timelineTime(shown.CreatedAt) + nested[shown.Material.Step] = append(nested[shown.Material.Step], timedNode{at: shown.CreatedAt, node: node}) + } + var nodes []*timelineNode var started, closing *action.RunEvent reported := make(map[string]bool) @@ -95,14 +117,16 @@ func renderRunTimeline(w io.Writer, events []*action.RunEvent, progress *action. if last := evs[len(evs)-1]; last.Status != timelineStarted { closing = last } - case evs[len(evs)-1].Type == timelineTypeCustom: + case custom[key]: // only a run in progress has progress, so only its open steps still run - nodes = append(nodes, timelineCustomStep(key, evs, progress != nil, now)) + nodes = append(nodes, timelineCustomStep(key, evs, nested[key], progress != nil, now)) default: if m := evs[len(evs)-1].Material; m != nil { reported[m.Name] = true } - nodes = append(nodes, timelineStep(key, evs, materials)) + if !inStep[key] { + nodes = append(nodes, timelineStep(key, evs, timelineShownEvent(evs), materials)) + } } } @@ -233,22 +257,31 @@ func timelineDigest(e *action.RunEvent) string { return d } -// timelineStep is the line of one step of evidence. A step with more than one event folds -// its events below it. -func timelineStep(key string, evs []*action.RunEvent, materials map[string]*action.RunProgressMaterial) *timelineNode { - last := evs[len(evs)-1] - // A failed add after a successful one leaves the material in the attestation, so the - // step shows the last successful add, and the failed attempts below it. The control - // plane applies the same rule to the progress (biz.BuildWorkflowRunProgress). The - // timeline needs its own copy because a finished run has no progress. - shown := last +// timelineShownEvent is the event that the line of a material shows. A failed add after a +// successful one leaves the material in the attestation, so it is the last successful add, +// else the last event. The control plane applies the same rule to the progress +// (biz.BuildWorkflowRunProgress). The timeline needs its own copy because a finished run +// has no progress. +func timelineShownEvent(evs []*action.RunEvent) *action.RunEvent { for _, e := range slices.Backward(evs) { if e.Status == timelineSucceeded { - shown = e - break + return e } } + return evs[len(evs)-1] +} + +// timedNode is a line of the tree with the time that orders it among the events of a step +type timedNode struct { + at *time.Time + node *timelineNode +} + +// timelineStep is the line of one step of evidence. A step with more than one event folds +// its events below it. +// It shows the shown event of the step (timelineShownEvent), and the failed attempts below it. +func timelineStep(key string, evs []*action.RunEvent, shown *action.RunEvent, materials map[string]*action.RunProgressMaterial) *timelineNode { name := action.RunStepName(key) node := &timelineNode{at: timelineTime(evs[0].CreatedAt), symbol: timelineSymbol(shown.Status), name: timelineEvidenceAction(shown, name)} @@ -292,8 +325,9 @@ func timelineStep(key string, evs []*action.RunEvent, materials map[string]*acti // timelineCustomStep is the line of a step that the pipeline recorded with // chainloop attestation event. It shows the status of its last event and its duration. -// A step with more than one event folds its events below it. -func timelineCustomStep(key string, evs []*action.RunEvent, inProgress bool, now time.Time) *timelineNode { +// A step with more than one event folds its events below it. The materials that the step +// added show below it too, in time order with its events. +func timelineCustomStep(key string, evs []*action.RunEvent, materials []timedNode, inProgress bool, now time.Time) *timelineNode { first, last := evs[0], evs[len(evs)-1] node := &timelineNode{at: timelineTime(first.CreatedAt), symbol: timelineSymbol(last.Status), name: "step " + timelineQuote(key)} @@ -305,7 +339,27 @@ func timelineCustomStep(key string, evs []*action.RunEvent, inProgress bool, now node.details = append(node.details, "took "+timelineDuration(*first.CreatedAt, *last.CreatedAt)) } - timelineFoldEvents(node, evs) + if len(materials) == 0 { + timelineFoldEvents(node, evs) + return node + } + + // each event is a line, so that the materials show between them + lines := make([]timedNode, 0, len(evs)+len(materials)) + for _, e := range evs { + lines = append(lines, timedNode{at: e.CreatedAt, node: timelineEventNode(e)}) + } + lines = append(lines, materials...) + slices.SortStableFunc(lines, func(a, b timedNode) int { + if a.at == nil || b.at == nil { + return 0 + } + return a.at.Compare(*b.at) + }) + for _, l := range lines { + node.children = append(node.children, l.node) + } + return node } @@ -320,10 +374,15 @@ func timelineFoldEvents(node *timelineNode, evs []*action.RunEvent) { } for _, e := range evs { - node.children = append(node.children, &timelineNode{at: timelineTime(e.CreatedAt), symbol: timelineSymbol(e.Status), name: timelineMessage(e)}) + node.children = append(node.children, timelineEventNode(e)) } } +// timelineEventNode is the line of one event of a step +func timelineEventNode(e *action.RunEvent) *timelineNode { + return &timelineNode{at: timelineTime(e.CreatedAt), symbol: timelineSymbol(e.Status), name: timelineMessage(e)} +} + func timelineDuration(from, to time.Time) string { return to.Sub(from).Round(time.Second).String() } diff --git a/app/cli/cmd/workflow_run_timeline_test.go b/app/cli/cmd/workflow_run_timeline_test.go index 7cc5dd8a1..3f5edc33f 100644 --- a/app/cli/cmd/workflow_run_timeline_test.go +++ b/app/cli/cmd/workflow_run_timeline_test.go @@ -43,6 +43,10 @@ func TestRenderRunTimeline(t *testing.T) { custom := func(d time.Duration, key, status, msg string) *action.RunEvent { return &action.RunEvent{CreatedAt: at(d), Source: timelineSourceCLI, Type: timelineTypeCustom, Key: key, Status: status, Message: msg} } + inStep := func(e *action.RunEvent, step string) *action.RunEvent { + e.Material.Step = step + return e + } testCases := []struct { name string @@ -126,6 +130,61 @@ func TestRenderRunTimeline(t *testing.T) { "├─ 10:05:02 ● step `approval` running for 43s\n" + "└─ ● waiting for push\n", }, + { + name: "evidence in the step that adds it", + events: []*action.RunEvent{ + started, + custom(60*time.Second, "sast-scan", "started", "Scanning 14 changed files"), + inStep(material(67*time.Second, "sast-report", "succeeded", "", &action.RunEventPolicyCount{Evaluated: 1, Passed: 1}), "sast-scan"), + custom(68*time.Second, "sast-scan", "succeeded", ""), + custom(70*time.Second, "iac-scan", "started", "Scanning 3 files"), + inStep(material(75*time.Second, "iac-report", "succeeded", "", nil), "iac-scan"), + }, + progress: &action.RunProgress{ + Materials: []*action.RunProgressMaterial{ + {Name: "sast-report", Requirement: action.RunMaterialNotInContract, Status: action.RunMaterialProvided}, + {Name: "iac-report", Requirement: action.RunMaterialNotInContract, Status: action.RunMaterialProvided}, + }, + }, + want: "Timeline (reported progress) · started 10:00:02 · running for 5m43s · 0 of 0 required provided\n" + + "├─ 10:00:02 ✓ initialized policies: 2 passed\n" + + "├─ 10:01:02 ✓ step `sast-scan` took 8s\n" + + "│ ├─ 10:01:02 ● Scanning 14 changed files\n" + + "│ ├─ 10:01:09 ✓ added evidence `sast-report` not in contract · policies: 1 passed\n" + + "│ └─ 10:01:10 ✓ succeeded\n" + + "├─ 10:01:12 ● step `iac-scan` running for 4m33s\n" + + "│ ├─ 10:01:12 ● Scanning 3 files\n" + + "│ └─ 10:01:17 ✓ added evidence `iac-report` not in contract\n" + + "└─ ● waiting for push\n", + }, + { + name: "evidence whose step has no custom event, and evidence retried in another step", + events: []*action.RunEvent{ + started, + custom(60*time.Second, "scan-a", "started", ""), + inStep(material(61*time.Second, "report", "failed", "invalid report", nil), "scan-a"), + custom(62*time.Second, "scan-a", "failed", ""), + custom(70*time.Second, "scan-b", "started", ""), + inStep(material(71*time.Second, "report", "succeeded", "", nil), "scan-b"), + custom(72*time.Second, "scan-b", "succeeded", ""), + inStep(material(80*time.Second, "sbom", "succeeded", "", nil), "no-such-step"), + {CreatedAt: at(120 * time.Second), Key: timelineKeyAttestation, Status: timelineSucceeded}, + }, + stored: &action.PolicyEvaluationStatus{}, + want: "Timeline · started 10:00:02 · finished 10:02:02 (2m0s) · stored\n" + + "├─ 10:00:02 ✓ initialized policies: 2 passed\n" + + "├─ 10:01:02 ✗ step `scan-a` took 2s\n" + + "│ ├─ 10:01:02 ● started\n" + + "│ └─ 10:01:04 ✗ failed\n" + + "├─ 10:01:12 ✓ step `scan-b` took 2s\n" + + "│ ├─ 10:01:12 ● started\n" + + "│ ├─ 10:01:13 ✓ added evidence `report` 1 failed attempt\n" + + "│ │ ├─ 10:01:03 ✗ invalid report\n" + + "│ │ └─ 10:01:13 ✓ succeeded\n" + + "│ └─ 10:01:14 ✓ succeeded\n" + + "├─ 10:01:22 ✓ added evidence `sbom`\n" + + "└─ 10:02:02 ✓ pushed and stored\n", + }, { name: "stored run, with a custom step that never ended", events: []*action.RunEvent{ diff --git a/app/cli/documentation/cli-reference.md b/app/cli/documentation/cli-reference.md index ce9d437cf..2ae75d804 100644 --- a/app/cli/documentation/cli-reference.md +++ b/app/cli/documentation/cli-reference.md @@ -242,6 +242,10 @@ 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 +Show the material in the custom step that adds it, in the timeline of the run. +The step is the one of "chainloop attestation event --step". +chainloop attestation add --name sast-report --value report.sarif --step sast-scan + 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 @@ -280,6 +284,7 @@ Options --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 +--step string custom step that adds the material, as in chainloop attestation event --step. It shows the material in that step of the run timeline --value string value to be recorded ``` @@ -312,7 +317,8 @@ Record a custom step of the pipeline, for example a security scan, in the timeli The step shows in "chainloop workflow run describe" while the attestation is in progress, and as history after the push. Events are progress information only. They are not part of the signed attestation. -The name uses letters, digits, "_" and "-", up to 64 characters. Events with the same name are one step of the timeline. +The step uses letters, digits, "_" and "-", up to 64 characters. Events with the same step are one step of the timeline. +To show a material in the step that adds it, use the same step in "chainloop attestation add --step". If the event cannot be recorded, the command shows a warning and exits with success, so it never breaks the pipeline. ``` @@ -323,11 +329,12 @@ Examples ``` Record the start and the end of a step -chainloop attestation event --name sast-scan --status started --message "Semgrep, ruleset p/ci" -chainloop attestation event --name sast-scan --status succeeded +chainloop attestation event --step sast-scan --status started --message "Semgrep, ruleset p/ci" +chainloop attestation add --name sast-report --value report.sarif --step sast-scan +chainloop attestation event --step sast-scan --status succeeded Record a step that did not run -chainloop attestation event --name dast-scan --status skipped --message "no web target" +chainloop attestation event --step dast-scan --status skipped --message "no web target" ``` Options @@ -336,8 +343,8 @@ Options --attestation-id string Unique identifier of the in-progress attestation -h, --help[=true|false] help for event --message string message of the event, up to 1 KB ---name string name of the step (required), with letters, digits, _ and -, up to 64 characters --status string status of the step (required), valid options are started, succeeded, failed, canceled, skipped +--step string key of the step (required), with letters, digits, _ and -, up to 64 characters ``` Options inherited from parent commands diff --git a/app/cli/pkg/action/attestation_add.go b/app/cli/pkg/action/attestation_add.go index c3dea5fb8..b564865f2 100644 --- a/app/cli/pkg/action/attestation_add.go +++ b/app/cli/pkg/action/attestation_add.go @@ -54,6 +54,9 @@ type AttestationAddOpts struct { // Replace overwrites a material that already exists in the attestation // with the same name. Without it, adding such a material fails. Replace bool + // Step is the key of the custom step that adds the material. It shows the material + // in that step of the timeline. It is progress data only. + Step string } type newCrafterOpts struct { @@ -71,6 +74,8 @@ type AttestationAdd struct { maxExtractEntries int maxExtractSize int64 replace bool + // step is the custom step of the material events, empty for none. The event recorder checks it. + step string *newCrafterOpts } @@ -108,6 +113,7 @@ func NewAttestationAdd(cfg *AttestationAddOpts) (*AttestationAdd, error) { maxExtractEntries: maxEntries, maxExtractSize: maxSize, replace: cfg.Replace, + step: cfg.Step, }, nil } @@ -148,7 +154,7 @@ func (action *AttestationAdd) Run(ctx context.Context, attestationID, materialNa } // Progress events are best effort, they never change the result of the add - events := newRunEventRecorderFromState(action.CPConnection, crafter.CraftingState.CraftingState, action.Logger) + events := newRunEventRecorderFromState(action.CPConnection, crafter.CraftingState.CraftingState, action.Logger).withStep(action.step) results, err := action.addMaterial(ctx, crafter, attestationID, materialName, materialValue, materialType, annotations, policyInputFiles, runtimeInputs) if err != nil { _ = events.Record(ctx, materialFailedEvent(crafter, materialName, materialType, materialValue, err)) diff --git a/app/cli/pkg/action/runevents.go b/app/cli/pkg/action/runevents.go index 3649bc986..ce53b750a 100644 --- a/app/cli/pkg/action/runevents.go +++ b/app/cli/pkg/action/runevents.go @@ -32,6 +32,7 @@ import ( api "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/api/attestation/v1" "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/materials" + "buf.build/go/protovalidate" "github.com/rs/zerolog" "google.golang.org/grpc" "google.golang.org/grpc/codes" @@ -63,6 +64,12 @@ const ( runEventKeyMaterialPrefix = runEventKeyMaterial + "." ) +// validateRunEventStepKey checks a step with the rules of the control plane for the step +// of a material event: the format and the limit of a custom key +func validateRunEventStepKey(step string) error { + return protovalidate.Validate(&pb.WorkflowRunEvent_MaterialAttributes{Step: step}) +} + // runEventRecorder sends progress events of an attestation to the control plane. // Events are informational only: callers must never stop the attestation on its error. // It turns itself off for the rest of the command when the control plane does not know the call. @@ -72,6 +79,24 @@ type runEventRecorder struct { logger zerolog.Logger timeout time.Duration disabled bool + // step is the custom step that the material events belong to, from attestation add --step + step string +} + +// withStep puts each material event that the recorder sends in the custom step. The step is +// progress data only, so a step that the control plane does not allow is dropped with a +// warning: the control plane would reject the whole event. +func (r *runEventRecorder) withStep(step string) *runEventRecorder { + if step == "" { + return r + } + if err := validateRunEventStepKey(step); err != nil { + r.logger.Warn().Err(err).Str("step", step).Msg("the material is added with no step") + return r + } + + r.step = step + return r } // newRunEventRecorder returns a recorder for the run. An empty run ID, for example @@ -106,6 +131,9 @@ func (r *runEventRecorder) Record(ctx context.Context, event *pb.WorkflowRunEven if m := event.GetMaterial(); m != nil { m.Value = truncateChars(m.GetValue(), runEventMaxValueChars) capPolicyNames(m.GetPolicies()) + if r.step != "" { + m.Step = r.step + } } if a := event.GetAttestation(); a != nil { capPolicyNames(a.GetPolicies()) diff --git a/app/cli/pkg/action/runevents_test.go b/app/cli/pkg/action/runevents_test.go index 4cb188e11..c0559b42d 100644 --- a/app/cli/pkg/action/runevents_test.go +++ b/app/cli/pkg/action/runevents_test.go @@ -59,6 +59,7 @@ const ( testSBOMs = "sboms" testCDX = "cdx" testInvalid = "invalid CycloneDX document" + testStep = "sast-scan" ) const testRunID = "4f8d2b7e-8c1b-4b1e-9f3a-2a6f1b2c3d4e" @@ -261,6 +262,7 @@ func TestAttestationAddArchiveEvents(t *testing.T) { add, err := NewAttestationAdd(&AttestationAddOpts{ ActionsOpts: &ActionsOpts{CPConnection: conn, Logger: zerolog.Nop()}, LocalStatePath: statePath, + Step: "sbom-scan", }) require.NoError(t, err) @@ -270,6 +272,9 @@ func TestAttestationAddArchiveEvents(t *testing.T) { got := fake.received() require.Len(t, got, tc.wantEvents) + for _, e := range got { + assert.Equal(t, "sbom-scan", e.GetEvent().GetMaterial().GetStep(), "each event of the add is in its step") + } // the archive event comes last, for the EVIDENCE material of the archive archive := got[len(got)-1].GetEvent() @@ -514,6 +519,59 @@ func TestAttestationAddRecordsEvents(t *testing.T) { } } +// An add with --step records the step on its material event, also on a failed add. A step +// that a custom key does not allow never fails the add: the event has no step (spec issue-3878 R-001). +func TestAttestationAddRecordsStep(t *testing.T) { + testCases := []struct { + name string + step string + value string + kind string + wantErr bool + wantStep string + }{ + {name: "add in a step", step: testStep, value: testCommit, wantStep: testStep}, + {name: "add with no step", value: testCommit}, + {name: "failed add in a step", step: testStep, value: "/does/not/exist.json", kind: testSBOMKind, wantErr: true, wantStep: testStep}, + {name: "step at the limit", step: strings.Repeat("a", 64), value: testCommit, wantStep: strings.Repeat("a", 64)}, + {name: "step over the limit", step: strings.Repeat("a", 65), value: testCommit}, + {name: "step with a dot", step: "chainloop.attestation", value: testCommit}, + {name: "step with a space", step: "sast scan", value: testCommit}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + fake := &fakeEventsControlPlane{} + conn := newFakeEventsConn(t, fake) + statePath := filepath.Join(t.TempDir(), "state.json") + newLocalCrafter(t, conn, statePath) + + add, err := NewAttestationAdd(&AttestationAddOpts{ + ActionsOpts: &ActionsOpts{CPConnection: conn, Logger: zerolog.Nop()}, + LocalStatePath: statePath, + Step: tc.step, + }) + require.NoError(t, err) + + name := "build-ref" + if tc.kind != "" { + name = testSBOM + } + _, err = add.Run(context.Background(), "", name, tc.value, tc.kind, nil, nil, nil) + if tc.wantErr { + require.Error(t, err) + } else { + require.NoError(t, err, "a step problem never fails the add") + } + + got := fake.received() + require.Len(t, got, 1) + assert.Equal(t, "chainloop.material."+name, got[0].GetEvent().GetKey(), "the material keeps its key") + assert.Equal(t, tc.wantStep, got[0].GetEvent().GetMaterial().GetStep()) + }) + } +} + // The start event lists the materials of the resolved contract, policy groups included, // so that the control plane can build the progress of the run // diff --git a/app/cli/pkg/action/workflow_run_describe.go b/app/cli/pkg/action/workflow_run_describe.go index 1f3b9557c..91da643da 100644 --- a/app/cli/pkg/action/workflow_run_describe.go +++ b/app/cli/pkg/action/workflow_run_describe.go @@ -557,6 +557,8 @@ type RunEventMaterial struct { InContract bool `json:"in_contract"` AddedByCollector bool `json:"added_by_collector"` Policies *RunEventPolicyCount `json:"policies,omitempty"` + // Step is the key of the custom step that added the material + Step string `json:"step,omitempty"` } type RunEventPolicyCount struct { @@ -634,6 +636,7 @@ func pbRunEventToAction(in *pb.WorkflowRunEvent) *RunEvent { out.Material = &RunEventMaterial{ Name: m.GetName(), MaterialType: m.GetMaterialType(), Value: m.GetValue(), Digest: m.GetDigest(), InContract: m.GetInContract(), AddedByCollector: m.GetAddedByCollector(), Policies: pbRunEventPolicyCountToAction(m.GetPolicies()), + Step: m.GetStep(), } } diff --git a/app/controlplane/api/controlplane/v1/workflow_run.pb.go b/app/controlplane/api/controlplane/v1/workflow_run.pb.go index 6bf4d259c..e68422a0f 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.pb.go +++ b/app/controlplane/api/controlplane/v1/workflow_run.pb.go @@ -2485,8 +2485,11 @@ type WorkflowRunEvent_MaterialAttributes struct { InContract bool `protobuf:"varint,5,opt,name=in_contract,json=inContract,proto3" json:"in_contract,omitempty"` AddedByCollector bool `protobuf:"varint,6,opt,name=added_by_collector,json=addedByCollector,proto3" json:"added_by_collector,omitempty"` Policies *WorkflowRunEvent_PolicyCounts `protobuf:"bytes,7,opt,name=policies,proto3" json:"policies,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // key of the custom step that added the material, from attestation add --step. + // It has the format of a custom key: letters, digits, _ and -, up to 64 characters. + Step string `protobuf:"bytes,8,opt,name=step,proto3" json:"step,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *WorkflowRunEvent_MaterialAttributes) Reset() { @@ -2568,6 +2571,13 @@ func (x *WorkflowRunEvent_MaterialAttributes) GetPolicies() *WorkflowRunEvent_Po return nil } +func (x *WorkflowRunEvent_MaterialAttributes) GetStep() string { + if x != nil { + return x.Step + } + return "" +} + type WorkflowRunEvent_PolicyCounts struct { state protoimpl.MessageState `protogen:"open.v1"` Evaluated int32 `protobuf:"varint,1,opt,name=evaluated,proto3" json:"evaluated,omitempty"` @@ -3019,7 +3029,7 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "$AttestationServiceRecordEventRequest\x120\n" + "\x0fworkflow_run_id\x18\x01 \x01(\tB\b\xbaH\x05r\x03\xb0\x01\x01R\rworkflowRunId\x12?\n" + "\x05event\x18\x02 \x01(\v2!.controlplane.v1.WorkflowRunEventB\x06\xbaH\x03\xc8\x01\x01R\x05event\"'\n" + - "%AttestationServiceRecordEventResponse\"\xfc\x0f\n" + + "%AttestationServiceRecordEventResponse\"\xa3\x10\n" + "\x10WorkflowRunEvent\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x129\n" + "\n" + @@ -3050,7 +3060,7 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\x04name\x18\x01 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\x04name\x12-\n" + "\rmaterial_type\x18\x02 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\fmaterialType\x12\x1a\n" + "\boptional\x18\x03 \x01(\bR\boptional\x12\x1e\n" + - "\x05group\x18\x04 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\x05group\x1a\xbe\x02\n" + + "\x05group\x18\x04 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\x05group\x1a\xe5\x02\n" + "\x12MaterialAttributes\x12\x1c\n" + "\x04name\x18\x01 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\x04name\x12-\n" + "\rmaterial_type\x18\x02 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\fmaterialType\x12\x1e\n" + @@ -3059,7 +3069,8 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\vin_contract\x18\x05 \x01(\bR\n" + "inContract\x12,\n" + "\x12added_by_collector\x18\x06 \x01(\bR\x10addedByCollector\x12J\n" + - "\bpolicies\x18\a \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x1a\xb8\x01\n" + + "\bpolicies\x18\a \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x12%\n" + + "\x04step\x18\b \x01(\tB\x11\xbaH\x0er\f\x18@2\b^[\\w-]*$R\x04step\x1a\xb8\x01\n" + "\fPolicyCounts\x12\x1c\n" + "\tevaluated\x18\x01 \x01(\x05R\tevaluated\x12\x16\n" + "\x06passed\x18\x02 \x01(\x05R\x06passed\x12\x1a\n" + diff --git a/app/controlplane/api/controlplane/v1/workflow_run.proto b/app/controlplane/api/controlplane/v1/workflow_run.proto index 91a2f17b2..2c4ba76bf 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.proto +++ b/app/controlplane/api/controlplane/v1/workflow_run.proto @@ -304,6 +304,12 @@ message WorkflowRunEvent { bool in_contract = 5; bool added_by_collector = 6; PolicyCounts policies = 7; + // key of the custom step that added the material, from attestation add --step. + // It has the format of a custom key: letters, digits, _ and -, up to 64 characters. + string step = 8 [(buf.validate.field).string = { + max_len: 64 + pattern: "^[\\w-]*$" + }]; } message PolicyCounts { diff --git a/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts index 45101266b..68eef56d5 100644 --- a/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts +++ b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts @@ -430,6 +430,11 @@ export interface WorkflowRunEvent_MaterialAttributes { inContract: boolean; addedByCollector: boolean; policies?: WorkflowRunEvent_PolicyCounts; + /** + * key of the custom step that added the material, from attestation add --step. + * It has the format of a custom key: letters, digits, _ and -, up to 64 characters. + */ + step: string; } export interface WorkflowRunEvent_PolicyCounts { @@ -2910,6 +2915,7 @@ function createBaseWorkflowRunEvent_MaterialAttributes(): WorkflowRunEvent_Mater inContract: false, addedByCollector: false, policies: undefined, + step: "", }; } @@ -2936,6 +2942,9 @@ export const WorkflowRunEvent_MaterialAttributes = { if (message.policies !== undefined) { WorkflowRunEvent_PolicyCounts.encode(message.policies, writer.uint32(58).fork()).ldelim(); } + if (message.step !== "") { + writer.uint32(66).string(message.step); + } return writer; }, @@ -2995,6 +3004,13 @@ export const WorkflowRunEvent_MaterialAttributes = { message.policies = WorkflowRunEvent_PolicyCounts.decode(reader, reader.uint32()); continue; + case 8: + if (tag !== 66) { + break; + } + + message.step = reader.string(); + continue; } if ((tag & 7) === 4 || tag === 0) { break; @@ -3013,6 +3029,7 @@ export const WorkflowRunEvent_MaterialAttributes = { inContract: isSet(object.inContract) ? Boolean(object.inContract) : false, addedByCollector: isSet(object.addedByCollector) ? Boolean(object.addedByCollector) : false, policies: isSet(object.policies) ? WorkflowRunEvent_PolicyCounts.fromJSON(object.policies) : undefined, + step: isSet(object.step) ? String(object.step) : "", }; }, @@ -3026,6 +3043,7 @@ export const WorkflowRunEvent_MaterialAttributes = { message.addedByCollector !== undefined && (obj.addedByCollector = message.addedByCollector); message.policies !== undefined && (obj.policies = message.policies ? WorkflowRunEvent_PolicyCounts.toJSON(message.policies) : undefined); + message.step !== undefined && (obj.step = message.step); return obj; }, @@ -3048,6 +3066,7 @@ export const WorkflowRunEvent_MaterialAttributes = { message.policies = (object.policies !== undefined && object.policies !== null) ? WorkflowRunEvent_PolicyCounts.fromPartial(object.policies) : undefined; + message.step = object.step ?? ""; return message; }, }; diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.jsonschema.json index 3ff751bbb..694158a73 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.jsonschema.json @@ -36,6 +36,12 @@ "policies": { "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json" }, + "step": { + "description": "key of the custom step that added the material, from attestation add --step.\n It has the format of a custom key: letters, digits, _ and -, up to 64 characters.", + "maxLength": 64, + "pattern": "^[\\w-]*$", + "type": "string" + }, "value": { "description": "value shown by attestation status, cut to 256 characters", "maxLength": 256, diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.schema.json index eb4562d1e..407069341 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.schema.json @@ -36,6 +36,12 @@ "policies": { "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json" }, + "step": { + "description": "key of the custom step that added the material, from attestation add --step.\n It has the format of a custom key: letters, digits, _ and -, up to 64 characters.", + "maxLength": 64, + "pattern": "^[\\w-]*$", + "type": "string" + }, "value": { "description": "value shown by attestation status, cut to 256 characters", "maxLength": 256, diff --git a/app/controlplane/internal/service/workflowrun.go b/app/controlplane/internal/service/workflowrun.go index 6d89f5489..7caa90120 100644 --- a/app/controlplane/internal/service/workflowrun.go +++ b/app/controlplane/internal/service/workflowrun.go @@ -721,6 +721,7 @@ func pbWorkflowRunEventToBiz(in *pb.WorkflowRunEvent) (*biz.WorkflowRunEvent, er InContract: m.GetInContract(), AddedByCollector: m.GetAddedByCollector(), Policies: pbPolicyCountsToBiz(m.GetPolicies()), + Step: m.GetStep(), }} } @@ -794,6 +795,7 @@ func bizWorkflowRunEventToPb(in *biz.WorkflowRunEvent) *pb.WorkflowRunEvent { InContract: m.InContract, AddedByCollector: m.AddedByCollector, Policies: bizPolicyCountsToPb(m.Policies), + Step: m.Step, }} } diff --git a/app/controlplane/internal/service/workflowrunevent_test.go b/app/controlplane/internal/service/workflowrunevent_test.go new file mode 100644 index 000000000..6abfcc8f5 --- /dev/null +++ b/app/controlplane/internal/service/workflowrunevent_test.go @@ -0,0 +1,56 @@ +// +// 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 service + +import ( + "testing" + + pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The step of a material event goes to the control plane and back with the other attributes +func TestWorkflowRunEventMaterialStepRoundTrip(t *testing.T) { + testCases := []struct { + name string + step string + }{ + {name: "material in a step", step: "sast-report-step"}, + {name: "material with no step"}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + in := &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_MATERIAL, + Key: "chainloop.material.sast-report", + Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{ + Name: "sast-report", Step: tc.step, + }}, + } + + ev, err := pbWorkflowRunEventToBiz(in) + require.NoError(t, err) + require.NotNil(t, ev.Attributes.Material) + assert.Equal(t, tc.step, ev.Attributes.Material.Step) + + out := bizWorkflowRunEventToPb(ev) + assert.Equal(t, tc.step, out.GetMaterial().GetStep()) + }) + } +} diff --git a/app/controlplane/pkg/biz/workflowrunevent.go b/app/controlplane/pkg/biz/workflowrunevent.go index 1c7e28c79..9852b3b9e 100644 --- a/app/controlplane/pkg/biz/workflowrunevent.go +++ b/app/controlplane/pkg/biz/workflowrunevent.go @@ -150,6 +150,8 @@ type WorkflowRunEventMaterialAttributes struct { InContract bool `json:"in_contract,omitempty"` AddedByCollector bool `json:"added_by_collector,omitempty"` Policies *WorkflowRunEventPolicyCounts `json:"policies,omitempty"` + // Key of the custom step that added the material. It has the format of a custom key. + Step string `json:"step,omitempty"` } type WorkflowRunEventPolicyCounts struct { @@ -238,6 +240,13 @@ func validateWorkflowRunEvent(ev *WorkflowRunEvent) error { return NewErrValidationStr(fmt.Sprintf("event attributes do not match the event type %q", ev.Type)) } + // the step of a material names a custom step, so it has the format of a custom key + if m := ev.Attributes; m != nil && m.Material != nil && m.Material.Step != "" { + if err := validateWorkflowRunEventCustomKey("material step", m.Material.Step); err != nil { + return err + } + } + return nil } @@ -245,7 +254,7 @@ func validateWorkflowRunEvent(ev *WorkflowRunEvent) error { // use the "chainloop." prefix. Custom events use the format of annotation names. func validateWorkflowRunEventKey(ev *WorkflowRunEvent) error { if ev.Type == WorkflowRunEventTypeCustom { - return validateWorkflowRunEventCustomKey(ev.Key) + return validateWorkflowRunEventCustomKey("custom event key", ev.Key) } if !strings.HasPrefix(ev.Key, workflowRunEventKeyPrefix) { @@ -255,14 +264,16 @@ func validateWorkflowRunEventKey(ev *WorkflowRunEvent) error { return nil } -func validateWorkflowRunEventCustomKey(key string) error { +// validateWorkflowRunEventCustomKey checks the format of a custom key. The label names the +// field in the error. +func validateWorkflowRunEventCustomKey(label, key string) error { // the format is ASCII only, so the byte length is the character count if len(key) > MaxWorkflowRunEventCustomKeyChars { - return NewErrValidationStr(fmt.Sprintf("custom event key is longer than %d characters", MaxWorkflowRunEventCustomKeyChars)) + return NewErrValidationStr(fmt.Sprintf("%s is longer than %d characters", label, MaxWorkflowRunEventCustomKeyChars)) } if !workflowRunEventCustomKeyRe.MatchString(key) { - return NewErrValidationStr(fmt.Sprintf("custom event key %q must contain only letters, digits, _ and -", key)) + return NewErrValidationStr(fmt.Sprintf("%s %q must contain only letters, digits, _ and -", label, key)) } return nil diff --git a/app/controlplane/pkg/biz/workflowrunevent_test.go b/app/controlplane/pkg/biz/workflowrunevent_test.go index 9a7efd0e7..72cf5ce0d 100644 --- a/app/controlplane/pkg/biz/workflowrunevent_test.go +++ b/app/controlplane/pkg/biz/workflowrunevent_test.go @@ -20,6 +20,8 @@ import ( "testing" "unicode/utf8" + "buf.build/go/protovalidate" + pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -33,6 +35,9 @@ const ( func TestValidateWorkflowRunEvent(t *testing.T) { material := &WorkflowRunEventAttributes{Material: &WorkflowRunEventMaterialAttributes{Name: "sbom"}} + materialInStep := func(step string) *WorkflowRunEventAttributes { + return &WorkflowRunEventAttributes{Material: &WorkflowRunEventMaterialAttributes{Name: "sbom", Step: step}} + } attestation := &WorkflowRunEventAttributes{Attestation: &WorkflowRunEventAttestationAttributes{ContractName: "build"}} testCases := []struct { @@ -114,6 +119,24 @@ func TestValidateWorkflowRunEvent(t *testing.T) { event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom, Key: "sast-scan", Attributes: material}, wantErr: "do not match", }, + { + name: "material event in a step", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Attributes: materialInStep("sast-scan")}, + }, + { + name: "material step at the limit", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Attributes: materialInStep(strings.Repeat("a", MaxWorkflowRunEventCustomKeyChars))}, + }, + { + name: "material step with a dot", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Attributes: materialInStep("chainloop.attestation")}, + wantErr: "material step", + }, + { + name: "material step over the limit", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Attributes: materialInStep(strings.Repeat("a", MaxWorkflowRunEventCustomKeyChars+1))}, + wantErr: "material step is longer than", + }, { name: "message over the limit", event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Message: strings.Repeat("a", MaxWorkflowRunEventMessageBytes+1)}, @@ -200,3 +223,40 @@ func TestTruncateBytes(t *testing.T) { }) } } + +// The step of a material event names a custom step, so it MUST validate exactly as the key +// of a custom event that the record API takes (spec issue-3878 R-001). The CLI checks the step +// with the proto rule before it sends it, so the proto rule must agree too. +func TestMaterialStepValidatesAsCustomEventKey(t *testing.T) { + testCases := []struct { + name string + key string + wantErr bool + }{ + {name: "letters, digits, _ and -", key: "sast_scan-2"}, + {name: "at the limit", key: strings.Repeat("a", MaxWorkflowRunEventCustomKeyChars)}, + {name: "over the limit", key: strings.Repeat("a", MaxWorkflowRunEventCustomKeyChars+1), wantErr: true}, + {name: "a dot", key: "chainloop.attestation", wantErr: true}, + {name: "a space", key: "sast scan", wantErr: true}, + {name: "a slash", key: "sast/scan", wantErr: true}, + {name: "a non-ASCII letter", key: "análisis", wantErr: true}, + {name: "a new line", key: "sast\n", wantErr: true}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + customErr := validateWorkflowRunEvent(&WorkflowRunEvent{ + Type: WorkflowRunEventTypeCustom, Key: tc.key, Status: WorkflowRunEventStatusStarted, + }) + stepErr := validateWorkflowRunEvent(&WorkflowRunEvent{ + Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Status: WorkflowRunEventStatusSucceeded, + Attributes: &WorkflowRunEventAttributes{Material: &WorkflowRunEventMaterialAttributes{Name: "sbom", Step: tc.key}}, + }) + protoErr := protovalidate.Validate(&pb.WorkflowRunEvent_MaterialAttributes{Step: tc.key}) + + assert.Equal(t, tc.wantErr, customErr != nil, "custom event key: %v", customErr) + assert.Equal(t, tc.wantErr, stepErr != nil, "material step: %v", stepErr) + assert.Equal(t, tc.wantErr, protoErr != nil, "proto rule of the material step: %v", protoErr) + }) + } +} diff --git a/docs/specs/issue-3878-evidence-in-its-step.md b/docs/specs/issue-3878-evidence-in-its-step.md new file mode 100644 index 000000000..2f7d06cf4 --- /dev/null +++ b/docs/specs/issue-3878-evidence-in-its-step.md @@ -0,0 +1,123 @@ +--- +owner: migmartri +ticket: https://github.com/chainloop-dev/chainloop/issues/3878 +prd: +--- + + + +# Spec issue-3878: Evidence in the step that adds it + +## Summary + +[Spec issue-3825](issue-3825-attestation-progress-events.md) gave each run a timeline of events, and `chainloop attestation event` lets a pipeline record its own steps on it. A step often makes a report and adds it with `chainloop attestation add`. Nothing links that evidence to its step, so the timeline shows it as a separate row after the step. This spec lets an `add` name its step, so that the evidence shows in the step that adds it. The event command names its step with the same `--step` flag. This changes R-013 of spec issue-3825. + +## Problem + +- The `add` of a report happens inside its step, but the timeline shows it after the step, as a separate row. +- The end event of the step has nothing useful to say. A message such as "report added" repeats the evidence row. With no end message, the row of the step loses its started message. +- The policy results of the report are on a row that has no link to the step. +- `--name` is the key of a step on `event`, and the name of a material on `add`. So one flag has two meanings, and `add` has no free word for its step. + +## Goals and Non-Goals + +- Goal: the evidence that a step adds shows in that step in `describe`. The run events hold what the UI needs to show it in the same way. +- Non-goal: build the UI view. The UI is in a different repository. The Proposal describes what it shows. Follow-up: a ticket in the UI repository. +- Non-goal: set the step of an `add` from an environment variable. A value that stays set in a job links later `add` commands to the wrong step. +- Non-goal: add the policy results of the materials of a step to the row of the step. The material rows in the step show them. +- Non-goal: record the step of a material in the signed attestation. The step is progress data, as all run events (D-003 of spec issue-3825). +- Non-goal: link the materials that collectors add at `init` to a step. No custom step is open at `init`. +- In scope: the event command takes its step key with `--step` (R-003). The ticket names it. Also, `add --step` must use the same word as the command that opens the step. So the two ship together. + +## Requirements + +### R-001: An `add` records its step +`chainloop attestation add --step ` MUST record the key of a custom step on each material event of the `add`. This includes a failed `add` and the summary event of a large archive. The step has the format of a custom key: letters, digits, `_`, and `-` (R-013 of spec issue-3825). It has at most 64 characters (R-008 of spec issue-3825). The material event keeps its `chainloop.material.` key, so the progress of the run does not change (R-011 of spec issue-3825). A `--step` problem MUST NOT fail the `add`. For a value with a wrong format or over 64 characters, the CLI shows a warning and records the event with no step. The control plane MUST reject a material event with a step that is not a valid custom key. This is the same as for the other limits (R-008 of spec issue-3825). +- Done when: `add --step sast-scan` records `sast-scan` on its material event, also when the `add` fails. An `add` with a step of 65 characters adds the material, shows a warning, and records the material event with no step. + +### R-002: `describe` shows the evidence in its step +`chainloop workflow run describe` MUST show a material in the custom step that its event names, in time order with the events of the step. A material shows as a top-level row, as today, when no custom event has the key of its step. The events of one material can have different steps. Then the material shows in the step of the event that its row shows. That is the last `add` that succeeded, else the last event. +- Done when: in `describe`, the material of `add --name sast-report --step sast-scan` shows in the `sast-scan` step, between the started and the succeeded events of the step. + +### R-003: The event command names its step with `--step` +`chainloop attestation event --step --status --message ` MUST record a custom event, with the behavior of R-013 of spec issue-3825. The command takes the key with `--step`, and has no `--name` flag (D-002). A call with `--name` fails as an unknown flag, with a non-zero exit. +- Done when: `chainloop attestation event --step sast-scan --status started` shows the step in `describe`. `--name sast-scan` fails with an unknown flag error. + +## Constraints + +- Compatibility: an older control plane does not know the step. It stores the material event without it, and the material shows as a top-level row. +- Compatibility: an older CLI sends no step. Its runs show as today. +- Data: the step is a key that the user chooses. R-005 of spec issue-3825 allows names in automatic events, and the step is the name of a step, so it is allowed data. + +## Proposal + +**What the user does and sees.** A pipeline step runs `chainloop attestation event --step sast-scan --status started --message "Scanning 14 changed files"`. It then runs the scan and adds its report with `chainloop attestation add --name sast-report --value report.json --step sast-scan`. At the end it runs `chainloop attestation event --step sast-scan --status succeeded`. In `describe`, the `sast-scan` step has three rows. The first is the started event with its message. The second is the added evidence `sast-report`, with its type, value, and policy results. The last is the succeeded event. + +**Event model.** The material attributes of a run event get an optional step. It is a typed attribute, as in D-006 of spec issue-3825. Each client groups the events by key, as today. Then it moves each material row into the custom step with the key that the material names. No database change is necessary, because the control plane stores the attributes as a document. + +**UI (described, built in a follow-up).** The run page nests the material in its step in the same way. The row of a step shows the latest message of the step that is not empty. So the "Scanning" message stays visible after the step ends. + +```mermaid +sequenceDiagram + participant CI as CI job (CLI) + participant CP as Control plane + participant U as User (describe or UI) + CI-->>CP: event: custom, key sast-scan, started + CI->>CI: run the scan + CI-->>CP: event: material, key chainloop.material.sast-report, step sast-scan + CI-->>CP: event: custom, key sast-scan, succeeded + U->>CP: list events + CP-->>U: events, oldest first + Note over U: group by key, then put each material in the step that it names +``` + +Dashed arrows are best effort. A failed event does not stop the attestation. + +## Decision Record + +### D-001: The `add` names its step, and does not end it +An `add` links to a step only through its `--step` flag. The CLI does not link an `add` to the custom step that is open. An `add` never ends a step. Follows D-004 of spec issue-3825. +- Why: the link has no state, as the keyed events of D-004. So parallel steps and steps that never end show correctly. A step can have more than one material, and a scan can fail after it adds its report. So only the events of the key of the step give its status. +- Alternatives considered: + - Link each `add` to the custom step that is open in the attestation state: no script change, but the link is hidden. It is wrong for parallel steps and for a step that never ends, and remote state must keep the open step. + - The `add` ends the step: wrong for a step with more than one material. Also, the status of a material becomes the status of the step. +- Source: drafting + +### D-002: `--step` replaces `--name` on the event command, with no alias +Replaces the flag name of R-013 of spec issue-3825. No hidden `--name` flag stays. +- Why: the key of a custom event is the name of its step, and `add --step` refers to it (R-001). One word for one thing keeps the scripts clear. The command shipped a short time before, and no known pipeline uses `--name`. So a hidden flag that only warns has no user, and a failed call shows a wrong script at once. +- Alternatives considered: + - Keep `--name`: two flag names for the same key, `event --name X` and `add --step X`. + - `--step` with `--name` as a hidden alias: old scripts keep their events, but the command keeps two names. + - A hidden `--name` that only shows a warning and exits with 0: no known pipeline uses `--name`, so the flag has no user. +- Source: drafting + +## Open Questions + +None. + +## Risks + +| Risk | Mitigation | +|------|------------| +| A pipeline that uses `event --name` from an earlier release fails. | No known pipeline uses it. The release notes name the change. | +| A step key with a typo shows the material as a top-level row. | Accepted. The material is still in the timeline and in the progress. |