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
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment thread
migmartri marked this conversation as resolved.
Resolved
- **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
Expand Down
3 changes: 2 additions & 1 deletion app/cli/cmd/attestation.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const (

var repositoryOrganizationCommands = map[string]bool{
"init": true, "add": true, "push": true, "status": true, "reset": true,
"event": true,
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
}

var (
Expand Down Expand Up @@ -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
}
Expand Down
86 changes: 86 additions & 0 deletions app/cli/cmd/attestation_event.go
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,
Comment thread
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
}
172 changes: 172 additions & 0 deletions app/cli/cmd/attestation_event_test.go
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
}
3 changes: 2 additions & 1 deletion app/cli/cmd/attestation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Loading
Loading