Repository navigation
feat: attestation progress events, M2 custom events (#3825) #3865
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
4e8a1d9
feat: record custom steps with chainloop attestation event (#3825)
migmartri aef3bad
test: iterate the repository organization commands in the test
migmartri ab14b40
feat(cli): attestation event warns on every failure, also a wrong call
migmartri 032b826
feat(cli): name the custom step with --name in attestation event
migmartri File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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, | ||
|
migmartri marked this conversation as resolved.
Resolved
|
||
| 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 | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.