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 @@ -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
Expand Down Expand Up @@ -78,6 +79,10 @@ func newAttestationAddCmd() *cobra.Command {
# Without --replace, adding a material with a name that already exists fails.
chainloop attestation add --name <material-name> --value <material-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

Expand Down Expand Up @@ -121,6 +126,7 @@ func newAttestationAddCmd() *cobra.Command {
MaxExtractEntries: maxExtractEntries,
MaxExtractSize: int64(maxExtractSizeBytes),
Replace: replace,
Step: step,
},
)
if err != nil {
Expand Down Expand Up @@ -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)
Expand Down
28 changes: 16 additions & 12 deletions app/cli/cmd/attestation_event.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import (
)

func newAttestationEventCmd() *cobra.Command {
var name, status, message string
var step, status, message string

cmd := &cobra.Command{
Use: "event",
Expand All @@ -33,29 +33,33 @@ 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{
useAPIToken: trueString,
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
}

Expand All @@ -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")
Expand All @@ -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)
Expand Down
29 changes: 18 additions & 11 deletions app/cli/cmd/attestation_event_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"},
}

Expand All @@ -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 {
Expand Down
95 changes: 77 additions & 18 deletions app/cli/cmd/workflow_run_timeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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))
}
}
}

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

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

Expand All @@ -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
}

Expand All @@ -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()
}
Expand Down
59 changes: 59 additions & 0 deletions app/cli/cmd/workflow_run_timeline_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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{
Expand Down
Loading
Loading