Skip to content
Open
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
88 changes: 32 additions & 56 deletions app/cli/cmd/attestation_event.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@
package cmd

import (
"errors"
"fmt"
"strconv"
"strings"

"github.com/chainloop-dev/chainloop/app/cli/pkg/action"
Expand All @@ -27,7 +25,10 @@ import (
)

func newAttestationEventCmd() *cobra.Command {
var step, status, message, current, total string
var (
step, status, message string
current, total int64
)

cmd := &cobra.Command{
Use: "event",
Expand All @@ -39,7 +40,7 @@ Events are progress information only. They are not part of the signed attestatio
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".
A long step can report its progress with --current and --total, for example 240 of 500 commits, in repeated started events.
If the event cannot be recorded, the command shows a warning and exits with success, so it never breaks the pipeline.`,
If the event cannot be recorded, the command fails like the other attestation commands. Use --graceful-exit to exit with success instead.`,
Example: ` # Record the start and the end of a step
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
Expand All @@ -51,83 +52,58 @@ If the event cannot be recorded, the command shows a warning and exits with succ

# Record a step that did not run
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,
Args: cobra.NoArgs,
Annotations: map[string]string{
useAPIToken: trueString,
supportsFederatedAuthAnnotation: trueString,
},
RunE: func(cmd *cobra.Command, args []string) error {
// 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 --step", args)
return nil
}
if step == "" {
logger.Warn().Msg("the event was not recorded: --step is required")
return nil
RunE: func(cmd *cobra.Command, _ []string) error {
// the values are checked here and not in PreRunE: cobra checks the
// required flags after PreRunE, and a missing flag must show its own error
if err := action.ValidateRunEventStep(step); err != nil {
return err
}

st, err := action.ParseRunEventStatus(status)
if err != nil {
logger.Warn().Err(err).Msg("the event was not recorded")
return nil
return err
}

progress, err := parseRunEventProgress(cmd.Flags().Changed("current"), cmd.Flags().Changed("total"), current, total)
if err != nil {
logger.Warn().Err(err).Msg("the event was not recorded")
return nil
// cobra already requires --current and --total together
var progress *pb.WorkflowRunEvent_Progress
if cmd.Flags().Changed("current") {
progress = &pb.WorkflowRunEvent_Progress{Current: current, Total: total}
if err := action.ValidateRunEventProgress(progress); err != nil {
return err
}
}

a := action.NewAttestationEvent(&action.AttestationEventOpts{ActionsOpts: ActionOpts, LocalStatePath: attestationLocalStatePath})
recorded, err := a.Run(cmd.Context(), attestationID, step, st, message, progress)
switch {
case err != nil:
logger.Warn().Err(err).Msg("the event was not recorded")
case !recorded:
if err != nil {
// as in the other attestation commands, --graceful-exit turns the failure into exit 0
return newGracefulError(err)
}

if !recorded {
logger.Info().Msg("dry run, the event was not recorded")
default:
logger.Info().Msg("event recorded")
return nil
}

logger.Info().Msg("event recorded")
return nil
},
}

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")
// string flags, so that a value that is not a number is a warning and not a failure
cmd.Flags().StringVar(&current, "current", "", "progress of the step: the work done so far, from 0 to --total. Requires --total")
cmd.Flags().StringVar(&total, "total", "", "progress of the step: the total work, more than 0. Requires --current")
cmd.Flags().Int64Var(&current, "current", 0, "progress of the step: the work done so far, from 0 to --total. Requires --total")
cmd.Flags().Int64Var(&total, "total", 0, "progress of the step: the total work, more than 0. Requires --current")
cobra.CheckErr(cmd.MarkFlagRequired("step"))
cobra.CheckErr(cmd.MarkFlagRequired("status"))
cmd.MarkFlagsRequiredTogether("current", "total")
flagAttestationID(cmd)

return cmd
}

// parseRunEventProgress returns the progress of the flags, or nil when neither is set. A flag
// that is set with an empty value is set, so its value is wrong. The action checks the values
// with the rules of the control plane.
func parseRunEventProgress(currentSet, totalSet bool, current, total string) (*pb.WorkflowRunEvent_Progress, error) {
if !currentSet && !totalSet {
return nil, nil
}
if !currentSet || !totalSet {
return nil, errors.New("set both --current and --total, or neither")
}

c, err := strconv.ParseInt(current, 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid --current %q: %w", current, err)
}
t, err := strconv.ParseInt(total, 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid --total %q: %w", total, err)
}

return &pb.WorkflowRunEvent_Progress{Current: c, Total: t}, nil
}
74 changes: 43 additions & 31 deletions app/cli/cmd/attestation_event_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ package cmd
import (
"bytes"
"context"
"errors"
"io"
"net"
"path/filepath"
"strings"
"sync"
"testing"

Expand Down Expand Up @@ -60,19 +62,22 @@ func (f *eventsControlPlane) received() []*pb.AttestationServiceRecordEventReque
return append([]*pb.AttestationServiceRecordEventRequest(nil), f.events...)
}

// 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).
// chainloop attestation event fails like the other attestation commands (spec issue-3825 R-014).
// A wrong call is a usage error. A failure to record the event is a graceful error, so
// --graceful-exit can turn it into exit 0. 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"
stepFlag = "--step"
statusFlag = "--status"
started = "started"
sastScan = "sast-scan"
invalidKey = "it must contain only letters, digits, _ and -, up to 64 characters"
currentFlag = "--current"
totalFlag = "--total"
bothFlags = "set both --current and --total, or neither"
eventRecorded = "event recorded"
bothFlags = "if any flags in the group [current total] are set they must all be set"
)
// remote selects remote state, so no local state is needed
remote := func(args ...string) []string { return append(args, "--attestation-id", runID) }
Expand All @@ -82,47 +87,58 @@ func TestAttestationEventCmd(t *testing.T) {
args []string
cpErr error
wantSent bool
wantKey string
// wantProgress is the current and total of the sent event, nil for no progress
wantProgress []int64
wantWarn string
wantInfo string
wantErr string
wantGraceful bool
}{
{
name: "recorded", args: remote(stepFlag, sastScan, statusFlag, started, "--message", "Semgrep"),
wantSent: true, wantKey: sastScan, wantInfo: "event recorded",
wantSent: true, wantInfo: eventRecorded,
},
{name: "skipped", args: remote(stepFlag, sastScan, statusFlag, "skipped"), wantSent: true, wantInfo: eventRecorded},
// a failure to record the event is a graceful error, as in the other attestation commands
{
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: "rejected by the control plane", args: remote(stepFlag, sastScan, statusFlag, started),
cpErr: status.Error(codes.InvalidArgument, "too many events"), wantSent: true,
wantErr: "too many events", wantGraceful: true,
},
{
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",
cpErr: status.Error(codes.Unimplemented, "unknown method"), wantSent: true,
wantErr: "unknown method", wantGraceful: true,
},
{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: "no attestation in progress", args: []string{stepFlag, sastScan, statusFlag, started},
wantErr: "not yet initialized", wantGraceful: true,
},
// a wrong call is a usage error, as in the other commands
{name: "invalid status", args: remote(stepFlag, sastScan, statusFlag, "done"), wantErr: `invalid status "done", valid options are`},
{name: "missing status", args: remote(stepFlag, sastScan), wantErr: `required flag(s) "status" not set`},
{name: "missing step", args: remote(statusFlag, started), wantErr: `required flag(s) "step" not set`},
{name: "missing step and status", args: remote(), wantErr: `required flag(s) "status", "step" not set`},
{name: "invalid step", args: remote(stepFlag, "sast.scan", statusFlag, started), wantErr: `invalid step "sast.scan", ` + invalidKey},
{name: "step too long", args: remote(stepFlag, strings.Repeat("a", 65), statusFlag, started), wantErr: invalidKey},
{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"},
{name: "positional argument", args: remote(sastScan, stepFlag, sastScan, statusFlag, started), wantErr: `unknown command "sast-scan"`},
{
name: "progress", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "240", totalFlag, "500"),
wantSent: true, wantKey: sastScan, wantProgress: []int64{240, 500}, wantInfo: "event recorded",
wantSent: true, wantProgress: []int64{240, 500}, wantInfo: eventRecorded,
},
{
name: "progress at zero", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "0", totalFlag, "500"),
wantSent: true, wantKey: sastScan, wantProgress: []int64{0, 500}, wantInfo: "event recorded",
wantSent: true, wantProgress: []int64{0, 500}, wantInfo: eventRecorded,
},
{name: "empty current and total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag+"=", totalFlag+"="), wantWarn: "invalid --current"},
{name: "current with no total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "240"), wantWarn: bothFlags},
{name: "total with no current", args: remote(stepFlag, sastScan, statusFlag, started, totalFlag, "500"), wantWarn: bothFlags},
{name: "current that is not a number", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "many", totalFlag, "500"), wantWarn: "invalid --current"},
{name: "total that is not a number", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "1", totalFlag, "1.5"), wantWarn: "invalid --total"},
{name: "current over total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "501", totalFlag, "500"), wantWarn: "current must not be greater than total"},
{name: "zero total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "0", totalFlag, "0"), wantWarn: "invalid progress"},
{name: "negative current", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "-1", totalFlag, "500"), wantWarn: "invalid progress"},
// a wrong progress is a usage error too
{name: "empty current and total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag+"=", totalFlag+"="), wantErr: `invalid argument "" for "--current"`},
{name: "current with no total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "240"), wantErr: bothFlags},
{name: "total with no current", args: remote(stepFlag, sastScan, statusFlag, started, totalFlag, "500"), wantErr: bothFlags},
{name: "current that is not a number", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "many", totalFlag, "500"), wantErr: `invalid argument "many" for "--current"`},
{name: "total that is not a number", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "1", totalFlag, "1.5"), wantErr: `invalid argument "1.5" for "--total"`},
{name: "current over total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "501", totalFlag, "500"), wantErr: "current must not be greater than total"},
{name: "zero total", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "0", totalFlag, "0"), wantErr: "invalid progress"},
{name: "negative current", args: remote(stepFlag, sastScan, statusFlag, started, currentFlag, "-1", totalFlag, "500"), wantErr: "invalid progress"},
}

for _, tc := range testCases {
Expand All @@ -138,6 +154,7 @@ func TestAttestationEventCmd(t *testing.T) {
err := cmd.Execute()
if tc.wantErr != "" {
require.ErrorContains(t, err, tc.wantErr)
assert.Equal(t, tc.wantGraceful, errors.As(err, &GracefulError{}), "graceful error")
} else {
require.NoError(t, err)
}
Expand All @@ -149,7 +166,7 @@ func TestAttestationEventCmd(t *testing.T) {
require.Len(t, got, 1)
assert.Equal(t, runID, got[0].GetWorkflowRunId())
assert.Equal(t, pb.WorkflowRunEvent_TYPE_CUSTOM, got[0].GetEvent().GetType())
assert.Equal(t, tc.wantKey, got[0].GetEvent().GetKey())
assert.Equal(t, sastScan, got[0].GetEvent().GetKey())
assert.Nil(t, got[0].GetEvent().GetAttributes())
if tc.wantProgress == nil {
assert.Nil(t, got[0].GetEvent().GetProgress())
Expand All @@ -160,12 +177,7 @@ func TestAttestationEventCmd(t *testing.T) {
}
}

if tc.wantWarn != "" {
assert.Contains(t, out.String(), `"level":"warn"`)
assert.Contains(t, out.String(), tc.wantWarn)
}
if tc.wantInfo != "" {
assert.NotContains(t, out.String(), `"level":"warn"`)
assert.Contains(t, out.String(), tc.wantInfo)
}
})
Expand Down
6 changes: 3 additions & 3 deletions app/cli/documentation/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ Events are progress information only. They are not part of the signed attestatio
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".
A long step can report its progress with --current and --total, for example 240 of 500 commits, in repeated started events.
If the event cannot be recorded, the command shows a warning and exits with success, so it never breaks the pipeline.
If the event cannot be recorded, the command fails like the other attestation commands. Use --graceful-exit to exit with success instead.

```
chainloop attestation event [flags]
Expand All @@ -346,12 +346,12 @@ Options

```
--attestation-id string Unique identifier of the in-progress attestation
--current string progress of the step: the work done so far, from 0 to --total. Requires --total
--current int progress of the step: the work done so far, from 0 to --total. Requires --total
-h, --help[=true|false] help for event
--message string message of the event, up to 1 KB
--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
--total string progress of the step: the total work, more than 0. Requires --current
--total int progress of the step: the total work, more than 0. Requires --current
```

Options inherited from parent commands
Expand Down
4 changes: 2 additions & 2 deletions app/cli/pkg/action/attestation_event.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func NewAttestationEvent(cfg *AttestationEventOpts) *AttestationEvent {

// Run records the event, with the progress of the step when it is not nil. It returns false,
// with no error, when the attestation is a dry run, which has no run in the control plane.
// The event is informational only: the caller must not fail the pipeline on its error.
// The command returns the error to the user, see spec issue-3825 R-016.
func (action *AttestationEvent) Run(ctx context.Context, attestationID, key string, st pb.WorkflowRunEvent_Status, message string, progress *pb.WorkflowRunEvent_Progress) (bool, error) {
event := &pb.WorkflowRunEvent{
Type: pb.WorkflowRunEvent_TYPE_CUSTOM,
Expand All @@ -87,7 +87,7 @@ func (action *AttestationEvent) Run(ctx context.Context, attestationID, key stri
}
if progress != nil {
// check the values before anything else, with the rules of the control plane
if err := validateRunEventProgress(progress); err != nil {
if err := ValidateRunEventProgress(progress); err != nil {
return false, err
}
event.Progress = progress
Expand Down
19 changes: 12 additions & 7 deletions app/cli/pkg/action/runevents.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,19 @@ 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})
// ValidateRunEventStep 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. The rule is the one of
// the API, so the CLI does not keep its own copy.
func ValidateRunEventStep(step string) error {
if err := protovalidate.Validate(&pb.WorkflowRunEvent_MaterialAttributes{Step: step}); err != nil {
return fmt.Errorf("invalid step %q, it must contain only letters, digits, _ and -, up to 64 characters", step)
}

return nil
}

// validateRunEventProgress checks the progress of a custom event with the rules of the control plane
func validateRunEventProgress(p *pb.WorkflowRunEvent_Progress) error {
// ValidateRunEventProgress checks the progress of a custom event with the rules of the control plane
func ValidateRunEventProgress(p *pb.WorkflowRunEvent_Progress) error {
if err := protovalidate.Validate(p); err != nil {
return fmt.Errorf("invalid progress: %w", err)
}
Expand Down Expand Up @@ -99,7 +104,7 @@ func (r *runEventRecorder) withStep(step string) *runEventRecorder {
if step == "" {
return r
}
if err := validateRunEventStepKey(step); err != nil {
if err := ValidateRunEventStep(step); err != nil {
r.logger.Warn().Err(err).Str("step", step).Msg("the material is added with no step")
return r
}
Expand Down
Loading
Loading