From 156ea4b01e97b42c8782f3ce8fd8c1c4eb6904da Mon Sep 17 00:00:00 2001 From: Arunanshu Biswas Date: Fri, 6 Nov 2026 16:19:54 +0530 Subject: [PATCH 1/5] feat(project): scan a branch or tag with project scan create --ref A plain name is a branch. refs/heads/ and refs/tags/ go through as given. One --ref applies to every selected project. A ref the server rejects fails with the server message, which names the project and the ref. Co-Authored-By: Claude Opus 5.5 --- docs/cmd/project-scan-create.md | 46 ++++++- internal/cmd/project/create.go | 19 ++- internal/cmd/project/create_test.go | 10 +- internal/cmd/project/grpc.go | 18 ++- internal/cmd/project/ref.go | 54 +++++++++ internal/cmd/project/ref_test.go | 182 ++++++++++++++++++++++++++++ internal/cmd/project/resolver.go | 2 +- 7 files changed, 316 insertions(+), 15 deletions(-) create mode 100644 internal/cmd/project/ref.go create mode 100644 internal/cmd/project/ref_test.go diff --git a/docs/cmd/project-scan-create.md b/docs/cmd/project-scan-create.md index f335671..c0a3242 100644 --- a/docs/cmd/project-scan-create.md +++ b/docs/cmd/project-scan-create.md @@ -5,7 +5,7 @@ Submit scans for one or more SafeDep projects to SafeDep Cloud-hosted scanners. ## Synopsis ``` -safedep project scan create [PROJECT_NAME...] [--project-id ID] [--output table|plain|json] +safedep project scan create [PROJECT_NAME...] [--project-id ID] [--ref REF] [--output table|plain|json] ``` ## Arguments @@ -27,9 +27,33 @@ does not scan the project locally or invoke `vet`. | Flag | Description | |------|-------------| | `--project-id ` | Project ID to scan instead of a name. Repeat the flag to select multiple projects by ID. | +| `--ref ` | Branch or tag to scan in every selected project. Without it, each project scans the default branch that its repository reports at admission. | Inherits root flags `--output` and `--profile`. +## Choose a branch or tag + +`--ref` takes one of three forms: + +| Value | Scans | +|-------|-------| +| `release/1.2` | The branch `release/1.2`. A plain name is always a branch. | +| `refs/heads/release/1.2` | The branch `release/1.2`. | +| `refs/tags/v1.2.0` | The tag `v1.2.0`. | + +A tag needs the `refs/tags/` form because one name can be a branch and a tag at +once. Control Tower rejects a name that is both, and does not guess. + +Control Tower resolves the ref to a commit at admission, and the scan reads that +commit even if the branch moves later. Results are stored under the short name, +for example `release/1.2`. + +One `--ref` applies to every selected project. If one repository does not have +the ref, Control Tower rejects the whole batch and the error names the project. + +Only GitHub projects take `--ref` today. A batch with `--ref` that selects a +Bitbucket project fails as not scannable. + ## Discover project IDs List GitHub-backed projects with the query service: @@ -63,6 +87,18 @@ safedep project scan create safedep/control-tower safedep/cli \ --project-id 01K88WX3G9RGAK8T3N5YJMFQN1 ``` +Scan a release branch in two projects: + +```bash +safedep project scan create safedep/control-tower safedep/cli --ref release/1.2 +``` + +Scan a tag: + +```bash +safedep project scan create safedep/cli --ref refs/tags/v1.2.0 +``` + Submit a batch and receive JSON: ```bash @@ -102,8 +138,8 @@ header and one tab-separated row per admitted scan. ## All-or-nothing admission -The CLI validates batch size and empty or duplicate selectors, then resolves -every exact project name before admission. A missing or ambiguous name fails +The CLI validates batch size, an empty `--ref`, and empty or duplicate +selectors, then resolves every exact project name before admission. A missing or ambiguous name fails the command without submitting any scans. When multiple projects share a name, the error lists their IDs, sources, and origin URLs so the caller can retry with a project ID. @@ -116,7 +152,9 @@ and quota errors preserve their gRPC status details internally. The CLI uses typed SafeDep error reasons when available and prints a concise message, stable error code, and recovery guidance instead of raw nested gRPC text. Expected local selector and project-name resolution failures use the same -presentation, including a recovery action. +presentation, including a recovery action. A ref that a repository does not +have, or a name that is both a branch and a tag, fails with the server's message +naming the project and the ref. ## Authentication diff --git a/internal/cmd/project/create.go b/internal/cmd/project/create.go index fdbdc2d..416316b 100644 --- a/internal/cmd/project/create.go +++ b/internal/cmd/project/create.go @@ -20,6 +20,8 @@ const ( type createInput struct { ProjectIDs []string ProjectNames []string + Ref string + RefSet bool } type createdScan struct { @@ -52,9 +54,11 @@ func createCmd(a *app.App) *cobra.Command { Short: "Submit project scans to SafeDep Cloud-hosted scanners", Long: "Atomically submit on-demand scans for one to 100 SafeDep projects by exact name or ID " + "to SafeDep Cloud-hosted scanners. The command returns after cloud admission while scan " + - "execution continues asynchronously in SafeDep Cloud.", - Args: func(_ *cobra.Command, args []string) error { + "execution continues asynchronously in SafeDep Cloud. Each project scans its default branch, " + + "or the branch or tag that --ref names.", + Args: func(cmd *cobra.Command, args []string) error { in.ProjectNames = args + in.RefSet = cmd.Flags().Changed("ref") return validateCreateInput(in) }, RunE: func(cmd *cobra.Command, args []string) error { @@ -82,6 +86,12 @@ func createCmd(a *app.App) *cobra.Command { nil, "project ID to scan instead of a name; repeat for multiple projects", ) + cmd.Flags().StringVar( + &in.Ref, + "ref", + "", + "branch or tag to scan in every selected project: a branch name, refs/heads/ or refs/tags/", + ) return cmd } @@ -97,7 +107,10 @@ func validateCreateInput(in createInput) error { if err := validateUniqueValues(in.ProjectIDs, "project ID"); err != nil { return err } - return validateUniqueValues(in.ProjectNames, "project name") + if err := validateUniqueValues(in.ProjectNames, "project name"); err != nil { + return err + } + return validateRef(in.Ref, in.RefSet) } func validateProjectIDs(projectIDs []string) error { diff --git a/internal/cmd/project/create_test.go b/internal/cmd/project/create_test.go index ec39c08..ea0b242 100644 --- a/internal/cmd/project/create_test.go +++ b/internal/cmd/project/create_test.go @@ -108,7 +108,7 @@ func TestCreateProjectScans_SendsOneOrderedBatch(t *testing.T) { ), } - result, err := createProjectScans(context.Background(), client, []string{"project-1", "project-2"}) + result, err := createProjectScans(context.Background(), client, []string{"project-1", "project-2"}, "") require.NoError(t, err) assert.Equal(t, 1, client.calls) @@ -135,7 +135,7 @@ func TestCreateProjectScans_ConvertsCreatedAtToUTC(t *testing.T) { ), } - result, err := createProjectScans(context.Background(), client, []string{"project-1", "project-2"}) + result, err := createProjectScans(context.Background(), client, []string{"project-1", "project-2"}, "") require.NoError(t, err) require.Len(t, result.scans, 2) require.NotNil(t, result.scans[0].CreatedAt) @@ -147,7 +147,7 @@ func TestCreateProjectScans_RejectsInvalidInputBeforeRPC(t *testing.T) { t.Parallel() client := &fakeCreateProjectScansClient{} - _, err := createProjectScans(context.Background(), client, []string{"duplicate", "duplicate"}) + _, err := createProjectScans(context.Background(), client, []string{"duplicate", "duplicate"}, "") require.Error(t, err) assert.Zero(t, client.calls) } @@ -204,7 +204,7 @@ func TestCreateProjectScans_RejectsMalformedResponses(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() client := &fakeCreateProjectScansClient{res: tt.res} - _, err := createProjectScans(context.Background(), client, []string{"project-1"}) + _, err := createProjectScans(context.Background(), client, []string{"project-1"}, "") require.Error(t, err) assert.Contains(t, err.Error(), "project scan create: invalid response") assert.Contains(t, err.Error(), tt.wantErr) @@ -221,7 +221,7 @@ func TestCreateProjectScans_PreservesGRPCStatusAndDetails(t *testing.T) { require.NoError(t, err) client := &fakeCreateProjectScansClient{err: rpcStatus.Err()} - _, err = createProjectScans(context.Background(), client, []string{"project-1"}) + _, err = createProjectScans(context.Background(), client, []string{"project-1"}, "") require.Error(t, err) assert.Contains(t, err.Error(), "project scan create") assert.Equal(t, codes.ResourceExhausted, status.Code(err)) diff --git a/internal/cmd/project/grpc.go b/internal/cmd/project/grpc.go index f7548c7..66336f5 100644 --- a/internal/cmd/project/grpc.go +++ b/internal/cmd/project/grpc.go @@ -6,8 +6,11 @@ import ( controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + scmv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/scm/v1" controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "github.com/safedep/cli/internal/paging" "github.com/safedep/cli/internal/tui" @@ -147,23 +150,34 @@ func createProjectScans( ctx context.Context, client createProjectScansClient, projectIDs []string, + ref string, ) (*createResult, error) { if err := validateProjectIDs(projectIDs); err != nil { return nil, err } - res, err := client.CreateProjectScans(ctx, newCreateRequest(projectIDs)) + res, err := client.CreateProjectScans(ctx, newCreateRequest(projectIDs, ref)) if err != nil { + if ref != "" && status.Code(err) == codes.InvalidArgument { + return nil, refRejectedError(err, qualifiedRef(ref)) + } return nil, fmt.Errorf("project scan create: %w", err) } return translateCreateResponse(res, len(projectIDs)) } -func newCreateRequest(projectIDs []string) *controltowerv1.CreateProjectScansRequest { +// newCreateRequest leaves the ref unset when ref is empty, so the server scans +// the default branch that the forge reports at admission. +func newCreateRequest(projectIDs []string, ref string) *controltowerv1.CreateProjectScansRequest { targets := make([]*controltowerv1.CreateProjectScansRequest_ProjectScanTarget, 0, len(projectIDs)) for _, projectID := range projectIDs { target := &controltowerv1.CreateProjectScansRequest_ProjectScanTarget{} target.SetProjectId(projectID) + if ref != "" { + gitRef := &scmv1.GitRef{} + gitRef.SetRef(qualifiedRef(ref)) + target.SetRef(gitRef) + } targets = append(targets, target) } req := &controltowerv1.CreateProjectScansRequest{} diff --git a/internal/cmd/project/ref.go b/internal/cmd/project/ref.go new file mode 100644 index 0000000..0ad09ac --- /dev/null +++ b/internal/cmd/project/ref.go @@ -0,0 +1,54 @@ +package project + +import ( + "fmt" + "strings" + + "github.com/safedep/dry/usefulerror" + "google.golang.org/grpc/status" +) + +const ( + refPrefix = "refs/" + branchRefPrefix = "refs/heads/" +) + +// qualifiedRef turns the --ref value into the full ref the API requires. A plain +// name is a branch, as in "git switch ". A tag needs refs/tags/ because a +// name can be a branch and a tag at once, and the server rejects that pair +// rather than guess. A value under refs/ goes through unchanged so the server +// owns the ref name rules. +func qualifiedRef(ref string) string { + if strings.HasPrefix(ref, refPrefix) { + return ref + } + return branchRefPrefix + ref +} + +func validateRef(ref string, set bool) error { + if set && ref == "" { + return newProjectError( + usefulerror.ErrBadRequest, + "Invalid ref", + "Pass a branch name, refs/heads/ or refs/tags/, or omit --ref to scan the default branch.", + fmt.Errorf("--ref must not be empty"), + ) + } + return nil +} + +// refRejectedError explains a server rejection of the requested ref. The +// generic InvalidArgument rendering hides the server message behind +// --verbose, and that message names the project and the ref that failed. +func refRejectedError(err error, ref string) error { + return newProjectError( + usefulerror.ErrBadRequest, + "Ref cannot be scanned", + fmt.Sprintf( + "%s. Check that %s exists in every selected repository. A plain name is a branch: pass refs/tags/ for a tag.", + status.Convert(err).Message(), + ref, + ), + fmt.Errorf("project scan create: %w", err), + ) +} diff --git a/internal/cmd/project/ref_test.go b/internal/cmd/project/ref_test.go new file mode 100644 index 0000000..a13d78b --- /dev/null +++ b/internal/cmd/project/ref_test.go @@ -0,0 +1,182 @@ +package project + +import ( + "context" + "strings" + "testing" + "time" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + errorv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/error/v1" + "github.com/safedep/dry/usefulerror" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func twoQueuedScans() *fakeCreateProjectScansClient { + return &fakeCreateProjectScansClient{ + res: createResponse( + projectScan("project-1", "session-1", messagescontroltowerv1.ScanStatus_SCAN_STATUS_QUEUED, time.Time{}), + projectScan("project-2", "session-2", messagescontroltowerv1.ScanStatus_SCAN_STATUS_QUEUED, time.Time{}), + ), + } +} + +func TestRunCreate_SendsTheRefForEveryProject(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + ref string + want string + }{ + {name: "plain name is a branch", ref: "main", want: "refs/heads/main"}, + {name: "plain name with a slash is a branch", ref: "release/1.2", want: "refs/heads/release/1.2"}, + {name: "plain name that looks like a tag is still a branch", ref: "v1.2.0", want: "refs/heads/v1.2.0"}, + {name: "full branch name", ref: "refs/heads/develop", want: "refs/heads/develop"}, + {name: "full tag name", ref: "refs/tags/v1.2.0", want: "refs/tags/v1.2.0"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + scanner := twoQueuedScans() + + _, err := runCreate(context.Background(), scanner, &fakeListProjectsClient{}, createInput{ + ProjectIDs: []string{"project-1", "project-2"}, + Ref: tt.ref, + RefSet: true, + }) + + require.NoError(t, err) + require.Len(t, scanner.req.GetTargets(), 2) + for _, target := range scanner.req.GetTargets() { + require.True(t, target.HasRef(), target.GetProjectId()) + assert.Equal(t, tt.want, target.GetRef().GetRef(), target.GetProjectId()) + } + }) + } +} + +func TestRunCreate_WithoutRefScansTheDefaultBranch(t *testing.T) { + t.Parallel() + scanner := twoQueuedScans() + + _, err := runCreate(context.Background(), scanner, &fakeListProjectsClient{}, createInput{ + ProjectIDs: []string{"project-1", "project-2"}, + }) + + require.NoError(t, err) + require.Len(t, scanner.req.GetTargets(), 2) + for _, target := range scanner.req.GetTargets() { + assert.False(t, target.HasRef(), target.GetProjectId()) + } +} + +func TestCreateCmd_RejectsAnEmptyRefBeforeAnyRequest(t *testing.T) { + t.Parallel() + + cmd := createCmd(nil) + require.NoError(t, cmd.ParseFlags([]string{"--ref", "", "--project-id", "project-1"})) + + err := cmd.Args(cmd, cmd.Flags().Args()) + + requireUsefulError( + t, + err, + usefulerror.ErrBadRequest, + "Invalid ref", + "Pass a branch name, refs/heads/ or refs/tags/, or omit --ref to scan the default branch.", + ) +} + +func TestRunCreate_ExplainsARefTheServerRejects(t *testing.T) { + t.Parallel() + + serverMessage := "project project-2 cannot scan refs/heads/release/1.2: git ref not found" + scanner := &fakeCreateProjectScansClient{err: status.Error(codes.InvalidArgument, serverMessage)} + + _, err := runCreate(context.Background(), scanner, &fakeListProjectsClient{}, createInput{ + ProjectIDs: []string{"project-1", "project-2"}, + Ref: "release/1.2", + RefSet: true, + }) + + requireUsefulError( + t, + err, + usefulerror.ErrBadRequest, + "Ref cannot be scanned", + serverMessage+". Check that refs/heads/release/1.2 exists in every selected repository. "+ + "A plain name is a branch: pass refs/tags/ for a tag.", + ) + assert.Equal(t, codes.InvalidArgument, status.Code(err)) +} + +func TestRunCreate_DoesNotBlameARefThatWasNotRequested(t *testing.T) { + t.Parallel() + + scanner := &fakeCreateProjectScansClient{err: status.Error(codes.InvalidArgument, "at least one target is required")} + + _, err := runCreate(context.Background(), scanner, &fakeListProjectsClient{}, createInput{ + ProjectIDs: []string{"project-1"}, + }) + + require.Error(t, err) + usefulErr, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.NotEqual(t, "Ref cannot be scanned", usefulErr.HumanError()) + assert.Equal(t, codes.InvalidArgument, status.Code(err)) +} + +func TestRunCreate_KeepsOtherServerErrorsWhenARefIsSet(t *testing.T) { + t.Parallel() + + rejection := usefulerror.NewStatus(codes.FailedPrecondition, "service execution failed"). + WithReason(errorv1.ErrorReason_ERROR_REASON_PROJECT_NOT_SCANNABLE). + Err() + scanner := &fakeCreateProjectScansClient{err: rejection} + + _, err := runCreate(context.Background(), scanner, &fakeListProjectsClient{}, createInput{ + ProjectIDs: []string{"project-1"}, + Ref: "main", + RefSet: true, + }) + + require.Error(t, err) + usefulErr, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.NotEqual(t, "Ref cannot be scanned", usefulErr.HumanError()) + assert.Equal(t, codes.FailedPrecondition, status.Code(err)) + reason, ok := usefulerror.ReasonOf(err) + require.True(t, ok) + assert.Equal(t, errorv1.ErrorReason_ERROR_REASON_PROJECT_NOT_SCANNABLE, reason) +} + +// FuzzNewCreateRequest_Ref checks the rule that maps any --ref value to the +// ref the API receives: a value under refs/ is sent as given, and any other +// value names a branch. +func FuzzNewCreateRequest_Ref(f *testing.F) { + for _, seed := range []string{ + "main", "release/1.2", "refs/heads/main", "refs/tags/v1.2.0", "refs/pull/1/head", + "refs/", "refs", "heads/main", "tags/v1", " refs/heads/main", "REFS/heads/main", + } { + f.Add(seed) + } + f.Fuzz(func(t *testing.T, ref string) { + if ref == "" { + return + } + + req := newCreateRequest([]string{"project-1"}, ref) + + got := req.GetTargets()[0].GetRef().GetRef() + if strings.HasPrefix(ref, "refs/") { + assert.Equal(t, ref, got) + } else { + assert.Equal(t, "refs/heads/"+ref, got) + } + }) +} diff --git a/internal/cmd/project/resolver.go b/internal/cmd/project/resolver.go index c77cbaa..acecb12 100644 --- a/internal/cmd/project/resolver.go +++ b/internal/cmd/project/resolver.go @@ -70,7 +70,7 @@ func runCreate( projectIDs = append(projectIDs, projectID) } - return createProjectScans(ctx, scanner, projectIDs) + return createProjectScans(ctx, scanner, projectIDs, in.Ref) } func resolveProjectNames( From 11c9afef4b82ea2024e12977964ae8a570044470 Mon Sep 17 00:00:00 2001 From: Arunanshu Biswas Date: Fri, 6 Nov 2026 16:19:54 +0530 Subject: [PATCH 2/5] docs(agents): add engineering, test and writing rules Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 1e4db00..ca5567a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,6 +33,26 @@ make release-snapshot # Local release build via goreleaser - Re-use existing patterns. Prefer refactoring over copying - `dry/log` for internal logging (`log.Warnf` for soft failures) - Humanize table cells with `dry/tui/humanize` (`Time`, `Duration`). Never a local formatter. New value shapes extend the dry package. See DEVGUIDE Output section +- Comments explain the current behaviour and its reason. No past-facing wording such as "keep the old behaviour". State the actual constraint instead +- DO NOT leak our conversation, prompt, or iteration history into code comments, pull request descriptions, or other maintainer-facing prose. Write for readers who have not seen our conversation + +## Engineering principles + +- Reuse before you build: the Go standard library, this repository, then modules already in `go.mod` (`safedep/dry`, cobra, testify). Grep for a helper before you write one +- New dependencies must be well known and maintained. Propose one before adding it when it overlaps an existing one. Bump one module with `go get @`, never `go get -u ./...` +- SOLID, DRY by the rule of three, KISS, YAGNI. No options, wrappers or config for a single caller +- Prefer guard clauses and early returns. Use the same name for the same concept everywhere +- Export the smallest surface. Define an interface where it is consumed, with only the methods that caller uses + +## Tests + +- Every test guards a behaviour a regression could break, or a bug that already happened. No smoke tests, no tests that restate the implementation, no tests that only raise coverage +- Test through the entry point a caller uses (the cobra command, the orchestration function) and assert outcomes, not the calls made inside +- Fake a dependency at its port: a small fake of the interface, or an `httptest` server for a remote API. A mock that returns fixed values for every call proves nothing +- A new test must fail when you remove the code it guards. Check that once before you commit +- Before adding a test, check that no existing test covers the behaviour. Extend an existing test before creating a new one +- For a parser or a mapping over free-form input, add a native `Fuzz` test with seeds. CI replays the seeds. Run `go test -fuzz` locally for a while before you commit +- Do not assume a failure is pre-existing. Reproduce it on `main` before calling it flaky, and file an issue For any changes in `.github/workflows/`: From 9307913f11374b3d25616378db111e75436d03bb Mon Sep 17 00:00:00 2001 From: Arunanshu Biswas Date: Fri, 6 Nov 2026 16:48:14 +0530 Subject: [PATCH 3/5] feat(project): add --branch and --tag to project scan create --branch and --tag take a short name and add the namespace, so a tag no longer needs refs/tags/. --ref stays for a full ref, such as GITHUB_REF in CI. At most one of the three may be set. Co-Authored-By: Claude Opus 5.5 --- docs/cmd/project-scan-create.md | 43 +++++--- internal/cmd/project/create.go | 28 +++-- internal/cmd/project/grpc.go | 8 +- internal/cmd/project/ref.go | 88 +++++++++++---- internal/cmd/project/ref_test.go | 182 ++++++++++++++++++++++--------- internal/cmd/project/resolver.go | 6 +- 6 files changed, 254 insertions(+), 101 deletions(-) diff --git a/docs/cmd/project-scan-create.md b/docs/cmd/project-scan-create.md index c0a3242..1ae4beb 100644 --- a/docs/cmd/project-scan-create.md +++ b/docs/cmd/project-scan-create.md @@ -5,7 +5,7 @@ Submit scans for one or more SafeDep projects to SafeDep Cloud-hosted scanners. ## Synopsis ``` -safedep project scan create [PROJECT_NAME...] [--project-id ID] [--ref REF] [--output table|plain|json] +safedep project scan create [PROJECT_NAME...] [--project-id ID] [--branch NAME | --tag NAME | --ref REF] [--output table|plain|json] ``` ## Arguments @@ -27,31 +27,34 @@ does not scan the project locally or invoke `vet`. | Flag | Description | |------|-------------| | `--project-id ` | Project ID to scan instead of a name. Repeat the flag to select multiple projects by ID. | -| `--ref ` | Branch or tag to scan in every selected project. Without it, each project scans the default branch that its repository reports at admission. | +| `--branch ` | Branch to scan in every selected project. | +| `--tag ` | Tag to scan in every selected project. | +| `--ref ` | Full ref to scan in every selected project, such as `refs/tags/v1.2.0`. A plain name is a branch. | Inherits root flags `--output` and `--profile`. ## Choose a branch or tag -`--ref` takes one of three forms: +Pass at most one of these flags. Without any of them, each project scans the +default branch that its repository reports at admission. -| Value | Scans | -|-------|-------| -| `release/1.2` | The branch `release/1.2`. A plain name is always a branch. | -| `refs/heads/release/1.2` | The branch `release/1.2`. | -| `refs/tags/v1.2.0` | The tag `v1.2.0`. | +| Flag | Example | Scans | +|------|---------|-------| +| `--branch ` | `--branch release/1.2` | The branch `release/1.2`. | +| `--tag ` | `--tag v1.2.0` | The tag `v1.2.0`. | +| `--ref ` | `--ref refs/tags/v1.2.0` | Exactly that ref. Use it when you already have a full ref, such as `$GITHUB_REF` in CI. A plain name is a branch: `--ref main` scans `refs/heads/main`. | -A tag needs the `refs/tags/` form because one name can be a branch and a tag at -once. Control Tower rejects a name that is both, and does not guess. +`--branch` and `--tag` take a short name. Pass a full ref with `--ref`. Control Tower resolves the ref to a commit at admission, and the scan reads that commit even if the branch moves later. Results are stored under the short name, -for example `release/1.2`. +for example `release/1.2`. A name that is both a branch and a tag is rejected, +because the two would share that short name. -One `--ref` applies to every selected project. If one repository does not have -the ref, Control Tower rejects the whole batch and the error names the project. +The ref applies to every selected project. If one repository does not have the +ref, Control Tower rejects the whole batch and the error names the project. -Only GitHub projects take `--ref` today. A batch with `--ref` that selects a +Only GitHub projects take a ref today. A batch with a ref that selects a Bitbucket project fails as not scannable. ## Discover project IDs @@ -90,13 +93,19 @@ safedep project scan create safedep/control-tower safedep/cli \ Scan a release branch in two projects: ```bash -safedep project scan create safedep/control-tower safedep/cli --ref release/1.2 +safedep project scan create safedep/control-tower safedep/cli --branch release/1.2 ``` Scan a tag: ```bash -safedep project scan create safedep/cli --ref refs/tags/v1.2.0 +safedep project scan create safedep/cli --tag v1.2.0 +``` + +Scan the ref a CI job runs on: + +```bash +safedep project scan create safedep/cli --ref "$GITHUB_REF" ``` Submit a batch and receive JSON: @@ -138,7 +147,7 @@ header and one tab-separated row per admitted scan. ## All-or-nothing admission -The CLI validates batch size, an empty `--ref`, and empty or duplicate +The CLI validates batch size, the ref flags, and empty or duplicate selectors, then resolves every exact project name before admission. A missing or ambiguous name fails the command without submitting any scans. When multiple projects share a name, the error lists their IDs, sources, and origin URLs so the caller can retry diff --git a/internal/cmd/project/create.go b/internal/cmd/project/create.go index 416316b..a0180f2 100644 --- a/internal/cmd/project/create.go +++ b/internal/cmd/project/create.go @@ -20,8 +20,7 @@ const ( type createInput struct { ProjectIDs []string ProjectNames []string - Ref string - RefSet bool + Refs refFlags } type createdScan struct { @@ -55,10 +54,10 @@ func createCmd(a *app.App) *cobra.Command { Long: "Atomically submit on-demand scans for one to 100 SafeDep projects by exact name or ID " + "to SafeDep Cloud-hosted scanners. The command returns after cloud admission while scan " + "execution continues asynchronously in SafeDep Cloud. Each project scans its default branch, " + - "or the branch or tag that --ref names.", + "or the branch or tag that --branch, --tag or --ref names.", Args: func(cmd *cobra.Command, args []string) error { in.ProjectNames = args - in.RefSet = cmd.Flags().Changed("ref") + in.Refs.Set = changedFlags(cmd, refFlag, branchFlag, tagFlag) return validateCreateInput(in) }, RunE: func(cmd *cobra.Command, args []string) error { @@ -86,11 +85,13 @@ func createCmd(a *app.App) *cobra.Command { nil, "project ID to scan instead of a name; repeat for multiple projects", ) + cmd.Flags().StringVar(&in.Refs.Branch, branchFlag, "", "branch to scan in every selected project") + cmd.Flags().StringVar(&in.Refs.Tag, tagFlag, "", "tag to scan in every selected project") cmd.Flags().StringVar( - &in.Ref, - "ref", + &in.Refs.Ref, + refFlag, "", - "branch or tag to scan in every selected project: a branch name, refs/heads/ or refs/tags/", + "full ref to scan in every selected project, such as refs/tags/v1.2.0; a plain name is a branch", ) return cmd } @@ -110,7 +111,18 @@ func validateCreateInput(in createInput) error { if err := validateUniqueValues(in.ProjectNames, "project name"); err != nil { return err } - return validateRef(in.Ref, in.RefSet) + _, err := in.Refs.qualified() + return err +} + +func changedFlags(cmd *cobra.Command, names ...string) []string { + var changed []string + for _, name := range names { + if cmd.Flags().Changed(name) { + changed = append(changed, name) + } + } + return changed } func validateProjectIDs(projectIDs []string) error { diff --git a/internal/cmd/project/grpc.go b/internal/cmd/project/grpc.go index 66336f5..f255981 100644 --- a/internal/cmd/project/grpc.go +++ b/internal/cmd/project/grpc.go @@ -159,15 +159,15 @@ func createProjectScans( res, err := client.CreateProjectScans(ctx, newCreateRequest(projectIDs, ref)) if err != nil { if ref != "" && status.Code(err) == codes.InvalidArgument { - return nil, refRejectedError(err, qualifiedRef(ref)) + return nil, refRejectedError(err, ref) } return nil, fmt.Errorf("project scan create: %w", err) } return translateCreateResponse(res, len(projectIDs)) } -// newCreateRequest leaves the ref unset when ref is empty, so the server scans -// the default branch that the forge reports at admission. +// newCreateRequest takes a full ref. It leaves the ref unset when ref is empty, +// so the server scans the default branch that the forge reports at admission. func newCreateRequest(projectIDs []string, ref string) *controltowerv1.CreateProjectScansRequest { targets := make([]*controltowerv1.CreateProjectScansRequest_ProjectScanTarget, 0, len(projectIDs)) for _, projectID := range projectIDs { @@ -175,7 +175,7 @@ func newCreateRequest(projectIDs []string, ref string) *controltowerv1.CreatePro target.SetProjectId(projectID) if ref != "" { gitRef := &scmv1.GitRef{} - gitRef.SetRef(qualifiedRef(ref)) + gitRef.SetRef(ref) target.SetRef(gitRef) } targets = append(targets, target) diff --git a/internal/cmd/project/ref.go b/internal/cmd/project/ref.go index 0ad09ac..782c2bb 100644 --- a/internal/cmd/project/ref.go +++ b/internal/cmd/project/ref.go @@ -11,44 +11,88 @@ import ( const ( refPrefix = "refs/" branchRefPrefix = "refs/heads/" + tagRefPrefix = "refs/tags/" + + refFlag = "ref" + branchFlag = "branch" + tagFlag = "tag" ) -// qualifiedRef turns the --ref value into the full ref the API requires. A plain -// name is a branch, as in "git switch ". A tag needs refs/tags/ because a -// name can be a branch and a tag at once, and the server rejects that pair -// rather than guess. A value under refs/ goes through unchanged so the server -// owns the ref name rules. -func qualifiedRef(ref string) string { - if strings.HasPrefix(ref, refPrefix) { - return ref - } - return branchRefPrefix + ref +// refFlags holds the three ways to name the ref to scan. Set records which +// flags the user passed, so an empty value is told apart from an absent flag. +type refFlags struct { + Ref string + Branch string + Tag string + Set []string } -func validateRef(ref string, set bool) error { - if set && ref == "" { - return newProjectError( - usefulerror.ErrBadRequest, - "Invalid ref", - "Pass a branch name, refs/heads/ or refs/tags/, or omit --ref to scan the default branch.", +// qualified is the full ref the API requires, or "" to scan the default +// branch. --branch and --tag name the namespace, so the CLI never guesses. +// A plain --ref name is a branch, as in "git switch ", and a full --ref +// goes through unchanged so the server owns the ref name rules. +func (f refFlags) qualified() (string, error) { + switch len(f.Set) { + case 0: + return "", nil + case 1: + default: + return "", invalidRefError( + fmt.Errorf("--%s cannot be combined", strings.Join(f.Set, ", --")), + "Pass only one of --branch, --tag or --ref.", + ) + } + + switch f.Set[0] { + case branchFlag: + return shortRef(branchFlag, f.Branch, branchRefPrefix) + case tagFlag: + return shortRef(tagFlag, f.Tag, tagRefPrefix) + } + if f.Ref == "" { + return "", invalidRefError( fmt.Errorf("--ref must not be empty"), + "Pass a branch name, refs/heads/ or refs/tags/, or omit --ref to scan the default branch.", + ) + } + if strings.HasPrefix(f.Ref, refPrefix) { + return f.Ref, nil + } + return branchRefPrefix + f.Ref, nil +} + +func shortRef(flag, name, prefix string) (string, error) { + if name == "" { + return "", invalidRefError( + fmt.Errorf("--%s must not be empty", flag), + fmt.Sprintf("Pass a %s name, or omit --%s to scan the default branch.", flag, flag), ) } - return nil + if strings.HasPrefix(name, refPrefix) { + return "", invalidRefError( + fmt.Errorf("--%s takes a short name, not %q", flag, name), + fmt.Sprintf("Pass the name without refs/, or pass the full ref with --ref %s.", name), + ) + } + return prefix + name, nil +} + +func invalidRefError(cause error, help string) error { + return newProjectError(usefulerror.ErrBadRequest, "Invalid ref", help, cause) } // refRejectedError explains a server rejection of the requested ref. The // generic InvalidArgument rendering hides the server message behind // --verbose, and that message names the project and the ref that failed. func refRejectedError(err error, ref string) error { + help := fmt.Sprintf("%s. Check that %s exists in every selected repository.", status.Convert(err).Message(), ref) + if name, ok := strings.CutPrefix(ref, branchRefPrefix); ok { + help += fmt.Sprintf(" If %s is a tag, pass --tag %s.", name, name) + } return newProjectError( usefulerror.ErrBadRequest, "Ref cannot be scanned", - fmt.Sprintf( - "%s. Check that %s exists in every selected repository. A plain name is a branch: pass refs/tags/ for a tag.", - status.Convert(err).Message(), - ref, - ), + help, fmt.Errorf("project scan create: %w", err), ) } diff --git a/internal/cmd/project/ref_test.go b/internal/cmd/project/ref_test.go index a13d78b..6f4b4d1 100644 --- a/internal/cmd/project/ref_test.go +++ b/internal/cmd/project/ref_test.go @@ -29,14 +29,31 @@ func TestRunCreate_SendsTheRefForEveryProject(t *testing.T) { tests := []struct { name string - ref string + refs refFlags want string }{ - {name: "plain name is a branch", ref: "main", want: "refs/heads/main"}, - {name: "plain name with a slash is a branch", ref: "release/1.2", want: "refs/heads/release/1.2"}, - {name: "plain name that looks like a tag is still a branch", ref: "v1.2.0", want: "refs/heads/v1.2.0"}, - {name: "full branch name", ref: "refs/heads/develop", want: "refs/heads/develop"}, - {name: "full tag name", ref: "refs/tags/v1.2.0", want: "refs/tags/v1.2.0"}, + { + name: "branch", + refs: refFlags{Branch: "release/1.2", Set: []string{branchFlag}}, + want: "refs/heads/release/1.2", + }, + {name: "tag", refs: refFlags{Tag: "v1.2.0", Set: []string{tagFlag}}, want: "refs/tags/v1.2.0"}, + {name: "plain ref is a branch", refs: refFlags{Ref: "main", Set: []string{refFlag}}, want: "refs/heads/main"}, + { + name: "plain ref that looks like a tag is still a branch", + refs: refFlags{Ref: "v1.2.0", Set: []string{refFlag}}, + want: "refs/heads/v1.2.0", + }, + { + name: "full branch ref", + refs: refFlags{Ref: "refs/heads/develop", Set: []string{refFlag}}, + want: "refs/heads/develop", + }, + { + name: "full tag ref", + refs: refFlags{Ref: "refs/tags/v1.2.0", Set: []string{refFlag}}, + want: "refs/tags/v1.2.0", + }, } for _, tt := range tests { @@ -46,8 +63,7 @@ func TestRunCreate_SendsTheRefForEveryProject(t *testing.T) { _, err := runCreate(context.Background(), scanner, &fakeListProjectsClient{}, createInput{ ProjectIDs: []string{"project-1", "project-2"}, - Ref: tt.ref, - RefSet: true, + Refs: tt.refs, }) require.NoError(t, err) @@ -75,44 +91,101 @@ func TestRunCreate_WithoutRefScansTheDefaultBranch(t *testing.T) { } } -func TestCreateCmd_RejectsAnEmptyRefBeforeAnyRequest(t *testing.T) { +func TestCreateCmd_RejectsABadRefSelectionBeforeAnyRequest(t *testing.T) { t.Parallel() - cmd := createCmd(nil) - require.NoError(t, cmd.ParseFlags([]string{"--ref", "", "--project-id", "project-1"})) + tests := []struct { + name string + flags []string + wantHelp string + }{ + { + name: "empty ref", + flags: []string{"--ref", ""}, + wantHelp: "Pass a branch name, refs/heads/ or refs/tags/, or omit --ref to scan the default branch.", + }, + { + name: "empty branch", + flags: []string{"--branch", ""}, + wantHelp: "Pass a branch name, or omit --branch to scan the default branch.", + }, + { + name: "empty tag", + flags: []string{"--tag", ""}, + wantHelp: "Pass a tag name, or omit --tag to scan the default branch.", + }, + { + name: "full ref given to branch", + flags: []string{"--branch", "refs/heads/main"}, + wantHelp: "Pass the name without refs/, or pass the full ref with --ref refs/heads/main.", + }, + { + name: "full ref given to tag", + flags: []string{"--tag", "refs/tags/v1"}, + wantHelp: "Pass the name without refs/, or pass the full ref with --ref refs/tags/v1.", + }, + { + name: "branch and tag", + flags: []string{"--branch", "main", "--tag", "v1"}, + wantHelp: "Pass only one of --branch, --tag or --ref.", + }, + { + name: "ref and branch", + flags: []string{"--ref", "refs/heads/main", "--branch", "main"}, + wantHelp: "Pass only one of --branch, --tag or --ref.", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + cmd := createCmd(nil) + require.NoError(t, cmd.ParseFlags(append(tt.flags, "--project-id", "project-1"))) - err := cmd.Args(cmd, cmd.Flags().Args()) + err := cmd.Args(cmd, cmd.Flags().Args()) - requireUsefulError( - t, - err, - usefulerror.ErrBadRequest, - "Invalid ref", - "Pass a branch name, refs/heads/ or refs/tags/, or omit --ref to scan the default branch.", - ) + requireUsefulError(t, err, usefulerror.ErrBadRequest, "Invalid ref", tt.wantHelp) + }) + } } func TestRunCreate_ExplainsARefTheServerRejects(t *testing.T) { t.Parallel() - serverMessage := "project project-2 cannot scan refs/heads/release/1.2: git ref not found" - scanner := &fakeCreateProjectScansClient{err: status.Error(codes.InvalidArgument, serverMessage)} + tests := []struct { + name string + refs refFlags + wantHelp string + }{ + { + name: "a branch suggests --tag", + refs: refFlags{Branch: "v1.2.0", Set: []string{branchFlag}}, + wantHelp: "project project-2 cannot scan refs/heads/v1.2.0: git ref not found. " + + "Check that refs/heads/v1.2.0 exists in every selected repository. If v1.2.0 is a tag, pass --tag v1.2.0.", + }, + { + name: "a tag does not suggest --tag", + refs: refFlags{Tag: "v1.2.0", Set: []string{tagFlag}}, + wantHelp: "project project-2 cannot scan refs/tags/v1.2.0: git ref not found. " + + "Check that refs/tags/v1.2.0 exists in every selected repository.", + }, + } - _, err := runCreate(context.Background(), scanner, &fakeListProjectsClient{}, createInput{ - ProjectIDs: []string{"project-1", "project-2"}, - Ref: "release/1.2", - RefSet: true, - }) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + serverMessage, _, _ := strings.Cut(tt.wantHelp, ". Check") + scanner := &fakeCreateProjectScansClient{err: status.Error(codes.InvalidArgument, serverMessage)} - requireUsefulError( - t, - err, - usefulerror.ErrBadRequest, - "Ref cannot be scanned", - serverMessage+". Check that refs/heads/release/1.2 exists in every selected repository. "+ - "A plain name is a branch: pass refs/tags/ for a tag.", - ) - assert.Equal(t, codes.InvalidArgument, status.Code(err)) + _, err := runCreate(context.Background(), scanner, &fakeListProjectsClient{}, createInput{ + ProjectIDs: []string{"project-1", "project-2"}, + Refs: tt.refs, + }) + + requireUsefulError(t, err, usefulerror.ErrBadRequest, "Ref cannot be scanned", tt.wantHelp) + assert.Equal(t, codes.InvalidArgument, status.Code(err)) + }) + } } func TestRunCreate_DoesNotBlameARefThatWasNotRequested(t *testing.T) { @@ -141,8 +214,7 @@ func TestRunCreate_KeepsOtherServerErrorsWhenARefIsSet(t *testing.T) { _, err := runCreate(context.Background(), scanner, &fakeListProjectsClient{}, createInput{ ProjectIDs: []string{"project-1"}, - Ref: "main", - RefSet: true, + Refs: refFlags{Branch: "main", Set: []string{branchFlag}}, }) require.Error(t, err) @@ -155,28 +227,40 @@ func TestRunCreate_KeepsOtherServerErrorsWhenARefIsSet(t *testing.T) { assert.Equal(t, errorv1.ErrorReason_ERROR_REASON_PROJECT_NOT_SCANNABLE, reason) } -// FuzzNewCreateRequest_Ref checks the rule that maps any --ref value to the -// ref the API receives: a value under refs/ is sent as given, and any other -// value names a branch. -func FuzzNewCreateRequest_Ref(f *testing.F) { +// FuzzRefFlags checks the rule that maps any value of each flag to the ref the +// API receives. --branch and --tag add their namespace and refuse a value that +// already has one. --ref sends a value under refs/ as given and treats any +// other value as a branch. +func FuzzRefFlags(f *testing.F) { for _, seed := range []string{ "main", "release/1.2", "refs/heads/main", "refs/tags/v1.2.0", "refs/pull/1/head", "refs/", "refs", "heads/main", "tags/v1", " refs/heads/main", "REFS/heads/main", } { f.Add(seed) } - f.Fuzz(func(t *testing.T, ref string) { - if ref == "" { + f.Fuzz(func(t *testing.T, value string) { + if value == "" { return } + underRefs := strings.HasPrefix(value, "refs/") - req := newCreateRequest([]string{"project-1"}, ref) - - got := req.GetTargets()[0].GetRef().GetRef() - if strings.HasPrefix(ref, "refs/") { - assert.Equal(t, ref, got) + ref, err := refFlags{Ref: value, Set: []string{refFlag}}.qualified() + require.NoError(t, err) + if underRefs { + assert.Equal(t, value, ref) } else { - assert.Equal(t, "refs/heads/"+ref, got) + assert.Equal(t, "refs/heads/"+value, ref) + } + + for flag, prefix := range map[string]string{branchFlag: "refs/heads/", tagFlag: "refs/tags/"} { + flags := refFlags{Branch: value, Tag: value, Set: []string{flag}} + ref, err := flags.qualified() + if underRefs { + require.Error(t, err, flag) + continue + } + require.NoError(t, err, flag) + assert.Equal(t, prefix+value, ref, flag) } }) } diff --git a/internal/cmd/project/resolver.go b/internal/cmd/project/resolver.go index acecb12..61c896b 100644 --- a/internal/cmd/project/resolver.go +++ b/internal/cmd/project/resolver.go @@ -47,6 +47,10 @@ func runCreate( if err := validateCreateInput(in); err != nil { return nil, err } + ref, err := in.Refs.qualified() + if err != nil { + return nil, err + } resolvedIDs, err := resolveProjectNames(ctx, resolver, in.ProjectNames) if err != nil { @@ -70,7 +74,7 @@ func runCreate( projectIDs = append(projectIDs, projectID) } - return createProjectScans(ctx, scanner, projectIDs, in.Ref) + return createProjectScans(ctx, scanner, projectIDs, ref) } func resolveProjectNames( From 57ab284bcf3e3fe7d7ef30f06f57319f5e7480aa Mon Sep 17 00:00:00 2001 From: Arunanshu Biswas Date: Fri, 6 Nov 2026 16:52:44 +0530 Subject: [PATCH 4/5] fix(project): refuse a --ref that is not a branch or a tag The API scans only refs/heads/ and refs/tags/. Another ref, such as a pull request ref, now fails before the request with advice, instead of as a ref the repository does not have. Co-Authored-By: Claude Opus 5.5 --- docs/cmd/project-scan-create.md | 6 +++--- internal/cmd/project/ref.go | 15 ++++++++++++--- internal/cmd/project/ref_test.go | 22 ++++++++++++++++------ 3 files changed, 31 insertions(+), 12 deletions(-) diff --git a/docs/cmd/project-scan-create.md b/docs/cmd/project-scan-create.md index 1ae4beb..1b48b2f 100644 --- a/docs/cmd/project-scan-create.md +++ b/docs/cmd/project-scan-create.md @@ -42,7 +42,7 @@ default branch that its repository reports at admission. |------|---------|-------| | `--branch ` | `--branch release/1.2` | The branch `release/1.2`. | | `--tag ` | `--tag v1.2.0` | The tag `v1.2.0`. | -| `--ref ` | `--ref refs/tags/v1.2.0` | Exactly that ref. Use it when you already have a full ref, such as `$GITHUB_REF` in CI. A plain name is a branch: `--ref main` scans `refs/heads/main`. | +| `--ref ` | `--ref refs/tags/v1.2.0` | Exactly that ref, which must start with `refs/heads/` or `refs/tags/`. Use it when you already have a full ref. A plain name is a branch: `--ref main` scans `refs/heads/main`. | `--branch` and `--tag` take a short name. Pass a full ref with `--ref`. @@ -102,10 +102,10 @@ Scan a tag: safedep project scan create safedep/cli --tag v1.2.0 ``` -Scan the ref a CI job runs on: +Scan a full ref: ```bash -safedep project scan create safedep/cli --ref "$GITHUB_REF" +safedep project scan create safedep/cli --ref refs/tags/v1.2.0 ``` Submit a batch and receive JSON: diff --git a/internal/cmd/project/ref.go b/internal/cmd/project/ref.go index 782c2bb..d3fc434 100644 --- a/internal/cmd/project/ref.go +++ b/internal/cmd/project/ref.go @@ -29,8 +29,8 @@ type refFlags struct { // qualified is the full ref the API requires, or "" to scan the default // branch. --branch and --tag name the namespace, so the CLI never guesses. -// A plain --ref name is a branch, as in "git switch ", and a full --ref -// goes through unchanged so the server owns the ref name rules. +// A plain --ref name is a branch, as in "git switch ". A full branch or +// tag ref goes through unchanged, so the server owns the ref name rules. func (f refFlags) qualified() (string, error) { switch len(f.Set) { case 0: @@ -55,9 +55,18 @@ func (f refFlags) qualified() (string, error) { "Pass a branch name, refs/heads/ or refs/tags/, or omit --ref to scan the default branch.", ) } - if strings.HasPrefix(f.Ref, refPrefix) { + if strings.HasPrefix(f.Ref, branchRefPrefix) || strings.HasPrefix(f.Ref, tagRefPrefix) { return f.Ref, nil } + // The API scans only branches and tags. Another ref, such as a pull + // request ref, fails here with advice instead of as a ref the repository + // does not have. + if strings.HasPrefix(f.Ref, refPrefix) { + return "", invalidRefError( + fmt.Errorf("--ref %q is not a branch or a tag", f.Ref), + "Only branches and tags can be scanned. Pass --branch, --tag, or a ref under refs/heads/ or refs/tags/.", + ) + } return branchRefPrefix + f.Ref, nil } diff --git a/internal/cmd/project/ref_test.go b/internal/cmd/project/ref_test.go index 6f4b4d1..4a2feea 100644 --- a/internal/cmd/project/ref_test.go +++ b/internal/cmd/project/ref_test.go @@ -124,6 +124,11 @@ func TestCreateCmd_RejectsABadRefSelectionBeforeAnyRequest(t *testing.T) { flags: []string{"--tag", "refs/tags/v1"}, wantHelp: "Pass the name without refs/, or pass the full ref with --ref refs/tags/v1.", }, + { + name: "pull request ref", + flags: []string{"--ref", "refs/pull/123/merge"}, + wantHelp: "Only branches and tags can be scanned. Pass --branch, --tag, or a ref under refs/heads/ or refs/tags/.", + }, { name: "branch and tag", flags: []string{"--branch", "main", "--tag", "v1"}, @@ -229,11 +234,11 @@ func TestRunCreate_KeepsOtherServerErrorsWhenARefIsSet(t *testing.T) { // FuzzRefFlags checks the rule that maps any value of each flag to the ref the // API receives. --branch and --tag add their namespace and refuse a value that -// already has one. --ref sends a value under refs/ as given and treats any -// other value as a branch. +// already has one. --ref sends a branch or tag ref as given, refuses any other +// value under refs/, and treats any other value as a branch. func FuzzRefFlags(f *testing.F) { for _, seed := range []string{ - "main", "release/1.2", "refs/heads/main", "refs/tags/v1.2.0", "refs/pull/1/head", + "main", "release/1.2", "refs/heads/main", "refs/tags/v1.2.0", "refs/pull/1/head", "refs/pull/1/merge", "refs/", "refs", "heads/main", "tags/v1", " refs/heads/main", "REFS/heads/main", } { f.Add(seed) @@ -243,12 +248,17 @@ func FuzzRefFlags(f *testing.F) { return } underRefs := strings.HasPrefix(value, "refs/") + branchOrTag := strings.HasPrefix(value, "refs/heads/") || strings.HasPrefix(value, "refs/tags/") ref, err := refFlags{Ref: value, Set: []string{refFlag}}.qualified() - require.NoError(t, err) - if underRefs { + switch { + case branchOrTag: + require.NoError(t, err) assert.Equal(t, value, ref) - } else { + case underRefs: + require.Error(t, err) + default: + require.NoError(t, err) assert.Equal(t, "refs/heads/"+value, ref) } From d821574f3628a86425cd2397d95cb140bdd8d4e4 Mon Sep 17 00:00:00 2001 From: Arunanshu Biswas Date: Fri, 6 Nov 2026 16:53:13 +0530 Subject: [PATCH 5/5] docs(project): show --ref and --branch in GitHub Actions workflows Co-Authored-By: Claude Opus 5.5 --- docs/cmd/project-scan-create.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/docs/cmd/project-scan-create.md b/docs/cmd/project-scan-create.md index 1b48b2f..0e52058 100644 --- a/docs/cmd/project-scan-create.md +++ b/docs/cmd/project-scan-create.md @@ -102,12 +102,24 @@ Scan a tag: safedep project scan create safedep/cli --tag v1.2.0 ``` -Scan a full ref: +Scan the branch or tag that a GitHub Actions push or tag workflow runs on: ```bash -safedep project scan create safedep/cli --ref refs/tags/v1.2.0 +safedep project scan create safedep/cli --ref "$GITHUB_REF" ``` +In a GitHub Actions pull request workflow, `GITHUB_REF` is +`refs/pull//merge`, a merge commit that GitHub builds for the pull request. +It is not a branch or a tag, so the CLI rejects it. Scan the pull request's +source branch instead: + +```bash +safedep project scan create safedep/cli --branch "$GITHUB_HEAD_REF" +``` + +This works when the source branch is in the scanned repository. A branch in a +fork is not, and the scan fails as not found. + Submit a batch and receive JSON: ```bash