diff --git a/docs/cmd/integration-bitbucket-allowlist-update.md b/docs/cmd/integration-bitbucket-allowlist-update.md index 568d27f..aa6852b 100644 --- a/docs/cmd/integration-bitbucket-allowlist-update.md +++ b/docs/cmd/integration-bitbucket-allowlist-update.md @@ -5,7 +5,7 @@ Change which repositories of a linked Bitbucket workspace SafeDep scans. ## Synopsis ``` -safedep integration bitbucket allowlist update [--link-id LINK_ID] +safedep integration bitbucket allowlist update [--account WORKSPACE] [--scope all|selected] [--enable REPOSITORY_UUID]... [--disable REPOSITORY_UUID]... @@ -24,7 +24,7 @@ opens the scope or fills the allowlist. | Flag | Description | |------|-------------| -| `--link-id ` | Bitbucket workspace link to update. Resolved automatically when the tenant has exactly one link. | +| `--account ` | Slug of the linked Bitbucket workspace to update, for example `safedep`. Matched without regard to case. Needed when the tenant has more than one linked workspace. | | `--scope ` | Scan scope after the update. Omit to keep the stored scope. Switching scope does not change the stored allowlist. | | `--enable ` | Repository UUID to add to the allowlist. Braced and uppercase forms are accepted and normalized. Repeat for multiple repositories. A UUID already on the allowlist is a no-op. | | `--disable ` | Repository UUID to remove from the allowlist. Braced and uppercase forms are accepted and normalized. Repeat for multiple repositories. A UUID not on the allowlist is a no-op. | @@ -34,12 +34,16 @@ takes no `--enable` or `--disable` values. At most 500 UUIDs per flag per request: a larger allowlist grows over several calls. Get repository UUIDs from `safedep integration bitbucket repository list`. +`--link-id ` still selects a link by its internal ID. It is hidden from +the help and stays for scripts. With `--link-id` alone, the command lists no +links. With `--link-id` and `--account`, both must name the same link. + ## Examples Scan every repository in the workspace: ```bash -safedep integration bitbucket allowlist update --scope all +safedep integration bitbucket allowlist update --account safedep --scope all ``` Scan two selected repositories only: @@ -62,9 +66,13 @@ safedep integration bitbucket allowlist update \ | Field | Description | |-------|-------------| | `link_id` | The workspace link the update ran against, supplied or resolved. | +| `account` | The workspace slug of that link. Omitted when only `--link-id` named the link. In `plain` output, the last column, with `-` for no slug. | | `scan_scope` | The scan scope after the update. | | `allowlisted_repository_count` | The number of repositories on the allowlist after the update. | +`table` shows the account in place of the link ID, or `link ` when only +`--link-id` named the link. + ## Authentication Requires a control-plane OAuth session with the tenant admin role. Run diff --git a/docs/cmd/integration-bitbucket-link-delete.md b/docs/cmd/integration-bitbucket-link-delete.md index c9d2b42..7e86c69 100644 --- a/docs/cmd/integration-bitbucket-link-delete.md +++ b/docs/cmd/integration-bitbucket-link-delete.md @@ -5,7 +5,7 @@ Unlink a Bitbucket workspace from the active SafeDep tenant. ## Synopsis ``` -safedep integration bitbucket link delete [--link-id ] +safedep integration bitbucket link delete [--account WORKSPACE] ``` ## Description @@ -13,10 +13,14 @@ safedep integration bitbucket link delete [--link-id ] SafeDep revokes the workspace link and discards the stored app token. After the unlink, SafeDep no longer scans the workspace's repositories. -With `--link-id`, the command is idempotent: deleting a link that is already -revoked succeeds. Without `--link-id`, the command resolves the tenant's only -active link. After that link is deleted, a repeat call without `--link-id` -finds no link and fails with not found. +`--account` names the workspace by its slug. Without it, the command resolves +the tenant's only active link. The command picks from active links only, so a +repeat call after the delete fails with not found. + +`--link-id ` still selects a link by its internal ID. It is hidden from +the help and stays for scripts. With `--link-id` alone, the command lists no +links and is idempotent: deleting a link that is already revoked succeeds. +With `--link-id` and `--account`, both must name the same active link. The SafeDep Forge app stays installed in the workspace. It keeps sending events, and SafeDep ignores them. Only a Bitbucket workspace admin can @@ -30,7 +34,7 @@ workspace's SafeDep settings page. No reinstall is needed. | Flag | Description | |------|-------------| -| `--link-id` | The workspace link to delete. When the tenant has exactly one link, the command resolves it automatically. Find link IDs with `safedep integration bitbucket link list`. | +| `--account ` | Slug of the linked Bitbucket workspace to unlink, for example `safedep`. Matched without regard to case. Needed when the tenant has more than one linked workspace. Find slugs with `safedep integration bitbucket link list`. | ## Examples @@ -39,7 +43,7 @@ safedep integration bitbucket link delete ``` ```bash -safedep integration bitbucket link delete --link-id 01J8X2... +safedep integration bitbucket link delete --account safedep ``` ## Authentication @@ -51,5 +55,5 @@ Requires a control-plane OAuth session with the admin role. Run | Code | Meaning | |------|---------| -| `0` | The link is revoked. With `--link-id`, this includes a link revoked before this call. | -| non-zero | Authentication failed, the tenant has no link or more than one link without `--link-id`, the link does not belong to the tenant, or the request failed. | +| `0` | The link is revoked. With `--link-id` alone, this includes a link revoked before this call. | +| non-zero | Authentication failed, the tenant has no link, more than one link without `--account`, or no active link for the account, the link does not belong to the tenant, or the request failed. | diff --git a/docs/cmd/integration-bitbucket-link-list.md b/docs/cmd/integration-bitbucket-link-list.md index f9db2b2..fee553a 100644 --- a/docs/cmd/integration-bitbucket-link-list.md +++ b/docs/cmd/integration-bitbucket-link-list.md @@ -10,10 +10,12 @@ safedep integration bitbucket link list [--output table|plain|json] ## Description -Each row is one linked workspace with its link ID. The link ID feeds -`safedep integration bitbucket repository list` and -`safedep integration bitbucket allowlist update`. The command walks every -page of the listing. +Each row is one linked workspace with its link ID and slug. The slug is the +`--account` value of `safedep integration bitbucket repository list`, +`safedep integration bitbucket allowlist update`, +`safedep integration bitbucket link delete` and `safedep project sync`. The +link ID is for scripts that pass the hidden `--link-id` flag. The command walks +every page of the listing. ## Examples @@ -31,7 +33,7 @@ safedep integration bitbucket link list --output json | jq -r '.links[].link_id' |-------|-------------| | `link_id` | The tenant-owned workspace link ID. | | `workspace_uuid` | The immutable Bitbucket workspace UUID: lowercase, hyphenated, no braces. | -| `workspace_slug` | The workspace slug at the last sync. Mutable metadata, not identity. | +| `workspace_slug` | The workspace slug at the last sync, and the `--account` value of the other commands. Mutable metadata, not identity. | | `workspace_name` | The workspace display name at the last sync. Mutable metadata. | ## Authentication diff --git a/docs/cmd/integration-bitbucket-repository-list.md b/docs/cmd/integration-bitbucket-repository-list.md index 6b3c004..3f51630 100644 --- a/docs/cmd/integration-bitbucket-repository-list.md +++ b/docs/cmd/integration-bitbucket-repository-list.md @@ -5,7 +5,7 @@ List the repositories of a linked Bitbucket workspace with their scan state. ## Synopsis ``` -safedep integration bitbucket repository list [--link-id LINK_ID] +safedep integration bitbucket repository list [--account WORKSPACE] [--output table|plain|json] ``` @@ -13,14 +13,18 @@ safedep integration bitbucket repository list [--link-id LINK_ID] | Flag | Description | |------|-------------| -| `--link-id ` | Bitbucket workspace link to list through. Resolved automatically when the tenant has exactly one link. | +| `--account ` | Slug of the linked Bitbucket workspace to list, for example `safedep`. Matched without regard to case. Needed when the tenant has more than one linked workspace. | Inherits root flags `--output` and `--profile`. -When `--link-id` is omitted, the CLI lists the tenant's workspace links and +When `--account` is omitted, the CLI lists the tenant's workspace links and uses the only one it finds. With no link, the command fails and points to -`link create`. With more than one link, it fails and lists the link IDs and -workspace slugs so you can pick one. +`link create`. With more than one link, it fails and lists the workspace +slugs so you can pick one with `--account`. + +`--link-id ` still selects a link by its internal ID. It is hidden from +the help and stays for scripts. With `--link-id` alone, the command lists no +links. With `--link-id` and `--account`, both must name the same link. ## Examples @@ -29,7 +33,7 @@ safedep integration bitbucket repository list ``` ```bash -safedep integration bitbucket repository list --link-id 01K88WX3G9RGAK8T3N5YJMFQN1 \ +safedep integration bitbucket repository list --account safedep \ --output json | jq -r '.repositories[] | select(.scan_state == "disabled") | .repository_uuid' ``` @@ -38,6 +42,7 @@ safedep integration bitbucket repository list --link-id 01K88WX3G9RGAK8T3N5YJMFQ | Field | Description | |-------|-------------| | `link_id` | The workspace link the listing ran through, supplied or resolved. | +| `account` | The workspace slug of that link. Omitted when only `--link-id` named the link. | | `scan_scope` | The workspace's scan scope: `all` or `selected`. | | `repository_uuid` | The immutable Bitbucket repository UUID. Feed it to `allowlist update`. | | `full_name` | The `workspace/repository` name. | diff --git a/docs/cmd/project-sync.md b/docs/cmd/project-sync.md index e3de5c0..6180172 100644 --- a/docs/cmd/project-sync.md +++ b/docs/cmd/project-sync.md @@ -7,8 +7,11 @@ source integration: a GitHub App installation or a Bitbucket workspace. ``` safedep project sync [OWNER/REPOSITORY...] [--source github|bitbucket] + [--account ACCOUNT] [--repository-id ID] [--repository-uuid UUID] - [--link-id LINK_ID] [--output table|plain|json] + [--output table|plain|json] +safedep project sync --account ACCOUNT --all [--source github|bitbucket] + [--output table|plain|json] ``` ## Arguments @@ -27,42 +30,86 @@ Bitbucket repository UUID. Names are metadata, so the CLI resolves every name to that identity before sending the request. Syncing is idempotent: repeating it for the same repository returns the same project ID. -## Sources +## Accounts + +An account is the GitHub organization or user of a GitHub App installation, +or the slug of a Bitbucket workspace. Each source link of the tenant has one +account. Accounts match without regard to case. + +The OWNER of each name picks the link whose account has that name. The match +also picks the source, so `safedep project sync safedep/vet acme/app` needs +neither `--source` nor `--account`. Names with two owners make one sync +request per link. The CLI resolves the names of every link before it sends +the first request, so a name that no link can reach syncs nothing. + +- When no link has the owner's account and the tenant has exactly one link + of the allowed sources, that link serves the name. This covers a link whose + account name is missing, or stale after a rename. +- When no link has the owner's account and the tenant has more links, the + command fails and lists the linked accounts. When the links span both + sources, it also names the `--source` value under which one link serves + the name. +- When the owner names a GitHub account and a Bitbucket workspace, the + command fails and asks for `--source`. +- One invocation serves one source. Names whose owners resolve to GitHub and + to Bitbucket fail, so sync each source in its own command. + +`--account` picks the link and every name resolves through it. You need it +with `--all`, and with `--repository-id` or `--repository-uuid` when the +tenant has more than one link of that source. Those selectors carry no owner, +so when you pass them, the names also resolve through the one link that the +selection picks. + +`--link-id ` still selects a link by its internal ID. It is hidden from +the help and stays for scripts. With `--link-id` and a known source, the +command lists no links. With `--link-id` and `--account`, both must name the +same link. -`--source` picks the repository source. When omitted: +## Sources -1. `--repository-id` implies `github` and `--repository-uuid` implies - `bitbucket`. -2. Otherwise the CLI uses the one source the tenant has links for. A tenant - with links to both sources must pass `--source` or `--link-id`, and a - link ID resolves to the source that owns it. A tenant with no link - fails with guidance. +`--source` picks the repository source. When omitted, `--repository-id` +implies `github` and `--repository-uuid` implies `bitbucket`. Otherwise the +account match decides, as Accounts describes. The CLI lists the links of the +allowed sources only. One invocation serves one source, so `--repository-id` and `--repository-uuid` do not combine. +## Sync every repository + +`--all` syncs every repository that the account's link can read and creates a +project for every repository not yet synced. It needs `--account` and takes no +repository names, `--repository-id` or `--repository-uuid`. + +The CLI lists every repository first, then sends sync requests of at most 100 +repositories, the server limit. It reports each request on stderr. A +repository that the listing returns twice counts once. + +On Bitbucket, `--all` syncs only the repositories whose scan state is +`enabled`, because the server refuses the others. The footer reports how many +it left out. When no repository is enabled, the command fails and points to +`safedep integration bitbucket allowlist update`. + +When a request fails after earlier requests wrote projects, the command stops, +exits non-zero, and reports that projects exist for at least the first N +repositories. The failed request can be written too, for example when the +server commits it and then times out. The error shows the server message. +When the failure is temporary (unavailable, timeout or rate limit), it says to +rerun the same command. A rerun is safe because the sync is idempotent. An +expired session shows the login guidance instead. + ## Flags | Flag | Description | |------|-------------| | `--source ` | Repository source. See Sources for the default. | +| `--account ` | GitHub organization or user, or Bitbucket workspace slug, to sync through. See Accounts. | +| `--all` | Sync every repository the account can read. See Sync every repository. | | `--repository-id ` | Immutable GitHub repository ID to sync instead of a name. Repeat the flag, or pass a comma-separated list, to select multiple repositories. | | `--repository-uuid ` | Immutable Bitbucket repository UUID to sync instead of a name. Braced and uppercase forms are accepted and normalized. Repeat for multiple repositories. Get UUIDs from `safedep integration bitbucket repository list`. | -| `--link-id ` | Source link to sync through. Resolved automatically when the tenant has exactly one link for the source. | Inherits root flags `--output` and `--profile`. -## Source links - -A link associates a GitHub App installation or a Bitbucket workspace with a -SafeDep tenant, and it is the access path used to resolve repositories. It is -not the identity of the resulting projects. - -When `--link-id` is omitted, the CLI lists the tenant's links for the source -and uses the only one it finds. With no link, the command fails and asks you -to install and link the source integration. With more than one link, it fails -and lists the link IDs so you can pick one with `--link-id`. - ## Examples Sync one repository: @@ -71,16 +118,16 @@ Sync one repository: safedep project sync safedep/cli ``` -Sync several repositories in one request: +Sync repositories of two GitHub organizations in one command: ```bash -safedep project sync safedep/cli safedep/vet safedep/pmg +safedep project sync safedep/cli safedep/vet acme/app ``` Sync by immutable repository ID, skipping name resolution: ```bash -safedep project sync --repository-id 1296269 --repository-id 10270250 +safedep project sync --account safedep --repository-id 1296269 --repository-id 10270250 ``` Sync a Bitbucket repository by name, or by UUID: @@ -90,10 +137,10 @@ safedep project sync safedep/vet-pipe --source bitbucket safedep project sync --repository-uuid d6c2f02b-7f78-49a8-b7e3-cf8b86efd115 ``` -Choose the source link explicitly: +Sync every repository of an organization: ```bash -safedep project sync safedep/cli --link-id 01K88WX3G9RGAK8T3N5YJMFQN1 +safedep project sync --account safedep --all ``` Sync and scan the resulting projects: @@ -108,54 +155,71 @@ safedep project sync safedep/cli --output json \ | Field | Description | |-------|-------------| -| `link_id` | The source link the sync ran through, whether supplied or resolved. Reported once per invocation, in the JSON body and the table footer. | +| `link_id` | Top level: the source link the sync ran through, when one link served the run. Omitted when the run used more than one link. Per project: the link of that project. | +| `account` | Top level: the account of that link, when one link served the run. Per project: the account of that project's link. Omitted when the link has no account name. | | `repository_id` | GitHub only: the immutable repository ID. | | `repository_uuid` | Bitbucket only: the immutable repository UUID. | | `repository_name` | The repository name as the source reports it. Empty for repositories selected by ID or UUID, which the CLI never resolved. | | `project_id` | The stable SafeDep project ID for that repository. | An unresolved repository name renders as `-` in table and plain output and is -omitted from JSON. +omitted from JSON. The sync response does not say if a project is new or +already existed, so the output reports only the count. JSON shape: ```json { "link_id": "link-id", + "account": "safedep", "projects": [ { "repository_id": 1296269, "repository_name": "safedep/cli", - "project_id": "project-id" + "project_id": "project-id", + "account": "safedep", + "link_id": "link-id" } ] } ``` -`table` renders one row per synced repository and reports the link ID in the -footer. `plain` renders a tab-separated header and one tab-separated row per -synced repository, so every row has the same field count and can be cut by -column. The link ID is not part of plain output: read it from `table` or `json`. +`table` renders one row per synced repository with an `ACCOUNT` column, and +names the account in the footer, for example +`3 repositories synced through account safedep`. A link without an account +name shows as `link `. With `--all`, the footer reads +`Synced 240 repositories through account safedep`, and on Bitbucket +`Synced 240 of 300 repositories through account safedep, 60 not enabled`. + +`plain` renders a tab-separated header and one tab-separated row per synced +repository. The columns are the repository name, the repository ID or UUID, +the project ID, and the account last, with `-` for a link without an account +name. Every row has the same field count and can be cut by column. ## Resolution and failure behaviour The CLI validates the batch size, the `OWNER/REPOSITORY` shape, and duplicate -selectors locally, then resolves the source link and every repository name -before it sends the sync request. A name that the source link cannot reach fails -the command without materializing any project, and the error names the -repository. Grant it to the GitHub App installation and retry, or retry with the -immutable selector: `--repository-id` for GitHub, `--repository-uuid` for -Bitbucket. Both immutable selectors skip name resolution. - -After resolution, the request carries the immutable selector values first, +selectors locally, then resolves the source links and every repository name +before it sends a sync request. A name that its link cannot reach fails the +command without materializing any project, and the error names the repository +and the account. Grant it to the GitHub App installation and retry, or retry +with the immutable selector: `--repository-id` for GitHub, `--repository-uuid` +for Bitbucket. Both immutable selectors skip name resolution. + +After resolution, each request carries the immutable selector values first, followed by resolved names in argument order. A name that resolves to an -already selected repository is rejected locally. - -Control Tower validates every repository against the link before it writes, so a -failed request materializes no projects. Installation, repository access, and -suspension failures preserve their gRPC status details internally. The CLI prints -a concise message, a stable error code, and recovery guidance instead of raw -nested gRPC text. +already selected repository is rejected locally. A Bitbucket name whose scan +state is not `enabled` fails before any write, because the server refuses it. +The error gives the `safedep integration bitbucket allowlist update` command +that enables it. + +Control Tower validates every repository against the link before it writes, so +a refused request materializes no projects. With names of several accounts, +the CLI sends one request per account. When a later request fails, the error +names the accounts whose projects exist and the account whose request failed. Installation, repository access, and suspension failures +preserve their gRPC status details internally. The CLI prints a concise +message, a stable error code, and recovery guidance instead of raw nested gRPC +text. ## Authentication @@ -166,4 +230,4 @@ Requires a control-plane OAuth session. Run `safedep auth login` first. | Code | Meaning | |------|---------| | `0` | Every requested repository has a SafeDep project. | -| non-zero | Local validation, link or repository resolution, authentication, or the sync request failed. | +| non-zero | Local validation, link or repository resolution, authentication, or a sync request failed. | diff --git a/internal/bitbucketlink/bitbucketlink.go b/internal/bitbucketlink/bitbucketlink.go index 4c6dea6..857d115 100644 --- a/internal/bitbucketlink/bitbucketlink.go +++ b/internal/bitbucketlink/bitbucketlink.go @@ -6,17 +6,14 @@ package bitbucketlink import ( "context" - "errors" "fmt" - "sort" - "strings" controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" "github.com/google/uuid" - "github.com/safedep/dry/usefulerror" "google.golang.org/grpc" "github.com/safedep/cli/internal/paging" + "github.com/safedep/cli/internal/sourcelink" ) // PageSize is the integration service's cap on a listing page. @@ -81,49 +78,40 @@ func List(ctx context.Context, client Lister, label string) ([]Link, error) { return links, nil } -// ResolveSingle returns the tenant's only workspace link when the caller did -// not pick one with --link-id. With no link or more than one, it fails with -// guidance, mirroring the GitHub link resolution in `project sync`. -func ResolveSingle(ctx context.Context, client Lister, label string) (string, error) { - links, err := List(ctx, client, label) - if err != nil { - return "", err +// ToSourceLinks names each workspace link by its slug, the OWNER part of a +// Bitbucket repository name. +func ToSourceLinks(links []Link) []sourcelink.Link { + out := make([]sourcelink.Link, 0, len(links)) + for _, link := range links { + out = append(out, sourcelink.Link{Source: sourcelink.Bitbucket, ID: link.ID, Account: link.WorkspaceSlug}) } - return PickSingle(links, label) + return out } -// PickSingle applies ResolveSingle's selection to links a caller already -// fetched, so one listing serves both the source inference and the link -// resolution in `project sync`. -func PickSingle(links []Link, label string) (string, error) { - switch len(links) { - case 0: - return "", usefulerror.NewUsefulError(). - WithCode(usefulerror.ErrNotFound). - WithHumanError("No linked Bitbucket workspace"). - WithHelp("Create a link code with `safedep integration bitbucket link create`, redeem it in the " + - "workspace's SafeDep settings page in Bitbucket, then retry."). - Wrap(fmt.Errorf("%s: the active tenant has no linked bitbucket workspace", label)) - case 1: - return links[0].ID, nil - default: - return "", ambiguousLinkError(links) +// Resolve returns the workspace link that account and linkID pick. A link +// ID alone skips the listing. The listing holds only active links, so the +// skip keeps a repeat delete of a revoked link a no-op, and a script that +// passes the ID keeps its RPC count. The returned link then carries only its +// ID. +func Resolve(ctx context.Context, client Lister, account, linkID, label string) (Link, error) { + if linkID != "" && account == "" { + return Link{ID: linkID}, nil } -} - -func ambiguousLinkError(links []Link) error { - choices := make([]string, 0, len(links)) + links, err := List(ctx, client, label) + if err != nil { + return Link{}, err + } + picked, err := sourcelink.Pick(ToSourceLinks(links), sourcelink.Selection{ + Source: sourcelink.Bitbucket, + Account: account, + LinkID: linkID, + }) + if err != nil { + return Link{}, err + } + byID := make(map[string]Link, len(links)) for _, link := range links { - slug := link.WorkspaceSlug - if slug == "" { - slug = link.WorkspaceUUID - } - choices = append(choices, fmt.Sprintf("%s (%s)", link.ID, slug)) + byID[link.ID] = link } - sort.Strings(choices) - return usefulerror.NewUsefulError(). - WithCode(usefulerror.ErrBadRequest). - WithHumanError("More than one linked Bitbucket workspace"). - WithHelp(fmt.Sprintf("Pick one with --link-id: %s.", strings.Join(choices, ", "))). - Wrap(errors.New("the active tenant has more than one linked bitbucket workspace")) + return byID[picked.ID], nil } diff --git a/internal/cmd/integration/bitbucket/allowlist.go b/internal/cmd/integration/bitbucket/allowlist.go index 0c250a1..87d648a 100644 --- a/internal/cmd/integration/bitbucket/allowlist.go +++ b/internal/cmd/integration/bitbucket/allowlist.go @@ -12,6 +12,7 @@ import ( "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/bitbucketlink" + "github.com/safedep/cli/internal/sourcelink" "github.com/safedep/cli/internal/tui" ) @@ -20,6 +21,7 @@ import ( const maxAllowlistItems = 500 type allowlistUpdateInput struct { + Account string LinkID string Scope string Enable []string @@ -28,12 +30,14 @@ type allowlistUpdateInput struct { type allowlistUpdateResult struct { linkID string + account string scanScope string allowlistCount uint32 } type allowlistUpdateResultJSON struct { LinkID string `json:"link_id"` + Account string `json:"account,omitempty"` ScanScope string `json:"scan_scope"` AllowlistedRepositoryCount uint32 `json:"allowlisted_repository_count"` } @@ -65,8 +69,7 @@ func allowlistUpdateCmd(a *app.App) *cobra.Command { } f := cmd.Flags() - f.StringVar(&in.LinkID, "link-id", "", - "Bitbucket workspace link to update; resolved automatically when the tenant has exactly one link") + addLinkFlags(cmd, &in.Account, &in.LinkID, "to update") f.StringVar(&in.Scope, "scope", "", "scan scope after the update: all or selected (omit to keep the stored scope)") f.StringSliceVar(&in.Enable, "enable", nil, @@ -98,17 +101,13 @@ func runAllowlistUpdate( return nil, err } - linkID := in.LinkID - if linkID == "" { - resolved, err := bitbucketlink.ResolveSingle(ctx, links, label) - if err != nil { - return nil, err - } - linkID = resolved + link, err := bitbucketlink.Resolve(ctx, links, in.Account, in.LinkID, label) + if err != nil { + return nil, err } req := &controltowerv1.UpdateBitbucketRepositoryAllowlistRequest{} - req.SetLinkId(linkID) + req.SetLinkId(link.ID) req.SetScanScope(scope) req.SetEnable(in.Enable) req.SetDisable(in.Disable) @@ -118,7 +117,8 @@ func runAllowlistUpdate( return nil, fmt.Errorf("%s: %w", label, err) } return &allowlistUpdateResult{ - linkID: linkID, + linkID: link.ID, + account: link.WorkspaceSlug, scanScope: tui.EnumToken(res.GetScanScope().String(), scanScopePrefix), allowlistCount: res.GetAllowlistedRepositoryCount(), }, nil @@ -224,27 +224,29 @@ func validateUniqueUUIDs(values []string, flag string) error { func (r *allowlistUpdateResult) RenderJSON() ([]byte, error) { return json.MarshalIndent(allowlistUpdateResultJSON{ LinkID: r.linkID, + Account: r.account, ScanScope: r.scanScope, AllowlistedRepositoryCount: r.allowlistCount, }, "", " ") } func (r *allowlistUpdateResult) RenderPlain() string { - return "link_id\tscan_scope\tallowlisted_repository_count\n" + strings.Join(r.cells(), "\t") + account := r.account + if account == "" { + account = tui.EmptyCell + } + return "link_id\tscan_scope\tallowlisted_repository_count\taccount\n" + + strings.Join([]string{r.linkID, r.scanScope, r.count(), account}, "\t") } func (r *allowlistUpdateResult) RenderTable() string { return table.New(). Title("Bitbucket scan allowlist"). - Headers("LINK ID", "SCAN SCOPE", "ALLOWLISTED REPOSITORIES"). - Rows(r.cells()). + Headers("ACCOUNT", "SCAN SCOPE", "ALLOWLISTED REPOSITORIES"). + Rows([]string{sourcelink.Label(r.account, r.linkID), r.scanScope, r.count()}). Render() } -func (r *allowlistUpdateResult) cells() []string { - return []string{ - r.linkID, - r.scanScope, - fmt.Sprintf("%d", r.allowlistCount), - } +func (r *allowlistUpdateResult) count() string { + return fmt.Sprintf("%d", r.allowlistCount) } diff --git a/internal/cmd/integration/bitbucket/bitbucket_test.go b/internal/cmd/integration/bitbucket/bitbucket_test.go index b44f227..6b478be 100644 --- a/internal/cmd/integration/bitbucket/bitbucket_test.go +++ b/internal/cmd/integration/bitbucket/bitbucket_test.go @@ -279,7 +279,60 @@ func TestRunLinkDelete(t *testing.T) { require.Error(t, err) usefulErr, ok := usefulerror.AsUsefulError(err) require.True(t, ok) - assert.Contains(t, usefulErr.Help(), "link-1 (one)") + assert.Contains(t, usefulErr.Help(), "--account one, --account two") + assert.Equal(t, 0, deleter.calls) + }) + + twoLinks := func() *fakeLinkLister { + return &fakeLinkLister{pages: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{ + newWorkspaceLinkPage("", + newWorkspaceLink("link-1", "uuid-1", "one", "One"), + newWorkspaceLink("link-2", "uuid-2", "two", "Two")), + }} + } + + t.Run("--account picks the link of that workspace", func(t *testing.T) { + deleter := &fakeLinkDeleter{} + + result, err := runLinkDelete(context.Background(), twoLinks(), deleter, linkDeleteInput{Account: "TWO"}) + require.NoError(t, err) + require.Equal(t, 1, deleter.calls) + assert.Equal(t, "link-2", deleter.req.GetLinkId()) + assert.Equal(t, "Unlinked Bitbucket workspace two (link link-2)", result.message()) + }) + + t.Run("--account of a deleted link is not found", func(t *testing.T) { + deleter := &fakeLinkDeleter{} + + _, err := runLinkDelete(context.Background(), twoLinks(), deleter, linkDeleteInput{Account: "gone"}) + require.Error(t, err) + usefulErr, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, usefulerror.ErrNotFound, usefulErr.Code()) + assert.Contains(t, usefulErr.Help(), "Linked accounts: one, two.") + assert.Equal(t, 0, deleter.calls) + }) + + t.Run("--link-id with its own --account lists and names the workspace", func(t *testing.T) { + links := twoLinks() + deleter := &fakeLinkDeleter{} + + result, err := runLinkDelete(context.Background(), links, deleter, linkDeleteInput{Account: "One", LinkID: "link-1"}) + require.NoError(t, err) + assert.Equal(t, 1, links.calls) + assert.Equal(t, "link-1", deleter.req.GetLinkId()) + assert.Equal(t, "Unlinked Bitbucket workspace one (link link-1)", result.message()) + }) + + t.Run("--link-id with another --account deletes nothing", func(t *testing.T) { + deleter := &fakeLinkDeleter{} + + _, err := runLinkDelete(context.Background(), twoLinks(), deleter, + linkDeleteInput{Account: "one", LinkID: "link-2"}) + require.Error(t, err) + usefulErr, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, "--account and --link-id name different links", usefulErr.HumanError()) assert.Equal(t, 0, deleter.calls) }) @@ -330,6 +383,7 @@ func TestRunRepositoryList(t *testing.T) { require.NoError(t, err) assert.Equal(t, 0, links.calls) assert.Equal(t, "link-9", result.linkID) + assert.Contains(t, result.RenderTable(), "in link link-9") assert.Equal(t, "all", result.scanScope) assert.Empty(t, result.repositories) }) @@ -357,8 +411,45 @@ func TestRunRepositoryList(t *testing.T) { require.Error(t, err) usefulErr, ok := usefulerror.AsUsefulError(err) require.True(t, ok) - assert.Contains(t, usefulErr.Help(), "link-1 (one)") - assert.Contains(t, usefulErr.Help(), "link-2 (two)") + assert.Contains(t, usefulErr.Help(), "--account one, --account two") + }) + + t.Run("--link-id with its own --account lists and fills the account", func(t *testing.T) { + links := &fakeLinkLister{pages: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{ + newWorkspaceLinkPage("", + newWorkspaceLink("link-1", "uuid-1", "one", "One"), + newWorkspaceLink("link-2", "uuid-2", "two", "Two")), + }} + repositories := &fakeRepositoryLister{pages: []*controltowerv1.ListBitbucketRepositoriesResponse{ + newRepositoryPage("", controltowerv1.BitbucketScanScope_BITBUCKET_SCAN_SCOPE_ALL), + }} + + result, err := runRepositoryList(context.Background(), links, repositories, + repositoryListInput{Account: "two", LinkID: "link-2"}) + require.NoError(t, err) + assert.Equal(t, 1, links.calls) + assert.Equal(t, "link-2", result.linkID) + assert.Equal(t, "two", result.account) + }) + + t.Run("--account picks the link and names the workspace", func(t *testing.T) { + links := &fakeLinkLister{pages: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{ + newWorkspaceLinkPage("", + newWorkspaceLink("link-1", "uuid-1", "one", "One"), + newWorkspaceLink("link-2", "uuid-2", "two", "Two")), + }} + repositories := &fakeRepositoryLister{pages: []*controltowerv1.ListBitbucketRepositoriesResponse{ + newRepositoryPage("", controltowerv1.BitbucketScanScope_BITBUCKET_SCAN_SCOPE_ALL), + }} + + result, err := runRepositoryList(context.Background(), links, repositories, repositoryListInput{Account: "Two"}) + require.NoError(t, err) + require.Len(t, repositories.requests, 1) + assert.Equal(t, "link-2", repositories.requests[0].GetLinkId()) + got, err := result.RenderJSON() + require.NoError(t, err) + assert.Contains(t, string(got), `"account": "two"`) + assert.Contains(t, result.RenderTable(), "0 repositories in account two, scan scope all") }) t.Run("rejects a repository without a UUID", func(t *testing.T) { @@ -433,6 +524,55 @@ func TestRunAllowlistUpdate(t *testing.T) { assert.Equal(t, controltowerv1.BitbucketScanScope_BITBUCKET_SCAN_SCOPE_UNSPECIFIED, updater.req.GetScanScope()) }) + t.Run("--link-id alone lists no links", func(t *testing.T) { + links := &fakeLinkLister{} + updater := &fakeAllowlistUpdater{ + res: newUpdaterResponse(controltowerv1.BitbucketScanScope_BITBUCKET_SCAN_SCOPE_ALL, 0), + } + + result, err := runAllowlistUpdate(context.Background(), links, updater, allowlistUpdateInput{LinkID: "link-9", Scope: "all"}) + require.NoError(t, err) + assert.Equal(t, 0, links.calls) + assert.Equal(t, "link-9", updater.req.GetLinkId()) + assert.Contains(t, result.RenderTable(), "link link-9") + assert.Equal(t, "link_id\tscan_scope\tallowlisted_repository_count\taccount\nlink-9\tall\t0\t-", result.RenderPlain()) + }) + + t.Run("--link-id with its own --account lists and fills the account", func(t *testing.T) { + links := &fakeLinkLister{pages: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{ + newWorkspaceLinkPage("", newWorkspaceLink("link-1", "uuid-1", "one", "One")), + }} + updater := &fakeAllowlistUpdater{ + res: newUpdaterResponse(controltowerv1.BitbucketScanScope_BITBUCKET_SCAN_SCOPE_ALL, 0), + } + + result, err := runAllowlistUpdate(context.Background(), links, updater, + allowlistUpdateInput{Account: "one", LinkID: "link-1", Scope: "all"}) + require.NoError(t, err) + assert.Equal(t, 1, links.calls) + assert.Equal(t, "link-1", updater.req.GetLinkId()) + assert.Equal(t, "one", result.account) + }) + + t.Run("--account picks the link and names the workspace", func(t *testing.T) { + links := &fakeLinkLister{pages: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{ + newWorkspaceLinkPage("", + newWorkspaceLink("link-1", "uuid-1", "one", "One"), + newWorkspaceLink("link-2", "uuid-2", "two", "Two")), + }} + updater := &fakeAllowlistUpdater{ + res: newUpdaterResponse(controltowerv1.BitbucketScanScope_BITBUCKET_SCAN_SCOPE_ALL, 0), + } + + result, err := runAllowlistUpdate(context.Background(), links, updater, allowlistUpdateInput{Account: "ONE", Scope: "all"}) + require.NoError(t, err) + assert.Equal(t, "link-1", updater.req.GetLinkId()) + got, err := result.RenderJSON() + require.NoError(t, err) + assert.Contains(t, string(got), `"account": "one"`) + assert.Equal(t, "link_id\tscan_scope\tallowlisted_repository_count\taccount\nlink-1\tall\t0\tone", result.RenderPlain()) + }) + t.Run("resolves the only link", func(t *testing.T) { links := &fakeLinkLister{pages: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{ newWorkspaceLinkPage("", newWorkspaceLink("link-1", "uuid-1", "one", "One")), diff --git a/internal/cmd/integration/bitbucket/client.go b/internal/cmd/integration/bitbucket/client.go index e70063e..71f99a0 100644 --- a/internal/cmd/integration/bitbucket/client.go +++ b/internal/cmd/integration/bitbucket/client.go @@ -5,6 +5,7 @@ import ( controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" + "github.com/spf13/cobra" "google.golang.org/grpc" ) @@ -43,3 +44,14 @@ type allowlistUpdater interface { func newIntegrationClient(conn grpc.ClientConnInterface) controltowerv1grpc.IntegrationServiceClient { return controltowerv1grpc.NewIntegrationServiceClient(conn) } + +// addLinkFlags wires the workspace selection every link-scoped command +// takes. --link-id is hidden: people name a workspace by its slug, and the +// flag stays for scripts that pass the internal link ID. +func addLinkFlags(cmd *cobra.Command, account, linkID *string, verb string) { + f := cmd.Flags() + f.StringVar(account, "account", "", + "Bitbucket workspace slug of the link "+verb+". Needed when the tenant has more than one linked workspace.") + f.StringVar(linkID, "link-id", "", "Bitbucket workspace link ID "+verb) + f.Lookup("link-id").Hidden = true +} diff --git a/internal/cmd/integration/bitbucket/link.go b/internal/cmd/integration/bitbucket/link.go index 194faaf..6f21fc7 100644 --- a/internal/cmd/integration/bitbucket/link.go +++ b/internal/cmd/integration/bitbucket/link.go @@ -124,8 +124,8 @@ func linkListCmd(a *app.App) *cobra.Command { Use: "list", Args: cobra.NoArgs, Short: "List Bitbucket workspaces linked to the tenant", - Long: "List every Bitbucket workspace linked to the active tenant, with the link ID " + - "the repository and allowlist commands take.", + Long: "List every Bitbucket workspace linked to the active tenant. The workspace slug " + + "is the --account value of the repository, allowlist and link delete commands.", RunE: func(cmd *cobra.Command, _ []string) error { client, err := a.ControlPlane() if err != nil { diff --git a/internal/cmd/integration/bitbucket/link_delete.go b/internal/cmd/integration/bitbucket/link_delete.go index 75f9324..b59a97f 100644 --- a/internal/cmd/integration/bitbucket/link_delete.go +++ b/internal/cmd/integration/bitbucket/link_delete.go @@ -20,7 +20,8 @@ const linkDeleteFollowUp = "The SafeDep Forge app stays installed in the workspa "To link again, run `safedep integration bitbucket link create` and redeem the code." type linkDeleteInput struct { - LinkID string + Account string + LinkID string } type linkDeleteResult struct { @@ -35,9 +36,9 @@ func linkDeleteCmd(a *app.App) *cobra.Command { Args: cobra.NoArgs, Short: "Unlink a Bitbucket workspace from the tenant", Long: "Unlink a Bitbucket workspace from the active tenant. SafeDep revokes the link " + - "and discards the stored app token. With --link-id, a repeat delete succeeds. " + - "Without it, the command needs exactly one active link, so a repeat delete of the " + - "tenant's only link fails with not found. The SafeDep Forge app stays installed in the workspace until a " + + "and discards the stored app token. --account names the workspace by its slug. Without it, " + + "the command needs exactly one active link. A repeat delete fails with not found, because " + + "the link is no longer active. The SafeDep Forge app stays installed in the workspace until a " + "workspace admin uninstalls it in Bitbucket.", RunE: func(cmd *cobra.Command, _ []string) error { client, err := a.ControlPlane() @@ -55,8 +56,7 @@ func linkDeleteCmd(a *app.App) *cobra.Command { return nil }, } - cmd.Flags().StringVar(&in.LinkID, "link-id", "", - "Bitbucket workspace link to delete; resolved automatically when the tenant has exactly one link") + addLinkFlags(cmd, &in.Account, &in.LinkID, "to delete") return cmd } @@ -68,19 +68,11 @@ func runLinkDelete( ) (*linkDeleteResult, error) { const label = "integration bitbucket link delete" - result := &linkDeleteResult{linkID: in.LinkID} - if result.linkID == "" { - listed, err := bitbucketlink.List(ctx, links, label) - if err != nil { - return nil, err - } - linkID, err := bitbucketlink.PickSingle(listed, label) - if err != nil { - return nil, err - } - result.linkID = linkID - result.workspace = workspaceLabel(listed[0]) + link, err := bitbucketlink.Resolve(ctx, links, in.Account, in.LinkID, label) + if err != nil { + return nil, err } + result := &linkDeleteResult{linkID: link.ID, workspace: workspaceLabel(link)} req := &controltowerv1.DeleteBitbucketWorkspaceLinkRequest{} req.SetLinkId(result.linkID) @@ -97,6 +89,9 @@ func (r *linkDeleteResult) message() string { return fmt.Sprintf("Unlinked Bitbucket workspace %s (link %s)", r.workspace, r.linkID) } +// workspaceLabel prefers the slug and falls back to the immutable UUID, +// because the server leaves the slug empty until its first sync. A link that +// only --link-id named carries neither, and the message names the link. func workspaceLabel(link bitbucketlink.Link) string { if link.WorkspaceSlug != "" { return link.WorkspaceSlug diff --git a/internal/cmd/integration/bitbucket/repository.go b/internal/cmd/integration/bitbucket/repository.go index 6b8310f..fd1a09b 100644 --- a/internal/cmd/integration/bitbucket/repository.go +++ b/internal/cmd/integration/bitbucket/repository.go @@ -13,6 +13,7 @@ import ( "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/bitbucketlink" "github.com/safedep/cli/internal/paging" + "github.com/safedep/cli/internal/sourcelink" "github.com/safedep/cli/internal/tui" ) @@ -23,7 +24,8 @@ const ( ) type repositoryListInput struct { - LinkID string + Account string + LinkID string } type listedRepository struct { @@ -36,12 +38,14 @@ type listedRepository struct { type repositoryListResult struct { linkID string + account string scanScope string repositories []listedRepository } type repositoryListResultJSON struct { LinkID string `json:"link_id"` + Account string `json:"account,omitempty"` ScanScope string `json:"scan_scope"` Repositories []listedRepository `json:"repositories"` } @@ -69,8 +73,7 @@ func repositoryListCmd(a *app.App) *cobra.Command { return a.Output.Print(result) }, } - cmd.Flags().StringVar(&in.LinkID, "link-id", "", - "Bitbucket workspace link to list through; resolved automatically when the tenant has exactly one link") + addLinkFlags(cmd, &in.Account, &in.LinkID, "to list") return cmd } @@ -82,17 +85,14 @@ func runRepositoryList( ) (*repositoryListResult, error) { const label = "integration bitbucket repository list" - linkID := in.LinkID - if linkID == "" { - resolved, err := bitbucketlink.ResolveSingle(ctx, links, label) - if err != nil { - return nil, err - } - linkID = resolved + link, err := bitbucketlink.Resolve(ctx, links, in.Account, in.LinkID, label) + if err != nil { + return nil, err } - result := &repositoryListResult{linkID: linkID} - err := paging.Paginate(ctx, label, func(ctx context.Context, pageToken string) (string, error) { + linkID := link.ID + result := &repositoryListResult{linkID: linkID, account: link.WorkspaceSlug} + err = paging.Paginate(ctx, label, func(ctx context.Context, pageToken string) (string, error) { req := &controltowerv1.ListBitbucketRepositoriesRequest{} req.SetLinkId(linkID) req.SetPagination(paging.NewPaginationRequest(bitbucketlink.PageSize, pageToken)) @@ -129,6 +129,7 @@ func (r *repositoryListResult) RenderJSON() ([]byte, error) { } return json.MarshalIndent(repositoryListResultJSON{ LinkID: r.linkID, + Account: r.account, ScanScope: r.scanScope, Repositories: repositories, }, "", " ") @@ -153,8 +154,8 @@ func (r *repositoryListResult) RenderTable() string { Title("Bitbucket repositories"). Headers("FULL NAME", "REPOSITORY UUID", "VISIBILITY", "DEFAULT BRANCH", "SCAN STATE"). Rows(rows...). - Footer(fmt.Sprintf("%d %s in link %s, scan scope %s", - len(rows), pluralRepositories(len(rows)), r.linkID, r.scanScope)). + Footer(fmt.Sprintf("%d %s in %s, scan scope %s", + len(rows), pluralRepositories(len(rows)), sourcelink.Describe(r.account, r.linkID), r.scanScope)). Render() } diff --git a/internal/cmd/project/bitbucket.go b/internal/cmd/project/bitbucket.go index f539ca0..a7e0e6f 100644 --- a/internal/cmd/project/bitbucket.go +++ b/internal/cmd/project/bitbucket.go @@ -2,17 +2,15 @@ package project import ( "context" - "encoding/json" "fmt" - "strings" controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" - "github.com/safedep/dry/tui/table" "github.com/safedep/dry/usefulerror" "google.golang.org/grpc" "github.com/safedep/cli/internal/bitbucketlink" "github.com/safedep/cli/internal/paging" + "github.com/safedep/cli/internal/sourcelink" ) type bitbucketRepositoryLister interface { @@ -31,75 +29,79 @@ type bitbucketProjectSyncer interface { ) (*controltowerv1.SyncBitbucketProjectsResponse, error) } +// bitbucketRepository keeps the scan state because SyncBitbucketProjects +// refuses a repository that SafeDep does not scan, and the refusal fails the +// whole request. type bitbucketRepository struct { uuid string fullName string + enabled bool } -type syncedBitbucketProject struct { - RepositoryUUID string `json:"repository_uuid"` - RepositoryName string `json:"repository_name,omitempty"` - ProjectID string `json:"project_id"` -} - -type bitbucketSyncResult struct { - linkID string - projects []syncedBitbucketProject +func newBitbucketRepository( + repository *controltowerv1.ListBitbucketRepositoriesResponse_BitbucketRepository, +) bitbucketRepository { + return bitbucketRepository{ + uuid: repository.GetRepositoryUuid(), + fullName: repository.GetFullName(), + enabled: repository.GetScanState() == + controltowerv1.ListBitbucketRepositoriesResponse_BitbucketRepository_SCAN_STATE_ENABLED, + } } -type bitbucketSyncResultJSON struct { - LinkID string `json:"link_id"` - Projects []syncedBitbucketProject `json:"projects"` +// bitbucketRequest is one SyncBitbucketProjects call: the link, the +// repository UUIDs in request order, and the names the CLI resolved. +type bitbucketRequest struct { + link sourcelink.Link + uuids []string + names map[string]string } -func runBitbucketSync( +// prepareBitbucketRequest resolves the plan's names through its link and +// refuses a name whose repository SafeDep does not scan. It sends no write, +// so a run checks every plan before it syncs any. +func prepareBitbucketRequest( ctx context.Context, - links bitbucketlink.Lister, repositories bitbucketRepositoryLister, - syncer bitbucketProjectSyncer, - in syncInput, -) (*bitbucketSyncResult, error) { - linkID := in.LinkID - if linkID == "" { - resolved, err := bitbucketlink.ResolveSingle(ctx, links, "project sync: resolve workspace link") - if err != nil { - return nil, err - } - linkID = resolved - } - - resolved, err := resolveBitbucketRepositoryNames(ctx, repositories, linkID, in.RepositoryNames) + plan syncPlan, +) (bitbucketRequest, error) { + resolved, err := resolveBitbucketRepositoryNames(ctx, repositories, plan.link, plan.names) if err != nil { - return nil, err + return bitbucketRequest{}, err } // Flag-selected UUIDs go first, then resolved names in argument order, // so the request order matches what the caller typed. - repositoryUUIDs := append([]string{}, in.RepositoryUUIDs...) - namesByUUID := make(map[string]string, len(resolved)) - seen := make(map[string]struct{}, len(repositoryUUIDs)+len(resolved)) - for _, repositoryUUID := range repositoryUUIDs { + req := bitbucketRequest{ + link: plan.link, + uuids: append([]string{}, plan.uuids...), + names: make(map[string]string, len(resolved)), + } + seen := make(map[string]struct{}, len(req.uuids)+len(resolved)) + for _, repositoryUUID := range req.uuids { seen[repositoryUUID] = struct{}{} } for _, repository := range resolved { + if !repository.enabled { + return bitbucketRequest{}, bitbucketRepositoryNotEnabledError(repository, plan.link) + } if _, duplicate := seen[repository.uuid]; duplicate { cause := fmt.Errorf( "duplicate repository UUID %s after name resolution: %q", repository.uuid, repository.fullName, ) - return nil, invalidRepositorySelectionError(cause, fmt.Sprintf( + return bitbucketRequest{}, invalidRepositorySelectionError(cause, fmt.Sprintf( "Repository %q resolves to repository UUID %s, which is already selected. Remove one of them and retry.", repository.fullName, repository.uuid, )) } seen[repository.uuid] = struct{}{} - namesByUUID[repository.uuid] = repository.fullName - repositoryUUIDs = append(repositoryUUIDs, repository.uuid) + req.names[repository.uuid] = repository.fullName + req.uuids = append(req.uuids, repository.uuid) } - - return syncBitbucketProjects(ctx, syncer, linkID, repositoryUUIDs, namesByUUID) + return req, nil } // resolveBitbucketRepositoryNames maps workspace/repository names to @@ -109,7 +111,7 @@ func runBitbucketSync( func resolveBitbucketRepositoryNames( ctx context.Context, client bitbucketRepositoryLister, - linkID string, + link sourcelink.Link, names []string, ) ([]bitbucketRepository, error) { if len(names) == 0 { @@ -125,7 +127,7 @@ func resolveBitbucketRepositoryNames( matches := make(map[string]bitbucketRepository, len(names)) err := paging.Paginate(ctx, label, func(ctx context.Context, pageToken string) (string, error) { req := &controltowerv1.ListBitbucketRepositoriesRequest{} - req.SetLinkId(linkID) + req.SetLinkId(link.ID) req.SetPagination(paging.NewPaginationRequest(bitbucketlink.PageSize, pageToken)) res, err := client.ListBitbucketRepositories(ctx, req) if err != nil { @@ -147,7 +149,7 @@ func resolveBitbucketRepositoryNames( for _, name := range names { match, ok := matches[repositoryKey(name)] if !ok { - return nil, bitbucketRepositoryNotAccessibleError(name, linkID) + return nil, bitbucketRepositoryNotAccessibleError(name, link) } resolved = append(resolved, match) } @@ -161,51 +163,119 @@ func collectBitbucketRepositoryMatches( matches map[string]bitbucketRepository, ) error { for i, repository := range res.GetRepositories() { - if repository.GetRepositoryUuid() == "" || repository.GetFullName() == "" { - return fmt.Errorf("%s: invalid response: repository %d is missing its identity", label, i+1) + if err := checkBitbucketRepository(repository, label, i); err != nil { + return err } key := repositoryKey(repository.GetFullName()) if _, ok := requested[key]; !ok { continue } - matches[key] = bitbucketRepository{ - uuid: repository.GetRepositoryUuid(), - fullName: repository.GetFullName(), - } + matches[key] = newBitbucketRepository(repository) } return nil } -func bitbucketRepositoryNotAccessibleError(name, linkID string) error { +func checkBitbucketRepository( + repository *controltowerv1.ListBitbucketRepositoriesResponse_BitbucketRepository, + label string, + i int, +) error { + if repository.GetRepositoryUuid() == "" || repository.GetFullName() == "" { + return fmt.Errorf("%s: invalid response: repository %d is missing its identity", label, i+1) + } + return nil +} + +// listEnabledBitbucketRepositories walks every page of the workspace's +// repositories and keeps those SafeDep scans. SyncBitbucketProjects refuses a +// repository whose scan state is not enabled, so a sync of the rest would +// fail the whole batch. It also returns how many repositories it left out. +// A repository on two pages counts once. +func listEnabledBitbucketRepositories( + ctx context.Context, + client bitbucketRepositoryLister, + linkID string, +) ([]bitbucketRepository, int, error) { + const label = "project sync: list repositories" + + var enabled []bitbucketRepository + notEnabled := 0 + seen := map[string]struct{}{} + err := paging.Paginate(ctx, label, func(ctx context.Context, pageToken string) (string, error) { + req := &controltowerv1.ListBitbucketRepositoriesRequest{} + req.SetLinkId(linkID) + req.SetPagination(paging.NewPaginationRequest(bitbucketlink.PageSize, pageToken)) + res, err := client.ListBitbucketRepositories(ctx, req) + if err != nil { + return "", fmt.Errorf("%s: %w", label, err) + } + for i, repository := range res.GetRepositories() { + if err := checkBitbucketRepository(repository, label, i); err != nil { + return "", err + } + if _, duplicate := seen[repository.GetRepositoryUuid()]; duplicate { + continue + } + seen[repository.GetRepositoryUuid()] = struct{}{} + listed := newBitbucketRepository(repository) + if !listed.enabled { + notEnabled++ + continue + } + enabled = append(enabled, listed) + } + return res.GetPagination().GetNextPageToken(), nil + }) + if err != nil { + return nil, 0, err + } + return enabled, notEnabled, nil +} + +func bitbucketRepositoryNotAccessibleError(name string, link sourcelink.Link) error { cause := fmt.Errorf( "project sync: repository %q is not accessible through workspace link %q", name, - linkID, + link.ID, ) return newProjectError( usefulerror.ErrNotFound, "Bitbucket repository not accessible", - fmt.Sprintf("Confirm %q is in the linked workspace, or retry with --repository-uuid.", name), + fmt.Sprintf("Confirm %q is in the workspace of %s, or retry with --repository-uuid.", + name, sourcelink.Describe(link.Account, link.ID)), cause, ) } +func bitbucketRepositoryNotEnabledError(repository bitbucketRepository, link sourcelink.Link) error { + return newProjectError( + usefulerror.ErrBadRequest, + fmt.Sprintf("SafeDep does not scan Bitbucket repository %q", repository.fullName), + fmt.Sprintf("Enable it with `%s --enable %s`, then retry.", + allowlistUpdateCommand(link), repository.uuid), + fmt.Errorf("project sync: repository %q has scan state disabled", repository.fullName), + ) +} + +// allowlistUpdateCommand is the command that enables repositories of the +// link's workspace. +func allowlistUpdateCommand(link sourcelink.Link) string { + if link.Account != "" { + return "safedep integration bitbucket allowlist update --account " + link.Account + } + return "safedep integration bitbucket allowlist update --link-id " + link.ID +} + func syncBitbucketProjects( ctx context.Context, client bitbucketProjectSyncer, - linkID string, - repositoryUUIDs []string, - namesByUUID map[string]string, -) (*bitbucketSyncResult, error) { - res, err := client.SyncBitbucketProjects(ctx, newBitbucketSyncRequest(linkID, repositoryUUIDs)) + req bitbucketRequest, +) ([]syncedBitbucketProject, error) { + res, err := client.SyncBitbucketProjects(ctx, newBitbucketSyncRequest(req.link.ID, req.uuids)) if err != nil { return nil, fmt.Errorf("project sync: %w", err) } - projects, err := translateBitbucketSyncResponse(res, repositoryUUIDs, namesByUUID) - if err != nil { - return nil, err - } - return &bitbucketSyncResult{linkID: linkID, projects: projects}, nil + return translateBitbucketSyncResponse(res, req) } func newBitbucketSyncRequest(linkID string, repositoryUUIDs []string) *controltowerv1.SyncBitbucketProjectsRequest { @@ -223,9 +293,9 @@ func newBitbucketSyncRequest(linkID string, repositoryUUIDs []string) *controlto func translateBitbucketSyncResponse( res *controltowerv1.SyncBitbucketProjectsResponse, - repositoryUUIDs []string, - namesByUUID map[string]string, + req bitbucketRequest, ) ([]syncedBitbucketProject, error) { + repositoryUUIDs := req.uuids mappings := res.GetProjects() if len(mappings) != len(repositoryUUIDs) { return nil, fmt.Errorf( @@ -265,53 +335,11 @@ func translateBitbucketSyncResponse( seen[repositoryUUID] = struct{}{} projects = append(projects, syncedBitbucketProject{ RepositoryUUID: repositoryUUID, - RepositoryName: namesByUUID[repositoryUUID], + RepositoryName: req.names[repositoryUUID], ProjectID: mapping.GetProjectId(), + Account: req.link.Account, + LinkID: req.link.ID, }) } return projects, nil } - -func (r *bitbucketSyncResult) RenderJSON() ([]byte, error) { - projects := r.projects - if projects == nil { - projects = []syncedBitbucketProject{} - } - return json.MarshalIndent(bitbucketSyncResultJSON{LinkID: r.linkID, Projects: projects}, "", " ") -} - -func (r *bitbucketSyncResult) RenderPlain() string { - var output strings.Builder - output.WriteString("repository_name\trepository_uuid\tproject_id") - for _, project := range r.projects { - output.WriteByte('\n') - output.WriteString(strings.Join(syncedBitbucketProjectCells(project), "\t")) - } - return output.String() -} - -func (r *bitbucketSyncResult) RenderTable() string { - rows := make([][]string, 0, len(r.projects)) - for _, project := range r.projects { - rows = append(rows, syncedBitbucketProjectCells(project)) - } - return table.New(). - Title("Synced projects"). - Headers("REPOSITORY", "REPOSITORY UUID", "PROJECT ID"). - Rows(rows...). - Footer(fmt.Sprintf("%d %s synced through link %s", - len(rows), pluralRepositories(len(rows)), r.linkID)). - Render() -} - -func syncedBitbucketProjectCells(project syncedBitbucketProject) []string { - name := project.RepositoryName - if name == "" { - name = unknownRepositoryName - } - return []string{ - name, - project.RepositoryUUID, - project.ProjectID, - } -} diff --git a/internal/cmd/project/bitbucket_test.go b/internal/cmd/project/bitbucket_test.go index 36043c3..9976439 100644 --- a/internal/cmd/project/bitbucket_test.go +++ b/internal/cmd/project/bitbucket_test.go @@ -9,8 +9,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" "github.com/safedep/cli/internal/bitbucketlink" ) @@ -37,17 +35,19 @@ func (f *fakeBitbucketLinkLister) ListBitbucketWorkspaceLinks( } type fakeBitbucketRepositoryLister struct { - pages []*controltowerv1.ListBitbucketRepositoriesResponse - calls int - err error + pages []*controltowerv1.ListBitbucketRepositoriesResponse + calls int + requests []*controltowerv1.ListBitbucketRepositoriesRequest + err error } func (f *fakeBitbucketRepositoryLister) ListBitbucketRepositories( _ context.Context, - _ *controltowerv1.ListBitbucketRepositoriesRequest, + req *controltowerv1.ListBitbucketRepositoriesRequest, _ ...grpc.CallOption, ) (*controltowerv1.ListBitbucketRepositoriesResponse, error) { f.calls++ + f.requests = append(f.requests, req) if f.err != nil { return nil, f.err } @@ -57,11 +57,16 @@ func (f *fakeBitbucketRepositoryLister) ListBitbucketRepositories( return f.pages[min(f.calls-1, len(f.pages)-1)], nil } +// fakeBitbucketProjectSyncer answers each request with one project per +// requested repository, unless res fixes the response. err fails every call, +// or only call failOnCall when that is set. type fakeBitbucketProjectSyncer struct { - calls int - req *controltowerv1.SyncBitbucketProjectsRequest - res *controltowerv1.SyncBitbucketProjectsResponse - err error + calls int + req *controltowerv1.SyncBitbucketProjectsRequest + reqs []*controltowerv1.SyncBitbucketProjectsRequest + res *controltowerv1.SyncBitbucketProjectsResponse + err error + failOnCall int } func (f *fakeBitbucketProjectSyncer) SyncBitbucketProjects( @@ -71,7 +76,27 @@ func (f *fakeBitbucketProjectSyncer) SyncBitbucketProjects( ) (*controltowerv1.SyncBitbucketProjectsResponse, error) { f.calls++ f.req = req - return f.res, f.err + f.reqs = append(f.reqs, req) + if f.err != nil && (f.failOnCall == 0 || f.failOnCall == f.calls) { + return nil, f.err + } + if f.res != nil { + return f.res, nil + } + mappings := make([]*controltowerv1.SyncBitbucketProjectsResponse_ProjectMapping, 0, len(req.GetRepositories())) + for _, selection := range req.GetRepositories() { + mappings = append(mappings, bitbucketProjectMapping(selection.GetRepositoryUuid(), + "project-"+selection.GetRepositoryUuid())) + } + return bitbucketSyncResponse(mappings...), nil +} + +func syncedUUIDs(req *controltowerv1.SyncBitbucketProjectsRequest) []string { + uuids := make([]string, 0, len(req.GetRepositories())) + for _, selection := range req.GetRepositories() { + uuids = append(uuids, selection.GetRepositoryUuid()) + } + return uuids } var ( @@ -87,9 +112,13 @@ func bitbucketLinksPage(links ...*controltowerv1.ListBitbucketWorkspaceLinksResp } func bitbucketWorkspaceLink(linkID string) *controltowerv1.ListBitbucketWorkspaceLinksResponse_WorkspaceLink { + return bitbucketWorkspaceLinkOf(linkID, "safedep") +} + +func bitbucketWorkspaceLinkOf(linkID, slug string) *controltowerv1.ListBitbucketWorkspaceLinksResponse_WorkspaceLink { link := &controltowerv1.ListBitbucketWorkspaceLinksResponse_WorkspaceLink{} link.SetLinkId(linkID) - link.SetWorkspaceSlug("safedep") + link.SetWorkspaceSlug(slug) return link } @@ -103,6 +132,7 @@ func bitbucketListedRepository(uuid, fullName string) *controltowerv1.ListBitbuc repository := &controltowerv1.ListBitbucketRepositoriesResponse_BitbucketRepository{} repository.SetRepositoryUuid(uuid) repository.SetFullName(fullName) + repository.SetScanState(controltowerv1.ListBitbucketRepositoriesResponse_BitbucketRepository_SCAN_STATE_ENABLED) return repository } @@ -124,8 +154,9 @@ const ( testBitbucketRepoUUIDb = "aaaa0000-1111-2222-3333-444455556666" ) -func TestRunBitbucketSync(t *testing.T) { +func TestRunSync_Bitbucket(t *testing.T) { t.Run("resolves names to UUIDs and syncs through the only link", func(t *testing.T) { + githubLinks := &fakeGitHubLinkLister{} links := &fakeBitbucketLinkLister{pages: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{ bitbucketLinksPage(bitbucketWorkspaceLink("link-1")), }} @@ -134,41 +165,40 @@ func TestRunBitbucketSync(t *testing.T) { bitbucketListedRepository(testBitbucketRepoUUIDa, "safedep/vet-pipe"), ), }} - syncer := &fakeBitbucketProjectSyncer{res: bitbucketSyncResponse( - bitbucketProjectMapping(testBitbucketRepoUUIDa, "project-1"), - )} + syncer := &fakeBitbucketProjectSyncer{} - result, err := runBitbucketSync(context.Background(), links, repositories, syncer, - syncInput{RepositoryNames: []string{"SafeDep/Vet-Pipe"}}) + got, err := runSync(context.Background(), syncDeps{ + githubLinks: githubLinks, bitbucketLinks: links, bitbucketRepositories: repositories, bitbucketSyncer: syncer, + }, syncInput{Source: "bitbucket", RepositoryNames: []string{"SafeDep/Vet-Pipe"}}) require.NoError(t, err) + assert.Zero(t, githubLinks.calls, "--source bitbucket lists no GitHub links") require.Equal(t, 1, syncer.calls) assert.Equal(t, "link-1", syncer.req.GetLinkId()) - require.Len(t, syncer.req.GetRepositories(), 1) - assert.Equal(t, testBitbucketRepoUUIDa, syncer.req.GetRepositories()[0].GetRepositoryUuid()) + assert.Equal(t, []string{testBitbucketRepoUUIDa}, syncedUUIDs(syncer.req)) + result, ok := got.(*bitbucketSyncResult) + require.True(t, ok) require.Len(t, result.projects, 1) assert.Equal(t, syncedBitbucketProject{ RepositoryUUID: testBitbucketRepoUUIDa, RepositoryName: "safedep/vet-pipe", - ProjectID: "project-1", + ProjectID: "project-" + testBitbucketRepoUUIDa, + Account: "safedep", + LinkID: "link-1", }, result.projects[0]) }) t.Run("UUID selectors skip name resolution", func(t *testing.T) { repositories := &fakeBitbucketRepositoryLister{} - syncer := &fakeBitbucketProjectSyncer{res: bitbucketSyncResponse( - bitbucketProjectMapping(testBitbucketRepoUUIDb, "project-2"), - )} + syncer := &fakeBitbucketProjectSyncer{} - result, err := runBitbucketSync(context.Background(), &fakeBitbucketLinkLister{}, - repositories, syncer, syncInput{ - LinkID: "link-9", - RepositoryUUIDs: []string{testBitbucketRepoUUIDb}, - }) + got, err := runSync(context.Background(), syncDeps{bitbucketRepositories: repositories, bitbucketSyncer: syncer}, + syncInput{LinkID: "link-9", RepositoryUUIDs: []string{testBitbucketRepoUUIDb}}) require.NoError(t, err) assert.Equal(t, 0, repositories.calls) assert.Equal(t, "link-9", syncer.req.GetLinkId()) - require.Len(t, result.projects, 1) - assert.Equal(t, unknownRepositoryName, syncedBitbucketProjectCells(result.projects[0])[0]) + result, ok := got.(*bitbucketSyncResult) + require.True(t, ok) + assert.Contains(t, result.RenderPlain(), "-\t"+testBitbucketRepoUUIDb) }) t.Run("an unreachable name fails without a sync", func(t *testing.T) { @@ -177,11 +207,8 @@ func TestRunBitbucketSync(t *testing.T) { }} syncer := &fakeBitbucketProjectSyncer{} - _, err := runBitbucketSync(context.Background(), &fakeBitbucketLinkLister{}, - repositories, syncer, syncInput{ - LinkID: "link-1", - RepositoryNames: []string{"safedep/ghost"}, - }) + _, err := runSync(context.Background(), syncDeps{bitbucketRepositories: repositories, bitbucketSyncer: syncer}, + syncInput{Source: "bitbucket", LinkID: "link-1", RepositoryNames: []string{"safedep/ghost"}}) require.ErrorContains(t, err, "not accessible through workspace link") assert.Equal(t, 0, syncer.calls) }) @@ -194,8 +221,8 @@ func TestRunBitbucketSync(t *testing.T) { }} syncer := &fakeBitbucketProjectSyncer{} - _, err := runBitbucketSync(context.Background(), &fakeBitbucketLinkLister{}, - repositories, syncer, syncInput{ + _, err := runSync(context.Background(), syncDeps{bitbucketRepositories: repositories, bitbucketSyncer: syncer}, + syncInput{ LinkID: "link-1", RepositoryNames: []string{"safedep/vet-pipe"}, RepositoryUUIDs: []string{testBitbucketRepoUUIDa}, @@ -207,11 +234,8 @@ func TestRunBitbucketSync(t *testing.T) { t.Run("rejects a response that does not cover the request", func(t *testing.T) { syncer := &fakeBitbucketProjectSyncer{res: bitbucketSyncResponse()} - _, err := runBitbucketSync(context.Background(), &fakeBitbucketLinkLister{}, - &fakeBitbucketRepositoryLister{}, syncer, syncInput{ - LinkID: "link-1", - RepositoryUUIDs: []string{testBitbucketRepoUUIDa}, - }) + _, err := runSync(context.Background(), syncDeps{bitbucketSyncer: syncer}, + syncInput{LinkID: "link-1", RepositoryUUIDs: []string{testBitbucketRepoUUIDa}}) require.ErrorContains(t, err, "response count 0 does not match request count 1") }) @@ -220,11 +244,8 @@ func TestRunBitbucketSync(t *testing.T) { bitbucketProjectMapping(testBitbucketRepoUUIDa, ""), )} - _, err := runBitbucketSync(context.Background(), &fakeBitbucketLinkLister{}, - &fakeBitbucketRepositoryLister{}, syncer, syncInput{ - LinkID: "link-1", - RepositoryUUIDs: []string{testBitbucketRepoUUIDa}, - }) + _, err := runSync(context.Background(), syncDeps{bitbucketSyncer: syncer}, + syncInput{LinkID: "link-1", RepositoryUUIDs: []string{testBitbucketRepoUUIDa}}) require.ErrorContains(t, err, "missing its project ID") }) } @@ -288,119 +309,3 @@ func TestRunSync_ListsEachSourceOnceForANamesOnlySync(t *testing.T) { assert.Equal(t, 1, bitbucketLinks.calls) assert.Equal(t, "gh-link-1", syncer.req.GetLinkId()) } - -func TestResolveSyncSource(t *testing.T) { - githubLinksPage := func(linkIDs ...string) *controltowerv1.ListGitHubAppInstallationLinksResponse { - links := make([]*controltowerv1.ListGitHubAppInstallationLinksResponse_IntegrationWithAttributes, 0, len(linkIDs)) - for _, linkID := range linkIDs { - links = append(links, link(linkID, "safedep")) - } - return linksResponse("", links...) - } - - cases := []struct { - name string - in syncInput - github []*controltowerv1.ListGitHubAppInstallationLinksResponse - bitbucket []*controltowerv1.ListBitbucketWorkspaceLinksResponse - bitbucketErr error - wantSource string - wantLinkID string - wantErr string - }{ - { - name: "explicit source wins and keeps the caller's link ID", - in: syncInput{Source: sourceBitbucket, LinkID: "link-1"}, - wantSource: sourceBitbucket, - wantLinkID: "link-1", - }, - { - name: "repository IDs imply github", - in: syncInput{RepositoryIDs: []int64{7}}, - wantSource: sourceGitHub, - }, - { - name: "repository UUIDs imply bitbucket", - in: syncInput{RepositoryUUIDs: []string{testBitbucketRepoUUIDa}}, - wantSource: sourceBitbucket, - }, - { - name: "a bitbucket-only tenant infers bitbucket and its link", - github: []*controltowerv1.ListGitHubAppInstallationLinksResponse{githubLinksPage()}, - bitbucket: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{bitbucketLinksPage(bitbucketWorkspaceLink("link-1"))}, - wantSource: sourceBitbucket, - wantLinkID: "link-1", - }, - { - name: "a github-only tenant infers github and its link", - github: []*controltowerv1.ListGitHubAppInstallationLinksResponse{githubLinksPage("gh-link-1")}, - bitbucket: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{bitbucketLinksPage()}, - wantSource: sourceGitHub, - wantLinkID: "gh-link-1", - }, - { - name: "links to both sources need an explicit source", - github: []*controltowerv1.ListGitHubAppInstallationLinksResponse{githubLinksPage("gh-link-1")}, - bitbucket: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{bitbucketLinksPage(bitbucketWorkspaceLink("link-1"))}, - wantErr: "has GitHub and Bitbucket links", - }, - { - name: "a link ID picks its owning source when both are linked", - in: syncInput{LinkID: "link-1"}, - github: []*controltowerv1.ListGitHubAppInstallationLinksResponse{githubLinksPage("gh-link-1")}, - bitbucket: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{bitbucketLinksPage(bitbucketWorkspaceLink("link-1"))}, - wantSource: sourceBitbucket, - wantLinkID: "link-1", - }, - { - name: "an unknown link ID is a not-found failure", - in: syncInput{LinkID: "missing"}, - github: []*controltowerv1.ListGitHubAppInstallationLinksResponse{githubLinksPage("gh-link-1")}, - bitbucket: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{bitbucketLinksPage(bitbucketWorkspaceLink("link-1"))}, - wantErr: `link "missing" is not a GitHub or Bitbucket link`, - }, - { - name: "a control plane without the bitbucket RPCs keeps github working", - github: []*controltowerv1.ListGitHubAppInstallationLinksResponse{githubLinksPage("gh-link-1")}, - bitbucketErr: status.Error(codes.Unimplemented, "unknown method"), - wantSource: sourceGitHub, - wantLinkID: "gh-link-1", - }, - { - name: "a caller without the bitbucket permission cannot infer a source", - github: []*controltowerv1.ListGitHubAppInstallationLinksResponse{githubLinksPage("gh-link-1")}, - bitbucketErr: status.Error(codes.PermissionDenied, "not allowed"), - wantErr: "resolve workspace link", - }, - { - name: "any other bitbucket listing failure stops the sync", - github: []*controltowerv1.ListGitHubAppInstallationLinksResponse{githubLinksPage("gh-link-1")}, - bitbucketErr: status.Error(codes.Unavailable, "try again"), - wantErr: "resolve workspace link", - }, - { - name: "no links at all is a not-found failure", - github: []*controltowerv1.ListGitHubAppInstallationLinksResponse{githubLinksPage()}, - bitbucket: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{bitbucketLinksPage()}, - wantErr: "no GitHub or Bitbucket link", - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - deps := syncDeps{ - githubLinks: &fakeGitHubLinkLister{pages: tc.github}, - bitbucketLinks: &fakeBitbucketLinkLister{pages: tc.bitbucket, err: tc.bitbucketErr}, - } - - source, linkID, err := resolveSyncSource(context.Background(), deps, tc.in) - if tc.wantErr != "" { - require.ErrorContains(t, err, tc.wantErr) - return - } - require.NoError(t, err) - assert.Equal(t, tc.wantSource, source) - assert.Equal(t, tc.wantLinkID, linkID) - }) - } -} diff --git a/internal/cmd/project/errors.go b/internal/cmd/project/errors.go index a3b753c..2171097 100644 --- a/internal/cmd/project/errors.go +++ b/internal/cmd/project/errors.go @@ -5,6 +5,11 @@ import ( "strings" "github.com/safedep/dry/usefulerror" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/safedep/cli/internal/rpcerror" + "github.com/safedep/cli/internal/sourcelink" ) func newProjectError(code, humanError, help string, cause error) error { @@ -43,3 +48,82 @@ func unknownFilterValueError(flag, value string, allowed []string) error { cause, ) } + +// batchStoppedError reports an --all run that failed after earlier batches +// wrote projects. The failed batch may have been written too: the server can +// commit it and still time out, or return a response the CLI rejects. A +// failure before the first write keeps its own rendering. +func batchStoppedError(err error, synced, total int) error { + if synced == 0 { + return err + } + return partialSyncError(err, + fmt.Sprintf("Sync stopped after %d of %d repositories", synced, total), + fmt.Sprintf("%s. Projects exist for at least the first %d %s.", + rpcMessage(err), synced, pluralRepositories(synced))) +} + +// linkStoppedError reports a run over several links that failed after the +// requests of earlier links wrote projects. It names the accounts, because +// the request order follows the links, not the argument order. +func linkStoppedError(err error, done []sourcelink.Link, failed sourcelink.Link) error { + if len(done) == 0 { + return err + } + written := make([]string, 0, len(done)) + for _, link := range done { + written = append(written, sourcelink.Describe(link.Account, link.ID)) + } + failedName := sourcelink.Describe(failed.Account, failed.ID) + return partialSyncError(err, + fmt.Sprintf("Sync through %s failed", failedName), + fmt.Sprintf("Projects exist for the repositories of %s. The request for %s failed: %s.", + strings.Join(written, ", "), failedName, rpcMessage(err))) +} + +// partialSyncError keeps the server message in the help, because the generic +// rendering of a gRPC error hides it behind --verbose. Rerun advice is given +// only for failures that a rerun can fix. An Unauthenticated failure stays +// as it is, so the entry point turns it into the login guidance. +func partialSyncError(err error, humanError, help string) error { + if status.Code(err) == codes.Unauthenticated { + return err + } + if retryable(err) { + help += " Rerun the same command to sync the rest. The sync is idempotent." + } + return newProjectError(rpcErrorCode(err), humanError, help, err) +} + +// rpcErrorCode reuses the gRPC code mapping of the converters that dry +// registers, so a wrapped error carries the code the generic rendering of the +// same failure shows. dry has no converter for FailedPrecondition, the code +// of a suspended or removed installation, so it maps to conflict as the +// policy commands map it. +func rpcErrorCode(err error) string { + if status.Code(err) == codes.FailedPrecondition { + return usefulerror.ErrConflict + } + if converted, ok := usefulerror.AsUsefulError(err); ok && converted.Code() != "" { + return converted.Code() + } + return usefulerror.ErrInternalServerError +} + +// rpcMessage returns the server's message without the labels the CLI wrapped +// around it. status.Convert on a wrapped error returns the whole chain. +func rpcMessage(err error) string { + if st, ok := rpcerror.InnerStatus(err); ok { + return st.Message() + } + return err.Error() +} + +func retryable(err error) bool { + switch status.Code(err) { + case codes.Unavailable, codes.DeadlineExceeded, codes.ResourceExhausted: + return true + default: + return false + } +} diff --git a/internal/cmd/project/github.go b/internal/cmd/project/github.go index a60458c..590af1f 100644 --- a/internal/cmd/project/github.go +++ b/internal/cmd/project/github.go @@ -2,10 +2,7 @@ package project import ( "context" - "errors" "fmt" - "sort" - "strings" controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/v1" @@ -13,6 +10,7 @@ import ( "google.golang.org/grpc" "github.com/safedep/cli/internal/paging" + "github.com/safedep/cli/internal/sourcelink" ) const ( @@ -46,11 +44,6 @@ type githubProjectSyncer interface { ) (*controltowerv1.SyncGitHubInstallationProjectsResponse, error) } -type githubLink struct { - id string - accountLogin string -} - type githubRepository struct { id int64 fullName string @@ -60,37 +53,35 @@ func newIntegrationClient(conn grpc.ClientConnInterface) controltowerv1grpc.Inte return controltowerv1grpc.NewIntegrationServiceClient(conn) } -func runGitHubSync( +// githubRequest is one SyncGitHubInstallationProjects call: the link, the +// repository IDs in request order, and the names the CLI resolved. +type githubRequest struct { + link sourcelink.Link + ids []int64 + names map[int64]string +} + +// prepareGitHubRequest resolves the plan's names through its link. It sends +// no write, so a run resolves every plan before it syncs any. +func prepareGitHubRequest( ctx context.Context, - links githubLinkLister, repositories githubRepositoryLister, - syncer githubProjectSyncer, - in syncInput, -) (*syncResult, error) { - if err := validateSyncInput(in); err != nil { - return nil, err - } - - linkID := in.LinkID - if linkID == "" { - resolved, err := resolveGitHubLink(ctx, links) - if err != nil { - return nil, err - } - linkID = resolved - } - - resolved, err := resolveRepositoryNames(ctx, repositories, linkID, in.RepositoryNames) + plan syncPlan, +) (githubRequest, error) { + resolved, err := resolveRepositoryNames(ctx, repositories, plan.link, plan.names) if err != nil { - return nil, err + return githubRequest{}, err } // Flag-selected IDs go first, then resolved names in argument order, so the // request order matches what the caller typed. - repositoryIDs := append([]int64{}, in.RepositoryIDs...) - namesByID := make(map[int64]string, len(resolved)) - seen := make(map[int64]struct{}, len(repositoryIDs)+len(resolved)) - for _, repositoryID := range repositoryIDs { + req := githubRequest{ + link: plan.link, + ids: append([]int64{}, plan.ids...), + names: make(map[int64]string, len(resolved)), + } + seen := make(map[int64]struct{}, len(req.ids)+len(resolved)) + for _, repositoryID := range req.ids { seen[repositoryID] = struct{}{} } for _, repository := range resolved { @@ -100,24 +91,23 @@ func runGitHubSync( repository.id, repository.fullName, ) - return nil, invalidRepositorySelectionError(cause, fmt.Sprintf( + return githubRequest{}, invalidRepositorySelectionError(cause, fmt.Sprintf( "Repository %q resolves to repository ID %d, which is already selected. Remove one of them and retry.", repository.fullName, repository.id, )) } seen[repository.id] = struct{}{} - namesByID[repository.id] = repository.fullName - repositoryIDs = append(repositoryIDs, repository.id) + req.names[repository.id] = repository.fullName + req.ids = append(req.ids, repository.id) } - - return syncGitHubProjects(ctx, syncer, linkID, repositoryIDs, namesByID) + return req, nil } -func listGitHubLinks(ctx context.Context, client githubLinkLister) ([]githubLink, error) { +func listGitHubLinks(ctx context.Context, client githubLinkLister) ([]sourcelink.Link, error) { const label = "project sync: resolve installation link" - var links []githubLink + var links []sourcelink.Link err := paging.Paginate(ctx, label, func(ctx context.Context, pageToken string) (string, error) { req := &controltowerv1.ListGitHubAppInstallationLinksRequest{} req.SetPagination(paging.NewPaginationRequest(githubLinkPageSize, pageToken)) @@ -129,7 +119,11 @@ func listGitHubLinks(ctx context.Context, client githubLinkLister) ([]githubLink if item.GetLinkId() == "" { return "", fmt.Errorf("%s: invalid response: link %d is missing its ID", label, i+1) } - links = append(links, githubLink{id: item.GetLinkId(), accountLogin: item.GetAccountLogin()}) + links = append(links, sourcelink.Link{ + Source: sourcelink.GitHub, + ID: item.GetLinkId(), + Account: item.GetAccountLogin(), + }) } return res.GetPagination().GetNextPageToken(), nil }) @@ -140,40 +134,13 @@ func listGitHubLinks(ctx context.Context, client githubLinkLister) ([]githubLink return links, nil } -func resolveGitHubLink(ctx context.Context, client githubLinkLister) (string, error) { - links, err := listGitHubLinks(ctx, client) - if err != nil { - return "", err - } - return pickGitHubLink(links) -} - -// pickGitHubLink applies resolveGitHubLink's selection to links a caller -// already fetched, so one listing serves both the source inference and the -// link resolution in `project sync`. -func pickGitHubLink(links []githubLink) (string, error) { - switch len(links) { - case 0: - return "", newProjectError( - usefulerror.ErrNotFound, - "No GitHub App installation link", - "Install the SafeDep GitHub App and link it to this tenant, then retry.", - errors.New("project sync: the active tenant has no GitHub App installation link"), - ) - case 1: - return links[0].id, nil - default: - return "", ambiguousGitHubLinkError(links) - } -} - // resolveRepositoryNames maps owner/repository names to immutable GitHub // repository IDs. The listing RPC is an unfiltered proxy over the installation, // so the walk stops as soon as every requested name has a match. func resolveRepositoryNames( ctx context.Context, client githubRepositoryLister, - linkID string, + link sourcelink.Link, names []string, ) ([]githubRepository, error) { if len(names) == 0 { @@ -189,7 +156,7 @@ func resolveRepositoryNames( matches := make(map[string]githubRepository, len(names)) err := paging.Paginate(ctx, label, func(ctx context.Context, pageToken string) (string, error) { req := &controltowerv1.ListGitHubInstallationRepositoriesRequest{} - req.SetLinkId(linkID) + req.SetLinkId(link.ID) req.SetPagination(paging.NewPaginationRequest(githubRepositoryPageSize, pageToken)) res, err := client.ListGitHubInstallationRepositories(ctx, req) if err != nil { @@ -211,7 +178,7 @@ func resolveRepositoryNames( for _, name := range names { match, ok := matches[repositoryKey(name)] if !ok { - return nil, repositoryNotAccessibleError(name, linkID) + return nil, repositoryNotAccessibleError(name, link) } resolved = append(resolved, match) } @@ -225,8 +192,8 @@ func collectRepositoryMatches( matches map[string]githubRepository, ) error { for i, repository := range res.GetRepositories() { - if repository.GetRepositoryId() <= 0 || repository.GetFullName() == "" { - return fmt.Errorf("%s: invalid response: repository %d is missing its identity", label, i+1) + if err := checkGitHubRepository(repository, label, i); err != nil { + return err } key := repositoryKey(repository.GetFullName()) if _, ok := requested[key]; !ok { @@ -240,16 +207,69 @@ func collectRepositoryMatches( return nil } -func repositoryNotAccessibleError(name, linkID string) error { +func checkGitHubRepository( + repository *controltowerv1.ListGitHubInstallationRepositoriesResponse_GitHubRepository, + label string, + i int, +) error { + if repository.GetRepositoryId() <= 0 || repository.GetFullName() == "" { + return fmt.Errorf("%s: invalid response: repository %d is missing its identity", label, i+1) + } + return nil +} + +// listAllGitHubRepositories walks every page of the installation's +// repositories. A repository on two pages counts once, because the listing +// proxies GitHub and a page boundary can move while the walk runs. +func listAllGitHubRepositories( + ctx context.Context, + client githubRepositoryLister, + linkID string, +) ([]githubRepository, error) { + const label = "project sync: list repositories" + + var repositories []githubRepository + seen := map[int64]struct{}{} + err := paging.Paginate(ctx, label, func(ctx context.Context, pageToken string) (string, error) { + req := &controltowerv1.ListGitHubInstallationRepositoriesRequest{} + req.SetLinkId(linkID) + req.SetPagination(paging.NewPaginationRequest(githubRepositoryPageSize, pageToken)) + res, err := client.ListGitHubInstallationRepositories(ctx, req) + if err != nil { + return "", fmt.Errorf("%s: %w", label, err) + } + for i, repository := range res.GetRepositories() { + if err := checkGitHubRepository(repository, label, i); err != nil { + return "", err + } + if _, duplicate := seen[repository.GetRepositoryId()]; duplicate { + continue + } + seen[repository.GetRepositoryId()] = struct{}{} + repositories = append(repositories, githubRepository{ + id: repository.GetRepositoryId(), + fullName: repository.GetFullName(), + }) + } + return res.GetPagination().GetNextPageToken(), nil + }) + if err != nil { + return nil, err + } + return repositories, nil +} + +func repositoryNotAccessibleError(name string, link sourcelink.Link) error { cause := fmt.Errorf( "project sync: repository %q is not accessible through installation link %q", name, - linkID, + link.ID, ) return newProjectError( usefulerror.ErrNotFound, "GitHub repository not accessible", - fmt.Sprintf("Grant %q to the linked GitHub App installation, or retry with --repository-id.", name), + fmt.Sprintf("Grant %q to the GitHub App installation of %s, or retry with --repository-id.", + name, sourcelink.Describe(link.Account, link.ID)), cause, ) } @@ -257,19 +277,13 @@ func repositoryNotAccessibleError(name, linkID string) error { func syncGitHubProjects( ctx context.Context, client githubProjectSyncer, - linkID string, - repositoryIDs []int64, - namesByID map[int64]string, -) (*syncResult, error) { - res, err := client.SyncGitHubInstallationProjects(ctx, newSyncRequest(linkID, repositoryIDs)) + req githubRequest, +) ([]syncedProject, error) { + res, err := client.SyncGitHubInstallationProjects(ctx, newSyncRequest(req.link.ID, req.ids)) if err != nil { return nil, fmt.Errorf("project sync: %w", err) } - projects, err := translateSyncResponse(res, repositoryIDs, namesByID) - if err != nil { - return nil, err - } - return &syncResult{linkID: linkID, projects: projects}, nil + return translateSyncResponse(res, req) } func newSyncRequest(linkID string, repositoryIDs []int64) *controltowerv1.SyncGitHubInstallationProjectsRequest { @@ -287,9 +301,9 @@ func newSyncRequest(linkID string, repositoryIDs []int64) *controltowerv1.SyncGi func translateSyncResponse( res *controltowerv1.SyncGitHubInstallationProjectsResponse, - repositoryIDs []int64, - namesByID map[int64]string, + req githubRequest, ) ([]syncedProject, error) { + repositoryIDs := req.ids mappings := res.GetProjects() if len(mappings) != len(repositoryIDs) { return nil, fmt.Errorf( @@ -330,34 +344,11 @@ func translateSyncResponse( } projects = append(projects, syncedProject{ RepositoryID: repositoryID, - RepositoryName: namesByID[repositoryID], + RepositoryName: req.names[repositoryID], ProjectID: mapping.GetProjectId(), + Account: req.link.Account, + LinkID: req.link.ID, }) } return projects, nil } - -func ambiguousGitHubLinkError(links []githubLink) error { - sort.Slice(links, func(i, j int) bool { return links[i].id < links[j].id }) - - labels := make([]string, 0, len(links)) - for _, link := range links { - if link.accountLogin == "" { - labels = append(labels, link.id) - continue - } - labels = append(labels, fmt.Sprintf("%s (%s)", link.id, link.accountLogin)) - } - joined := strings.Join(labels, ", ") - cause := fmt.Errorf( - "project sync: the active tenant has %d GitHub App installation links: %s", - len(links), - joined, - ) - return newProjectError( - usefulerror.ErrBadRequest, - "GitHub App installation link is ambiguous", - "Retry with --link-id set to one of: "+joined+".", - cause, - ) -} diff --git a/internal/cmd/project/github_test.go b/internal/cmd/project/github_test.go index a3cd456..937afe2 100644 --- a/internal/cmd/project/github_test.go +++ b/internal/cmd/project/github_test.go @@ -3,6 +3,7 @@ package project import ( "context" "errors" + "fmt" "testing" controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" @@ -13,6 +14,8 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/safedep/cli/internal/sourcelink" ) type fakeGitHubLinkLister struct { @@ -57,11 +60,16 @@ func (f *fakeGitHubRepositoryLister) ListGitHubInstallationRepositories( return f.pages[min(len(f.requests)-1, len(f.pages)-1)], nil } +// fakeGitHubProjectSyncer answers each request with one project per +// requested repository, unless res fixes the response. err fails every call, +// or only call failOnCall when that is set. type fakeGitHubProjectSyncer struct { - calls int - req *controltowerv1.SyncGitHubInstallationProjectsRequest - res *controltowerv1.SyncGitHubInstallationProjectsResponse - err error + calls int + req *controltowerv1.SyncGitHubInstallationProjectsRequest + reqs []*controltowerv1.SyncGitHubInstallationProjectsRequest + res *controltowerv1.SyncGitHubInstallationProjectsResponse + err error + failOnCall int } func (f *fakeGitHubProjectSyncer) SyncGitHubInstallationProjects( @@ -71,7 +79,27 @@ func (f *fakeGitHubProjectSyncer) SyncGitHubInstallationProjects( ) (*controltowerv1.SyncGitHubInstallationProjectsResponse, error) { f.calls++ f.req = req - return f.res, f.err + f.reqs = append(f.reqs, req) + if f.err != nil && (f.failOnCall == 0 || f.failOnCall == f.calls) { + return nil, f.err + } + if f.res != nil { + return f.res, nil + } + mappings := make([]*controltowerv1.SyncGitHubInstallationProjectsResponse_ProjectMapping, 0, len(req.GetRepositories())) + for _, selection := range req.GetRepositories() { + mappings = append(mappings, projectMapping(selection.GetRepositoryId(), + fmt.Sprintf("project-%d", selection.GetRepositoryId()))) + } + return syncResponse(mappings...), nil +} + +func syncedIDs(req *controltowerv1.SyncGitHubInstallationProjectsRequest) []int64 { + ids := make([]int64, 0, len(req.GetRepositories())) + for _, selection := range req.GetRepositories() { + ids = append(ids, selection.GetRepositoryId()) + } + return ids } var ( @@ -95,13 +123,11 @@ func TestRunSync_ResolvesNamesAndSendsFlagIDsFirst(t *testing.T) { repositoriesResponse("", repository(11, "safedep/vet"), repository(12, "safedep/cli")), }, } - syncer := &fakeGitHubProjectSyncer{res: syncResponse( - projectMapping(99, "project-99"), - projectMapping(12, "project-12"), - projectMapping(11, "project-11"), - )} + syncer := &fakeGitHubProjectSyncer{} - result, err := runGitHubSync(context.Background(), links, repositories, syncer, syncInput{ + got, err := runSync(context.Background(), syncDeps{ + githubLinks: links, githubRepositories: repositories, githubSyncer: syncer, + }, syncInput{ RepositoryNames: []string{"safedep/cli", "safedep/vet"}, RepositoryIDs: []int64{99}, }) @@ -113,39 +139,38 @@ func TestRunSync_ResolvesNamesAndSendsFlagIDsFirst(t *testing.T) { require.Equal(t, 1, syncer.calls) assert.Equal(t, "link-1", syncer.req.GetLinkId()) - require.Len(t, syncer.req.GetRepositories(), 3) - assert.Equal(t, int64(99), syncer.req.GetRepositories()[0].GetRepositoryId()) - assert.Equal(t, int64(12), syncer.req.GetRepositories()[1].GetRepositoryId()) - assert.Equal(t, int64(11), syncer.req.GetRepositories()[2].GetRepositoryId()) + assert.Equal(t, []int64{99, 12, 11}, syncedIDs(syncer.req)) - assert.Equal(t, "link-1", result.linkID) + result, ok := got.(*syncResult) + require.True(t, ok) require.Len(t, result.projects, 3) - assert.Equal(t, syncedProject{RepositoryID: 99, ProjectID: "project-99"}, result.projects[0]) - assert.Equal(t, syncedProject{ - RepositoryID: 12, RepositoryName: "safedep/cli", ProjectID: "project-12", - }, result.projects[1]) assert.Equal(t, syncedProject{ - RepositoryID: 11, RepositoryName: "safedep/vet", ProjectID: "project-11", - }, result.projects[2]) + RepositoryID: 99, ProjectID: "project-99", Account: "safedep", LinkID: "link-1", + }, result.projects[0]) + assert.Equal(t, "safedep/cli", result.projects[1].RepositoryName) + assert.Equal(t, "safedep/vet", result.projects[2].RepositoryName) } -func TestRunSync_SkipsLinkResolutionWhenLinkIDIsSupplied(t *testing.T) { +func TestRunSync_HiddenLinkIDWithAKnownSourceListsNoLinks(t *testing.T) { t.Parallel() links := &fakeGitHubLinkLister{} + bitbucketLinks := &fakeBitbucketLinkLister{} repositories := &fakeGitHubRepositoryLister{} - syncer := &fakeGitHubProjectSyncer{res: syncResponse(projectMapping(99, "project-99"))} + syncer := &fakeGitHubProjectSyncer{} - result, err := runGitHubSync(context.Background(), links, repositories, syncer, syncInput{ - LinkID: "link-explicit", - RepositoryIDs: []int64{99}, - }) + got, err := runSync(context.Background(), syncDeps{ + githubLinks: links, githubRepositories: repositories, githubSyncer: syncer, bitbucketLinks: bitbucketLinks, + }, syncInput{LinkID: "link-explicit", RepositoryIDs: []int64{99}}) require.NoError(t, err) assert.Zero(t, links.calls) + assert.Zero(t, bitbucketLinks.calls) assert.Empty(t, repositories.requests, "no name needs resolving") assert.Equal(t, "link-explicit", syncer.req.GetLinkId()) - assert.Equal(t, "link-explicit", result.linkID) + result, ok := got.(*syncResult) + require.True(t, ok) + assert.Contains(t, result.RenderTable(), "1 repository synced through link link-explicit") } func TestRunSync_MatchesRepositoryNamesCaseInsensitively(t *testing.T) { @@ -156,14 +181,14 @@ func TestRunSync_MatchesRepositoryNamesCaseInsensitively(t *testing.T) { repositoriesResponse("", repository(12, "SafeDep/CLI")), }, } - syncer := &fakeGitHubProjectSyncer{res: syncResponse(projectMapping(12, "project-12"))} - result, err := runGitHubSync(context.Background(), &fakeGitHubLinkLister{}, repositories, syncer, syncInput{ - LinkID: "link-1", - RepositoryNames: []string{"safedep/cli"}, - }) + got, err := runSync(context.Background(), syncDeps{ + githubRepositories: repositories, githubSyncer: &fakeGitHubProjectSyncer{}, + }, syncInput{Source: "github", LinkID: "link-1", RepositoryNames: []string{"safedep/cli"}}) require.NoError(t, err) + result, ok := got.(*syncResult) + require.True(t, ok) require.Len(t, result.projects, 1) assert.Equal(t, "SafeDep/CLI", result.projects[0].RepositoryName, "GitHub's spelling wins over the caller's") @@ -179,11 +204,8 @@ func TestRunSync_RejectsANameThatCollidesWithASelectedID(t *testing.T) { } syncer := &fakeGitHubProjectSyncer{} - _, err := runGitHubSync(context.Background(), &fakeGitHubLinkLister{}, repositories, syncer, syncInput{ - LinkID: "link-1", - RepositoryNames: []string{"safedep/cli"}, - RepositoryIDs: []int64{12}, - }) + _, err := runSync(context.Background(), syncDeps{githubRepositories: repositories, githubSyncer: syncer}, + syncInput{LinkID: "link-1", RepositoryNames: []string{"safedep/cli"}, RepositoryIDs: []int64{12}}) require.Error(t, err) assert.Contains(t, err.Error(), "duplicate repository ID 12") assert.Zero(t, syncer.calls, "nothing must be materialized") @@ -196,76 +218,46 @@ func TestRunSync_RejectsInvalidInputBeforeAnyRPC(t *testing.T) { repositories := &fakeGitHubRepositoryLister{} syncer := &fakeGitHubProjectSyncer{} - _, err := runGitHubSync(context.Background(), links, repositories, syncer, syncInput{}) + _, err := runSync(context.Background(), syncDeps{ + githubLinks: links, githubRepositories: repositories, githubSyncer: syncer, + }, syncInput{}) require.Error(t, err) assert.Zero(t, links.calls) assert.Empty(t, repositories.requests) assert.Zero(t, syncer.calls) } -func TestResolveGitHubLink(t *testing.T) { +func TestListGitHubLinks(t *testing.T) { t.Parallel() - tests := []struct { - name string - pages []*controltowerv1.ListGitHubAppInstallationLinksResponse - want string - wantErr string - }{ - { - name: "exactly one link", - pages: []*controltowerv1.ListGitHubAppInstallationLinksResponse{linksResponse("", link("link-1", "safedep"))}, - want: "link-1", - }, - { - name: "no link", - pages: []*controltowerv1.ListGitHubAppInstallationLinksResponse{linksResponse("")}, - wantErr: "no GitHub App installation link", - }, - { - name: "several links", - pages: []*controltowerv1.ListGitHubAppInstallationLinksResponse{ - linksResponse("", link("link-2", "acme"), link("link-1", "")), - }, - wantErr: "link-1, link-2 (acme)", - }, - { - name: "several links across pages", + t.Run("walks every page and keeps the account login", func(t *testing.T) { + links, err := listGitHubLinks(context.Background(), &fakeGitHubLinkLister{ pages: []*controltowerv1.ListGitHubAppInstallationLinksResponse{ linksResponse("page-2", link("link-1", "safedep")), - linksResponse("", link("link-2", "acme")), + linksResponse("", link("link-2", "")), }, - wantErr: "link-1 (safedep), link-2 (acme)", - }, - { - name: "missing link ID", - pages: []*controltowerv1.ListGitHubAppInstallationLinksResponse{linksResponse("", link("", "safedep"))}, - wantErr: "link 1 is missing its ID", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - got, err := resolveGitHubLink(context.Background(), &fakeGitHubLinkLister{pages: tt.pages}) - if tt.wantErr == "" { - require.NoError(t, err) - assert.Equal(t, tt.want, got) - return - } - require.Error(t, err) - assert.Contains(t, err.Error(), tt.wantErr) }) - } -} + require.NoError(t, err) + assert.Equal(t, []sourcelink.Link{ + {Source: sourcelink.GitHub, ID: "link-1", Account: "safedep"}, + {Source: sourcelink.GitHub, ID: "link-2"}, + }, links) + }) -func TestResolveGitHubLink_PreservesGRPCStatus(t *testing.T) { - t.Parallel() + t.Run("rejects a link without an ID", func(t *testing.T) { + _, err := listGitHubLinks(context.Background(), &fakeGitHubLinkLister{ + pages: []*controltowerv1.ListGitHubAppInstallationLinksResponse{linksResponse("", link("", "safedep"))}, + }) + require.ErrorContains(t, err, "link 1 is missing its ID") + }) - client := &fakeGitHubLinkLister{err: status.Error(codes.Unavailable, "github unavailable")} - _, err := resolveGitHubLink(context.Background(), client) - require.Error(t, err) - assert.Equal(t, codes.Unavailable, status.Code(err)) + t.Run("preserves the gRPC status", func(t *testing.T) { + _, err := listGitHubLinks(context.Background(), &fakeGitHubLinkLister{ + err: status.Error(codes.Unavailable, "github unavailable"), + }) + require.Error(t, err) + assert.Equal(t, codes.Unavailable, status.Code(err)) + }) } func TestResolveRepositoryNames_StopsPagingOnceEveryNameIsMatched(t *testing.T) { @@ -280,7 +272,7 @@ func TestResolveRepositoryNames_StopsPagingOnceEveryNameIsMatched(t *testing.T) } resolved, err := resolveRepositoryNames( - context.Background(), client, "link-1", []string{"safedep/cli", "safedep/vet"}, + context.Background(), client, testGitHubLink, []string{"safedep/cli", "safedep/vet"}, ) require.NoError(t, err) @@ -296,7 +288,7 @@ func TestResolveRepositoryNames_NoRequestWithoutNames(t *testing.T) { t.Parallel() client := &fakeGitHubRepositoryLister{} - resolved, err := resolveRepositoryNames(context.Background(), client, "link-1", nil) + resolved, err := resolveRepositoryNames(context.Background(), client, testGitHubLink, nil) require.NoError(t, err) assert.Empty(t, resolved) assert.Empty(t, client.requests) @@ -312,7 +304,7 @@ func TestResolveRepositoryNames_FailsOnAnInaccessibleRepository(t *testing.T) { } _, err := resolveRepositoryNames( - context.Background(), client, "link-1", []string{"safedep/vet", "safedep/secret"}, + context.Background(), client, testGitHubLink, []string{"safedep/vet", "safedep/secret"}, ) require.Error(t, err) assert.Contains(t, err.Error(), `repository "safedep/secret" is not accessible`) @@ -339,7 +331,7 @@ func TestResolveRepositoryNames_RejectsMalformedResponses(t *testing.T) { repositoriesResponse("", tt.repository), }, } - _, err := resolveRepositoryNames(context.Background(), client, "link-1", []string{"safedep/cli"}) + _, err := resolveRepositoryNames(context.Background(), client, testGitHubLink, []string{"safedep/cli"}) require.Error(t, err) assert.Contains(t, err.Error(), "repository 1 is missing its identity") }) @@ -355,7 +347,7 @@ func TestResolveRepositoryNames_StopsOnARepeatedPageToken(t *testing.T) { }, } - _, err := resolveRepositoryNames(context.Background(), client, "link-1", []string{"safedep/cli"}) + _, err := resolveRepositoryNames(context.Background(), client, testGitHubLink, []string{"safedep/cli"}) require.Error(t, err) assert.Contains(t, err.Error(), "repeated page token") assert.Len(t, client.requests, 2) @@ -391,9 +383,9 @@ func TestSyncGitHubProjects_RejectsMalformedResponses(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() syncer := &fakeGitHubProjectSyncer{res: tt.res} - _, err := syncGitHubProjects( - context.Background(), syncer, "link-1", []int64{11, 12}, map[int64]string{}, - ) + _, err := syncGitHubProjects(context.Background(), syncer, githubRequest{ + link: testGitHubLink, ids: []int64{11, 12}, names: map[int64]string{}, + }) require.Error(t, err) assert.Contains(t, err.Error(), "project sync: invalid response") assert.Contains(t, err.Error(), tt.wantErr) @@ -405,12 +397,14 @@ func TestSyncGitHubProjects_PreservesGRPCStatus(t *testing.T) { t.Parallel() syncer := &fakeGitHubProjectSyncer{err: status.Error(codes.FailedPrecondition, "installation suspended")} - _, err := syncGitHubProjects(context.Background(), syncer, "link-1", []int64{11}, nil) + _, err := syncGitHubProjects(context.Background(), syncer, githubRequest{link: testGitHubLink, ids: []int64{11}}) require.Error(t, err) assert.Contains(t, err.Error(), "project sync") assert.Equal(t, codes.FailedPrecondition, status.Code(err)) } +var testGitHubLink = sourcelink.Link{Source: sourcelink.GitHub, ID: "link-1", Account: "safedep"} + func linksResponse( nextPageToken string, links ...*controltowerv1.ListGitHubAppInstallationLinksResponse_IntegrationWithAttributes, diff --git a/internal/cmd/project/sync.go b/internal/cmd/project/sync.go index a970170..b4a39f9 100644 --- a/internal/cmd/project/sync.go +++ b/internal/cmd/project/sync.go @@ -1,66 +1,32 @@ package project import ( - "context" - "encoding/json" "errors" "fmt" - "strconv" "strings" - "github.com/safedep/dry/tui/table" - "github.com/safedep/dry/usefulerror" + "github.com/safedep/dry/tui" "github.com/spf13/cobra" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" "github.com/safedep/cli/internal/app" "github.com/safedep/cli/internal/bitbucketlink" - "github.com/safedep/cli/internal/tui" + "github.com/safedep/cli/internal/sourcelink" ) -const ( - // SyncGitHubInstallationProjects accepts between one and one hundred - // repository selections per request. - maxSyncRepositories = 100 - - // unknownRepositoryName marks a project materialized from a repository ID - // the caller supplied directly, so the CLI never resolved its name. - unknownRepositoryName = "-" -) +// SyncGitHubInstallationProjects accepts between one and one hundred +// repository selections per request. +const maxSyncRepositories = 100 type syncInput struct { Source string + Account string LinkID string + All bool RepositoryNames []string RepositoryIDs []int64 RepositoryUUIDs []string } -const ( - sourceGitHub = "github" - sourceBitbucket = "bitbucket" -) - -// syncedProject carries its own JSON tags because the wire shape and the -// display shape are identical here, unlike the scan results whose timestamps and -// URLs need reshaping. -type syncedProject struct { - RepositoryID int64 `json:"repository_id"` - RepositoryName string `json:"repository_name,omitempty"` - ProjectID string `json:"project_id"` -} - -type syncResult struct { - linkID string - projects []syncedProject -} - -type syncResultJSON struct { - LinkID string `json:"link_id"` - Projects []syncedProject `json:"projects"` -} - func syncCmd(a *app.App) *cobra.Command { var in syncInput cmd := &cobra.Command{ @@ -70,8 +36,10 @@ func syncCmd(a *app.App) *cobra.Command { "source integration: a GitHub App installation or a Bitbucket workspace. " + "Repository names are resolved to the source's immutable identity before the " + "request, and the sync is idempotent: repeating it returns the same project " + - "for the same repository. When --source is omitted, the CLI uses the one " + - "source the tenant has links for.", + "for the same repository. The owner of each OWNER/REPOSITORY name picks the " + + "linked GitHub organization or user, or Bitbucket workspace, with that name. " + + "--all syncs every repository of one account and creates a project for every " + + "repository not yet synced.", Args: func(_ *cobra.Command, args []string) error { in.RepositoryNames = args return validateSyncInput(in) @@ -85,6 +53,7 @@ func syncCmd(a *app.App) *cobra.Command { in.RepositoryNames = args integration := newIntegrationClient(client.Connection()) deps := syncDeps{ + progress: tui.Info, githubLinks: integration, githubRepositories: integration, githubSyncer: integration, @@ -102,9 +71,17 @@ func syncCmd(a *app.App) *cobra.Command { f := cmd.Flags() f.StringVar(&in.Source, "source", "", - "repository source: github or bitbucket (inferred from the tenant's links, or from --repository-id and --repository-uuid, when omitted)") - f.StringVar(&in.LinkID, "link-id", "", - "source link to sync through; resolved automatically when the tenant has exactly one link") + "repository source: github or bitbucket (inferred from the account of each name, or from --repository-id and --repository-uuid, when omitted)") + f.StringVar(&in.Account, "account", "", + "GitHub organization or user, or Bitbucket workspace, to sync through. Needed with --all, and with "+ + "--repository-id or --repository-uuid when the tenant has more than one link of that source.") + f.BoolVar(&in.All, "all", false, + "sync every repository the account can read and create a project for every repository not yet synced. "+ + "On Bitbucket, only repositories with scan state enabled.") + // --link-id is hidden: people name a link by its account, and the flag + // stays for scripts that pass the internal link ID. + f.StringVar(&in.LinkID, "link-id", "", "source link ID to sync through") + f.Lookup("link-id").Hidden = true f.Int64SliceVar(&in.RepositoryIDs, "repository-id", nil, "GitHub repository ID to sync instead of a name; repeat for multiple repositories") f.StringSliceVar(&in.RepositoryUUIDs, "repository-uuid", nil, @@ -118,7 +95,7 @@ func syncCmd(a *app.App) *cobra.Command { } func validateSyncInput(in syncInput) error { - if in.Source != "" && in.Source != sourceGitHub && in.Source != sourceBitbucket { + if in.Source != "" && in.Source != string(sourcelink.GitHub) && in.Source != string(sourcelink.Bitbucket) { cause := fmt.Errorf("unknown --source value %q: allowed values are github, bitbucket", in.Source) return invalidRepositorySelectionError(cause, "Retry --source with github or bitbucket.") } @@ -126,16 +103,24 @@ func validateSyncInput(in syncInput) error { cause := fmt.Errorf("--repository-id selects GitHub and --repository-uuid selects Bitbucket") return invalidRepositorySelectionError(cause, "One sync serves one source. Drop one of the flags and retry.") } - if in.Source == sourceGitHub && len(in.RepositoryUUIDs) > 0 { + if in.Source == string(sourcelink.GitHub) && len(in.RepositoryUUIDs) > 0 { cause := fmt.Errorf("--repository-uuid selects Bitbucket repositories") return invalidRepositorySelectionError(cause, "Drop --repository-uuid, or use --source bitbucket.") } - if in.Source == sourceBitbucket && len(in.RepositoryIDs) > 0 { + if in.Source == string(sourcelink.Bitbucket) && len(in.RepositoryIDs) > 0 { cause := fmt.Errorf("--repository-id selects GitHub repositories") return invalidRepositorySelectionError(cause, "Drop --repository-id, or use --source github.") } + if strings.Contains(in.Account, "/") { + cause := fmt.Errorf("--account %q is not an account name", in.Account) + return invalidRepositorySelectionError(cause, "Pass the account name only, for example --account safedep.") + } + total := len(in.RepositoryIDs) + len(in.RepositoryNames) + len(in.RepositoryUUIDs) + if in.All { + return validateSyncAll(in, total) + } if total < 1 || total > maxSyncRepositories { cause := fmt.Errorf("project sync requires between 1 and %d repositories", maxSyncRepositories) return invalidRepositorySelectionError( @@ -152,138 +137,6 @@ func validateSyncInput(in syncInput) error { return validateRepositoryIDs(in.RepositoryIDs) } -type syncDeps struct { - githubLinks githubLinkLister - githubRepositories githubRepositoryLister - githubSyncer githubProjectSyncer - bitbucketLinks bitbucketlink.Lister - bitbucketRepositories bitbucketRepositoryLister - bitbucketSyncer bitbucketProjectSyncer -} - -func runSync(ctx context.Context, deps syncDeps, in syncInput) (tui.Renderable, error) { - if err := normalizeSyncRepositoryUUIDs(in.RepositoryUUIDs); err != nil { - return nil, err - } - if err := validateSyncInput(in); err != nil { - return nil, err - } - - source, linkID, err := resolveSyncSource(ctx, deps, in) - if err != nil { - return nil, err - } - in.LinkID = linkID - - if source == sourceBitbucket { - return runBitbucketSync(ctx, deps.bitbucketLinks, deps.bitbucketRepositories, - deps.bitbucketSyncer, in) - } - return runGitHubSync(ctx, deps.githubLinks, deps.githubRepositories, - deps.githubSyncer, in) -} - -// resolveSyncSource picks the repository source and the link to sync -// through. An explicit --source wins, then the source a selector flag -// implies; those paths list nothing and keep the caller's --link-id, so the -// per-source path resolves the link with its own single walk. With names -// only, the tenant's links decide: --link-id picks the source that owns it, -// a tenant with one linked source uses that source, and a tenant with both -// must pick one. The listings also resolve the link, so the per-source path -// never repeats the walk. -func resolveSyncSource(ctx context.Context, deps syncDeps, in syncInput) (string, string, error) { - if in.Source != "" { - return in.Source, in.LinkID, nil - } - if len(in.RepositoryIDs) > 0 { - return sourceGitHub, in.LinkID, nil - } - if len(in.RepositoryUUIDs) > 0 { - return sourceBitbucket, in.LinkID, nil - } - - githubLinks, err := listGitHubLinks(ctx, deps.githubLinks) - if err != nil { - return "", "", err - } - bitbucketLinks, err := listBitbucketLinksForInference(ctx, deps.bitbucketLinks) - if err != nil { - return "", "", err - } - - if in.LinkID != "" { - return sourceOwningLink(in.LinkID, githubLinks, bitbucketLinks) - } - - switch { - case len(githubLinks) > 0 && len(bitbucketLinks) > 0: - cause := errors.New("project sync: the active tenant has GitHub and Bitbucket links") - return "", "", invalidRepositorySelectionError(cause, - "Pass --source github or --source bitbucket.") - case len(bitbucketLinks) > 0: - linkID, err := bitbucketlink.PickSingle(bitbucketLinks, syncLinkLabel) - if err != nil { - return "", "", err - } - return sourceBitbucket, linkID, nil - case len(githubLinks) > 0: - linkID, err := pickGitHubLink(githubLinks) - if err != nil { - return "", "", err - } - return sourceGitHub, linkID, nil - default: - return "", "", newProjectError( - usefulerror.ErrNotFound, - "No source integration link", - "Install and link the SafeDep GitHub App, or link a Bitbucket workspace, then retry.", - errors.New("project sync: the active tenant has no GitHub or Bitbucket link"), - ) - } -} - -const syncLinkLabel = "project sync: resolve workspace link" - -// listBitbucketLinksForInference treats a control plane without the -// Bitbucket RPCs as a tenant with no Bitbucket links, which Unimplemented -// proves. Without this, a GitHub-only tenant against such a control plane -// loses every names-only sync to the failing listing. Every other failure, -// PermissionDenied included, leaves the source undecidable and stops the -// sync: links the caller cannot inspect may exist, and picking GitHub then -// could sync a name against the wrong source. -func listBitbucketLinksForInference(ctx context.Context, - client bitbucketlink.Lister, -) ([]bitbucketlink.Link, error) { - links, err := bitbucketlink.List(ctx, client, syncLinkLabel) - if status.Code(err) == codes.Unimplemented { - return nil, nil - } - return links, err -} - -// sourceOwningLink maps --link-id to the source that owns it, so a tenant -// with links to both sources can sync by name without --source. -func sourceOwningLink(linkID string, githubLinks []githubLink, - bitbucketLinks []bitbucketlink.Link, -) (string, string, error) { - for _, link := range githubLinks { - if link.id == linkID { - return sourceGitHub, linkID, nil - } - } - for _, link := range bitbucketLinks { - if link.ID == linkID { - return sourceBitbucket, linkID, nil - } - } - return "", "", newProjectError( - usefulerror.ErrNotFound, - "Source link not found", - "List link IDs with `safedep integration bitbucket link list`, or drop --link-id to use the tenant's only link.", - fmt.Errorf("project sync: link %q is not a GitHub or Bitbucket link of the active tenant", linkID), - ) -} - // normalizeSyncRepositoryUUIDs rewrites every --repository-uuid value to the // canonical lowercase, unbraced form the control plane requires, so a UUID // pasted from the Bitbucket UI works and a malformed value fails before any @@ -330,6 +183,18 @@ func validateRepositoryNames(names []string) error { return nil } +func validateSyncAll(in syncInput, selected int) error { + if in.Account == "" && in.LinkID == "" { + cause := errors.New("--all needs --account") + return invalidRepositorySelectionError(cause, "Pass --account with --all, for example --account safedep.") + } + if selected > 0 { + cause := errors.New("--all takes no repository names, --repository-id or --repository-uuid") + return invalidRepositorySelectionError(cause, "Drop the repository names and the ID flags, or drop --all.") + } + return nil +} + func validateRepositoryIDs(ids []int64) error { seen := make(map[int64]struct{}, len(ids)) for i, id := range ids { @@ -355,54 +220,3 @@ func validateRepositoryIDs(ids []int64) error { func repositoryKey(name string) string { return strings.ToLower(name) } - -func (r *syncResult) RenderJSON() ([]byte, error) { - projects := r.projects - if projects == nil { - projects = []syncedProject{} - } - return json.MarshalIndent(syncResultJSON{LinkID: r.linkID, Projects: projects}, "", " ") -} - -func (r *syncResult) RenderPlain() string { - var output strings.Builder - output.WriteString("repository_name\trepository_id\tproject_id") - for _, project := range r.projects { - output.WriteByte('\n') - output.WriteString(strings.Join(syncedProjectCells(project), "\t")) - } - return output.String() -} - -func (r *syncResult) RenderTable() string { - rows := make([][]string, 0, len(r.projects)) - for _, project := range r.projects { - rows = append(rows, syncedProjectCells(project)) - } - return table.New(). - Title("Synced projects"). - Headers("REPOSITORY", "REPOSITORY ID", "PROJECT ID"). - Rows(rows...). - Footer(fmt.Sprintf("%d %s synced through link %s", - len(rows), pluralRepositories(len(rows)), r.linkID)). - Render() -} - -func syncedProjectCells(project syncedProject) []string { - name := project.RepositoryName - if name == "" { - name = unknownRepositoryName - } - return []string{ - name, - strconv.FormatInt(project.RepositoryID, 10), - project.ProjectID, - } -} - -func pluralRepositories(n int) string { - if n == 1 { - return "repository" - } - return "repositories" -} diff --git a/internal/cmd/project/sync_all.go b/internal/cmd/project/sync_all.go new file mode 100644 index 0000000..01c048e --- /dev/null +++ b/internal/cmd/project/sync_all.go @@ -0,0 +1,116 @@ +package project + +import ( + "context" + "fmt" + "slices" + + "github.com/safedep/dry/usefulerror" + + "github.com/safedep/cli/internal/sourcelink" + "github.com/safedep/cli/internal/tui" +) + +// runSyncAll syncs every repository the link can read. It lists them all +// before the first write, so the batches cover one consistent listing. +func runSyncAll(ctx context.Context, deps syncDeps, link sourcelink.Link) (tui.Renderable, error) { + if link.Source == sourcelink.Bitbucket { + return runBitbucketSyncAll(ctx, deps, link) + } + return runGitHubSyncAll(ctx, deps, link) +} + +func runGitHubSyncAll(ctx context.Context, deps syncDeps, link sourcelink.Link) (*syncResult, error) { + repositories, err := listAllGitHubRepositories(ctx, deps.githubRepositories, link.ID) + if err != nil { + return nil, err + } + + ids := make([]int64, 0, len(repositories)) + names := make(map[int64]string, len(repositories)) + for _, repository := range repositories { + ids = append(ids, repository.id) + names[repository.id] = repository.fullName + } + + projects, err := syncInBatches(ctx, deps, ids, func(ctx context.Context, batch []int64) ([]syncedProject, error) { + return syncGitHubProjects(ctx, deps.githubSyncer, githubRequest{link: link, ids: batch, names: names}) + }) + if err != nil { + return nil, err + } + return &syncResult{links: []sourcelink.Link{link}, projects: projects, all: true}, nil +} + +func runBitbucketSyncAll(ctx context.Context, deps syncDeps, link sourcelink.Link) (*bitbucketSyncResult, error) { + repositories, notEnabled, err := listEnabledBitbucketRepositories(ctx, deps.bitbucketRepositories, link.ID) + if err != nil { + return nil, err + } + if len(repositories) == 0 && notEnabled > 0 { + return nil, noEnabledRepositoryError(link, notEnabled) + } + + uuids := make([]string, 0, len(repositories)) + names := make(map[string]string, len(repositories)) + for _, repository := range repositories { + uuids = append(uuids, repository.uuid) + names[repository.uuid] = repository.fullName + } + + projects, err := syncInBatches(ctx, deps, uuids, func(ctx context.Context, batch []string) ([]syncedBitbucketProject, error) { + return syncBitbucketProjects(ctx, deps.bitbucketSyncer, bitbucketRequest{link: link, uuids: batch, names: names}) + }) + if err != nil { + return nil, err + } + return &bitbucketSyncResult{ + links: []sourcelink.Link{link}, projects: projects, all: true, notEnabled: notEnabled, + }, nil +} + +// syncInBatches sends the selections in requests of at most +// maxSyncRepositories, the server's cap, and stops at the first failure. +func syncInBatches[T, P any]( + ctx context.Context, + deps syncDeps, + items []T, + sync func(context.Context, []T) ([]P, error), +) ([]P, error) { + var synced []P + for batch := range slices.Chunk(items, maxSyncRepositories) { + deps.report("Syncing repositories %d to %d of %d", len(synced)+1, len(synced)+len(batch), len(items)) + projects, err := sync(ctx, batch) + if err != nil { + return nil, batchStoppedError(err, len(synced), len(items)) + } + synced = append(synced, projects...) + } + return synced, nil +} + +func noEnabledRepositoryError(link sourcelink.Link, notEnabled int) error { + account := sourcelink.Describe(link.Account, link.ID) + command := allowlistUpdateCommand(link) + return newProjectError( + usefulerror.ErrNotFound, + fmt.Sprintf("No repository of %s has scan state enabled", account), + fmt.Sprintf("SafeDep syncs only repositories it scans, and %d %s not enabled. "+ + "Enable them with `%s`, then retry.", + notEnabled, pluralRepositoriesAre(notEnabled), command), + fmt.Errorf("project sync: %s has %d repositories and none is enabled", account, notEnabled), + ) +} + +func pluralRepositoriesAre(n int) string { + if n == 1 { + return "repository is" + } + return "repositories are" +} + +func (d syncDeps) report(format string, args ...any) { + if d.progress != nil { + d.progress(format, args...) + } +} diff --git a/internal/cmd/project/sync_all_test.go b/internal/cmd/project/sync_all_test.go new file mode 100644 index 0000000..674e0bb --- /dev/null +++ b/internal/cmd/project/sync_all_test.go @@ -0,0 +1,282 @@ +package project + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + + messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/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" +) + +// githubRepositoryRange lists repositories first..last as owner safedep. +func githubRepositoryRange(first, last int64) []*controltowerv1.ListGitHubInstallationRepositoriesResponse_GitHubRepository { + var out []*controltowerv1.ListGitHubInstallationRepositoriesResponse_GitHubRepository + for id := first; id <= last; id++ { + out = append(out, repository(id, fmt.Sprintf("safedep/repo-%d", id))) + } + return out +} + +func TestRunSync_AllGitHub(t *testing.T) { + linksPage := linksResponse("", link("gh-1", "safedep"), link("gh-2", "acme")) + + t.Run("syncs every listed repository in batches of 100", func(t *testing.T) { + // Pages of 60, 100 and 80 repositories. Page two repeats repository + // 60, which the sync must count once. + page2 := append(githubRepositoryRange(61, 160), repository(60, "safedep/repo-60")) + repositories := &fakeGitHubRepositoryLister{pages: []*controltowerv1.ListGitHubInstallationRepositoriesResponse{ + repositoriesResponse("p2", githubRepositoryRange(1, 60)...), + repositoriesResponse("p3", page2...), + repositoriesResponse("", githubRepositoryRange(161, 240)...), + }} + syncer := &fakeGitHubProjectSyncer{} + var progress []string + + got, err := runSync(context.Background(), syncDeps{ + progress: func(format string, args ...any) { progress = append(progress, fmt.Sprintf(format, args...)) }, + githubLinks: &fakeGitHubLinkLister{pages: []*controltowerv1.ListGitHubAppInstallationLinksResponse{linksPage}}, + githubRepositories: repositories, + githubSyncer: syncer, + }, syncInput{Source: "github", Account: "Acme", All: true}) + require.NoError(t, err) + + require.Len(t, repositories.requests, 3) + assert.Equal(t, "gh-2", repositories.requests[0].GetLinkId()) + assert.Equal(t, "p3", repositories.requests[2].GetPagination().GetPageToken()) + + require.Len(t, syncer.reqs, 3) + sizes := make([]int, 0, len(syncer.reqs)) + for _, req := range syncer.reqs { + assert.Equal(t, "gh-2", req.GetLinkId()) + sizes = append(sizes, len(req.GetRepositories())) + } + assert.Equal(t, []int{100, 100, 40}, sizes) + assert.Equal(t, []string{ + "Syncing repositories 1 to 100 of 240", + "Syncing repositories 101 to 200 of 240", + "Syncing repositories 201 to 240 of 240", + }, progress) + + result, ok := got.(*syncResult) + require.True(t, ok) + assert.Len(t, result.projects, 240) + assert.Equal(t, "safedep/repo-240", result.projects[239].RepositoryName) + assert.Contains(t, result.RenderTable(), "Synced 240 repositories through account acme") + }) + + t.Run("an installation without repositories syncs nothing", func(t *testing.T) { + syncer := &fakeGitHubProjectSyncer{} + + got, err := runSync(context.Background(), syncDeps{ + githubLinks: &fakeGitHubLinkLister{pages: []*controltowerv1.ListGitHubAppInstallationLinksResponse{linksPage}}, + githubRepositories: &fakeGitHubRepositoryLister{pages: []*controltowerv1.ListGitHubInstallationRepositoriesResponse{ + repositoriesResponse(""), + }}, + githubSyncer: syncer, + }, syncInput{Source: "github", Account: "acme", All: true}) + require.NoError(t, err) + assert.Zero(t, syncer.calls) + result, ok := got.(*syncResult) + require.True(t, ok) + assert.Contains(t, result.RenderTable(), "Synced 0 repositories through account acme") + }) + + failures := []struct { + name string + err error + wantCode string + wantRerun bool + }{ + { + name: "a refusal stops the run without rerun advice", + err: status.Error(codes.FailedPrecondition, "installation suspended"), + wantCode: usefulerror.ErrConflict, + }, + { + name: "an outage stops the run with rerun advice", + err: status.Error(codes.Unavailable, "control plane unavailable"), + wantCode: usefulerror.ErrServiceUnavailable, + wantRerun: true, + }, + { + name: "a timeout stops the run with rerun advice", + err: status.Error(codes.DeadlineExceeded, "deadline exceeded"), + wantCode: usefulerror.ErrGatewayTimeout, + wantRerun: true, + }, + { + name: "a rate limit stops the run with rerun advice", + err: status.Error(codes.ResourceExhausted, "too many requests"), + wantCode: usefulerror.ErrQuotaExceeded, + wantRerun: true, + }, + } + for _, tc := range failures { + t.Run(tc.name, func(t *testing.T) { + syncer := &fakeGitHubProjectSyncer{err: tc.err, failOnCall: 2} + + _, err := runSync(context.Background(), syncDeps{ + githubLinks: &fakeGitHubLinkLister{pages: []*controltowerv1.ListGitHubAppInstallationLinksResponse{linksPage}}, + githubRepositories: &fakeGitHubRepositoryLister{pages: []*controltowerv1.ListGitHubInstallationRepositoriesResponse{ + repositoriesResponse("", githubRepositoryRange(1, 240)...), + }}, + githubSyncer: syncer, + }, syncInput{Source: "github", Account: "acme", All: true}) + require.Error(t, err) + assert.Equal(t, 2, syncer.calls, "the batch after the failure must not be sent") + + usefulErr, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, "Sync stopped after 100 of 240 repositories", usefulErr.HumanError()) + assert.Equal(t, tc.wantCode, usefulErr.Code()) + assert.Equal(t, status.Convert(tc.err).Message()+". Projects exist for at least the first 100 repositories.", + strings.TrimSuffix(usefulErr.Help(), " Rerun the same command to sync the rest. The sync is idempotent.")) + assert.Equal(t, tc.wantRerun, strings.Contains(usefulErr.Help(), "Rerun the same command")) + assert.Equal(t, status.Code(tc.err), status.Code(err)) + }) + } +} + +func TestRunSync_AllKeepsAnExpiredSessionForTheLoginGuidance(t *testing.T) { + syncer := &fakeGitHubProjectSyncer{err: status.Error(codes.Unauthenticated, "token expired"), failOnCall: 2} + + _, err := runSync(context.Background(), syncDeps{ + githubRepositories: &fakeGitHubRepositoryLister{pages: []*controltowerv1.ListGitHubInstallationRepositoriesResponse{ + repositoriesResponse("", githubRepositoryRange(1, 240)...), + }}, + githubSyncer: syncer, + }, syncInput{Source: "github", LinkID: "gh-1", All: true}) + require.Error(t, err) + assert.Equal(t, codes.Unauthenticated, status.Code(err)) + var stopped usefulerror.UsefulError + assert.False(t, errors.As(err, &stopped), + "the entry point turns Unauthenticated into the login guidance, which a wrapped error would hide") +} + +func TestRunSync_AllThroughAHiddenLinkID(t *testing.T) { + links := &fakeGitHubLinkLister{} + syncer := &fakeGitHubProjectSyncer{} + + got, err := runSync(context.Background(), syncDeps{ + githubLinks: links, + githubRepositories: &fakeGitHubRepositoryLister{pages: []*controltowerv1.ListGitHubInstallationRepositoriesResponse{ + repositoriesResponse("", githubRepositoryRange(1, 3)...), + }}, + githubSyncer: syncer, + }, syncInput{Source: "github", LinkID: "gh-9", All: true}) + require.NoError(t, err) + assert.Zero(t, links.calls) + require.Equal(t, 1, syncer.calls) + assert.Equal(t, "gh-9", syncer.req.GetLinkId()) + result, ok := got.(*syncResult) + require.True(t, ok) + assert.Contains(t, result.RenderTable(), "Synced 3 repositories through link gh-9") +} + +func TestRunSync_AllBitbucket(t *testing.T) { + const ( + enabled = controltowerv1.ListBitbucketRepositoriesResponse_BitbucketRepository_SCAN_STATE_ENABLED + disabled = controltowerv1.ListBitbucketRepositoriesResponse_BitbucketRepository_SCAN_STATE_DISABLED + ) + listed := func(uuid string, state controltowerv1.ListBitbucketRepositoriesResponse_BitbucketRepository_ScanState) *controltowerv1.ListBitbucketRepositoriesResponse_BitbucketRepository { + repository := bitbucketListedRepository(uuid, "safedep/"+uuid[:4]) + repository.SetScanState(state) + return repository + } + + t.Run("syncs only repositories with scan state enabled", func(t *testing.T) { + syncer := &fakeBitbucketProjectSyncer{} + got, err := runSync(context.Background(), syncDeps{ + bitbucketLinks: &fakeBitbucketLinkLister{pages: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{ + bitbucketLinksPage(bitbucketWorkspaceLink("bb-1")), + }}, + bitbucketRepositories: &fakeBitbucketRepositoryLister{pages: []*controltowerv1.ListBitbucketRepositoriesResponse{ + bitbucketRepositoriesPage( + listed(testBitbucketRepoUUIDa, enabled), + listed("11111111-0000-4000-8000-000000000001", disabled), + listed(testBitbucketRepoUUIDb, enabled), + listed("11111111-0000-4000-8000-000000000002", + controltowerv1.ListBitbucketRepositoriesResponse_BitbucketRepository_SCAN_STATE_UNSPECIFIED), + ), + }}, + bitbucketSyncer: syncer, + }, syncInput{Source: "bitbucket", Account: "safedep", All: true}) + require.NoError(t, err) + require.Equal(t, 1, syncer.calls) + assert.Equal(t, []string{testBitbucketRepoUUIDa, testBitbucketRepoUUIDb}, syncedUUIDs(syncer.req)) + result, ok := got.(*bitbucketSyncResult) + require.True(t, ok) + assert.Contains(t, result.RenderTable(), "Synced 2 of 4 repositories through account safedep, 2 not enabled") + }) + + t.Run("a repository on two pages syncs once", func(t *testing.T) { + page1 := bitbucketRepositoriesPage(listed(testBitbucketRepoUUIDa, enabled)) + next := &messagescontroltowerv1.PaginationResponse{} + next.SetNextPageToken("p2") + page1.SetPagination(next) + syncer := &fakeBitbucketProjectSyncer{} + + _, err := runSync(context.Background(), syncDeps{ + bitbucketRepositories: &fakeBitbucketRepositoryLister{pages: []*controltowerv1.ListBitbucketRepositoriesResponse{ + page1, + bitbucketRepositoriesPage(listed(testBitbucketRepoUUIDa, enabled), listed(testBitbucketRepoUUIDb, enabled)), + }}, + bitbucketSyncer: syncer, + }, syncInput{Source: "bitbucket", LinkID: "bb-1", All: true}) + require.NoError(t, err) + require.Equal(t, 1, syncer.calls) + assert.Equal(t, []string{testBitbucketRepoUUIDa, testBitbucketRepoUUIDb}, syncedUUIDs(syncer.req)) + }) + + t.Run("a workspace with no enabled repository fails with the allowlist command", func(t *testing.T) { + syncer := &fakeBitbucketProjectSyncer{} + _, err := runSync(context.Background(), syncDeps{ + bitbucketLinks: &fakeBitbucketLinkLister{pages: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{ + bitbucketLinksPage(bitbucketWorkspaceLink("bb-1")), + }}, + bitbucketRepositories: &fakeBitbucketRepositoryLister{pages: []*controltowerv1.ListBitbucketRepositoriesResponse{ + bitbucketRepositoriesPage(listed(testBitbucketRepoUUIDa, disabled)), + }}, + bitbucketSyncer: syncer, + }, syncInput{Source: "bitbucket", Account: "safedep", All: true}) + require.Error(t, err) + assert.Contains(t, errorText(err), "safedep integration bitbucket allowlist update --account safedep") + assert.Zero(t, syncer.calls) + }) + + t.Run("an account on both sources needs --source", func(t *testing.T) { + deps, githubSyncer, bitbucketSyncer := newTwoSourceDeps( + []*controltowerv1.ListGitHubAppInstallationLinksResponse_IntegrationWithAttributes{link("gh-1", "safedep")}, + []*controltowerv1.ListBitbucketWorkspaceLinksResponse_WorkspaceLink{bitbucketWorkspaceLink("bb-1")}, + nil) + + _, err := runSync(context.Background(), deps, syncInput{Account: "safedep", All: true}) + require.Error(t, err) + assert.Contains(t, errorText(err), "--source github or --source bitbucket") + assert.Zero(t, githubSyncer.calls+bitbucketSyncer.calls) + }) + + t.Run("--source settles an account on both sources", func(t *testing.T) { + deps, githubSyncer, bitbucketSyncer := newTwoSourceDeps( + []*controltowerv1.ListGitHubAppInstallationLinksResponse_IntegrationWithAttributes{link("gh-1", "safedep")}, + []*controltowerv1.ListBitbucketWorkspaceLinksResponse_WorkspaceLink{bitbucketWorkspaceLink("bb-1")}, + nil) + deps.bitbucketRepositories = &fakeBitbucketRepositoryLister{pages: []*controltowerv1.ListBitbucketRepositoriesResponse{ + bitbucketRepositoriesPage(listed(testBitbucketRepoUUIDa, enabled)), + }} + + _, err := runSync(context.Background(), deps, syncInput{Source: "bitbucket", Account: "safedep", All: true}) + require.NoError(t, err) + assert.Zero(t, githubSyncer.calls) + require.Equal(t, 1, bitbucketSyncer.calls) + assert.Equal(t, "bb-1", bitbucketSyncer.req.GetLinkId()) + }) +} diff --git a/internal/cmd/project/sync_output.go b/internal/cmd/project/sync_output.go new file mode 100644 index 0000000..c325a19 --- /dev/null +++ b/internal/cmd/project/sync_output.go @@ -0,0 +1,181 @@ +package project + +import ( + "encoding/json" + "fmt" + "strconv" + "strings" + + "github.com/safedep/dry/tui/table" + + "github.com/safedep/cli/internal/sourcelink" + "github.com/safedep/cli/internal/tui" +) + +// syncedProject carries its own JSON tags because the wire shape and the +// display shape are identical here, unlike the scan results whose timestamps and +// URLs need reshaping. +type syncedProject struct { + RepositoryID int64 `json:"repository_id"` + RepositoryName string `json:"repository_name,omitempty"` + ProjectID string `json:"project_id"` + Account string `json:"account,omitempty"` + LinkID string `json:"link_id"` +} + +type syncedBitbucketProject struct { + RepositoryUUID string `json:"repository_uuid"` + RepositoryName string `json:"repository_name,omitempty"` + ProjectID string `json:"project_id"` + Account string `json:"account,omitempty"` + LinkID string `json:"link_id"` +} + +// syncResult lists the links a run synced through in request order. all +// marks a run of --all, whose footer reports the total. +type syncResult struct { + links []sourcelink.Link + projects []syncedProject + all bool +} + +type bitbucketSyncResult struct { + links []sourcelink.Link + projects []syncedBitbucketProject + all bool + notEnabled int +} + +// syncResultJSON reports the link at the top level only when one link served +// the run. With several links, each project names its own. +type syncResultJSON[P any] struct { + LinkID string `json:"link_id,omitempty"` + Account string `json:"account,omitempty"` + Projects []P `json:"projects"` +} + +func newSyncResultJSON[P any](links []sourcelink.Link, projects []P) syncResultJSON[P] { + if projects == nil { + projects = []P{} + } + out := syncResultJSON[P]{Projects: projects} + if len(links) == 1 { + out.LinkID = links[0].ID + out.Account = links[0].Account + } + return out +} + +func (r *syncResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(newSyncResultJSON(r.links, r.projects), "", " ") +} + +func (r *syncResult) RenderPlain() string { + rows := make([][]string, 0, len(r.projects)) + for _, project := range r.projects { + rows = append(rows, []string{ + orEmptyCell(project.RepositoryName), + strconv.FormatInt(project.RepositoryID, 10), + project.ProjectID, + orEmptyCell(project.Account), + }) + } + return plainRows("repository_name\trepository_id\tproject_id\taccount", rows) +} + +func (r *syncResult) RenderTable() string { + rows := make([][]string, 0, len(r.projects)) + for _, project := range r.projects { + rows = append(rows, []string{ + orEmptyCell(project.RepositoryName), + strconv.FormatInt(project.RepositoryID, 10), + project.ProjectID, + sourcelink.Label(project.Account, project.LinkID), + }) + } + return table.New(). + Title("Synced projects"). + Headers("REPOSITORY", "REPOSITORY ID", "PROJECT ID", "ACCOUNT"). + Rows(rows...). + Footer(syncFooter(len(rows), r.links, r.all, 0)). + Render() +} + +func (r *bitbucketSyncResult) RenderJSON() ([]byte, error) { + return json.MarshalIndent(newSyncResultJSON(r.links, r.projects), "", " ") +} + +func (r *bitbucketSyncResult) RenderPlain() string { + rows := make([][]string, 0, len(r.projects)) + for _, project := range r.projects { + rows = append(rows, []string{ + orEmptyCell(project.RepositoryName), + project.RepositoryUUID, + project.ProjectID, + orEmptyCell(project.Account), + }) + } + return plainRows("repository_name\trepository_uuid\tproject_id\taccount", rows) +} + +func (r *bitbucketSyncResult) RenderTable() string { + rows := make([][]string, 0, len(r.projects)) + for _, project := range r.projects { + rows = append(rows, []string{ + orEmptyCell(project.RepositoryName), + project.RepositoryUUID, + project.ProjectID, + sourcelink.Label(project.Account, project.LinkID), + }) + } + return table.New(). + Title("Synced projects"). + Headers("REPOSITORY", "REPOSITORY UUID", "PROJECT ID", "ACCOUNT"). + Rows(rows...). + Footer(syncFooter(len(rows), r.links, r.all, r.notEnabled)). + Render() +} + +// plainRows keeps the account last, so a pipeline that cuts the first three +// columns reads the same fields in every release. +func plainRows(header string, rows [][]string) string { + var output strings.Builder + output.WriteString(header) + for _, row := range rows { + output.WriteByte('\n') + output.WriteString(strings.Join(row, "\t")) + } + return output.String() +} + +// orEmptyCell fills the name of a repository selected by ID or UUID, which +// the CLI never resolved, and the account of a link without an account name. +func orEmptyCell(value string) string { + if value == "" { + return tui.EmptyCell + } + return value +} + +func syncFooter(synced int, links []sourcelink.Link, all bool, notEnabled int) string { + through := fmt.Sprintf("%d accounts", len(links)) + if len(links) == 1 { + through = sourcelink.Describe(links[0].Account, links[0].ID) + } + switch { + case !all: + return fmt.Sprintf("%d %s synced through %s", synced, pluralRepositories(synced), through) + case notEnabled == 0: + return fmt.Sprintf("Synced %d %s through %s", synced, pluralRepositories(synced), through) + default: + return fmt.Sprintf("Synced %d of %d repositories through %s, %d not enabled", + synced, synced+notEnabled, through, notEnabled) + } +} + +func pluralRepositories(n int) string { + if n == 1 { + return "repository" + } + return "repositories" +} diff --git a/internal/cmd/project/sync_run.go b/internal/cmd/project/sync_run.go new file mode 100644 index 0000000..f0affd5 --- /dev/null +++ b/internal/cmd/project/sync_run.go @@ -0,0 +1,200 @@ +package project + +import ( + "context" + "errors" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/safedep/cli/internal/bitbucketlink" + "github.com/safedep/cli/internal/sourcelink" + "github.com/safedep/cli/internal/tui" +) + +const syncLinkLabel = "project sync: resolve workspace link" + +type syncDeps struct { + // progress reports each --all batch on stderr. Nil reports nothing. + progress func(format string, args ...any) + githubLinks githubLinkLister + githubRepositories githubRepositoryLister + githubSyncer githubProjectSyncer + bitbucketLinks bitbucketlink.Lister + bitbucketRepositories bitbucketRepositoryLister + bitbucketSyncer bitbucketProjectSyncer +} + +// syncPlan is what one link syncs. +type syncPlan struct { + link sourcelink.Link + names []string + ids []int64 + uuids []string +} + +func runSync(ctx context.Context, deps syncDeps, in syncInput) (tui.Renderable, error) { + if err := normalizeSyncRepositoryUUIDs(in.RepositoryUUIDs); err != nil { + return nil, err + } + if err := validateSyncInput(in); err != nil { + return nil, err + } + + sel := sourcelink.Selection{Source: selectedSource(in), Account: in.Account, LinkID: in.LinkID} + links, err := syncLinks(ctx, deps, sel) + if err != nil { + return nil, err + } + + if in.All { + link, err := sourcelink.Pick(links, sel) + if err != nil { + return nil, err + } + return runSyncAll(ctx, deps, link) + } + + plans, err := planSync(links, sel, in) + if err != nil { + return nil, err + } + if plans[0].link.Source == sourcelink.Bitbucket { + projects, err := syncPlans(ctx, plans, + func(ctx context.Context, plan syncPlan) (bitbucketRequest, error) { + return prepareBitbucketRequest(ctx, deps.bitbucketRepositories, plan) + }, + func(ctx context.Context, req bitbucketRequest) ([]syncedBitbucketProject, error) { + return syncBitbucketProjects(ctx, deps.bitbucketSyncer, req) + }) + if err != nil { + return nil, err + } + return &bitbucketSyncResult{links: planLinks(plans), projects: projects}, nil + } + projects, err := syncPlans(ctx, plans, + func(ctx context.Context, plan syncPlan) (githubRequest, error) { + return prepareGitHubRequest(ctx, deps.githubRepositories, plan) + }, + func(ctx context.Context, req githubRequest) ([]syncedProject, error) { + return syncGitHubProjects(ctx, deps.githubSyncer, req) + }) + if err != nil { + return nil, err + } + return &syncResult{links: planLinks(plans), projects: projects}, nil +} + +// selectedSource is the source the selection allows before any listing: an +// explicit --source, or the source an immutable selector belongs to. Empty +// allows both. +func selectedSource(in syncInput) sourcelink.Source { + switch { + case in.Source != "": + return sourcelink.Source(in.Source) + case len(in.RepositoryIDs) > 0: + return sourcelink.GitHub + case len(in.RepositoryUUIDs) > 0: + return sourcelink.Bitbucket + } + return "" +} + +// syncLinks lists the links of the sources the selection allows. A hidden +// --link-id with a known source lists nothing, as scripts expect. When both +// sources are allowed, Unimplemented from the Bitbucket listing means a +// control plane without those RPCs, so a GitHub-only tenant keeps working. +// Any other failure stops the sync, because links the caller cannot inspect +// may exist and a name could then sync against the wrong source. +func syncLinks(ctx context.Context, deps syncDeps, sel sourcelink.Selection) ([]sourcelink.Link, error) { + if sel.LinkID != "" && sel.Account == "" && sel.Source != "" { + return []sourcelink.Link{{Source: sel.Source, ID: sel.LinkID}}, nil + } + + var links []sourcelink.Link + if sel.Source != sourcelink.Bitbucket { + github, err := listGitHubLinks(ctx, deps.githubLinks) + if err != nil { + return nil, err + } + links = append(links, github...) + } + if sel.Source != sourcelink.GitHub { + bitbucket, err := bitbucketlink.List(ctx, deps.bitbucketLinks, syncLinkLabel) + if sel.Source == "" && status.Code(err) == codes.Unimplemented { + bitbucket, err = nil, nil + } + if err != nil { + return nil, err + } + links = append(links, bitbucketlink.ToSourceLinks(bitbucket)...) + } + return links, nil +} + +// planSync gives each link its share of the selection. Immutable selectors +// carry no owner, so with them the selection picks one link for everything. +// Otherwise the owner of each name picks its link. One invocation serves one +// source, because the two sources identify repositories differently. +func planSync(links []sourcelink.Link, sel sourcelink.Selection, in syncInput) ([]syncPlan, error) { + if len(in.RepositoryIDs) > 0 || len(in.RepositoryUUIDs) > 0 { + link, err := sourcelink.Pick(links, sel) + if err != nil { + return nil, err + } + return []syncPlan{{ + link: link, names: in.RepositoryNames, ids: in.RepositoryIDs, uuids: in.RepositoryUUIDs, + }}, nil + } + + groups, err := sourcelink.GroupByOwner(links, sel, in.RepositoryNames) + if err != nil { + return nil, err + } + plans := make([]syncPlan, 0, len(groups)) + for _, group := range groups { + if group.Link.Source != groups[0].Link.Source { + cause := errors.New("project sync: the names resolve to GitHub and Bitbucket accounts") + return nil, invalidRepositorySelectionError(cause, + "The names resolve to GitHub and Bitbucket accounts. Sync each source in its own command.") + } + plans = append(plans, syncPlan{link: group.Link, names: group.Names}) + } + return plans, nil +} + +// syncPlans prepares every plan before the first sync request, so a bad name +// in any plan materializes no project. It stops at the first failed request. +func syncPlans[R, P any]( + ctx context.Context, + plans []syncPlan, + prepare func(context.Context, syncPlan) (R, error), + sync func(context.Context, R) ([]P, error), +) ([]P, error) { + requests := make([]R, 0, len(plans)) + for _, plan := range plans { + req, err := prepare(ctx, plan) + if err != nil { + return nil, err + } + requests = append(requests, req) + } + + var projects []P + for i, req := range requests { + synced, err := sync(ctx, req) + if err != nil { + return nil, linkStoppedError(err, planLinks(plans[:i]), plans[i].link) + } + projects = append(projects, synced...) + } + return projects, nil +} + +func planLinks(plans []syncPlan) []sourcelink.Link { + links := make([]sourcelink.Link, 0, len(plans)) + for _, plan := range plans { + links = append(links, plan.link) + } + return links +} diff --git a/internal/cmd/project/sync_run_test.go b/internal/cmd/project/sync_run_test.go new file mode 100644 index 0000000..9b98da6 --- /dev/null +++ b/internal/cmd/project/sync_run_test.go @@ -0,0 +1,367 @@ +package project + +import ( + "context" + "testing" + + controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/services/controltower/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" +) + +// TestRunSync_PicksTheLink runs whole syncs against a tenant whose links the +// case sets, and checks which link each sync request went through. Every +// link sees the same repositories, so only link selection decides the +// outcome. +func TestRunSync_PicksTheLink(t *testing.T) { + type githubLinks = []*controltowerv1.ListGitHubAppInstallationLinksResponse_IntegrationWithAttributes + type bitbucketLinks = []*controltowerv1.ListBitbucketWorkspaceLinksResponse_WorkspaceLink + + cases := []struct { + name string + in syncInput + github githubLinks + bitbucket bitbucketLinks + bitbucketErr error + wantGitHub [][]int64 + wantGitHubVia []string + wantListedVia []string + wantBitbucket []string + wantErr []string + }{ + { + name: "an explicit source and link ID list nothing", + in: syncInput{Source: "bitbucket", LinkID: "bb-1", RepositoryUUIDs: []string{testBitbucketRepoUUIDa}}, + wantBitbucket: []string{"bb-1"}, + }, + { + name: "a repository ID selects GitHub before any listing", + in: syncInput{RepositoryIDs: []int64{7}}, + github: githubLinks{link("gh-1", "safedep")}, + bitbucket: bitbucketLinks{bitbucketWorkspaceLinkOf("bb-1", "foo")}, + wantGitHub: [][]int64{{7}}, + wantGitHubVia: []string{"gh-1"}, + }, + { + name: "a repository UUID selects Bitbucket before any listing", + in: syncInput{RepositoryUUIDs: []string{testBitbucketRepoUUIDa}}, + github: githubLinks{link("gh-1", "safedep")}, + bitbucket: bitbucketLinks{bitbucketWorkspaceLinkOf("bb-1", "foo")}, + wantBitbucket: []string{"bb-1"}, + }, + { + name: "a Bitbucket-only tenant syncs a name through its link", + in: syncInput{RepositoryNames: []string{"safedep/cli"}}, + bitbucket: bitbucketLinks{bitbucketWorkspaceLink("bb-1")}, + wantBitbucket: []string{"bb-1"}, + }, + { + name: "the owner picks the source when both are linked", + in: syncInput{RepositoryNames: []string{"SafeDep/cli"}}, + github: githubLinks{link("gh-1", "safedep")}, + bitbucket: bitbucketLinks{bitbucketWorkspaceLinkOf("bb-1", "foo")}, + wantGitHub: [][]int64{{12}}, + wantGitHubVia: []string{"gh-1"}, + }, + { + name: "two owners make one request per link", + in: syncInput{RepositoryNames: []string{"safedep/cli", "acme/app"}}, + github: githubLinks{link("gh-1", "safedep"), link("gh-2", "acme")}, + wantGitHub: [][]int64{{12}, {13}}, + wantGitHubVia: []string{"gh-1", "gh-2"}, + wantListedVia: []string{"gh-1", "gh-2"}, + }, + { + name: "an unknown owner lists the linked accounts", + in: syncInput{RepositoryNames: []string{"nope/cli"}}, + github: githubLinks{link("gh-1", "safedep"), link("gh-2", "acme")}, + wantErr: []string{`No linked account named "nope"`, "Linked accounts: acme, safedep."}, + }, + { + name: "the only link serves an owner when its login is empty", + in: syncInput{RepositoryNames: []string{"safedep/cli"}}, + github: githubLinks{link("gh-1", "")}, + wantGitHub: [][]int64{{12}}, + wantGitHubVia: []string{"gh-1"}, + }, + { + name: "the only link serves an owner its stale login misses", + in: syncInput{RepositoryNames: []string{"safedep/cli"}}, + github: githubLinks{link("gh-1", "old-name")}, + wantGitHub: [][]int64{{12}}, + wantGitHubVia: []string{"gh-1"}, + }, + { + name: "an owner linked on both sources needs --source", + in: syncInput{RepositoryNames: []string{"safedep/cli"}}, + github: githubLinks{link("gh-1", "safedep")}, + bitbucket: bitbucketLinks{bitbucketWorkspaceLink("bb-1")}, + wantErr: []string{"--source github or --source bitbucket"}, + }, + { + name: "--source settles an owner linked on both sources", + in: syncInput{Source: "bitbucket", RepositoryNames: []string{"safedep/cli"}}, + github: githubLinks{link("gh-1", "safedep")}, + bitbucket: bitbucketLinks{bitbucketWorkspaceLink("bb-1")}, + wantBitbucket: []string{"bb-1"}, + }, + { + name: "names on two sources are refused", + in: syncInput{RepositoryNames: []string{"safedep/cli", "foo/app"}}, + github: githubLinks{link("gh-1", "safedep")}, + bitbucket: bitbucketLinks{bitbucketWorkspaceLinkOf("bb-1", "foo")}, + wantErr: []string{"Sync each source in its own command"}, + }, + { + name: "--account picks the link for repository IDs", + in: syncInput{Account: "ACME", RepositoryIDs: []int64{7}}, + github: githubLinks{link("gh-1", "safedep"), link("gh-2", "acme")}, + wantGitHub: [][]int64{{7}}, + wantGitHubVia: []string{"gh-2"}, + }, + { + name: "--account serves every name, whatever its owner", + in: syncInput{Account: "acme", RepositoryNames: []string{"safedep/cli"}}, + github: githubLinks{link("gh-1", "safedep"), link("gh-2", "acme")}, + wantGitHub: [][]int64{{12}}, + wantGitHubVia: []string{"gh-2"}, + }, + { + name: "repository IDs with two links need --account", + in: syncInput{RepositoryIDs: []int64{7}}, + github: githubLinks{link("gh-1", "safedep"), link("gh-2", "acme")}, + wantErr: []string{"Retry with one of: --account acme, --account safedep."}, + }, + { + name: "--link-id and another --account conflict", + in: syncInput{LinkID: "gh-1", Account: "acme", RepositoryIDs: []int64{7}}, + github: githubLinks{link("gh-1", "safedep"), link("gh-2", "acme")}, + wantErr: []string{"Drop --link-id and retry with --account acme."}, + }, + { + name: "a hidden link ID picks its source for names when both are linked", + in: syncInput{LinkID: "bb-1", RepositoryNames: []string{"safedep/cli"}}, + github: githubLinks{link("gh-1", "safedep")}, + bitbucket: bitbucketLinks{bitbucketWorkspaceLink("bb-1")}, + wantBitbucket: []string{"bb-1"}, + }, + { + name: "an unknown link ID is not found", + in: syncInput{LinkID: "missing", RepositoryNames: []string{"safedep/cli"}}, + github: githubLinks{link("gh-1", "safedep")}, + bitbucket: bitbucketLinks{bitbucketWorkspaceLink("bb-1")}, + wantErr: []string{"Source link not found"}, + }, + { + name: "a control plane without the Bitbucket RPCs keeps GitHub working", + in: syncInput{RepositoryNames: []string{"safedep/cli"}}, + github: githubLinks{link("gh-1", "safedep")}, + bitbucketErr: status.Error(codes.Unimplemented, "unknown method"), + wantGitHub: [][]int64{{12}}, + wantGitHubVia: []string{"gh-1"}, + }, + { + name: "a caller without the Bitbucket permission cannot infer a source", + in: syncInput{RepositoryNames: []string{"safedep/cli"}}, + github: githubLinks{link("gh-1", "safedep")}, + bitbucketErr: status.Error(codes.PermissionDenied, "not allowed"), + wantErr: []string{"resolve workspace link"}, + }, + { + name: "any other Bitbucket listing failure stops the sync", + in: syncInput{RepositoryNames: []string{"safedep/cli"}}, + github: githubLinks{link("gh-1", "safedep")}, + bitbucketErr: status.Error(codes.Unavailable, "try again"), + wantErr: []string{"resolve workspace link"}, + }, + { + name: "no links at all is a not-found failure", + in: syncInput{RepositoryNames: []string{"safedep/cli"}}, + wantErr: []string{"No source integration link"}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + deps, githubSyncer, bitbucketSyncer := newTwoSourceDeps(tc.github, tc.bitbucket, tc.bitbucketErr) + + _, err := runSync(context.Background(), deps, tc.in) + if len(tc.wantErr) > 0 { + require.Error(t, err) + text := errorText(err) + for _, want := range tc.wantErr { + assert.Contains(t, text, want) + } + assert.Zero(t, githubSyncer.calls+bitbucketSyncer.calls, "a failed selection syncs nothing") + return + } + require.NoError(t, err) + + var via []string + var ids [][]int64 + for _, req := range githubSyncer.reqs { + via = append(via, req.GetLinkId()) + ids = append(ids, syncedIDs(req)) + } + assert.Equal(t, tc.wantGitHubVia, via) + assert.Equal(t, tc.wantGitHub, ids) + + if tc.wantListedVia != nil { + lister, ok := deps.githubRepositories.(*fakeGitHubRepositoryLister) + require.True(t, ok) + var listedVia []string + for _, req := range lister.requests { + listedVia = append(listedVia, req.GetLinkId()) + } + assert.Equal(t, tc.wantListedVia, listedVia, "each name resolves through its own link") + } + + var bitbucketVia []string + for _, req := range bitbucketSyncer.reqs { + bitbucketVia = append(bitbucketVia, req.GetLinkId()) + } + assert.Equal(t, tc.wantBitbucket, bitbucketVia) + }) + } +} + +func TestRunSync_SourceGitHubListsNoBitbucketLinks(t *testing.T) { + deps, syncer, _ := newTwoSourceDeps( + []*controltowerv1.ListGitHubAppInstallationLinksResponse_IntegrationWithAttributes{link("gh-1", "safedep")}, + nil, nil) + bitbucketLinks := &fakeBitbucketLinkLister{} + deps.bitbucketLinks = bitbucketLinks + + _, err := runSync(context.Background(), deps, syncInput{Source: "github", RepositoryNames: []string{"safedep/cli"}}) + require.NoError(t, err) + assert.Zero(t, bitbucketLinks.calls) + assert.Equal(t, 1, syncer.calls) +} + +func TestRunSync_ResolvesEveryNameBeforeTheFirstSync(t *testing.T) { + deps, githubSyncer, _ := newTwoSourceDeps( + []*controltowerv1.ListGitHubAppInstallationLinksResponse_IntegrationWithAttributes{ + link("gh-1", "safedep"), link("gh-2", "acme"), + }, nil, nil) + + _, err := runSync(context.Background(), deps, syncInput{RepositoryNames: []string{"safedep/cli", "acme/missing"}}) + require.ErrorContains(t, err, `repository "acme/missing" is not accessible`) + assert.Zero(t, githubSyncer.calls, "a bad name in the second group must stop the first group's sync") +} + +func TestRunSync_StopsAtAFailedLinkAndNamesTheAccounts(t *testing.T) { + deps, githubSyncer, _ := newTwoSourceDeps( + []*controltowerv1.ListGitHubAppInstallationLinksResponse_IntegrationWithAttributes{ + link("gh-1", "safedep"), link("gh-2", "acme"), + }, nil, nil) + githubSyncer.err = status.Error(codes.FailedPrecondition, "installation suspended") + githubSyncer.failOnCall = 2 + + // The names interleave the owners, so the first request carries the + // first and the third name. + _, err := runSync(context.Background(), deps, + syncInput{RepositoryNames: []string{"safedep/cli", "acme/app", "safedep/vet"}}) + require.Error(t, err) + require.Len(t, githubSyncer.reqs, 2) + assert.Equal(t, []int64{12, 14}, syncedIDs(githubSyncer.reqs[0])) + + usefulErr, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, "Sync through account acme failed", usefulErr.HumanError()) + assert.Equal(t, "Projects exist for the repositories of account safedep. "+ + "The request for account acme failed: installation suspended.", usefulErr.Help()) + assert.Equal(t, codes.FailedPrecondition, status.Code(err)) +} + +func TestRunSync_BitbucketWorkspaces(t *testing.T) { + bitbucketLinks := []*controltowerv1.ListBitbucketWorkspaceLinksResponse_WorkspaceLink{ + bitbucketWorkspaceLinkOf("bb-1", "safedep"), bitbucketWorkspaceLinkOf("bb-2", "foo"), + } + + t.Run("each workspace gets its own request", func(t *testing.T) { + deps, _, syncer := newTwoSourceDeps(nil, bitbucketLinks, nil) + + _, err := runSync(context.Background(), deps, syncInput{RepositoryNames: []string{"foo/app", "safedep/cli"}}) + require.NoError(t, err) + require.Len(t, syncer.reqs, 2) + assert.Equal(t, "bb-2", syncer.reqs[0].GetLinkId()) + assert.Equal(t, []string{testBitbucketRepoUUIDb}, syncedUUIDs(syncer.reqs[0])) + assert.Equal(t, "bb-1", syncer.reqs[1].GetLinkId()) + }) + + t.Run("a failed workspace names the written one", func(t *testing.T) { + deps, _, syncer := newTwoSourceDeps(nil, bitbucketLinks, nil) + syncer.err = status.Error(codes.Unavailable, "bitbucket unavailable") + syncer.failOnCall = 2 + + _, err := runSync(context.Background(), deps, syncInput{RepositoryNames: []string{"safedep/cli", "foo/app"}}) + require.Error(t, err) + usefulErr, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, "Sync through account foo failed", usefulErr.HumanError()) + assert.Contains(t, usefulErr.Help(), "Projects exist for the repositories of account safedep.") + assert.Contains(t, usefulErr.Help(), "Rerun the same command") + }) + + t.Run("a name that SafeDep does not scan fails before any write", func(t *testing.T) { + deps, _, syncer := newTwoSourceDeps(nil, bitbucketLinks, nil) + disabled := bitbucketListedRepository(testBitbucketRepoUUIDb, "foo/app") + disabled.SetScanState(controltowerv1.ListBitbucketRepositoriesResponse_BitbucketRepository_SCAN_STATE_DISABLED) + deps.bitbucketRepositories = &fakeBitbucketRepositoryLister{pages: []*controltowerv1.ListBitbucketRepositoriesResponse{ + bitbucketRepositoriesPage(bitbucketListedRepository(testBitbucketRepoUUIDa, "safedep/cli"), disabled), + }} + + _, err := runSync(context.Background(), deps, syncInput{RepositoryNames: []string{"safedep/cli", "foo/app"}}) + require.Error(t, err) + text := errorText(err) + assert.Contains(t, text, `SafeDep does not scan Bitbucket repository "foo/app"`) + assert.Contains(t, text, "safedep integration bitbucket allowlist update --account foo --enable "+testBitbucketRepoUUIDb) + assert.Zero(t, syncer.calls, "the enabled workspace must not be written either") + }) +} + +// newTwoSourceDeps fakes a tenant with the given links on both sources. Each +// source lists the same repositories for every link: GitHub safedep/cli (12), +// acme/app (13) and safedep/vet (14), Bitbucket safedep/cli and foo/app. +func newTwoSourceDeps( + github []*controltowerv1.ListGitHubAppInstallationLinksResponse_IntegrationWithAttributes, + bitbucket []*controltowerv1.ListBitbucketWorkspaceLinksResponse_WorkspaceLink, + bitbucketErr error, +) (syncDeps, *fakeGitHubProjectSyncer, *fakeBitbucketProjectSyncer) { + githubSyncer := &fakeGitHubProjectSyncer{} + bitbucketSyncer := &fakeBitbucketProjectSyncer{} + deps := syncDeps{ + githubLinks: &fakeGitHubLinkLister{pages: []*controltowerv1.ListGitHubAppInstallationLinksResponse{ + linksResponse("", github...), + }}, + githubRepositories: &fakeGitHubRepositoryLister{pages: []*controltowerv1.ListGitHubInstallationRepositoriesResponse{ + repositoriesResponse("", repository(12, "safedep/cli"), repository(13, "acme/app"), repository(14, "safedep/vet")), + }}, + githubSyncer: githubSyncer, + bitbucketLinks: &fakeBitbucketLinkLister{ + pages: []*controltowerv1.ListBitbucketWorkspaceLinksResponse{bitbucketLinksPage(bitbucket...)}, + err: bitbucketErr, + }, + bitbucketRepositories: &fakeBitbucketRepositoryLister{pages: []*controltowerv1.ListBitbucketRepositoriesResponse{ + bitbucketRepositoriesPage( + bitbucketListedRepository(testBitbucketRepoUUIDa, "safedep/cli"), + bitbucketListedRepository(testBitbucketRepoUUIDb, "foo/app"), + ), + }}, + bitbucketSyncer: bitbucketSyncer, + } + return deps, githubSyncer, bitbucketSyncer +} + +// errorText joins what a person reads of an error: the cause, the summary +// and the help. +func errorText(err error) string { + text := err.Error() + if usefulErr, ok := usefulerror.AsUsefulError(err); ok { + text += "\n" + usefulErr.HumanError() + "\n" + usefulErr.Help() + } + return text +} diff --git a/internal/cmd/project/sync_test.go b/internal/cmd/project/sync_test.go index a718e76..2915bf0 100644 --- a/internal/cmd/project/sync_test.go +++ b/internal/cmd/project/sync_test.go @@ -7,6 +7,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/safedep/cli/internal/sourcelink" ) func TestSyncCmd_PositionalArgumentsAreRepositoryNames(t *testing.T) { @@ -15,8 +17,9 @@ func TestSyncCmd_PositionalArgumentsAreRepositoryNames(t *testing.T) { cmd := syncCmd(nil) assert.Equal(t, "sync [OWNER/REPOSITORY...]", cmd.Use) - require.NotNil(t, cmd.Flags().Lookup("link-id")) require.NotNil(t, cmd.Flags().Lookup("repository-id")) + assert.Contains(t, cmd.UsageString(), "--account") + assert.NotContains(t, cmd.UsageString(), "--link-id", "the link ID flag is for scripts, not for people") require.NoError(t, cmd.Args(cmd, []string{"safedep/cli"})) @@ -97,6 +100,24 @@ func TestValidateSyncInput(t *testing.T) { in: syncInput{RepositoryIDs: []int64{7, 7}}, wantErr: "duplicate repository ID 7", }, + { + name: "an account with a slash", + in: syncInput{Account: "safedep/cli", RepositoryIDs: []int64{7}}, + wantErr: "is not an account name", + }, + {name: "--all with --account", in: syncInput{All: true, Account: "safedep"}}, + {name: "--all with a hidden link ID", in: syncInput{All: true, LinkID: "link-1", Source: "github"}}, + {name: "--all without an account", in: syncInput{All: true}, wantErr: "--all needs --account"}, + { + name: "--all with a name", + in: syncInput{All: true, Account: "safedep", RepositoryNames: []string{"safedep/cli"}}, + wantErr: "--all takes no repository names", + }, + { + name: "--all with a repository ID", + in: syncInput{All: true, Account: "safedep", RepositoryIDs: []int64{7}}, + wantErr: "--all takes no repository names", + }, } for _, tt := range tests { @@ -116,65 +137,92 @@ func TestValidateSyncInput(t *testing.T) { func TestSyncResult_RenderJSON(t *testing.T) { t.Parallel() - result := &syncResult{ - linkID: "link-1", - projects: []syncedProject{ - {RepositoryID: 1296269, RepositoryName: "safedep/cli", ProjectID: "project-1"}, - {RepositoryID: 10270250, ProjectID: "project-2"}, - }, + safedep := sourcelink.Link{Source: sourcelink.GitHub, ID: "link-1", Account: "safedep"} + acme := sourcelink.Link{Source: sourcelink.GitHub, ID: "link-2", Account: "acme"} + projects := []syncedProject{ + {RepositoryID: 1296269, RepositoryName: "safedep/cli", ProjectID: "project-1", Account: "safedep", LinkID: "link-1"}, + {RepositoryID: 10270250, ProjectID: "project-2", Account: "acme", LinkID: "link-2"}, } - got, err := result.RenderJSON() - require.NoError(t, err) - - var parsed struct { - LinkID string `json:"link_id"` - Projects []map[string]any `json:"projects"` - } - require.NoError(t, json.Unmarshal(got, &parsed)) - assert.Equal(t, "link-1", parsed.LinkID) - require.Len(t, parsed.Projects, 2) - assert.InDelta(t, 1296269, parsed.Projects[0]["repository_id"], 0) - assert.Equal(t, "safedep/cli", parsed.Projects[0]["repository_name"]) - assert.Equal(t, "project-1", parsed.Projects[0]["project_id"]) - assert.NotContains(t, parsed.Projects[1], "repository_name") + t.Run("one link keeps the top-level link ID and adds its account", func(t *testing.T) { + got, err := (&syncResult{links: []sourcelink.Link{safedep}, projects: projects[:1]}).RenderJSON() + require.NoError(t, err) + + var parsed map[string]any + require.NoError(t, json.Unmarshal(got, &parsed)) + assert.Equal(t, "link-1", parsed["link_id"]) + assert.Equal(t, "safedep", parsed["account"]) + project := parsed["projects"].([]any)[0].(map[string]any) + assert.InDelta(t, 1296269, project["repository_id"], 0) + assert.Equal(t, "safedep/cli", project["repository_name"]) + assert.Equal(t, "project-1", project["project_id"]) + assert.Equal(t, "safedep", project["account"]) + assert.Equal(t, "link-1", project["link_id"]) + }) + + t.Run("several links name the link on each project only", func(t *testing.T) { + got, err := (&syncResult{links: []sourcelink.Link{safedep, acme}, projects: projects}).RenderJSON() + require.NoError(t, err) + + var parsed map[string]any + require.NoError(t, json.Unmarshal(got, &parsed)) + assert.NotContains(t, parsed, "link_id") + assert.NotContains(t, parsed, "account") + second := parsed["projects"].([]any)[1].(map[string]any) + assert.NotContains(t, second, "repository_name") + assert.Equal(t, "acme", second["account"]) + }) } func TestSyncResult_RenderPlain(t *testing.T) { t.Parallel() result := &syncResult{ - linkID: "link-1", + links: []sourcelink.Link{{Source: sourcelink.GitHub, ID: "link-1"}}, projects: []syncedProject{ - {RepositoryID: 1296269, RepositoryName: "safedep/cli", ProjectID: "project-1"}, - {RepositoryID: 10270250, ProjectID: "project-2"}, + {RepositoryID: 1296269, RepositoryName: "safedep/cli", ProjectID: "project-1", Account: "safedep", LinkID: "link-1"}, + {RepositoryID: 10270250, ProjectID: "project-2", LinkID: "link-1"}, }, } lines := strings.Split(result.RenderPlain(), "\n") require.Len(t, lines, 3, "plain output is a header plus one line per project, nothing else") - assert.Equal(t, "repository_name\trepository_id\tproject_id", lines[0]) - assert.Equal(t, "safedep/cli\t1296269\tproject-1", lines[1]) - assert.Equal(t, "-\t10270250\tproject-2", lines[2]) - for i, line := range lines { - assert.NotContains(t, line, "link_id", "line %d", i) - } + assert.Equal(t, "repository_name\trepository_id\tproject_id\taccount", lines[0]) + assert.Equal(t, "safedep/cli\t1296269\tproject-1\tsafedep", lines[1]) + assert.Equal(t, "-\t10270250\tproject-2\t-", lines[2]) } func TestSyncResult_RenderTable(t *testing.T) { t.Parallel() - result := &syncResult{ - linkID: "link-1", - projects: []syncedProject{{RepositoryID: 1296269, RepositoryName: "safedep/cli", ProjectID: "project-1"}}, - } - - got := result.RenderTable() - for _, want := range []string{ - "REPOSITORY", "REPOSITORY ID", "PROJECT ID", - "safedep/cli", "1296269", "project-1", - "1 repository synced through link link-1", - } { - assert.Contains(t, got, want) - } + t.Run("one account", func(t *testing.T) { + result := &syncResult{ + links: []sourcelink.Link{{Source: sourcelink.GitHub, ID: "link-1", Account: "safedep"}}, + projects: []syncedProject{ + {RepositoryID: 1296269, RepositoryName: "safedep/cli", ProjectID: "project-1", Account: "safedep", LinkID: "link-1"}, + }, + } + got := result.RenderTable() + for _, want := range []string{ + "REPOSITORY", "REPOSITORY ID", "PROJECT ID", "ACCOUNT", + "safedep/cli", "1296269", "project-1", + "1 repository synced through account safedep", + } { + assert.Contains(t, got, want) + } + assert.NotContains(t, got, "link-1") + }) + + t.Run("a link without an account name shows its ID", func(t *testing.T) { + result := &syncResult{ + links: []sourcelink.Link{{Source: sourcelink.GitHub, ID: "link-1"}}, + projects: []syncedProject{{RepositoryID: 7, ProjectID: "project-7", LinkID: "link-1"}}, + } + assert.Contains(t, result.RenderTable(), "1 repository synced through link link-1") + }) + + t.Run("several accounts", func(t *testing.T) { + result := &syncResult{links: []sourcelink.Link{{ID: "link-1"}, {ID: "link-2"}}} + assert.Contains(t, result.RenderTable(), "0 repositories synced through 2 accounts") + }) } diff --git a/internal/sourcelink/sourcelink.go b/internal/sourcelink/sourcelink.go new file mode 100644 index 0000000..11ed51e --- /dev/null +++ b/internal/sourcelink/sourcelink.go @@ -0,0 +1,337 @@ +// Package sourcelink picks the tenant's GitHub or Bitbucket link that a +// command works through, from the account name a person knows instead of the +// internal link ID. It lives outside internal/cmd because both the project +// and the integration command trees need it, and sibling command packages +// must not import each other. +package sourcelink + +import ( + "errors" + "fmt" + "sort" + "strings" + + "github.com/safedep/dry/usefulerror" +) + +type Source string + +const ( + GitHub Source = "github" + Bitbucket Source = "bitbucket" +) + +// Link is one source link of the tenant. Account is the GitHub organization +// or user login, or the Bitbucket workspace slug. The server leaves it empty +// when it has no account name for the link. +type Link struct { + Source Source + ID string + Account string +} + +// Selection is what the caller asked for. An empty Source allows both +// sources. +type Selection struct { + Source Source + Account string + LinkID string +} + +// Group is the repository names one link serves, in argument order. +type Group struct { + Link Link + Names []string +} + +// Label names a link for people: its account, or its ID when the link has no +// account name. +func Label(account, linkID string) string { + if account != "" { + return account + } + return "link " + linkID +} + +// Describe names a link in a sentence: "account safedep", or "link " +// when the link has no account name. +func Describe(account, linkID string) string { + if account != "" { + return "account " + account + } + return Label(account, linkID) +} + +// Pick returns the one link the selection names. A link ID wins, and an +// account given with it must be the link's account. An account matches +// without regard to case, as GitHub logins do. Without either, the tenant +// must have exactly one link of the allowed sources. +func Pick(links []Link, sel Selection) (Link, error) { + links = ofSource(links, sel.Source) + if sel.LinkID != "" { + return pickByID(links, sel) + } + if len(links) == 0 { + return Link{}, noLinkError(sel.Source) + } + if sel.Account != "" { + matches := ofAccount(links, sel.Account) + if len(matches) == 0 { + return Link{}, notLinkedError(sel.Account, sel.Source, links, "") + } + return pickMatch(sel.Account, matches) + } + if len(links) > 1 { + return Link{}, ambiguousError(links) + } + return links[0], nil +} + +// GroupByOwner assigns every OWNER/REPOSITORY name to a link. An account or +// a link ID in the selection serves every name. Otherwise the owner of each +// name picks the link with that account. When no link has the owner's +// account and the allowed sources hold exactly one link, that link serves +// the name: the account name can be stale or missing, and a single link +// needs no choice. +func GroupByOwner(links []Link, sel Selection, names []string) ([]Group, error) { + if sel.LinkID != "" || sel.Account != "" { + link, err := Pick(links, sel) + if err != nil { + return nil, err + } + return []Group{{Link: link, Names: append([]string{}, names...)}}, nil + } + + allowed := ofSource(links, sel.Source) + var groups []Group + index := map[string]int{} + for _, name := range names { + owner, _, _ := strings.Cut(name, "/") + link, err := pickOwner(allowed, sel.Source, owner) + if err != nil { + return nil, err + } + i, ok := index[link.ID] + if !ok { + i = len(groups) + index[link.ID] = i + groups = append(groups, Group{Link: link}) + } + groups[i].Names = append(groups[i].Names, name) + } + return groups, nil +} + +func pickOwner(links []Link, source Source, owner string) (Link, error) { + if len(links) == 0 { + return Link{}, noLinkError(source) + } + matches := ofAccount(links, owner) + if len(matches) > 0 { + return pickMatch(owner, matches) + } + if len(links) == 1 { + return links[0], nil + } + return Link{}, notLinkedError(owner, source, links, sourceFallbackHint(links)) +} + +// sourceFallbackHint names the --source values under which the owner's name +// resolves. Under one source, the only link of that source serves any owner. +func sourceFallbackHint(links []Link) string { + if !spansSources(links) { + return "" + } + var hints []string + for _, source := range []Source{GitHub, Bitbucket} { + if len(ofSource(links, source)) == 1 { + hints = append(hints, fmt.Sprintf("--source %s to use the only %s link", source, sourceTitle(source))) + } + } + if len(hints) == 0 { + return "" + } + return " Or retry with " + strings.Join(hints, ", or ") + "." +} + +func pickByID(links []Link, sel Selection) (Link, error) { + for _, link := range links { + if link.ID != sel.LinkID { + continue + } + if sel.Account != "" && !strings.EqualFold(link.Account, sel.Account) { + return Link{}, conflictError(link, sel.Account) + } + return link, nil + } + return Link{}, usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrNotFound). + WithHumanError("Source link not found"). + WithHelp("Drop --link-id and retry with --account set to the GitHub organization or user, or the Bitbucket workspace."). + Wrap(fmt.Errorf("link %q is not a %s link of the active tenant", sel.LinkID, sourceNoun(sel.Source))) +} + +func pickMatch(account string, matches []Link) (Link, error) { + if len(matches) == 1 { + return matches[0], nil + } + if spansSources(matches) { + return Link{}, usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrBadRequest). + WithHumanError(fmt.Sprintf("Account %q is linked on GitHub and Bitbucket", account)). + WithHelp("Retry with --source github or --source bitbucket."). + Wrap(fmt.Errorf("account %q has a GitHub link and a Bitbucket link", account)) + } + // One account on two links of one source happens when GitHub misses an + // uninstall webhook, or when a login is reused. GitHub links never get a + // revocation time, so the server lists both. Only the link ID tells them + // apart. + ids := make([]string, 0, len(matches)) + for _, link := range matches { + ids = append(ids, link.ID) + } + sort.Strings(ids) + return Link{}, usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrBadRequest). + WithHumanError(fmt.Sprintf("Account %q has more than one %s link", account, sourceTitle(matches[0].Source))). + WithHelp(fmt.Sprintf("Retry with --link-id set to one of: %s.", strings.Join(ids, ", "))). + Wrap(fmt.Errorf("account %q has %d %s links", account, len(matches), matches[0].Source)) +} + +func noLinkError(source Source) error { + switch source { + case GitHub: + return usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrNotFound). + WithHumanError("No GitHub App installation link"). + WithHelp("Install the SafeDep GitHub App and link it to this tenant, then retry."). + Wrap(errors.New("the active tenant has no GitHub App installation link")) + case Bitbucket: + return usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrNotFound). + WithHumanError("No linked Bitbucket workspace"). + WithHelp("Create a link code with `safedep integration bitbucket link create`, redeem it in the " + + "workspace's SafeDep settings page in Bitbucket, then retry."). + Wrap(errors.New("the active tenant has no linked bitbucket workspace")) + default: + return usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrNotFound). + WithHumanError("No source integration link"). + WithHelp("Install and link the SafeDep GitHub App, or link a Bitbucket workspace, then retry."). + Wrap(errors.New("the active tenant has no GitHub or Bitbucket link")) + } +} + +func notLinkedError(account string, source Source, links []Link, hint string) error { + var addHelp string + switch source { + case GitHub: + addHelp = fmt.Sprintf("To add %q, install the SafeDep GitHub App on it and link it in SafeDep Cloud.", account) + case Bitbucket: + addHelp = fmt.Sprintf("To add %q, create a link code with `safedep integration bitbucket link create` "+ + "and redeem it in the workspace's SafeDep settings page in Bitbucket.", account) + default: + addHelp = fmt.Sprintf("To add %q, link the GitHub organization or user in SafeDep Cloud, "+ + "or link the Bitbucket workspace with `safedep integration bitbucket link create`.", account) + } + return usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrNotFound). + WithHumanError(fmt.Sprintf("No linked account named %q", account)). + WithHelp(fmt.Sprintf("Linked accounts: %s. %s%s", strings.Join(choices(links, false), ", "), addHelp, hint)). + Wrap(fmt.Errorf("no %s link of the active tenant has account %q", sourceNoun(source), account)) +} + +func ambiguousError(links []Link) error { + return usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrBadRequest). + WithHumanError("More than one linked account"). + WithHelp(fmt.Sprintf("Retry with one of: %s.", strings.Join(choices(links, true), ", "))). + Wrap(fmt.Errorf("the active tenant has %d source links", len(links))) +} + +func conflictError(link Link, account string) error { + if link.Account == "" { + return usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrBadRequest). + WithHumanError("--account and --link-id name different links"). + WithHelp(fmt.Sprintf("Link %s has no account name. Drop --account and retry with --link-id %s alone.", + link.ID, link.ID)). + Wrap(fmt.Errorf("link %q has no account name, not %q", link.ID, account)) + } + return usefulerror.NewUsefulError(). + WithCode(usefulerror.ErrBadRequest). + WithHumanError("--account and --link-id name different links"). + WithHelp(fmt.Sprintf("Drop --link-id and retry with --account %s.", account)). + Wrap(fmt.Errorf("link %q belongs to account %q, not %q", link.ID, link.Account, account)) +} + +// choices names each link the way a person picks it: by account, or by +// --link-id when the link has no account name. The source follows each +// entry only when the links span both sources. +func choices(links []Link, withFlag bool) []string { + tagSource := spansSources(links) + out := make([]string, 0, len(links)) + for _, link := range links { + var entry string + switch { + case link.Account == "": + entry = "--link-id " + link.ID + case withFlag: + entry = "--account " + link.Account + default: + entry = link.Account + } + if tagSource { + entry += fmt.Sprintf(" (%s)", link.Source) + } + out = append(out, entry) + } + sort.Strings(out) + return out +} + +func ofSource(links []Link, source Source) []Link { + if source == "" { + return links + } + var out []Link + for _, link := range links { + if link.Source == source { + out = append(out, link) + } + } + return out +} + +func ofAccount(links []Link, account string) []Link { + var out []Link + for _, link := range links { + if link.Account != "" && strings.EqualFold(link.Account, account) { + out = append(out, link) + } + } + return out +} + +func spansSources(links []Link) bool { + for _, link := range links { + if link.Source != links[0].Source { + return true + } + } + return false +} + +func sourceTitle(source Source) string { + if source == Bitbucket { + return "Bitbucket" + } + return "GitHub" +} + +func sourceNoun(source Source) string { + if source == "" { + return "GitHub or Bitbucket" + } + return sourceTitle(source) +} diff --git a/internal/sourcelink/sourcelink_test.go b/internal/sourcelink/sourcelink_test.go new file mode 100644 index 0000000..8344b46 --- /dev/null +++ b/internal/sourcelink/sourcelink_test.go @@ -0,0 +1,286 @@ +package sourcelink + +import ( + "strings" + "testing" + + "github.com/safedep/dry/usefulerror" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var ( + ghSafedep = Link{Source: GitHub, ID: "gh-1", Account: "SafeDep"} + ghAcme = Link{Source: GitHub, ID: "gh-2", Account: "acme"} + ghNoName = Link{Source: GitHub, ID: "gh-3"} + bbSafedep = Link{Source: Bitbucket, ID: "bb-1", Account: "safedep"} + bbFoo = Link{Source: Bitbucket, ID: "bb-2", Account: "foo"} +) + +func TestPick(t *testing.T) { + cases := []struct { + name string + links []Link + sel Selection + want Link + wantCode string + wantHelp []string + }{ + {name: "the only link", links: []Link{ghAcme}, want: ghAcme}, + { + name: "an account matches without regard to case", links: []Link{ghSafedep, ghAcme}, + sel: Selection{Account: "safedep"}, want: ghSafedep, + }, + { + name: "a source keeps the other source out", links: []Link{ghSafedep, bbFoo}, + sel: Selection{Source: Bitbucket}, want: bbFoo, + }, + { + name: "an account on both sources needs a source", links: []Link{ghSafedep, bbSafedep}, + sel: Selection{Account: "safedep"}, wantCode: usefulerror.ErrBadRequest, + wantHelp: []string{"--source github or --source bitbucket"}, + }, + { + name: "a source settles an account on both sources", links: []Link{ghSafedep, bbSafedep}, + sel: Selection{Source: Bitbucket, Account: "safedep"}, want: bbSafedep, + }, + { + name: "an unknown account lists the linked accounts", links: []Link{ghSafedep, bbFoo, ghNoName}, + sel: Selection{Account: "nope"}, wantCode: usefulerror.ErrNotFound, + wantHelp: []string{"Linked accounts: --link-id gh-3 (github), SafeDep (github), foo (bitbucket).", `To add "nope"`}, + }, + { + name: "an unknown Bitbucket account points to link create", links: []Link{bbFoo}, + sel: Selection{Source: Bitbucket, Account: "nope"}, wantCode: usefulerror.ErrNotFound, + wantHelp: []string{"safedep integration bitbucket link create"}, + }, + { + name: "an account never matches a link without an account name", links: []Link{ghNoName}, + sel: Selection{Account: "gh-3"}, wantCode: usefulerror.ErrNotFound, + }, + { + name: "two links of one account list their IDs", + links: []Link{ghSafedep, {Source: GitHub, ID: "gh-9", Account: "safedep"}}, + sel: Selection{Account: "safedep"}, wantCode: usefulerror.ErrBadRequest, + wantHelp: []string{"--link-id set to one of: gh-1, gh-9"}, + }, + { + name: "more than one link lists accounts and the IDs of unnamed links", links: []Link{ghSafedep, ghAcme, ghNoName}, + wantCode: usefulerror.ErrBadRequest, + wantHelp: []string{"Retry with one of: --account SafeDep, --account acme, --link-id gh-3."}, + }, + {name: "no link", wantCode: usefulerror.ErrNotFound, wantHelp: []string{"GitHub App, or link a Bitbucket workspace"}}, + { + name: "a link ID picks its link", links: []Link{ghSafedep, bbFoo}, + sel: Selection{LinkID: "bb-2"}, want: bbFoo, + }, + { + name: "a link ID with its own account passes", links: []Link{ghSafedep}, + sel: Selection{LinkID: "gh-1", Account: "SAFEDEP"}, want: ghSafedep, + }, + { + name: "a link ID with another account conflicts", links: []Link{ghSafedep, ghAcme}, + sel: Selection{LinkID: "gh-1", Account: "acme"}, wantCode: usefulerror.ErrBadRequest, + wantHelp: []string{"Drop --link-id and retry with --account acme."}, + }, + { + name: "a link ID without an account name and an --account conflict", links: []Link{ghNoName}, + sel: Selection{LinkID: "gh-3", Account: "acme"}, wantCode: usefulerror.ErrBadRequest, + wantHelp: []string{"Link gh-3 has no account name. Drop --account and retry with --link-id gh-3 alone."}, + }, + { + name: "an unknown link ID", links: []Link{ghSafedep}, + sel: Selection{LinkID: "missing"}, wantCode: usefulerror.ErrNotFound, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := Pick(tc.links, tc.sel) + if tc.wantCode == "" { + require.NoError(t, err) + assert.Equal(t, tc.want, got) + return + } + require.Error(t, err) + usefulErr, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Equal(t, tc.wantCode, usefulErr.Code()) + for _, want := range tc.wantHelp { + assert.Contains(t, usefulErr.Help(), want) + } + }) + } +} + +func TestGroupByOwner(t *testing.T) { + cases := []struct { + name string + links []Link + sel Selection + names []string + want []Group + wantErr string + }{ + { + name: "each owner picks its link, in first-seen order", + links: []Link{ghSafedep, ghAcme}, + names: []string{"acme/a", "safedep/b", "ACME/c"}, + want: []Group{{Link: ghAcme, Names: []string{"acme/a", "ACME/c"}}, {Link: ghSafedep, Names: []string{"safedep/b"}}}, + }, + { + name: "the owner decides the source", + links: []Link{ghAcme, bbFoo}, + names: []string{"foo/a"}, + want: []Group{{Link: bbFoo, Names: []string{"foo/a"}}}, + }, + { + name: "the only link serves an owner without an account name", + links: []Link{ghNoName}, + names: []string{"safedep/a"}, + want: []Group{{Link: ghNoName, Names: []string{"safedep/a"}}}, + }, + { + name: "the only link serves an owner its stale account name misses", + links: []Link{{Source: GitHub, ID: "gh-1", Account: "old-name"}}, + names: []string{"new-name/a"}, + want: []Group{{Link: Link{Source: GitHub, ID: "gh-1", Account: "old-name"}, Names: []string{"new-name/a"}}}, + }, + { + name: "the only link of the selected source serves an unknown owner", + links: []Link{ghAcme, bbFoo}, + sel: Selection{Source: Bitbucket}, + names: []string{"other/a"}, + want: []Group{{Link: bbFoo, Names: []string{"other/a"}}}, + }, + { + name: "an unknown owner among several links fails", + links: []Link{ghSafedep, ghAcme}, + names: []string{"safedep/a", "nope/b"}, + wantErr: `no GitHub or Bitbucket link of the active tenant has account "nope"`, + }, + { + name: "an unknown owner across both sources points to the one-link source", + links: []Link{ghSafedep, ghAcme, bbFoo}, + names: []string{"nope/b"}, + wantErr: "Or retry with --source bitbucket to use the only Bitbucket link.", + }, + { + name: "an account serves every name", + links: []Link{ghSafedep, ghAcme}, + sel: Selection{Account: "acme"}, + names: []string{"safedep/a", "acme/b"}, + want: []Group{{Link: ghAcme, Names: []string{"safedep/a", "acme/b"}}}, + }, + { + name: "a link ID serves every name", + links: []Link{ghSafedep, bbFoo}, + sel: Selection{LinkID: "bb-2"}, + names: []string{"safedep/a"}, + want: []Group{{Link: bbFoo, Names: []string{"safedep/a"}}}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := GroupByOwner(tc.links, tc.sel, tc.names) + if tc.wantErr != "" { + require.Error(t, err) + usefulErr, ok := usefulerror.AsUsefulError(err) + require.True(t, ok) + assert.Contains(t, err.Error()+"\n"+usefulErr.Help(), tc.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tc.want, got) + }) + } +} + +func FuzzGroupByOwner(f *testing.F) { + pool := []Link{ghSafedep, ghAcme, ghNoName, bbSafedep, bbFoo, {Source: GitHub, ID: "gh-4", Account: "ACME"}} + sources := []Source{"", GitHub, Bitbucket} + for _, seed := range []struct { + names string + source uint8 + links uint8 + account string + }{ + {"safedep/vet,acme/api", 0, 0b000011, ""}, + {"SAFEDEP/vet", 1, 0b000001, ""}, + {"safedep/vet", 0, 0b001001, ""}, + {"safedep/vet", 2, 0b001001, ""}, + {"stale/repo", 1, 0b000100, ""}, + {"acme/api", 1, 0b100010, ""}, + {"nope/x,foo/y", 2, 0b011000, ""}, + {"a/b,c/d", 0, 0b000011, "acme"}, + {"noslash,/x,x/", 0, 0b000001, ""}, + {"", 0, 0, ""}, + } { + f.Add(seed.names, seed.source, seed.links, seed.account) + } + f.Fuzz(func(t *testing.T, rawNames string, sourceIndex, linkBits uint8, account string) { + var links []Link + for i, link := range pool { + if linkBits&(1<