diff --git a/CLAUDE.md b/CLAUDE.md index cf45331d9..c025c88ae 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -241,6 +241,7 @@ Workflow Contracts define the structure and requirements for CI/CD attestations. ### CLI Development - **Commands**: Add new commands in `cmd/` following Cobra patterns +- **Flags, not positional arguments**: identify what a command acts on with a flag (for example `--name`, as in `chainloop attestation add --name sbom`), not with a positional argument - **Actions**: Implement business logic in `internal/action/` - **Policy Development**: Use `internal/policydevel/` for local policy testing - **Default Endpoints**: Override with `-ldflags` at build time using `defaultCASAPI` and `defaultCPAPI` variables diff --git a/app/cli/cmd/attestation.go b/app/cli/cmd/attestation.go index a11d6bad6..b5277c08c 100644 --- a/app/cli/cmd/attestation.go +++ b/app/cli/cmd/attestation.go @@ -38,6 +38,7 @@ const ( var repositoryOrganizationCommands = map[string]bool{ "init": true, "add": true, "push": true, "status": true, "reset": true, + "event": true, } var ( @@ -93,7 +94,7 @@ func newAttestationCmd() *cobra.Command { cmd.PersistentFlags().StringVar(&attestationLocalStatePath, "local-state-path", "", "path to store the attestation state locally, default: [tmpDir]/chainloop_attestation.tmp.json") cmd.AddCommand(newAttestationInitCmd(), newAttestationAddCmd(), newAttestationStatusCmd(), newAttestationPushCmd(), - newAttestationResetCmd(), newAttestationVerifyCmd()) + newAttestationResetCmd(), newAttestationVerifyCmd(), newAttestationEventCmd()) return cmd } diff --git a/app/cli/cmd/attestation_event.go b/app/cli/cmd/attestation_event.go new file mode 100644 index 000000000..196f55ff7 --- /dev/null +++ b/app/cli/cmd/attestation_event.go @@ -0,0 +1,86 @@ +// +// 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 cmd + +import ( + "fmt" + "strings" + + "github.com/chainloop-dev/chainloop/app/cli/pkg/action" + "github.com/spf13/cobra" +) + +func newAttestationEventCmd() *cobra.Command { + var name, status, message string + + cmd := &cobra.Command{ + Use: "event", + Short: "record a custom step of the pipeline in the progress of the attestation", + Long: `Record a custom step of the pipeline, for example a security scan, in the timeline of the attestation in progress. +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. +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`, + // 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-009), so every + // failure, also a wrong call, is a warning and the command exits with success + if len(args) > 0 { + logger.Warn().Msgf("the event was not recorded: unexpected arguments %q, set the step with --name", args) + return nil + } + if name == "" { + logger.Warn().Msg("the event was not recorded: --name is required") + return nil + } + + st, err := action.ParseRunEventStatus(status) + if err != nil { + logger.Warn().Err(err).Msg("the event was not recorded") + return nil + } + + a := action.NewAttestationEvent(&action.AttestationEventOpts{ActionsOpts: ActionOpts, LocalStatePath: attestationLocalStatePath}) + recorded, err := a.Run(cmd.Context(), attestationID, name, st, message) + switch { + case err != nil: + logger.Warn().Err(err).Msg("the event was not recorded") + case !recorded: + logger.Info().Msg("dry run, the event was not recorded") + default: + logger.Info().Msg("event recorded") + } + + return nil + }, + } + + cmd.Flags().StringVar(&name, "name", "", "name 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) + + return cmd +} diff --git a/app/cli/cmd/attestation_event_test.go b/app/cli/cmd/attestation_event_test.go new file mode 100644 index 000000000..388213f56 --- /dev/null +++ b/app/cli/cmd/attestation_event_test.go @@ -0,0 +1,172 @@ +// +// 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 cmd + +import ( + "bytes" + "context" + "io" + "net" + "path/filepath" + "sync" + "testing" + + "github.com/chainloop-dev/chainloop/app/cli/pkg/action" + pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" +) + +// eventsControlPlane records the custom events it receives and answers with err +type eventsControlPlane struct { + pb.UnimplementedAttestationServiceServer + mu sync.Mutex + events []*pb.AttestationServiceRecordEventRequest + err error +} + +func (f *eventsControlPlane) RecordEvent(_ context.Context, req *pb.AttestationServiceRecordEventRequest) (*pb.AttestationServiceRecordEventResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.events = append(f.events, req) + if f.err != nil { + return nil, f.err + } + return &pb.AttestationServiceRecordEventResponse{}, nil +} + +func (f *eventsControlPlane) received() []*pb.AttestationServiceRecordEventRequest { + f.mu.Lock() + defer f.mu.Unlock() + 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. +func TestAttestationEventCmd(t *testing.T) { + const ( + runID = "4f8d2b7e-8c1b-4b1e-9f3a-2a6f1b2c3d4e" + invalidStatus = "invalid status" + nameFlag = "--name" + statusFlag = "--status" + started = "started" + sastScan = "sast-scan" + ) + // remote selects remote state, so no local state is needed + remote := func(args ...string) []string { return append(args, "--attestation-id", runID) } + + testCases := []struct { + name string + args []string + cpErr error + wantSent bool + wantKey string + wantWarn string + wantInfo string + }{ + { + name: "recorded", args: remote(nameFlag, 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), + 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), + 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: "positional argument", args: remote(sastScan, statusFlag, started), wantWarn: "unexpected arguments"}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + fake := &eventsControlPlane{err: tc.cpErr} + var out bytes.Buffer + setEventCmdGlobals(t, newEventsConn(t, fake), filepath.Join(t.TempDir(), "state.json"), &out) + + cmd := newAttestationEventCmd() + cmd.SetArgs(tc.args) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + require.NoError(t, cmd.Execute()) + + got := fake.received() + if !tc.wantSent { + assert.Empty(t, got) + } else { + 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()) + } + + 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) + } + }) + } +} + +// setEventCmdGlobals points the globals that the command reads to the test, and restores them +func setEventCmdGlobals(t *testing.T, conn *grpc.ClientConn, statePath string, out io.Writer) { + t.Helper() + + prevOpts, prevLogger, prevStatePath, prevID := ActionOpts, logger, attestationLocalStatePath, attestationID + t.Cleanup(func() { + ActionOpts, logger, attestationLocalStatePath, attestationID = prevOpts, prevLogger, prevStatePath, prevID + }) + + logger = zerolog.New(out) + ActionOpts = &action.ActionsOpts{CPConnection: conn, Logger: zerolog.Nop()} + attestationLocalStatePath = statePath +} + +func newEventsConn(t *testing.T, fake *eventsControlPlane) *grpc.ClientConn { + t.Helper() + + l := bufconn.Listen(1 << 20) + srv := grpc.NewServer() + pb.RegisterAttestationServiceServer(srv, fake) + go func() { _ = srv.Serve(l) }() + + conn, err := grpc.NewClient("passthrough:///bufnet", + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return l.DialContext(ctx) }), + grpc.WithTransportCredentials(insecure.NewCredentials()), + ) + require.NoError(t, err) + t.Cleanup(func() { + conn.Close() + srv.Stop() + }) + + return conn +} diff --git a/app/cli/cmd/attestation_test.go b/app/cli/cmd/attestation_test.go index d66c4516b..ed2d8b1d2 100644 --- a/app/cli/cmd/attestation_test.go +++ b/app/cli/cmd/attestation_test.go @@ -122,7 +122,8 @@ func TestAttestationRepositoryOrganizationCommands(t *testing.T) { require.NoError(t, err) t.Chdir(dir) - for _, name := range []string{"init", "add", "push", "status", "reset"} { + require.Len(t, repositoryOrganizationCommands, 6) + for name := range repositoryOrganizationCommands { t.Run(name, func(t *testing.T) { _, cmd := newAttestationOrganizationTestCommand(t, name, "saved-org") require.NoError(t, resolveAttestationOrganization(cmd)) diff --git a/app/cli/cmd/workflow_run_timeline.go b/app/cli/cmd/workflow_run_timeline.go index f525ad47a..dca22d00c 100644 --- a/app/cli/cmd/workflow_run_timeline.go +++ b/app/cli/cmd/workflow_run_timeline.go @@ -32,10 +32,11 @@ const ( // timelineMaxDetail keeps each line of the tree readable. JSON output has the full text. timelineMaxDetail = 120 - timelineFailed = "failed" - timelineSourceCLI = "cli" - timelineStarted = "started" - timelineSucceeded = "succeeded" + timelineFailed = action.RunEventStatusFailed + timelineSourceCLI = "cli" + timelineStarted = action.RunEventStatusStarted + timelineSucceeded = action.RunEventStatusSucceeded + timelineTypeCustom = action.RunEventTypeCustom ) // timelineNode is one line of the timeline tree @@ -81,8 +82,8 @@ func renderRunTimeline(w io.Writer, events []*action.RunEvent, progress *action. reported := make(map[string]bool) for _, key := range keys { evs := groups[key] - switch key { - case timelineKeyAttestation: + switch { + case key == timelineKeyAttestation: for _, e := range evs { if e.Status == timelineStarted { started = e @@ -94,6 +95,9 @@ 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: + // only a run in progress has progress, so only its open steps still run + nodes = append(nodes, timelineCustomStep(key, evs, progress != nil, now)) default: if m := evs[len(evs)-1].Material; m != nil { reported[m.Name] = true @@ -145,11 +149,11 @@ func timelineHeader(started *action.RunEvent, events []*action.RunEvent, closing case closing != nil: end := "finished " + timelineTime(closing.CreatedAt) if start != nil && closing.CreatedAt != nil { - end += fmt.Sprintf(" (%s)", closing.CreatedAt.Sub(*start).Round(time.Second)) + end += fmt.Sprintf(" (%s)", timelineDuration(*start, *closing.CreatedAt)) } parts = append(parts, end, timelineStatus(closing.Status)) case start != nil: - parts = append(parts, "running for "+now.Sub(*start).Round(time.Second).String()) + parts = append(parts, "running for "+timelineDuration(*start, now)) } if progress != nil { @@ -282,10 +286,8 @@ func timelineStep(key string, evs []*action.RunEvent, materials map[string]*acti } } + timelineFoldEvents(node, evs) if len(evs) == 1 { - if last.Message != "" { - node.details = append(node.details, timelineMessage(last)) - } return node } @@ -294,7 +296,6 @@ func timelineStep(key string, evs []*action.RunEvent, materials map[string]*acti if e.Status == timelineFailed { failed++ } - node.children = append(node.children, &timelineNode{at: timelineTime(e.CreatedAt), symbol: timelineSymbol(e.Status), name: timelineMessage(e)}) } switch { case failed == 1: @@ -306,6 +307,44 @@ func timelineStep(key string, evs []*action.RunEvent, materials map[string]*acti return node } +// 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 { + first, last := evs[0], evs[len(evs)-1] + node := &timelineNode{at: timelineTime(first.CreatedAt), symbol: timelineSymbol(last.Status), name: "step " + timelineQuote(key)} + + switch { + case first.CreatedAt == nil: + case last.Status == timelineStarted && inProgress: + node.details = append(node.details, "running for "+timelineDuration(*first.CreatedAt, now)) + case last.Status != timelineStarted && len(evs) > 1 && last.CreatedAt != nil: + node.details = append(node.details, "took "+timelineDuration(*first.CreatedAt, *last.CreatedAt)) + } + + timelineFoldEvents(node, evs) + return node +} + +// timelineFoldEvents adds the message of a single event to the line of its step, or +// folds the events of a repeated step below it +func timelineFoldEvents(node *timelineNode, evs []*action.RunEvent) { + if len(evs) == 1 { + if evs[0].Message != "" { + node.details = append(node.details, timelineMessage(evs[0])) + } + return + } + + for _, e := range evs { + node.children = append(node.children, &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() +} + // timelineEvidenceAction names what happened to a piece of evidence func timelineEvidenceAction(last *action.RunEvent, name string) string { quoted := timelineQuote(name) @@ -372,7 +411,7 @@ func timelineSymbol(status string) string { return text.FgHiGreen.Sprint("✓") case timelineFailed: return text.FgHiRed.Sprint("✗") - case "canceled": + case action.RunEventStatusCanceled: return text.FgYellow.Sprint("⊘") default: return text.FgYellow.Sprint("●") diff --git a/app/cli/cmd/workflow_run_timeline_test.go b/app/cli/cmd/workflow_run_timeline_test.go index 13d1a2431..f00298999 100644 --- a/app/cli/cmd/workflow_run_timeline_test.go +++ b/app/cli/cmd/workflow_run_timeline_test.go @@ -40,6 +40,9 @@ func TestRenderRunTimeline(t *testing.T) { return &action.RunEvent{CreatedAt: at(d), Source: timelineSourceCLI, Key: "chainloop.material." + name, Status: status, Message: msg, Material: &action.RunEventMaterial{Name: name, Policies: policies}} } + 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} + } testCases := []struct { name string @@ -97,6 +100,45 @@ func TestRenderRunTimeline(t *testing.T) { "│ └─ 10:02:02 ✗ material already exists in the attestation\n" + "└─ ● waiting for push\n", }, + { + name: "run in progress, with custom steps", + events: []*action.RunEvent{ + started, + custom(60*time.Second, "sast-scan", "started", "Semgrep, ruleset p/ci"), + material(90*time.Second, "sbom", "succeeded", "", nil), + custom(183*time.Second, "sast-scan", "succeeded", ""), + custom(200*time.Second, "unit-tests", "failed", "3 tests failed"), + custom(300*time.Second, "approval", "started", ""), + }, + progress: &action.RunProgress{ + RequiredTotal: 1, RequiredProvided: 1, + Materials: []*action.RunProgressMaterial{ + {Name: "sbom", Requirement: action.RunMaterialRequired, Status: action.RunMaterialProvided}, + }, + }, + want: "Timeline (reported progress) · started 10:00:02 · running for 5m43s · 1 of 1 required provided\n" + + "├─ 10:00:02 ✓ initialized contract build rev 3 · GITHUB_ACTION · local state · policies: 2 passed\n" + + "├─ 10:01:02 ✓ step `sast-scan` took 2m3s\n" + + "│ ├─ 10:01:02 ● Semgrep, ruleset p/ci\n" + + "│ └─ 10:03:05 ✓ succeeded\n" + + "├─ 10:01:32 ✓ added evidence `sbom` required\n" + + "├─ 10:03:22 ✗ step `unit-tests` 3 tests failed\n" + + "├─ 10:05:02 ● step `approval` running for 43s\n" + + "└─ ● waiting for push\n", + }, + { + name: "stored run, with a custom step that never ended", + events: []*action.RunEvent{ + started, + custom(60*time.Second, "approval", "started", "waiting for approval"), + {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 contract build rev 3 · GITHUB_ACTION · local state · policies: 2 passed\n" + + "├─ 10:01:02 ● step `approval` waiting for approval\n" + + "└─ 10:02:02 ✓ pushed and stored\n", + }, { name: "stored run", events: []*action.RunEvent{ diff --git a/app/cli/documentation/cli-reference.md b/app/cli/documentation/cli-reference.md index acc30b54b..f25ed893e 100644 --- a/app/cli/documentation/cli-reference.md +++ b/app/cli/documentation/cli-reference.md @@ -302,6 +302,60 @@ Options inherited from parent commands -y, --yes[=true|false] Skip confirmation ``` +### chainloop attestation event + +record a custom step of the pipeline in the progress of the attestation + +Synopsis + +Record a custom step of the pipeline, for example a security scan, in the timeline of the attestation in progress. +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. +If the event cannot be recorded, the command shows a warning and exits with success, so it never breaks the pipeline. + +``` +chainloop attestation event [flags] +``` + +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 +``` + +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 +``` + +Options inherited from parent commands + +``` +--artifact-cas string URL for the Artifacts Content Addressable Storage API ($CHAINLOOP_ARTIFACT_CAS_API) (default "cas.chainloop.dev:443") +--artifact-cas-ca string CUSTOM CA file for the Artifacts CAS API (optional) ($CHAINLOOP_ARTIFACT_CAS_API_CA) +-c, --config string Path to an existing config file (default is $HOME/.config/chainloop/config.toml) +--control-plane string URL for the Control Plane API ($CHAINLOOP_CONTROL_PLANE_API) (default "cp.chainloop.dev:443") +--control-plane-ca string CUSTOM CA file for the Control Plane API (optional) ($CHAINLOOP_CONTROL_PLANE_API_CA) +--debug[=true|false] Enable debug/verbose logging mode +--graceful-exit[=true|false] exit 0 in case of error. NOTE: this flag will be removed once Chainloop reaches 1.0 +-i, --insecure[=true|false] Skip TLS transport during connection to the control plane ($CHAINLOOP_API_INSECURE) +--local-state-path string path to store the attestation state locally, default: [tmpDir]/chainloop_attestation.tmp.json +--max-recv-msg-size int Max size in bytes for incoming gRPC messages (0 = default 33554432) ($CHAINLOOP_API_MAX_RECV_MSG_SIZE) +-n, --org string organization name +-o, --output string Output format, valid options are json and table (default "table") +-t, --token string API token. NOTE: Alternatively use the env variable CHAINLOOP_TOKEN +-y, --yes[=true|false] Skip confirmation +``` + ### chainloop attestation help Help about any command diff --git a/app/cli/pkg/action/attestation_event.go b/app/cli/pkg/action/attestation_event.go new file mode 100644 index 000000000..1ca1eace9 --- /dev/null +++ b/app/cli/pkg/action/attestation_event.go @@ -0,0 +1,127 @@ +// +// 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 action + +import ( + "context" + "fmt" + "strings" + + pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" + "github.com/chainloop-dev/chainloop/pkg/attestation/crafter" + api "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/api/attestation/v1" + "github.com/rs/zerolog" +) + +// RunEventTypeCustom is the type of a step that the pipeline records +const RunEventTypeCustom = "custom" + +// Statuses of a run event +const ( + RunEventStatusStarted = "started" + RunEventStatusSucceeded = "succeeded" + RunEventStatusFailed = "failed" + RunEventStatusCanceled = "canceled" +) + +// RunEventStatuses are the statuses that a custom run event accepts +var RunEventStatuses = []string{RunEventStatusStarted, RunEventStatusSucceeded, RunEventStatusFailed, RunEventStatusCanceled} + +// runEventStatusToPb limits the statuses that the CLI accepts to the ones of the spec (R-009) +var runEventStatusToPb = map[string]pb.WorkflowRunEvent_Status{ + RunEventStatusStarted: pb.WorkflowRunEvent_STATUS_STARTED, + RunEventStatusSucceeded: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + RunEventStatusFailed: pb.WorkflowRunEvent_STATUS_FAILED, + RunEventStatusCanceled: pb.WorkflowRunEvent_STATUS_CANCELED, +} + +// ParseRunEventStatus returns the API status of a custom run event +func ParseRunEventStatus(s string) (pb.WorkflowRunEvent_Status, error) { + st, ok := runEventStatusToPb[s] + if !ok { + return pb.WorkflowRunEvent_STATUS_UNSPECIFIED, fmt.Errorf("invalid status %q, valid options are %s", s, strings.Join(RunEventStatuses, ", ")) + } + + return st, nil +} + +type AttestationEventOpts struct { + *ActionsOpts + LocalStatePath string +} + +// AttestationEvent records a custom step of the pipeline on the run of the attestation in progress +type AttestationEvent struct { + *ActionsOpts + localStatePath string +} + +func NewAttestationEvent(cfg *AttestationEventOpts) *AttestationEvent { + return &AttestationEvent{ActionsOpts: cfg.ActionsOpts, localStatePath: cfg.LocalStatePath} +} + +// Run records the event. 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. +func (action *AttestationEvent) Run(ctx context.Context, attestationID, key string, st pb.WorkflowRunEvent_Status, message string) (bool, error) { + // the caller reports the error, so the recorder does not log it again + var recorder *runEventRecorder + if attestationID != "" { + // with remote state, the attestation ID is the run ID. The control plane rejects + // a run that is not in progress, so the state is not downloaded. + recorder = newRunEventRecorder(action.CPConnection, attestationID, zerolog.Nop()) + } else { + state, err := action.localState(ctx) + if err != nil { + return false, err + } + if state.GetDryRun() { + return false, nil + } + recorder = newRunEventRecorderFromState(action.CPConnection, state, zerolog.Nop()) + } + + if err := recorder.Record(ctx, &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_CUSTOM, + Key: key, + Status: st, + Message: message, + }); err != nil { + return false, err + } + + return true, nil +} + +// localState loads the crafting state of the attestation in progress from the local state file +func (action *AttestationEvent) localState(ctx context.Context) (*api.CraftingState, error) { + c, err := newCrafter(&newCrafterStateOpts{localStatePath: action.localStatePath}, action.CPConnection, crafter.WithLogger(&action.Logger)) + if err != nil { + return nil, fmt.Errorf("failed to load crafter: %w", err) + } + + if initialized, err := c.AlreadyInitialized(ctx, ""); err != nil { + return nil, fmt.Errorf("checking if attestation is already initialized: %w", err) + } else if !initialized { + return nil, ErrAttestationNotInitialized + } + + if err := c.LoadCraftingState(ctx, ""); err != nil { + return nil, fmt.Errorf("loading existing attestation: %w", err) + } + + return c.CraftingState.CraftingState, nil +} diff --git a/app/cli/pkg/action/attestation_event_test.go b/app/cli/pkg/action/attestation_event_test.go new file mode 100644 index 000000000..7bfffb634 --- /dev/null +++ b/app/cli/pkg/action/attestation_event_test.go @@ -0,0 +1,150 @@ +// +// 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 action + +import ( + "context" + "path/filepath" + "testing" + + pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" + schemaapi "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" + "github.com/chainloop-dev/chainloop/pkg/attestation/crafter" + api "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/api/attestation/v1" + "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/runners" + "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/statemanager/filesystem" + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestAttestationEvent(t *testing.T) { + const ( + key = "sast-scan" + message = "Semgrep, ruleset p/ci" + ) + + testCases := []struct { + name string + // initialized seeds a local attestation for the run of testRunID + initialized bool + // attestationID selects remote state, where the ID is the run ID + attestationID string + status string + cpErr error + wantErr error + wantErrCode codes.Code + wantStatus pb.WorkflowRunEvent_Status + }{ + {name: "started", initialized: true, status: RunEventStatusStarted, wantStatus: pb.WorkflowRunEvent_STATUS_STARTED}, + {name: "succeeded", initialized: true, status: RunEventStatusSucceeded, wantStatus: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, + {name: "failed", initialized: true, status: RunEventStatusFailed, wantStatus: pb.WorkflowRunEvent_STATUS_FAILED}, + {name: "canceled", initialized: true, status: RunEventStatusCanceled, wantStatus: pb.WorkflowRunEvent_STATUS_CANCELED}, + {name: "no attestation in progress", status: RunEventStatusStarted, wantErr: ErrAttestationNotInitialized}, + // remote state needs no local state: the control plane checks that the run is in progress + {name: "remote state", attestationID: testRunID, status: RunEventStatusSucceeded, wantStatus: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, + { + name: "rejected by the control plane", initialized: true, status: RunEventStatusStarted, + cpErr: status.Error(codes.InvalidArgument, "custom event key"), wantErrCode: codes.InvalidArgument, wantStatus: pb.WorkflowRunEvent_STATUS_STARTED, + }, + { + name: "control plane without custom events", initialized: true, status: RunEventStatusStarted, + cpErr: status.Error(codes.Unimplemented, "unknown method"), wantErrCode: codes.Unimplemented, wantStatus: pb.WorkflowRunEvent_STATUS_STARTED, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + fake := &fakeEventsControlPlane{err: tc.cpErr} + conn := newFakeEventsConn(t, fake) + statePath := filepath.Join(t.TempDir(), "state.json") + if tc.initialized { + newLocalCrafter(t, conn, statePath) + } + + a := NewAttestationEvent(&AttestationEventOpts{ + ActionsOpts: &ActionsOpts{CPConnection: conn, Logger: zerolog.Nop()}, + LocalStatePath: statePath, + }) + + st, err := ParseRunEventStatus(tc.status) + require.NoError(t, err) + recorded, err := a.Run(context.Background(), tc.attestationID, key, st, message) + switch { + case tc.wantErr != nil: + require.ErrorIs(t, err, tc.wantErr) + assert.False(t, recorded) + assert.Empty(t, fake.received()) + return + case tc.wantErrCode != codes.OK: + require.Error(t, err) + assert.Equal(t, tc.wantErrCode, status.Code(err)) + assert.False(t, recorded) + default: + require.NoError(t, err) + assert.True(t, recorded) + } + + got := fake.received() + require.Len(t, got, 1) + assert.Equal(t, testRunID, got[0].GetWorkflowRunId()) + ev := got[0].GetEvent() + assert.Equal(t, pb.WorkflowRunEvent_TYPE_CUSTOM, ev.GetType()) + assert.Equal(t, key, ev.GetKey()) + assert.Equal(t, tc.wantStatus, ev.GetStatus()) + assert.Equal(t, message, ev.GetMessage()) + assert.Nil(t, ev.GetAttributes()) + }) + } +} + +// A dry run has no run in the control plane, so nothing is sent +func TestAttestationEventDryRun(t *testing.T) { + fake := &fakeEventsControlPlane{} + conn := newFakeEventsConn(t, fake) + statePath := filepath.Join(t.TempDir(), "state.json") + sm, err := filesystem.New(statePath) + require.NoError(t, err) + c, err := crafter.NewCrafter(sm, pb.NewAttestationServiceClient(conn)) + require.NoError(t, err) + require.NoError(t, c.Init(context.Background(), &crafter.InitOpts{ + SchemaV1: &schemaapi.CraftingSchema{SchemaVersion: "v1"}, + WfInfo: &api.WorkflowMetadata{WorkflowRunId: testRunID}, + Runner: runners.NewGeneric(), + DryRun: true, + })) + + a := NewAttestationEvent(&AttestationEventOpts{ActionsOpts: &ActionsOpts{CPConnection: conn, Logger: zerolog.Nop()}, LocalStatePath: statePath}) + recorded, err := a.Run(context.Background(), "", "sast-scan", pb.WorkflowRunEvent_STATUS_STARTED, "") + require.NoError(t, err) + assert.False(t, recorded) + assert.Empty(t, fake.received()) +} + +func TestParseRunEventStatus(t *testing.T) { + for _, s := range RunEventStatuses { + st, err := ParseRunEventStatus(s) + require.NoError(t, err, s) + assert.NotEqual(t, pb.WorkflowRunEvent_STATUS_UNSPECIFIED, st, s) + } + + for _, s := range []string{"", "done", "STATUS_STARTED"} { + _, err := ParseRunEventStatus(s) + assert.ErrorContains(t, err, "invalid status", s) + } +} diff --git a/app/controlplane/api/controlplane/v1/workflow_run.pb.go b/app/controlplane/api/controlplane/v1/workflow_run.pb.go index 1bbfe1b77..922ccb578 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.pb.go +++ b/app/controlplane/api/controlplane/v1/workflow_run.pb.go @@ -143,6 +143,9 @@ const ( WorkflowRunEvent_TYPE_UNSPECIFIED WorkflowRunEvent_Type = 0 WorkflowRunEvent_TYPE_ATTESTATION WorkflowRunEvent_Type = 1 WorkflowRunEvent_TYPE_MATERIAL WorkflowRunEvent_Type = 2 + // A step that the pipeline records with chainloop attestation event. It has no attributes, + // and its key has the format of an annotation name, up to 64 characters. + WorkflowRunEvent_TYPE_CUSTOM WorkflowRunEvent_Type = 4 ) // Enum value maps for WorkflowRunEvent_Type. @@ -151,11 +154,13 @@ var ( 0: "TYPE_UNSPECIFIED", 1: "TYPE_ATTESTATION", 2: "TYPE_MATERIAL", + 4: "TYPE_CUSTOM", } WorkflowRunEvent_Type_value = map[string]int32{ "TYPE_UNSPECIFIED": 0, "TYPE_ATTESTATION": 1, "TYPE_MATERIAL": 2, + "TYPE_CUSTOM": 4, } ) @@ -3010,7 +3015,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\"\xd6\x0f\n" + + "%AttestationServiceRecordEventResponse\"\xe7\x0f\n" + "\x10WorkflowRunEvent\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x129\n" + "\n" + @@ -3061,11 +3066,12 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\x12SOURCE_UNSPECIFIED\x10\x00\x12\x0e\n" + "\n" + "SOURCE_CLI\x10\x01\x12\x18\n" + - "\x14SOURCE_CONTROL_PLANE\x10\x02\"V\n" + + "\x14SOURCE_CONTROL_PLANE\x10\x02\"g\n" + "\x04Type\x12\x14\n" + "\x10TYPE_UNSPECIFIED\x10\x00\x12\x14\n" + "\x10TYPE_ATTESTATION\x10\x01\x12\x11\n" + - "\rTYPE_MATERIAL\x10\x02\"\x04\b\x03\x10\x03*\tTYPE_PUSH\"r\n" + + "\rTYPE_MATERIAL\x10\x02\x12\x0f\n" + + "\vTYPE_CUSTOM\x10\x04\"\x04\b\x03\x10\x03*\tTYPE_PUSH\"r\n" + "\x06Status\x12\x16\n" + "\x12STATUS_UNSPECIFIED\x10\x00\x12\x12\n" + "\x0eSTATUS_STARTED\x10\x01\x12\x14\n" + diff --git a/app/controlplane/api/controlplane/v1/workflow_run.proto b/app/controlplane/api/controlplane/v1/workflow_run.proto index 53f7c5ef4..b5f16d4f9 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.proto +++ b/app/controlplane/api/controlplane/v1/workflow_run.proto @@ -258,6 +258,9 @@ message WorkflowRunEvent { TYPE_MATERIAL = 2; reserved 3; reserved "TYPE_PUSH"; + // A step that the pipeline records with chainloop attestation event. It has no attributes, + // and its key has the format of an annotation name, up to 64 characters. + TYPE_CUSTOM = 4; } enum Status { 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 eb10c4afc..2a71631d4 100644 --- a/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts +++ b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts @@ -294,6 +294,11 @@ export enum WorkflowRunEvent_Type { TYPE_UNSPECIFIED = 0, TYPE_ATTESTATION = 1, TYPE_MATERIAL = 2, + /** + * TYPE_CUSTOM - A step that the pipeline records with chainloop attestation event. It has no attributes, + * and its key has the format of an annotation name, up to 64 characters. + */ + TYPE_CUSTOM = 4, UNRECOGNIZED = -1, } @@ -308,6 +313,9 @@ export function workflowRunEvent_TypeFromJSON(object: any): WorkflowRunEvent_Typ case 2: case "TYPE_MATERIAL": return WorkflowRunEvent_Type.TYPE_MATERIAL; + case 4: + case "TYPE_CUSTOM": + return WorkflowRunEvent_Type.TYPE_CUSTOM; case -1: case "UNRECOGNIZED": default: @@ -323,6 +331,8 @@ export function workflowRunEvent_TypeToJSON(object: WorkflowRunEvent_Type): stri return "TYPE_ATTESTATION"; case WorkflowRunEvent_Type.TYPE_MATERIAL: return "TYPE_MATERIAL"; + case WorkflowRunEvent_Type.TYPE_CUSTOM: + return "TYPE_CUSTOM"; case WorkflowRunEvent_Type.UNRECOGNIZED: default: return "UNRECOGNIZED"; diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json index 0a9901f11..b575ee56e 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json @@ -77,7 +77,8 @@ "enum": [ "TYPE_UNSPECIFIED", "TYPE_ATTESTATION", - "TYPE_MATERIAL" + "TYPE_MATERIAL", + "TYPE_CUSTOM" ], "title": "Type", "type": "string" diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json index 0f335e9c3..8a650aa07 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json @@ -77,7 +77,8 @@ "enum": [ "TYPE_UNSPECIFIED", "TYPE_ATTESTATION", - "TYPE_MATERIAL" + "TYPE_MATERIAL", + "TYPE_CUSTOM" ], "title": "Type", "type": "string" diff --git a/app/controlplane/internal/service/workflowrun.go b/app/controlplane/internal/service/workflowrun.go index 17923e26a..70c97f115 100644 --- a/app/controlplane/internal/service/workflowrun.go +++ b/app/controlplane/internal/service/workflowrun.go @@ -650,10 +650,12 @@ var ( pbToBizRunEventType = map[pb.WorkflowRunEvent_Type]biz.WorkflowRunEventType{ pb.WorkflowRunEvent_TYPE_ATTESTATION: biz.WorkflowRunEventTypeAttestation, pb.WorkflowRunEvent_TYPE_MATERIAL: biz.WorkflowRunEventTypeMaterial, + pb.WorkflowRunEvent_TYPE_CUSTOM: biz.WorkflowRunEventTypeCustom, } bizToPbRunEventType = map[biz.WorkflowRunEventType]pb.WorkflowRunEvent_Type{ biz.WorkflowRunEventTypeAttestation: pb.WorkflowRunEvent_TYPE_ATTESTATION, biz.WorkflowRunEventTypeMaterial: pb.WorkflowRunEvent_TYPE_MATERIAL, + biz.WorkflowRunEventTypeCustom: pb.WorkflowRunEvent_TYPE_CUSTOM, } pbToBizRunEventStatus = map[pb.WorkflowRunEvent_Status]biz.WorkflowRunEventStatus{ pb.WorkflowRunEvent_STATUS_STARTED: biz.WorkflowRunEventStatusStarted, diff --git a/app/controlplane/internal/service/workflowrunevent_integration_test.go b/app/controlplane/internal/service/workflowrunevent_integration_test.go index fad838121..443941c13 100644 --- a/app/controlplane/internal/service/workflowrunevent_integration_test.go +++ b/app/controlplane/internal/service/workflowrunevent_integration_test.go @@ -17,6 +17,7 @@ package service import ( "context" + "strings" "testing" pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" @@ -330,6 +331,32 @@ func (s *workflowRunEventRBACIntegrationSuite) TestRecordAndGetProgress() { s.Equal(pb.WorkflowRunEvent_STATUS_SUCCEEDED, closing.GetStatus()) } +func (s *workflowRunEventRBACIntegrationSuite) TestRecordCustomEvent() { + ctx := s.attCtxForToken(s.org, s.orgToken) + runID := s.runA.ID.String() + + for _, st := range []pb.WorkflowRunEvent_Status{pb.WorkflowRunEvent_STATUS_STARTED, pb.WorkflowRunEvent_STATUS_SUCCEEDED} { + _, err := s.attSvc.RecordEvent(ctx, &pb.AttestationServiceRecordEventRequest{WorkflowRunId: runID, Event: &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_CUSTOM, Key: "sast-scan", Status: st, Message: "Semgrep, ruleset p/ci", + }}) + s.Require().NoError(err) + } + + resp, err := s.runSvc.GetProgress(s.apiCtxForToken(s.org, s.orgToken), &pb.WorkflowRunServiceGetProgressRequest{WorkflowRunId: runID}) + s.Require().NoError(err) + s.Require().Len(resp.GetEvents(), 2) + for _, e := range resp.GetEvents() { + s.Equal(pb.WorkflowRunEvent_TYPE_CUSTOM, e.GetType()) + s.Equal(pb.WorkflowRunEvent_SOURCE_CLI, e.GetSource()) + s.Equal("sast-scan", e.GetKey()) + s.Equal("Semgrep, ruleset p/ci", e.GetMessage()) + s.Nil(e.GetAttributes()) + } + s.Equal(pb.WorkflowRunEvent_STATUS_SUCCEEDED, resp.GetEvents()[1].GetStatus()) + // a custom step does not count as a material + s.Zero(resp.GetProgress().GetRequiredProvided()) +} + func (s *workflowRunEventRBACIntegrationSuite) TestRecordEventValidation() { ctx := s.attCtxForToken(s.org, s.orgToken) runID := s.runA.ID.String() @@ -351,6 +378,25 @@ func (s *workflowRunEventRBACIntegrationSuite) TestRecordEventValidation() { Type: pb.WorkflowRunEvent_TYPE_MATERIAL, Key: "sbom", Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, }, }, + { + name: "custom key with a dot", + event: &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_CUSTOM, Key: "chainloop.attestation", Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + }, + }, + { + name: "custom key over 64 characters", + event: &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_CUSTOM, Key: strings.Repeat("a", 65), Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + }, + }, + { + name: "custom event with attributes", + event: &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_CUSTOM, Key: "sast-scan", Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{Name: sbomMaterial}}, + }, + }, } for _, tc := range testCases { diff --git a/app/controlplane/pkg/biz/workflowrunevent.go b/app/controlplane/pkg/biz/workflowrunevent.go index 00c1ef665..b04cae099 100644 --- a/app/controlplane/pkg/biz/workflowrunevent.go +++ b/app/controlplane/pkg/biz/workflowrunevent.go @@ -18,6 +18,7 @@ package biz import ( "context" "fmt" + "regexp" "slices" "strings" "time" @@ -37,6 +38,8 @@ const ( MaxWorkflowRunEventMessageBytes = 1024 // WorkflowRunEventKeyAttestation is the key of the events that open and close the timeline of a run WorkflowRunEventKeyAttestation = "chainloop.attestation" + // MaxWorkflowRunEventCustomKeyChars is the maximum length of the key of a custom event + MaxWorkflowRunEventCustomKeyChars = 64 // workflowRunEventKeyPrefix is the prefix of the keys of the automatic events workflowRunEventKeyPrefix = "chainloop." // workflowRunEventExpiredMessage is the message of the closing event of an expired run @@ -60,13 +63,20 @@ type WorkflowRunEventType string const ( WorkflowRunEventTypeAttestation WorkflowRunEventType = "attestation" WorkflowRunEventTypeMaterial WorkflowRunEventType = "material" + // WorkflowRunEventTypeCustom is a step that the pipeline records. It has no attributes. + WorkflowRunEventTypeCustom WorkflowRunEventType = "custom" ) // Values implements the ent enum interface func (WorkflowRunEventType) Values() []string { - return []string{string(WorkflowRunEventTypeAttestation), string(WorkflowRunEventTypeMaterial)} + return []string{string(WorkflowRunEventTypeAttestation), string(WorkflowRunEventTypeMaterial), string(WorkflowRunEventTypeCustom)} } +// workflowRunEventCustomKeyRe is the format of annotation names, as in the annotation name +// rule of workflowcontract/v1/crafting_schema.proto. It has no dot, so a custom key never +// matches the key of an automatic event. +var workflowRunEventCustomKeyRe = regexp.MustCompile(`^[\w-]+$`) + type WorkflowRunEventStatus string const ( @@ -192,8 +202,13 @@ func (uc *WorkflowRunEventUseCase) Record(ctx context.Context, runID string, eve } func validateWorkflowRunEvent(ev *WorkflowRunEvent) error { - if !strings.HasPrefix(ev.Key, workflowRunEventKeyPrefix) { - return NewErrValidationStr(fmt.Sprintf("event key must start with %q", workflowRunEventKeyPrefix)) + // the key format depends on the type, so the type comes first + if !slices.Contains(ev.Type.Values(), string(ev.Type)) { + return NewErrValidationStr(fmt.Sprintf("unsupported event type %q", ev.Type)) + } + + if err := validateWorkflowRunEventKey(ev); err != nil { + return err } if len(ev.Message) > MaxWorkflowRunEventMessageBytes { @@ -211,10 +226,6 @@ func validateWorkflowRunEvent(ev *WorkflowRunEvent) error { } } - if !slices.Contains(ev.Type.Values(), string(ev.Type)) { - return NewErrValidationStr(fmt.Sprintf("unsupported event type %q", ev.Type)) - } - if len(set) > 1 || (len(set) == 1 && set[0] != ev.Type) { return NewErrValidationStr(fmt.Sprintf("event attributes do not match the event type %q", ev.Type)) } @@ -222,6 +233,33 @@ func validateWorkflowRunEvent(ev *WorkflowRunEvent) error { return nil } +// validateWorkflowRunEventKey checks the key format of the event type. Automatic events +// 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) + } + + if !strings.HasPrefix(ev.Key, workflowRunEventKeyPrefix) { + return NewErrValidationStr(fmt.Sprintf("event key must start with %q", workflowRunEventKeyPrefix)) + } + + return nil +} + +func validateWorkflowRunEventCustomKey(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)) + } + + if !workflowRunEventCustomKeyRe.MatchString(key) { + return NewErrValidationStr(fmt.Sprintf("custom event key %q must contain only letters, digits, _ and -", key)) + } + + return nil +} + // List returns the events of a run, oldest first. func (uc *WorkflowRunEventUseCase) List(ctx context.Context, runID string) ([]*WorkflowRunEvent, error) { ctx, span := otelx.Start(ctx, workflowRunEventTracer, "WorkflowRunEventUseCase.List") diff --git a/app/controlplane/pkg/biz/workflowrunevent_test.go b/app/controlplane/pkg/biz/workflowrunevent_test.go index 329916027..f098500e2 100644 --- a/app/controlplane/pkg/biz/workflowrunevent_test.go +++ b/app/controlplane/pkg/biz/workflowrunevent_test.go @@ -26,8 +26,9 @@ import ( ) const ( - sbomKey = "chainloop.material.sbom" - shortText = "abc" + sbomKey = "chainloop.material.sbom" + shortText = "abc" + errCustomKey = "custom event key" ) func TestValidateWorkflowRunEvent(t *testing.T) { @@ -59,9 +60,46 @@ func TestValidateWorkflowRunEvent(t *testing.T) { }, { name: "unknown type", - event: &WorkflowRunEvent{Type: "custom", Key: "chainloop.x"}, + event: &WorkflowRunEvent{Type: "other", Key: "chainloop.x"}, wantErr: "unsupported event type", }, + { + name: "custom event", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom, Key: "sast-scan"}, + }, + { + name: "custom key with letters, digits, _ and -", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom, Key: "Unit_tests-2"}, + }, + { + name: "custom key at the limit", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom, Key: strings.Repeat("a", MaxWorkflowRunEventCustomKeyChars)}, + }, + { + name: "custom key with a dot", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom, Key: "chainloop.attestation"}, + wantErr: errCustomKey, + }, + { + name: "custom key with a space", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom, Key: "sast scan"}, + wantErr: errCustomKey, + }, + { + name: "empty custom key", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom}, + wantErr: errCustomKey, + }, + { + name: "custom key over the limit", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom, Key: strings.Repeat("a", MaxWorkflowRunEventCustomKeyChars+1)}, + wantErr: "longer than", + }, + { + name: "custom event with attributes", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeCustom, Key: "sast-scan", Attributes: material}, + wantErr: "do not match", + }, { name: "message over the limit", event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Message: strings.Repeat("a", MaxWorkflowRunEventMessageBytes+1)}, diff --git a/app/controlplane/pkg/biz/workflowrunprogress_test.go b/app/controlplane/pkg/biz/workflowrunprogress_test.go index 4f798fd78..37634d125 100644 --- a/app/controlplane/pkg/biz/workflowrunprogress_test.go +++ b/app/controlplane/pkg/biz/workflowrunprogress_test.go @@ -70,6 +70,15 @@ func TestBuildWorkflowRunProgress(t *testing.T) { material: progressSBOM, wantTotal: 1, want: &WorkflowRunProgressMaterial{Name: progressSBOM, MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialRequired, Status: WorkflowRunMaterialMissing}, }, + { + // a custom step with the name of a material is not an add of that material + name: "custom event with the name of a material", contract: contract, + events: []*WorkflowRunEvent{started(), { + Type: WorkflowRunEventTypeCustom, Key: progressSBOM, Status: WorkflowRunEventStatusFailed, Message: "scan failed", + }}, + material: progressSBOM, wantTotal: 1, + want: &WorkflowRunProgressMaterial{Name: progressSBOM, MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialRequired, Status: WorkflowRunMaterialMissing}, + }, { name: "failed add, never provided", contract: contract, events: []*WorkflowRunEvent{failed(progressSBOM, "bad bomFormat")}, material: progressSBOM, wantTotal: 1, diff --git a/app/controlplane/pkg/data/ent/migrate/schema.go b/app/controlplane/pkg/data/ent/migrate/schema.go index 54c8eff7f..8f64e1983 100644 --- a/app/controlplane/pkg/data/ent/migrate/schema.go +++ b/app/controlplane/pkg/data/ent/migrate/schema.go @@ -1001,7 +1001,7 @@ var ( {Name: "id", Type: field.TypeUUID, Unique: true}, {Name: "created_at", Type: field.TypeTime, Default: "CURRENT_TIMESTAMP"}, {Name: "source", Type: field.TypeEnum, Enums: []string{"cli", "control_plane"}}, - {Name: "type", Type: field.TypeEnum, Enums: []string{"attestation", "material"}}, + {Name: "type", Type: field.TypeEnum, Enums: []string{"attestation", "material", "custom"}}, {Name: "key", Type: field.TypeString}, {Name: "status", Type: field.TypeEnum, Enums: []string{"started", "succeeded", "failed", "canceled"}}, {Name: "message", Type: field.TypeString, Nullable: true, Size: 2147483647}, diff --git a/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go b/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go index d6848ea54..388af84e6 100644 --- a/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go +++ b/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go @@ -89,7 +89,7 @@ func SourceValidator(s biz.WorkflowRunEventSource) error { // TypeValidator is a validator for the "type" field enum values. It is called by the builders before save. func TypeValidator(_type biz.WorkflowRunEventType) error { switch _type { - case "attestation", "material": + case "attestation", "material", "custom": return nil default: return fmt.Errorf("workflowrunevent: invalid enum value for type field: %q", _type) diff --git a/docs/specs/issue-3825-attestation-progress-events.md b/docs/specs/issue-3825-attestation-progress-events.md index 49a09ab86..e65657347 100644 --- a/docs/specs/issue-3825-attestation-progress-events.md +++ b/docs/specs/issue-3825-attestation-progress-events.md @@ -97,8 +97,10 @@ The control plane MUST delete run events that are older than a retention period. ### R-008: Limits The control plane MUST reject an event that goes past a limit. The limits are 1,000 events for each run, 64 characters for a custom key, and 1 KB for a message. The CLI builds automatic keys from material names that the contract already accepts, so the custom key limit does not apply to them. Each field of an event also has a bound (D-010). Any key has at most 128 characters, and each attribute text at most 256 characters. Each list of policy names has at most 100 names of 256 characters. The CLI cuts a list of policy names to 100 before it sends it, and the policy counts stay complete. The CLI cuts a message to 1 KB before it sends it, so the error text of a failed action is not lost. When the control plane rejects an event, the CLI shows a warning and continues (R-002). -### R-009: Custom events -`chainloop attestation event --status --message ` MUST record a custom event on the run of the attestation in progress. The status is started, succeeded, failed, or canceled. The command finds the run in the same way as the other attestation commands. A custom key MUST use the format of annotation names: letters, digits, `_`, and `-`. A custom key cannot hold a dot, so it never matches an automatic `chainloop.` key. When the command cannot record the event, for example against an older control plane, it shows a warning and exits with success. A progress signal never breaks a pipeline. +### ~~R-009: Custom events~~ +Superseded by R-012. + +~~`chainloop attestation event --status --message ` MUST record a custom event on the run of the attestation in progress. The status is started, succeeded, failed, or canceled. The command finds the run in the same way as the other attestation commands. A custom key MUST use the format of annotation names: letters, digits, `_`, and `-`. A custom key cannot hold a dot, so it never matches an automatic `chainloop.` key. When the command cannot record the event, for example against an older control plane, it shows a warning and exits with success. A progress signal never breaks a pipeline.~~ ### R-010: Automatic events for every attestation Supersedes R-001. The CLI MUST record a run event at each action of the attestation, with no new flags, in local and remote state modes. The CLI records no event for the `push`. The closing event of the store shows it, and the signed attestation holds its policy results (D-011). The actions are: @@ -111,6 +113,10 @@ Supersedes R-001. The CLI MUST record a run event at each action of the attestat Supersedes R-003. A read call next to the run view MUST return the events of a run, oldest first. It has the permissions of the run view. For a run in progress, the call MUST also return the progress of the run. The progress has one row for each expected material, with its requirement and its status: missing, provided, or failed. It also has the required counts and the attestation policy results of `init`. The control plane builds the progress, so that the CLI, the UI, and other tools show it with no logic of their own (D-012). The expected materials are the ones that `init` resolves, from the contract and its policy groups. The start event lists them. A run whose start event has no list uses the materials of its contract. - Done when: a material that a policy group requires shows as missing until it is added. A failed `add` after a successful one keeps the material as provided, with the error. +### R-012: Custom events +Supersedes R-009. `chainloop attestation event --name --status --message ` MUST record a custom event on the run of the attestation in progress. The command takes the key with the `--name` flag, not as a positional argument, as `chainloop attestation add --name` does. The status is started, succeeded, failed, or canceled. The command finds the run in the same way as the other attestation commands. A custom key MUST use the format of annotation names: letters, digits, `_`, and `-`. A custom key cannot hold a dot, so it never matches an automatic `chainloop.` key. When the command cannot record the event, it shows a warning and exits with success. This also applies to a wrong call, for example a missing `--name`, and to an older control plane. A progress signal never breaks a pipeline. +- Done when: `chainloop attestation event --name sast-scan --status started` between `init` and `push` shows the step in `describe`. Each failure shows a warning, and the command exits with 0. + ## Constraints - Open source: the feature works in the control plane and the CLI alone. It does not need the event bus or any commercial component. @@ -259,7 +265,7 @@ None. ## Milestones 1. **Automatic progress.** Automatic events (R-001, R-002, R-005, R-006), the read call (R-003), `describe` for runs in progress (R-004), retention (R-007), and limits (R-008). R-010 supersedes R-001, and R-011 supersedes R-003. -2. **Custom events.** `chainloop attestation event` (R-009). +2. **Custom events.** `chainloop attestation event` (R-009). R-012 supersedes R-009. ## Risks