diff --git a/CHANGELOG.md b/CHANGELOG.md index ae4b17e..5f980c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `repo collaborator remove --yes` removes a collaborator from a repository (`-R` or the current one); gh has no such command. Without `--yes` it fails with `--yes required when not running interactively` before anything else. It checks `GET /repos/{owner}/{repo}/collaborators/{login}` first, since Gitea answers 204 to a delete of a non-collaborator: a 404 fails with ` is not a collaborator of /`. Then it sends `DELETE /repos/{owner}/{repo}/collaborators/{login}` and prints `Removed from /`. A login that is not a Gitea login fails before the request; Copia's other refusals are shown with the HTTP status and its message (#50) +- `repo collaborator list` (alias `ls`) and `repo collaborator add ` manage the collaborators of a repository (`-R` or the current one); gh has no such commands. `list` reads `GET /repos/{owner}/{repo}/collaborators` up to `-L/--limit` (default 30): the columns LOGIN and NAME, `--json` takes `login` and `full_name`, with `--jq` and `--template`; none prints `no collaborators found in /` on standard error, exit 0. It shows no permission: Copia answers Gitea's `GET /repos/{owner}/{repo}/collaborators/{login}/permission` with a plain-text `404 page not found` (the route is not registered). `add` sends `PUT /repos/{owner}/{repo}/collaborators/{login}` with `-p/--permission` `read`, `write` (the default, Gitea's) or `admin`, then `Added to / with permission`, also when the user was a collaborator already (Gitea changes the permission). Any other permission, and a login that is not a Gitea login, fail before the request; an unknown user fails with `user not found`, Copia's other refusals are shown with the HTTP status and its message (#486) +- `gpg-key delete ` deletes a GPG key from your Copia account, as in `gh`. The key is named by its GPG key ID, compared regardless of case, and looked up on every page of `GET /user/gpg_keys` (Gitea answers 204 to a delete of an unknown id); no match fails with `unable to delete GPG key : either the GPG key is not found or it is not owned by you`, a match is deleted with `DELETE /user/gpg_keys/{id}`, then `GPG key deleted from your account`. There is no prompt, so `-y/--yes` is required (`--yes required when not running interactively`). Copia's refusals are shown with the HTTP status and its message (#483) +- `gpg-key list` (alias `ls`) and `gpg-key add []` manage the GPG keys of your Copia account, as in `gh`. `list` reads every page of `GET /user/gpg_keys`: the columns EMAIL (the key's emails joined with `, `), KEY ID, PUBLIC KEY (cut in the middle on a terminal), ADDED and EXPIRES (`Never` or the date on a terminal, RFC 3339 without one); `--json` takes `id`, `key_id`, `primary_key_id`, `emails`, `public_key`, `created_at`, `expires_at`, `verified` and `can_sign`, with `--jq` and `--template`. No keys prints `no GPG keys present in the Copia account` on standard error, exit 0. `add` reads the armored key file, or standard input with `-` or without an argument when standard input is not a terminal, and sends it with `POST /user/gpg_keys`, then `GPG key added to your account`. Copia adds only a key whose email is a verified email of the account; its 404 for any other key is shown with a hint to add and verify that email (Copia has no `GET /user/gpg_key_token`, so Gitea's signature route and a `--signature` flag do not apply). A key Copia already has fails with `the key already exists in your account`; only public key blocks are sent: a private or secret key of any armored format (PGP, OpenSSH, PKCS#8, RSA, EC, DSA), also after a public block, is refused, and any other content fails with gh's hint that the key might not be ASCII-armored, both before any request. Copia's refusals are shown with the HTTP status and its message (cut to 512 bytes, read from at most 64 KiB of the response); a message that quotes the key, also re-wrapped or joined, is left out. gh's `-t/--title` is left out, since Gitea's GPG keys have no title (#482) - `repo sync [-s/--source owner/repo] [-b/--branch branch] [--force]` syncs a branch of the local clone from a git remote, as `gh repo sync` does: the source is `--source` or the default repository (`-R`, `repo set-default`, else `origin`), the branch defaults to the source's default branch, `git fetch` gets the token only for an https remote on the configured host, and the branch is fast-forwarded (`merge --ff-only` when checked out, `branch --force` otherwise, created when missing). Diverging changes fail unless `--force` (`reset --hard`), and a dirty working tree is refused, both with gh's messages; success prints `Synced the "" branch from "/" to local repository`. `repo sync ` syncs a fork from its parent through `POST /repos/{owner}/{repo}/merge-upstream` fast-forward only; app.copia.io has no such route, so there it fails with `Copia does not offer fork sync through its API` (#45) - `repo archive [] --yes` and `repo unarchive [] --yes` archive and unarchive the given repository, the current one or `-R`, as in `gh`: `PATCH /repos/{owner}/{repo}` with `archived`, then `Archived repository /` or `Unarchived repository /`. A repository already in that state gets `! Repository / is already archived` (or `is not archived`) on standard error, no change and exit 0; without `-y/--yes` both fail with `--yes required when not running interactively` before any API call. `repo view --json` gains the `archived` field (#462) - `repo rename --yes` renames the current repository or `-R`, as in `gh`: `PATCH /repos/{owner}/{repo}` with the new name, then `Renamed repository /`. A name with `/` fails with gh's message and makes no API call; without `-y/--yes` it fails with `renaming / to needs confirmation; use --yes to confirm`. Without `-R` the git remote that points at the old repository on the configured host (the `repo set-default` one first, then `origin`) gets the new name with `git remote set-url`, keeping its scheme, user, host and `.git` suffix, and `Updated the "" remote` is printed; when no remote matches or git fails, a warning goes to standard error and the command still succeeds (#461) diff --git a/CLAUDE.md b/CLAUDE.md index dda7aed..5671588 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -85,7 +85,7 @@ copia-cli/ Phase 1 (MVP): auth, repo list/view/clone, issue CRUD, pr CRUD, label list/create — **DONE** Phase 2: release CRUD, repo create/delete/fork, pr review/diff/checkout, issue edit, Homebrew tap — **DONE** Phase 3: `copia-cli api` escape hatch, search, orgs, notifications, `-R` flag, completion, Jekyll manual, AGPL license — **DONE** -Phase 4: ~~winget~~, ~~COPR~~, ~~AUR~~, ~~Snap~~, ~~OS keyring~~, ~~aliases~~, ~~browse~~, ~~status dashboard~~, ssh-key, pr checks, changelog, collaborators +Phase 4: ~~winget~~, ~~COPR~~, ~~AUR~~, ~~Snap~~, ~~OS keyring~~, ~~aliases~~, ~~browse~~, ~~status dashboard~~, gpg-key (list and add done; ssh-key dropped, Copia has SSH disabled), pr checks, changelog, collaborators **Out of scope:** workflow/run, codespace, copilot, project, cache, GUI @@ -93,4 +93,4 @@ Phase 4: ~~winget~~, ~~COPR~~, ~~AUR~~, ~~Snap~~, ~~OS keyring~~, ~~aliases~~, ~ - `docs/api-reference.md` — Full Gitea API endpoint mapping with request/response examples - `docs/authentication.md` — Auth methods, token generation, config file format, multi-instance setup -- `docs/parity.md` — Feature parity tracker against the Gitea 1.26 API (84 implementable: 76 implemented, 4 full, 4 partial; 13 impossible) +- `docs/parity.md` — Feature parity tracker against the Gitea 1.26 API (86 implementable: 81 implemented, 1 full, 4 partial; 15 impossible) diff --git a/docs/parity.md b/docs/parity.md index c9a4f1b..13c18fe 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -48,7 +48,7 @@ Token storage follows gh: `auth login` stores the token in the OS keyring (go-ke | `gh repo edit` | Full | `copia-cli repo edit` | [x] | | `gh repo set-default` | n/a | `copia-cli repo set-default` | [x] | | `gh repo sync` | Partial | `copia-cli repo sync` | [x] | -| `gh repo deploy-key` | Full | `copia-cli repo deploy-key` | [ ] | +| `gh repo deploy-key` | None | n/a, app.copia.io has SSH disabled | — | `gh repo view --web/-w`: client side, no API call and no token, opened as for the issue commands: `/{owner}/{repo}` of the argument, `-R` or the git remote. gh's `--branch` does not exist in `repo view`. @@ -64,7 +64,7 @@ Token storage follows gh: `auth login` stores the token in the OS keyring (go-ke `gh repo sync`: Partial. Without an argument it syncs the local clone with git, as gh does: the source is `-s/--source owner/repo` or the default repository (`-R`, the remote marked by `repo set-default`, else `origin`) and must be one of the git remotes (owner and name in any case), the branch is `-b/--branch` or the source's `default_branch` from `GET /repos/{owner}/{repo}`. `git fetch` of the branch from that remote gets the token only when the remote's URL is https on the configured host (the scoped credential helper of `repo clone`), then a checked-out branch is fast-forwarded with `merge --ff-only`, another one is moved with `branch --force`, a missing one is created tracking the remote. Diverged branches fail with gh's message unless `--force`, which uses `reset --hard`; a dirty working tree on the checked-out branch is refused with gh's message. With an argument (`owner/repo`) gh syncs a fork from its parent on the server. app.copia.io has no `/repos/{owner}/{repo}/merge-upstream` route: `POST` answers the plain-text `404 page not found` of an unknown path (found by the `integration` job of #45, 2026-11-07), so the remote mode reports `Copia does not offer fork sync through its API`, as Copia has no forks either (`gh repo fork`). Against a Gitea-compatible server that serves the route it sends `{"branch", "ff_only": true}` (the branch defaults to the repository's `default_branch`), prints `Synced the ":" branch from its parent` or that it is already up to date, and reports `/ is not a fork` and diverging changes (gh's message, pointing at a local `--force`); `--force` and `-s/--source` are refused with an argument, since the endpoint only fast-forwards from the parent. Differences from gh: the success line is printed also without a terminal, and gh's worktree hints on a branch checked out in another worktree are left out (git's own error is shown). -`gh repo deploy-key`: `GET` and `POST /repos/{owner}/{repo}/keys`, `DELETE /repos/{owner}/{repo}/keys/{id}` for list, add and delete. +`gh repo deploy-key`: None on Copia. Gitea serves deploy keys at `/repos/{owner}/{repo}/keys`, but a deploy key only grants access over SSH, and app.copia.io has SSH disabled: it answers `POST /user/keys` with 422 `SSH is disabled` (found by the `integration` job of #487, 2026-11-08), see `gh ssh-key`. ## issue @@ -194,6 +194,24 @@ Client side, no API call. The keys are `output` (`table` or `json`, default `tab Client side, no API call. Aliases are stored under the top-level key `aliases` of `config.yml` and expanded before the command runs when the alias is the first argument, as in gh: `$1`, `$2` and so on take the arguments after the alias, otherwise they are appended, and an expansion that starts with `!` (or was set with `--shell/-s`) runs through `sh -c` with the arguments as `$1`, `$2`. Differences from gh: an argument fills a placeholder after the expansion is split into words, so it is never split again (gh replaces the placeholders in the text and splits afterwards); an alias name may not be empty, start with `-` or contain blanks, and the expansion of an alias that is no shell alias must start with a copia-cli command (gh also accepts an extension or another alias, which copia-cli does not have or expand); a built-in command also wins over an alias of the same name that was written into the config file by hand; `alias list` and `alias set`, `delete` and `import` print their messages whether or not the output is a terminal, and `alias import` exits with an error when it refused an alias, after it imported the others (gh exits 0). +## gpg-key + +| gh command | Parity | Copia CLI | Status | +|-----------|--------|-----------|--------| +| `gh gpg-key list` | Full | `copia-cli gpg-key list` | [x] | +| `gh gpg-key add` | Full | `copia-cli gpg-key add` | [x] | +| `gh gpg-key delete` | Full | `copia-cli gpg-key delete` | [x] | + +The keys are those of the authenticated Copia account (`/user/gpg_keys`). + +`gh gpg-key list`: every page of `GET /user/gpg_keys`. On a terminal the columns are gh's EMAIL (the key's emails joined with `, `; Gitea lists only the emails that are verified emails of the account), KEY ID, PUBLIC KEY (cut in the middle to fit the terminal width), ADDED (the time in words) and EXPIRES (`Never` or the date); without a terminal the same columns tab-separated without a header, the times in RFC 3339 as Gitea gives them. Gitea's `public_key` is its base64 encoding of the primary key packet, not the armored key. `--json` takes `id`, `key_id`, `primary_key_id`, `emails`, `public_key`, `created_at`, `expires_at`, `verified` and `can_sign` (gh has no `--json` here), with `--jq` and `--template`. No keys prints `no GPG keys present in the Copia account` on standard error and exits 0; with `--json` it prints `[]`. + +`gh gpg-key add []`: reads the file, or standard input with `-` or without an argument when standard input is not a terminal (on a terminal it fails with gh's `GPG key file missing`), and sends it as `armored_public_key` with `POST /user/gpg_keys`, then `GPG key added to your account`, printed on standard output also without a terminal (gh prints it on a terminal only). Only public key blocks are sent: every line holding `-----BEGIN ` must be `-----BEGIN PGP PUBLIC KEY BLOCK-----`, and one must exist. A header that names `PRIVATE` or `SECRET` (a PGP private or secret key block, an OpenSSH, PKCS#8, RSA, EC or DSA private key, also after a public block) is refused with `the key file holds a private key`, any other content with gh's hint that the key might not be ASCII-armored (`gpg --armor --export | copia-cli gpg-key add -`), both before any request; gh sends both and reads the server's 422. Gitea's 422 `A key with the same id already exists` becomes gh's `the key already exists in your account`, exit 1. gh's `-t/--title` is left out: Gitea's GPG keys have no title. + +Copia adds only a key whose email is a verified email of the account. For any other key Gitea answers 404 `None of the emails attached to the GPG key could be found. It may still be added if you provide a valid signature for the token: `; copia-cli shows the first sentence with the HTTP status and a hint to add and verify the key's email in the Copia settings, never the token. Gitea's other route, a detached signature over the token of `GET /user/gpg_key_token` sent as `armored_signature`, does not exist on Copia: app.copia.io answers that route with Go's plain-text `404 page not found` (the route is not registered), so copia-cli has no `--signature` flag, like gh. Gitea's other refusals are shown with the HTTP status and Gitea's words, cut to 512 bytes and read from at most 64 KiB of the response (as for every paged list); a message that holds 16 bytes in a row of the key's material, compared without white space so a re-wrapped or joined quote counts, is left out and only the HTTP status is shown. + +`gh gpg-key delete `: the key is named by its GPG key ID, as `gpg-key list` shows it, compared regardless of case (gh compares it exactly), and looked up on every page of `GET /user/gpg_keys`, since Gitea answers 204 to a `DELETE` of an unknown id. No match fails with gh's `unable to delete GPG key : either the GPG key is not found or it is not owned by you` before any `DELETE`; a match is deleted with `DELETE /user/gpg_keys/{id}`, then `GPG key deleted from your account`, printed on standard output also without a terminal (gh prints it on a terminal only). There is no prompt: without `-y/--yes` it fails with gh's `--yes required when not running interactively`, before any request. Gitea's refusals are shown with the HTTP status and Gitea's words. The integration test deletes a random key ID (not found) and checks the list, since no test adds a key (see `gh gpg-key add`); the delete of an existing key is covered by the unit tests. + ## Other implemented commands | Command | Status | @@ -209,13 +227,14 @@ Client side, no API call. Aliases are stored under the top-level key `aliases` o | `copia-cli browse` (`gh browse`: repository, issue or PR number, commit SHA (`/commit/{sha}`), ``, `:` and `:-` (`/src/branch/{branch}/{path}`, with a line `?display=source#L{n}` or `#L{n}-L{m}`, Gitea's counterpart of gh's `?plain=1`), `--branch/-b`, `--commit/-c` (`/src/commit/{sha}/{path}`; without a SHA the last commit of the current branch, of the default branch with `-R`, from `GET /repos/{owner}/{repo}/branches/{branch}`), `--blame` (`/blame/branch/...` or `/blame/commit/...`), `--settings/-s`, `--wiki/-w`, `--releases/-r`, `--actions/-a`, `--projects/-p`, `--no-browser/-n`; a path without `--branch` or `--commit` reads the default branch with `GET /repos/{owner}/{repo}`, everything else makes no API call. Conflicting flags fail with gh's messages before anything opens. Unlike gh, `--no-browser` does not check that the repository exists) | [x] | | `copia-cli status` (`gh status`, Partial: the sections Assigned Issues, Assigned Pull Requests, Review Requests and Mentions come from `GET /repos/issues/search?state=open` with `assigned=true` (split on `pull_request`), `review_requested=true&type=pulls` and `mentioned=true`, the first 25 results of each sorted by `updated_at` and five shown, as gh reads 25 search results and shows five. gh takes its mentions from the notifications with the reason `mention`; Gitea's notifications carry no reason, so the search filter is used. Repository Activity is the ten newest of `GET /notifications?all=true` with the subject type (`issue`, `PR`, `commit`, `repository`) instead of gh's `new issue`, `new PR` and `comment on` from `/users/{user}/received_events`, which Gitea 1.26 does not have. `--org/-o` is sent as the search's `owner` and checked on every result and notification, `--exclude/-e` is applied on the client, both regardless of case; an `--exclude` value that is not `owner/repo` fails. The layout is gh's: two half-width columns separated by `│` at the terminal width (80 when not a terminal), without colour) | [x] | | `copia-cli completion` | [x] | +| `copia-cli repo collaborator list` and `repo collaborator add` (gh has no collaborator commands. `list` (alias `ls`): `GET /repos/{owner}/{repo}/collaborators` up to `-L/--limit` (default 30), the columns LOGIN and NAME, `--json login,full_name` with `--jq` and `--template`; none prints `no collaborators found in /` on standard error, exit 0. No permission: app.copia.io answers Gitea's `GET /repos/{owner}/{repo}/collaborators/{login}/permission` with Go's plain-text `404 page not found` (the route is not registered). `add [-p/--permission read\|write\|admin]` (default `write`, Gitea's): `PUT /repos/{owner}/{repo}/collaborators/{login}`, then `Added to / with permission`, also for a collaborator already there, whose permission Gitea changes. Another permission, which Gitea answers with 500, and a login that is not a Gitea login fail before any request; Gitea's 422 for an unknown user becomes `user not found`, its other refusals are shown with the HTTP status and Gitea's words) | [x] | +| `copia-cli repo collaborator remove` (gh has no collaborator commands. `remove -y/--yes`; without `--yes` it fails with `--yes required when not running interactively` before anything else. `GET /repos/{owner}/{repo}/collaborators/{login}` first, since Gitea answers 204 to a `DELETE` of a non-collaborator: its 404 becomes ` is not a collaborator of /`; then `DELETE /repos/{owner}/{repo}/collaborators/{login}` and `Removed from /`. A login that is not a Gitea login fails before any request; Gitea's other refusals are shown with the HTTP status and Gitea's words) | [x] | ## Other gh commands (not yet implemented) | gh command group | Parity | Notes | |-----------------|--------|-------| -| `gh ssh-key` | Full | `GET/POST /user/keys` | -| `gh gpg-key` | Full | `GET/POST /user/gpg_keys` | +| `gh ssh-key` | None | app.copia.io has SSH disabled: it answers `POST /user/keys` with 422 `SSH is disabled` (found by the `integration` job of #487, 2026-11-08), so an SSH key cannot be added and would grant nothing; Copia is reached over https only | | `gh gist` | None | No Gitea equivalent | | `gh workflow` | Full | `/repos/{owner}/{repo}/actions/workflows`: list, view, `run` (`/{workflow_id}/dispatches`), `enable`, `disable`. Whether Copia enables Actions is unknown | | `gh run` | Partial | `/repos/{owner}/{repo}/actions/runs`: list, view, delete, `rerun` (`/rerun`, `/rerun-failed-jobs`, `/jobs/{job_id}/rerun`), job logs (`/actions/jobs/{job_id}/logs`), `download` (`/actions/artifacts`), `watch` by polling. No `cancel`: Gitea 1.26 has no endpoint for it. Whether Copia enables Actions is unknown | @@ -235,10 +254,10 @@ Client side, no API call. Aliases are stored under the top-level key `aliases` o | Status | Count | |--------|-------| -| Implemented | 76 | -| Not yet implemented (Full parity) | 4 | +| Implemented | 81 | +| Not yet implemented (Full parity) | 1 | | Not yet implemented (Partial) | 4 | -| No equivalent | 13 | -| **Total implementable** | **84** | +| No equivalent | 15 | +| **Total implementable** | **86** | Counted from the rows above: every `[x]` row, and every other row by its Parity value. The Parity values follow the Gitea 1.26 API (`release/v1.26` swagger); `TestAPI_Version` in `test/integration/api_test.go` logs what Copia's `GET /version` reports in the PR `integration` job. On 2026-11-04 that was `0.59.0`, Copia's own version number, not a Gitea release, so the API does not show which Gitea version Copia is built on; a command's integration test shows whether Copia serves its endpoint. diff --git a/docs/project-layout.md b/docs/project-layout.md index a68e31e..399cfc7 100644 --- a/docs/project-layout.md +++ b/docs/project-layout.md @@ -35,6 +35,7 @@ graph TB search[search: issues/repos] org[org: list/view] notification[notification: list/read] + gpgkey[gpg-key: list/add] browse[browse: open repo/issue/PR URL] status[status: dashboard across repositories] configcmd[config: get/set/list] @@ -55,15 +56,15 @@ graph TB copiacmd --> build copiacmd --> config factory --> iostreams - copiacmd --> auth & repo & issue & pr & label & release & apicmd & search & org & notification & browse & status & configcmd & aliascmd & completion - auth & repo & issue & pr & label & release & apicmd & search & org & notification & status --> factory + copiacmd --> auth & repo & issue & pr & label & release & apicmd & search & org & notification & gpgkey & browse & status & configcmd & aliascmd & completion + auth & repo & issue & pr & label & release & apicmd & search & org & notification & gpgkey & status --> factory browse --> factory configcmd --> factory aliascmd --> factory completion --> iostreams auth & repo & issue & pr & label & release & apicmd & search & org & notification -.-> client client --> gitea - httpmock -.-> auth & repo & issue & pr & label & release & apicmd & search & org & notification + httpmock -.-> auth & repo & issue & pr & label & release & apicmd & search & org & notification & gpgkey integration --> gitea ``` @@ -90,6 +91,7 @@ copia-cli/ │ │ ├── search/ # issues, repos │ │ ├── org/ # list, view │ │ ├── notification/ # list, read +│ │ ├── gpgkey/ # list, add (the gpg-key group) │ │ ├── browse/ # single command: browse [ | | ] │ │ ├── status/ # single command: status (gh's dashboard) │ │ ├── config/ # get, set, list @@ -196,6 +198,7 @@ func xxxRun(opts *XxxOptions) error { ... } // unexported, testable | `search` | issues, repos | Raw HTTP | | `org` | list, view | Raw HTTP | | `notification` | list, read | Raw HTTP (read: PATCH one thread, PUT with `--all`) | +| `gpg-key` | list, add | Raw HTTP: `GET` and `POST /user/gpg_keys` | | `browse` | none (single command `browse [ \| \| ]`) | URL built client-side, opened with `cmdutil.Browser`; raw HTTP only for the default branch of a path and the last commit of `--commit` | | `status` | none (single command `status`) | Raw HTTP: the issue search and the notifications | | `config` | get, set, list | No API call; reads and writes the settings of `config.yml`, `set` validates before it saves | diff --git a/docs/site/_includes/sidebar.html b/docs/site/_includes/sidebar.html index 320cd1b..c670498 100644 --- a/docs/site/_includes/sidebar.html +++ b/docs/site/_includes/sidebar.html @@ -31,6 +31,11 @@
  • list
  • set
  • +
  • gpg-key
  • +
  • add
  • +
  • delete
  • +
  • list
  • +
  • issue
  • close
  • comment
  • @@ -76,6 +81,8 @@
  • repo
  • clone
  • +
  • collaborator add
  • +
  • collaborator list
  • create
  • delete
  • fork
  • diff --git a/internal/copiacmd/root.go b/internal/copiacmd/root.go index 736e445..8368c34 100644 --- a/internal/copiacmd/root.go +++ b/internal/copiacmd/root.go @@ -19,6 +19,7 @@ import ( browseCmd "github.com/qubernetic/copia-cli/pkg/cmd/browse" completionCmd "github.com/qubernetic/copia-cli/pkg/cmd/completion" configCmd "github.com/qubernetic/copia-cli/pkg/cmd/config" + gpgkeyCmd "github.com/qubernetic/copia-cli/pkg/cmd/gpgkey" issueCmd "github.com/qubernetic/copia-cli/pkg/cmd/issue" labelCmd "github.com/qubernetic/copia-cli/pkg/cmd/label" notificationCmd "github.com/qubernetic/copia-cli/pkg/cmd/notification" @@ -60,6 +61,7 @@ func NewRootCmd(f *cmdutil.Factory) *cobra.Command { cmd.AddCommand(searchCmd.NewCmdSearch(f)) cmd.AddCommand(orgCmd.NewCmdOrg(f)) cmd.AddCommand(notificationCmd.NewCmdNotification(f)) + cmd.AddCommand(gpgkeyCmd.NewCmdGPGKey(f)) cmd.AddCommand(browseCmd.NewCmdBrowse(f)) cmd.AddCommand(statusCmd.NewCmdStatus(f)) cmd.AddCommand(configCmd.NewCmdConfig(f)) diff --git a/internal/copiacmd/root_test.go b/internal/copiacmd/root_test.go index 63c46de..9f2a8a1 100644 --- a/internal/copiacmd/root_test.go +++ b/internal/copiacmd/root_test.go @@ -26,7 +26,7 @@ func TestNewRootCmd_RegistersCommands(t *testing.T) { } for _, want := range []string{ "auth", "repo", "issue", "label", "pr", "release", - "api", "search", "org", "notification", "browse", "status", "completion", "config", "alias", + "api", "search", "org", "notification", "browse", "status", "completion", "config", "alias", "gpg-key", } { assert.Contains(t, names, want) } diff --git a/pkg/cmd/gpgkey/add/add.go b/pkg/cmd/gpgkey/add/add.go new file mode 100644 index 0000000..e6f38b0 --- /dev/null +++ b/pkg/cmd/gpgkey/add/add.go @@ -0,0 +1,177 @@ +package add + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + + "github.com/spf13/cobra" + "github.com/qubernetic/copia-cli/pkg/cmdutil" + "github.com/qubernetic/copia-cli/pkg/iostreams" +) + +// AddOptions holds all inputs for the gpg-key add command. +type AddOptions struct { + IO *iostreams.IOStreams + HTTPClient *http.Client + Host string + Token string + KeyFile string +} + +// addRequest leaves out Gitea's armored_signature: the signature is made +// over the token of GET /user/gpg_key_token, a route Copia does not have. +type addRequest struct { + ArmoredPublicKey string `json:"armored_public_key"` +} + +// Gitea's messages for the refusals add turns into its own. +const ( + duplicateKeyMessage = "A key with the same id already exists" + noEmailMessage = "None of the emails attached to the GPG key could be found." +) + +// publicKeyHeader is the only armor header a key file may hold. +const publicKeyHeader = "-----BEGIN PGP PUBLIC KEY BLOCK-----" + +// NewCmdAdd creates the `copia-cli gpg-key add` command. +func NewCmdAdd(f *cmdutil.Factory) *cobra.Command { + return newCmdAdd(f, nil) +} + +// newCmdAdd is NewCmdAdd with runF, when not nil, run instead of AddRun +// after the arguments are parsed. +func newCmdAdd(f *cmdutil.Factory, runF func(*AddOptions) error) *cobra.Command { + opts := &AddOptions{} + + cmd := &cobra.Command{ + Use: "add []", + Short: "Add a GPG key to your Copia account", + Long: `Add an ASCII-armored GPG public key to your Copia account. + +With "-", or without a file when standard input is not a terminal, the key +is read from standard input. + +Copia adds a key only when one of its emails is a verified email of your +account.`, + Example: ` $ gpg --armor --export | copia-cli gpg-key add - + $ copia-cli gpg-key add key.asc`, + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + opts.IO = f.IOStreams + if len(args) == 0 { + if opts.IO.IsStdinTTY() { + return errors.New("GPG key file missing") + } + opts.KeyFile = "-" + } else { + opts.KeyFile = args[0] + } + if runF != nil { + return runF(opts) + } + + host, token, err := f.ResolveAuth() + if err != nil { + return err + } + opts.Host = host + opts.Token = token + opts.HTTPClient = cmdutil.NewHTTPClient() + return AddRun(opts) + }, + } + + return cmd +} + +func AddRun(opts *AddOptions) error { + data, err := cmdutil.ReadFile(opts.KeyFile, opts.IO.In) + if err != nil { + return err + } + key := string(data) + + // The private half never leaves the machine, so only public key blocks + // are sent; anything else is refused here rather than by the server. + switch cmdutil.CheckArmor(key, publicKeyHeader) { + case cmdutil.ArmorPrivate: + return errors.New("the key file holds a private key; add the public key (gpg --armor --export )") + case cmdutil.ArmorOther: + return errors.New("the GPG key you are trying to upload might not be in ASCII-armored format.\n" + + "Find your GPG key ID with: gpg --list-keys\n" + + "Then add it to your account: gpg --armor --export | copia-cli gpg-key add -") + } + + body, err := json.Marshal(addRequest{ArmoredPublicKey: key}) + if err != nil { + return err + } + req, err := http.NewRequest("POST", fmt.Sprintf("https://%s/api/v1/user/gpg_keys", opts.Host), bytes.NewReader(body)) + if err != nil { + return err + } + req.Header.Set("Authorization", "token "+opts.Token) + req.Header.Set("Content-Type", "application/json") + + resp, err := opts.HTTPClient.Do(req) + if err != nil { + return fmt.Errorf("connecting to %s: %w", opts.Host, err) + } + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusCreated { + message := cmdutil.ReadAPIMessage(resp.Body) + switch { + case message == "" || quotesKey(message, key): + return fmt.Errorf("failed to add GPG key (HTTP %d)", resp.StatusCode) + case resp.StatusCode == http.StatusUnprocessableEntity && message == duplicateKeyMessage: + return errors.New("the key already exists in your account") + case resp.StatusCode == http.StatusNotFound && strings.HasPrefix(message, noEmailMessage): + // The rest of Gitea's message offers to sign a token, which + // Copia gives no route for, so only its first sentence is shown. + return fmt.Errorf("failed to add GPG key (HTTP %d): %s\n"+ + "Copia adds a GPG key only when one of its emails is a verified email of your account;\n"+ + "add and verify that email in your Copia settings, then add the key again", resp.StatusCode, noEmailMessage) + } + return fmt.Errorf("failed to add GPG key (HTTP %d): %s", resp.StatusCode, message) + } + + _, _ = fmt.Fprintln(opts.IO.Out, "GPG key added to your account") + return nil +} + +// quoteWindow is the shortest run of key material quotesKey looks for. +const quoteWindow = 16 + +// quotesKey reports whether message holds quoteWindow bytes in a row of the +// key material in key, both compared without whitespace, so a key the server +// quotes re-wrapped or joined is found as well. The key material is every +// line but the armor lines (-----) and armor headers (Key: value), which are +// no secret. An error then shows no part of the key file. +func quotesKey(message, key string) bool { + var material strings.Builder + for _, line := range strings.Split(key, "\n") { + line = strings.TrimSpace(line) + if strings.HasPrefix(line, "-----") || strings.Contains(line, ": ") { + continue + } + material.WriteString(line) + } + body := stripSpace(material.String()) + message = stripSpace(message) + for i := 0; i+quoteWindow <= len(body); i++ { + if strings.Contains(message, body[i:i+quoteWindow]) { + return true + } + } + return false +} + +// stripSpace returns s without any white space. +func stripSpace(s string) string { + return strings.Join(strings.Fields(s), "") +} diff --git a/pkg/cmd/gpgkey/add/add_test.go b/pkg/cmd/gpgkey/add/add_test.go new file mode 100644 index 0000000..092633f --- /dev/null +++ b/pkg/cmd/gpgkey/add/add_test.go @@ -0,0 +1,340 @@ +package add + +import ( + "encoding/json" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/qubernetic/copia-cli/pkg/cmdutil" + "github.com/qubernetic/copia-cli/pkg/httpmock" + "github.com/qubernetic/copia-cli/pkg/iostreams" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + privateKeyErr = "the key file holds a private key; add the public key (gpg --armor --export )" + armorHintErr = "the GPG key you are trying to upload might not be in ASCII-armored format.\n" + + "Find your GPG key ID with: gpg --list-keys\n" + + "Then add it to your account: gpg --armor --export | copia-cli gpg-key add -" +) + +const armoredKey ="-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nmDMEaS0ZRhYJKwYBBAHaRw8BAQdAc29tZWtleW1hdGVyaWFsZm9ydGVzdHM\n=AbCd\n-----END PGP PUBLIC KEY BLOCK-----\n" + +func writeFile(t *testing.T, name, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), name) + require.NoError(t, os.WriteFile(path, []byte(content), 0o600)) + return path +} + +func newOpts(reg *httpmock.Registry, ios *iostreams.IOStreams, keyFile string) *AddOptions { + return &AddOptions{ + IO: ios, + HTTPClient: &http.Client{Transport: reg}, + Host: "app.copia.io", + Token: "test-token", + KeyFile: keyFile, + } +} + +// postedBody returns the JSON body of the POST the registry got. +func postedBody(t *testing.T, reg *httpmock.Registry) map[string]any { + t.Helper() + require.Len(t, reg.Requests, 1) + data, err := io.ReadAll(reg.Requests[0].Body) + require.NoError(t, err) + var body map[string]any + require.NoError(t, json.Unmarshal(data, &body)) + return body +} + +func TestAddRun_Adds(t *testing.T) { + tests := []struct { + name string + key string + keyStdin bool + }{ + {name: "a key file", key: armoredKey}, + {name: "the key from standard input", key: armoredKey, keyStdin: true}, + {name: "two public key blocks", key: armoredKey + armoredKey}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + reg.Register(httpmock.REST("POST", "/api/v1/user/gpg_keys"), httpmock.StringResponse(http.StatusCreated, `{"id":4}`)) + + ios, stdin, stdout, stderr := iostreams.Test() + keyFile := "-" + if tt.keyStdin { + stdin.WriteString(tt.key) + } else { + keyFile = writeFile(t, "key.asc", tt.key) + } + opts := newOpts(reg, ios, keyFile) + + require.NoError(t, AddRun(opts)) + assert.Equal(t, "GPG key added to your account\n", stdout.String()) + assert.Empty(t, stderr.String()) + assert.Equal(t, map[string]any{"armored_public_key": tt.key}, postedBody(t, reg)) + assert.Equal(t, "token test-token", reg.Requests[0].Header.Get("Authorization")) + assert.Equal(t, "application/json", reg.Requests[0].Header.Get("Content-Type")) + }) + } +} + +func TestAddRun_RefusedBeforeAnyRequest(t *testing.T) { + tests := []struct { + name string + key string + wantErr string + }{ + { + name: "a key that is not armored", + key: "mDMEaS0ZRhYJKwYBBAHaRw8BAQdAbinarykey\n", + wantErr: "the GPG key you are trying to upload might not be in ASCII-armored format.\n" + + "Find your GPG key ID with: gpg --list-keys\n" + + "Then add it to your account: gpg --armor --export | copia-cli gpg-key add -", + }, + { + name: "a private key", + key: "-----BEGIN PGP PRIVATE KEY BLOCK-----\n\nlFgEaS0ZRhYJKwYBBAHaRw8BAQdAsecret\n-----END PGP PRIVATE KEY BLOCK-----\n", + wantErr: privateKeyErr, + }, + { + name: "an OpenSSH private key", + key: "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmU\n-----END OPENSSH PRIVATE KEY-----\n", + wantErr: privateKeyErr, + }, + { + name: "a PKCS#8 private key", + key: "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIBy\n-----END PRIVATE KEY-----\n", + wantErr: privateKeyErr, + }, + { + name: "an RSA private key", + key: "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA\n-----END RSA PRIVATE KEY-----\n", + wantErr: privateKeyErr, + }, + { + name: "a legacy PGP secret key", + key: "-----BEGIN PGP SECRET KEY BLOCK-----\n\nlFgEaS0ZRhYJKwYBBAHaRw8B\n-----END PGP SECRET KEY BLOCK-----\n", + wantErr: privateKeyErr, + }, + { + name: "a public key followed by a private key", + key: armoredKey + "-----BEGIN PGP PRIVATE KEY BLOCK-----\n\nlFgEaS0ZRhYJKwYBBAHaRw8B\n-----END PGP PRIVATE KEY BLOCK-----\n", + wantErr: privateKeyErr, + }, + { + name: "a signature instead of a key", + key: "-----BEGIN PGP SIGNATURE-----\n\niHUEABYKAB0WIQRzaWdu\n-----END PGP SIGNATURE-----\n", + wantErr: armorHintErr, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + ios, _, stdout, _ := iostreams.Test() + err := AddRun(newOpts(reg, ios, writeFile(t, "key.asc", tt.key))) + require.EqualError(t, err, tt.wantErr) + assert.Empty(t, reg.Requests) + assert.Empty(t, stdout.String()) + }) + } +} + +func TestAddRun_GiteaError(t *testing.T) { + const token = "1f2e3d4c5b6a79881f2e3d4c5b6a79881f2e3d4c5b6a79881f2e3d4c5b6a7988" + keyLine := strings.Split(armoredKey, "\n")[2] + tests := []struct { + name string + status int + body string + wantErr string + }{ + { + name: "a duplicate key ID", + status: http.StatusUnprocessableEntity, + body: `{"message":"A key with the same id already exists","url":"https://app.copia.io/api/swagger"}`, + wantErr: "the key already exists in your account", + }, + { + name: "a key without a verified email", + status: http.StatusNotFound, + body: `{"message":"None of the emails attached to the GPG key could be found. It may still be added if you provide a valid signature for the token: ` + token + `"}`, + // Gitea's advice to sign the token cannot be followed on + // Copia, which has no token route, so it is left out. + wantErr: "failed to add GPG key (HTTP 404): None of the emails attached to the GPG key could be found.\n" + + "Copia adds a GPG key only when one of its emails is a verified email of your account;\n" + + "add and verify that email in your Copia settings, then add the key again", + }, + { + name: "the GPG key feature turned off", + status: http.StatusNotFound, + body: `{"message":"Not Found"}`, + wantErr: "failed to add GPG key (HTTP 404): Not Found", + }, + { + name: "a message that quotes a key line is withheld", + status: http.StatusUnprocessableEntity, + body: `{"message":"failed to parse gpg key ` + keyLine + `"}`, + wantErr: "failed to add GPG key (HTTP 422)", + }, + { + name: "a message that quotes the key joined on one line is withheld", + status: http.StatusUnprocessableEntity, + body: `{"message":"bad key ` + strings.Join(strings.Fields(armoredKey), "") + `"}`, + wantErr: "failed to add GPG key (HTTP 422)", + }, + { + name: "a message that quotes part of a key line is withheld", + status: http.StatusUnprocessableEntity, + body: `{"message":"bad key …` + keyLine[10:30] + `…"}`, + wantErr: "failed to add GPG key (HTTP 422)", + }, + { + name: "a long message is cut", + status: http.StatusInternalServerError, + body: `{"message":"` + strings.Repeat("m", 10<<10) + `"}`, + wantErr: "failed to add GPG key (HTTP 500): " + strings.Repeat("m", cmdutil.MaxAPIMessage), + }, + { + name: "a 1 MiB body", + status: http.StatusInternalServerError, + body: `{"message":"` + strings.Repeat("m", 100<<10) + `","pad":"` + strings.Repeat("p", 1<<20) + `"}`, + wantErr: "failed to add GPG key (HTTP 500)", + }, + { + name: "no message", + status: http.StatusInternalServerError, + body: ``, + wantErr: "failed to add GPG key (HTTP 500)", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + reg.Register(httpmock.REST("POST", "/api/v1/user/gpg_keys"), httpmock.StringResponse(tt.status, tt.body)) + + ios, _, stdout, _ := iostreams.Test() + err := AddRun(newOpts(reg, ios, writeFile(t, "key.asc", armoredKey))) + require.EqualError(t, err, tt.wantErr) + assert.NotContains(t, err.Error(), token) + assert.Empty(t, stdout.String()) + }) + } +} + +func TestAddRun_MissingFile(t *testing.T) { + reg := &httpmock.Registry{} + ios, _, _, _ := iostreams.Test() + err := AddRun(newOpts(reg, ios, filepath.Join(t.TempDir(), "missing.asc"))) + require.Error(t, err) + assert.Empty(t, reg.Requests) +} + +func TestQuotesKey(t *testing.T) { + body := strings.Split(armoredKey, "\n")[2] + // The key re-wrapped at 20 columns, as a server might quote it. + var wrapped []string + for s := body; s != ""; { + n := min(20, len(s)) + wrapped = append(wrapped, s[:n]) + s = s[n:] + } + tests := []struct { + name string + message string + key string + want bool + }{ + {name: "a key line", message: "bad " + body + " here", key: armoredKey, want: true}, + {name: "the key re-wrapped", message: "bad " + strings.Join(wrapped, "\n"), key: armoredKey, want: true}, + {name: "the key joined on one line", message: strings.Join(strings.Fields(armoredKey), ""), key: armoredKey, want: true}, + {name: "16 bytes of the key", message: "x" + body[5:21] + "x", key: armoredKey, want: true}, + {name: "a single-line key file", message: "bad " + body[:16], key: body, want: true}, + {name: "15 bytes of the key", message: "x" + body[5:20] + "x", key: armoredKey, want: false}, + {name: "the armor header", message: "no -----BEGIN PGP PUBLIC KEY BLOCK----- found", key: armoredKey, want: false}, + {name: "an unrelated message", message: "A key with the same id already exists", key: armoredKey, want: false}, + {name: "a key shorter than 16 bytes", message: "=AbCd", key: "=AbCd\n", want: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, quotesKey(tt.message, tt.key)) + }) + } +} + +func TestNewCmdAdd_Args(t *testing.T) { + tests := []struct { + name string + args []string + stdinTTY bool + wantFile string + wantErr string + }{ + {name: "a file", args: []string{"key.asc"}, wantFile: "key.asc"}, + {name: "no --signature", args: []string{"key.asc", "--signature", "sig.asc"}, wantErr: "unknown flag: --signature"}, + {name: "a dash", args: []string{"-"}, stdinTTY: true, wantFile: "-"}, + {name: "no argument with piped stdin", wantFile: "-"}, + {name: "no argument on a terminal", stdinTTY: true, wantErr: "GPG key file missing"}, + {name: "two arguments", args: []string{"a", "b"}, wantErr: "accepts at most 1 arg(s), received 2"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ios, _, _, _ := iostreams.Test() + ios.SetStdinTTY(tt.stdinTTY) + f := &cmdutil.Factory{IOStreams: ios} + + var got *AddOptions + cmd := newCmdAdd(f, func(opts *AddOptions) error { + got = opts + return nil + }) + cmd.SetArgs(tt.args) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + + err := cmd.Execute() + if tt.wantErr != "" { + require.EqualError(t, err, tt.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.wantFile, got.KeyFile) + }) + } +} + +func TestNewCmdAdd_Flags(t *testing.T) { + ios, _, _, _ := iostreams.Test() + cmd := NewCmdAdd(&cmdutil.Factory{IOStreams: ios}) + assert.Nil(t, cmd.Flags().Lookup("signature")) + assert.Nil(t, cmd.Flags().Lookup("title")) + assert.Equal(t, "add []", cmd.Use) + assert.Contains(t, cmd.Long, "only when one of its emails is a verified email of your\naccount") + assert.NotContains(t, cmd.Long, "gpg_key_token") +} + +func TestNewCmdAdd_Runs(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + httpmock.ReplaceDefaultTransport(t, reg) + reg.Register(httpmock.REST("POST", "/api/v1/user/gpg_keys"), httpmock.StringResponse(http.StatusCreated, `{"id":4}`)) + + ios, _, stdout, _ := iostreams.Test() + cmd := NewCmdAdd(&cmdutil.Factory{IOStreams: ios, Host: "app.copia.io", Token: "flag-token"}) + cmd.SetArgs([]string{writeFile(t, "key.asc", armoredKey)}) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + require.NoError(t, cmd.Execute()) + assert.Equal(t, "GPG key added to your account\n", stdout.String()) + assert.Equal(t, "token flag-token", reg.Requests[0].Header.Get("Authorization")) +} diff --git a/pkg/cmd/gpgkey/delete/delete.go b/pkg/cmd/gpgkey/delete/delete.go new file mode 100644 index 0000000..4b9fceb --- /dev/null +++ b/pkg/cmd/gpgkey/delete/delete.go @@ -0,0 +1,108 @@ +package delete + +import ( + "errors" + "fmt" + "net/http" + "strings" + + "github.com/spf13/cobra" + gpgkeylist "github.com/qubernetic/copia-cli/pkg/cmd/gpgkey/list" + "github.com/qubernetic/copia-cli/pkg/cmdutil" + "github.com/qubernetic/copia-cli/pkg/iostreams" +) + +// DeleteOptions holds all inputs for the gpg-key delete command. +type DeleteOptions struct { + IO *iostreams.IOStreams + HTTPClient *http.Client + Host string + Token string + KeyID string +} + +// NewCmdDelete creates the `copia-cli gpg-key delete` command. +func NewCmdDelete(f *cmdutil.Factory) *cobra.Command { + opts := &DeleteOptions{} + var confirmed bool + + cmd := &cobra.Command{ + Use: "delete ", + Short: "Delete a GPG key from your Copia account", + Long: `Delete a GPG key from your Copia account. + +The key is named by its GPG key ID, as gpg-key list shows it, in any case. +There is no prompt, so --yes is required.`, + Example: ` $ copia-cli gpg-key delete 3AA5C34371567BD2 --yes`, + Args: func(cmd *cobra.Command, args []string) error { + if len(args) != 1 { + return errors.New("cannot delete: key id required") + } + return nil + }, + RunE: func(cmd *cobra.Command, args []string) error { + if !confirmed { + return errors.New("--yes required when not running interactively") + } + opts.IO = f.IOStreams + opts.KeyID = args[0] + + host, token, err := f.ResolveAuth() + if err != nil { + return err + } + opts.Host = host + opts.Token = token + opts.HTTPClient = cmdutil.NewHTTPClient() + return DeleteRun(opts) + }, + } + + cmd.Flags().BoolVarP(&confirmed, "yes", "y", false, "Skip the confirmation prompt") + + return cmd +} + +// DeleteRun looks the key up by its GPG key ID on every page of GET +// /user/gpg_keys and deletes it with DELETE /user/gpg_keys/{id}; Gitea +// answers 204 to a delete of an unknown id, so the lookup comes first. The +// command has checked --yes before. +func DeleteRun(opts *DeleteOptions) error { + keys, err := gpgkeylist.FetchKeys(opts.HTTPClient, opts.Host, opts.Token) + if err != nil { + return err + } + + var id int64 + for _, k := range keys { + if strings.EqualFold(k.KeyID, opts.KeyID) { + id = k.ID + break + } + } + if id == 0 { + return fmt.Errorf("unable to delete GPG key %s: either the GPG key is not found or it is not owned by you", opts.KeyID) + } + + req, err := http.NewRequest("DELETE", fmt.Sprintf("https://%s/api/v1/user/gpg_keys/%d", opts.Host, id), nil) + if err != nil { + return err + } + req.Header.Set("Authorization", "token "+opts.Token) + + resp, err := opts.HTTPClient.Do(req) + if err != nil { + return fmt.Errorf("connecting to %s: %w", opts.Host, err) + } + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusNoContent { + if message := cmdutil.ReadAPIMessage(resp.Body); message != "" { + return fmt.Errorf("failed to delete GPG key (HTTP %d): %s", resp.StatusCode, message) + } + return fmt.Errorf("failed to delete GPG key (HTTP %d)", resp.StatusCode) + } + + _, _ = fmt.Fprintf(opts.IO.Out, "GPG key %s deleted from your account\n", opts.KeyID) + return nil +} diff --git a/pkg/cmd/gpgkey/delete/delete_test.go b/pkg/cmd/gpgkey/delete/delete_test.go new file mode 100644 index 0000000..92b5791 --- /dev/null +++ b/pkg/cmd/gpgkey/delete/delete_test.go @@ -0,0 +1,199 @@ +package delete + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "testing" + + "github.com/qubernetic/copia-cli/pkg/cmdutil" + "github.com/qubernetic/copia-cli/pkg/httpmock" + "github.com/qubernetic/copia-cli/pkg/iostreams" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const keysPath = "/api/v1/user/gpg_keys" + +// fullPage answers a page of 50 keys, which makes the pager ask for the +// next one. +func fullPage() string { + type key struct { + ID int64 `json:"id"` + KeyID string `json:"key_id"` + } + keys := make([]key, 50) + for i := range keys { + keys[i] = key{ID: int64(i + 1), KeyID: fmt.Sprintf("00000000000000%02X", i)} + } + b, _ := json.Marshal(keys) + return string(b) +} + +func runCmd(f *cmdutil.Factory, args ...string) error { + cmd := NewCmdDelete(f) + cmd.SetArgs(args) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + return cmd.Execute() +} + +func deleted(t *testing.T) httpmock.Responder { + return func(req *http.Request) (*http.Response, error) { + assert.Equal(t, "token test-token", req.Header.Get("Authorization")) + return httpmock.StringResponse(http.StatusNoContent, "")(req) + } +} + +func TestNewCmdDelete(t *testing.T) { + tests := []struct { + name string + keyID string + page2 string + }{ + {name: "match on the second page", keyID: "3AA5C34371567BD2", page2: `[{"id":77,"key_id":"3AA5C34371567BD2"}]`}, + {name: "match in another case", keyID: "3aa5c34371567bd2", page2: `[{"id":77,"key_id":"3AA5C34371567BD2"}]`}, + } + + for _, tt := range tests { + for _, yes := range []string{"--yes", "-y"} { + t.Run(tt.name+" "+yes, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + httpmock.ReplaceDefaultTransport(t, reg) + reg.Register( + httpmock.QueryMatcher("GET", keysPath, url.Values{"page": {"1"}, "limit": {"50"}}), + httpmock.StringResponse(http.StatusOK, fullPage()), + ) + reg.Register( + httpmock.QueryMatcher("GET", keysPath, url.Values{"page": {"2"}, "limit": {"50"}}), + httpmock.StringResponse(http.StatusOK, tt.page2), + ) + reg.Register(httpmock.REST("DELETE", keysPath+"/77"), deleted(t)) + + ios, _, stdout, stderr := iostreams.Test() + f := &cmdutil.Factory{IOStreams: ios, Host: "app.copia.io", Token: "test-token"} + + require.NoError(t, runCmd(f, tt.keyID, yes)) + assert.Equal(t, "GPG key "+tt.keyID+" deleted from your account\n", stdout.String()) + assert.Empty(t, stderr.String()) + }) + } + } +} + +func TestNewCmdDelete_Refused(t *testing.T) { + tests := []struct { + name string + args []string + wantErr string + }{ + {name: "no --yes", args: []string{"3AA5C34371567BD2"}, wantErr: "--yes required when not running interactively"}, + {name: "no key ID", args: []string{"--yes"}, wantErr: "cannot delete: key id required"}, + {name: "two key IDs", args: []string{"A", "B", "--yes"}, wantErr: "cannot delete: key id required"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + httpmock.ReplaceDefaultTransport(t, reg) + + ios, _, stdout, _ := iostreams.Test() + f := &cmdutil.Factory{IOStreams: ios, Host: "app.copia.io", Token: "test-token"} + + require.EqualError(t, runCmd(f, tt.args...), tt.wantErr) + assert.Empty(t, stdout.String()) + }) + } +} + +func TestDeleteRun_Errors(t *testing.T) { + list := httpmock.StringResponse(http.StatusOK, `[{"id":3,"key_id":"1111111111111111"},{"id":5,"key_id":"3AA5C34371567BD2"}]`) + + tests := []struct { + name string + host string + list httpmock.Responder + del httpmock.Responder + wantErr string + }{ + { + name: "not found", + list: httpmock.StringResponse(http.StatusOK, `[{"id":3,"key_id":"1111111111111111"}]`), + wantErr: "unable to delete GPG key 3AA5C34371567BD2: either the GPG key is not found or it is not owned by you", + }, + { + name: "no keys", + list: httpmock.StringResponse(http.StatusOK, `[]`), + wantErr: "unable to delete GPG key 3AA5C34371567BD2: either the GPG key is not found or it is not owned by you", + }, + { + name: "list fails with a message", + list: httpmock.StringResponse(http.StatusForbidden, `{"message":"token does not have at least one of required scope(s): [read:user]"}`), + wantErr: "failed to list GPG keys (HTTP 403): token does not have at least one of required scope(s): [read:user]", + }, + { + name: "list is not JSON", + list: httpmock.StringResponse(http.StatusOK, `nope`), + wantErr: "parsing response", + }, + { + name: "delete refused with a message", + list: list, + del: httpmock.StringResponse(http.StatusForbidden, `{"message":"token does not have at least one of required scope(s): [write:user]"}`), + wantErr: "failed to delete GPG key (HTTP 403): token does not have at least one of required scope(s): [write:user]", + }, + { + name: "delete refused without a message", + list: list, + del: httpmock.StringResponse(http.StatusInternalServerError, ``), + wantErr: "failed to delete GPG key (HTTP 500)", + }, + { + name: "transport error on delete", + list: list, + del: func(*http.Request) (*http.Response, error) { + return nil, errors.New("boom") + }, + wantErr: "connecting to app.copia.io: ", + }, + { + name: "invalid host", + host: "bad\x7fhost", + wantErr: "invalid control character", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + if tt.list != nil { + reg.Register(httpmock.REST("GET", keysPath), tt.list) + } + if tt.del != nil { + reg.Register(httpmock.REST("DELETE", keysPath+"/5"), tt.del) + } + host := tt.host + if host == "" { + host = "app.copia.io" + } + + ios, _, stdout, _ := iostreams.Test() + err := DeleteRun(&DeleteOptions{ + IO: ios, + HTTPClient: &http.Client{Transport: reg}, + Host: host, + Token: "test-token", + KeyID: "3AA5C34371567BD2", + }) + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + assert.Empty(t, stdout.String()) + }) + } +} diff --git a/pkg/cmd/gpgkey/gpgkey.go b/pkg/cmd/gpgkey/gpgkey.go new file mode 100644 index 0000000..4d1cafa --- /dev/null +++ b/pkg/cmd/gpgkey/gpgkey.go @@ -0,0 +1,26 @@ +package gpgkey + +import ( + "github.com/spf13/cobra" + addCmd "github.com/qubernetic/copia-cli/pkg/cmd/gpgkey/add" + deleteCmd "github.com/qubernetic/copia-cli/pkg/cmd/gpgkey/delete" + listCmd "github.com/qubernetic/copia-cli/pkg/cmd/gpgkey/list" + "github.com/qubernetic/copia-cli/pkg/cmdutil" +) + +// NewCmdGPGKey creates the `copia-cli gpg-key` command group. +func NewCmdGPGKey(f *cmdutil.Factory) *cobra.Command { + cmd := &cobra.Command{ + Use: "gpg-key ", + Short: "Manage GPG keys", + Long: "Manage GPG keys registered with your Copia account.", + } + + cmdutil.AddGroup(cmd, "General commands", + listCmd.NewCmdList(f), + addCmd.NewCmdAdd(f), + deleteCmd.NewCmdDelete(f), + ) + + return cmd +} diff --git a/pkg/cmd/gpgkey/gpgkey_test.go b/pkg/cmd/gpgkey/gpgkey_test.go new file mode 100644 index 0000000..fb2a045 --- /dev/null +++ b/pkg/cmd/gpgkey/gpgkey_test.go @@ -0,0 +1,25 @@ +package gpgkey + +import ( + "testing" + + "github.com/qubernetic/copia-cli/pkg/cmdutil" + "github.com/stretchr/testify/assert" +) + +func TestNewCmdGPGKey_Subcommands(t *testing.T) { + cmd := NewCmdGPGKey(&cmdutil.Factory{}) + + assert.Equal(t, "gpg-key ", cmd.Use) + assert.Contains(t, cmd.Long, "Copia account") + + groups := map[string]string{} + for _, c := range cmd.Commands() { + groups[c.Name()] = c.GroupID + } + assert.Equal(t, map[string]string{ + "list": "General commands", + "add": "General commands", + "delete": "General commands", + }, groups) +} diff --git a/pkg/cmd/gpgkey/list/list.go b/pkg/cmd/gpgkey/list/list.go new file mode 100644 index 0000000..dc8fda7 --- /dev/null +++ b/pkg/cmd/gpgkey/list/list.go @@ -0,0 +1,200 @@ +package list + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "text/tabwriter" + "time" + + "github.com/spf13/cobra" + "github.com/qubernetic/copia-cli/pkg/cmdutil" + "github.com/qubernetic/copia-cli/pkg/iostreams" +) + +var validJSONFields = []string{"id", "key_id", "primary_key_id", "emails", "public_key", "created_at", "expires_at", "verified", "can_sign"} + +// ListOptions holds all inputs for the gpg-key list command. +type ListOptions struct { + IO *iostreams.IOStreams + HTTPClient *http.Client + Host string + Token string + JSON cmdutil.JSONFlags + + // Now is the clock the ADDED column measures against. + Now func() time.Time +} + +// Email is one email of a GPG key, as Gitea returns it. +type Email struct { + Email string `json:"email"` + Verified bool `json:"verified"` +} + +// Key is one GPG key of the account, as GET /user/gpg_keys returns it. +type Key struct { + ID int64 `json:"id"` + KeyID string `json:"key_id"` + PrimaryKeyID string `json:"primary_key_id"` + Emails []Email `json:"emails"` + PublicKey string `json:"public_key"` + CreatedAt string `json:"created_at"` + ExpiresAt string `json:"expires_at"` + Verified bool `json:"verified"` + CanSign bool `json:"can_sign"` +} + +// emails joins the key's emails with ", ", as gh does. +func (k Key) emails() string { + list := make([]string, len(k.Emails)) + for i, e := range k.Emails { + list[i] = e.Email + } + return strings.Join(list, ", ") +} + +// NewCmdList creates the `copia-cli gpg-key list` command. +func NewCmdList(f *cmdutil.Factory) *cobra.Command { + opts := &ListOptions{} + + cmd := &cobra.Command{ + Use: "list", + Short: "List GPG keys in your Copia account", + Aliases: []string{"ls"}, + Args: cobra.NoArgs, + Example: ` $ copia-cli gpg-key list + $ copia-cli gpg-key list --json key_id,verified`, + RunE: func(cmd *cobra.Command, args []string) error { + opts.IO = f.IOStreams + host, token, err := f.ResolveAuth() + if err != nil { + return err + } + opts.Host = host + opts.Token = token + opts.HTTPClient = cmdutil.NewHTTPClient() + opts.Now = time.Now + return ListRun(opts) + }, + } + + cmdutil.AddJSONFlags(cmd, &opts.JSON, validJSONFields) + + return cmd +} + +func decodeKeys(body []byte) ([]Key, error) { + var keys []Key + err := json.Unmarshal(body, &keys) + return keys, err +} + +// FetchKeys reads every page of the GPG keys of the authenticated user. +func FetchKeys(client *http.Client, host, token string) ([]Key, error) { + keys, err := cmdutil.FetchPages(client, fmt.Sprintf("https://%s/api/v1/user/gpg_keys", host), token, 0, decodeKeys) + if err != nil { + var httpErr *cmdutil.HTTPError + if errors.As(err, &httpErr) { + if httpErr.Message != "" { + return nil, fmt.Errorf("failed to list GPG keys (HTTP %d): %s", httpErr.StatusCode, httpErr.Message) + } + return nil, fmt.Errorf("failed to list GPG keys (HTTP %d)", httpErr.StatusCode) + } + return nil, err + } + return keys, nil +} + +func ListRun(opts *ListOptions) error { + keys, err := FetchKeys(opts.HTTPClient, opts.Host, opts.Token) + if err != nil { + return err + } + + if opts.JSON.IsJSON() { + if keys == nil { + keys = []Key{} + } + return opts.JSON.Print(opts.IO.Out, keys) + } + + if len(keys) == 0 { + _, _ = fmt.Fprintln(opts.IO.ErrOut, "no GPG keys present in the Copia account") + return nil + } + + if err := opts.IO.StartPager(); err != nil { + _, _ = fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err) + } + defer opts.IO.StopPager() + + if !opts.IO.IsStdoutTTY() { + for _, k := range keys { + _, _ = fmt.Fprintf(opts.IO.Out, "%s\t%s\t%s\t%s\t%s\n", k.emails(), k.KeyID, k.PublicKey, k.CreatedAt, k.ExpiresAt) + } + return nil + } + + now := opts.Now() + rows := make([][5]string, len(keys)) + widths := [5]int{len("EMAIL"), len("KEY ID"), len("PUBLIC KEY"), len("ADDED"), len("EXPIRES")} + for i, k := range keys { + rows[i] = [5]string{k.emails(), k.KeyID, k.PublicKey, timeAgo(now, k.CreatedAt), expires(k.ExpiresAt)} + for c, v := range rows[i] { + widths[c] = max(widths[c], len(v)) + } + } + // The public key takes what the other columns and the padding leave of + // the terminal width, cut in the middle as gh does. + keyWidth := opts.IO.TerminalWidth() - widths[0] - widths[1] - widths[3] - widths[4] - 4*2 + w := tabwriter.NewWriter(opts.IO.Out, 0, 0, 2, ' ', 0) + _, _ = fmt.Fprintln(w, "EMAIL\tKEY ID\tPUBLIC KEY\tADDED\tEXPIRES") + for _, r := range rows { + _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", r[0], r[1], truncateMiddle(max(keyWidth, len("PUBLIC KEY")), r[2]), r[3], r[4]) + } + return w.Flush() +} + +// expires is the EXPIRES column on a terminal: Never for a key without an +// expiry, which Gitea gives as the zero time or the Unix epoch, otherwise +// the date. A time that does not parse is returned unchanged. +func expires(s string) string { + t, err := time.Parse(time.RFC3339, s) + if err != nil { + return s + } + if t.Unix() <= 0 { + return "Never" + } + return t.Format("2006-01-02") +} + +// timeAgo describes an RFC 3339 time in words, or returns it unchanged when +// it does not parse. +func timeAgo(now time.Time, s string) string { + t, err := time.Parse(time.RFC3339, s) + if err != nil { + return s + } + return cmdutil.TimeAgo(now, t) +} + +// truncateMiddle cuts t to maxWidth bytes with "..." in the middle, as gh's +// gpg-key list does; a public key in base64 is ASCII. +func truncateMiddle(maxWidth int, t string) string { + if len(t) <= maxWidth { + return t + } + + ellipsis := "..." + if maxWidth < len(ellipsis)+2 { + return t[0:maxWidth] + } + + halfWidth := (maxWidth - len(ellipsis)) / 2 + remainder := (maxWidth - len(ellipsis)) % 2 + return t[0:halfWidth+remainder] + ellipsis + t[len(t)-halfWidth:] +} diff --git a/pkg/cmd/gpgkey/list/list_test.go b/pkg/cmd/gpgkey/list/list_test.go new file mode 100644 index 0000000..9761a1b --- /dev/null +++ b/pkg/cmd/gpgkey/list/list_test.go @@ -0,0 +1,215 @@ +package list + +import ( + "fmt" + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/qubernetic/copia-cli/pkg/cmdutil" + "github.com/qubernetic/copia-cli/pkg/httpmock" + "github.com/qubernetic/copia-cli/pkg/iostreams" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const twoKeys = `[ + {"id":7,"primary_key_id":"","key_id":"3AA5C34371567BD2","public_key":"xsBNBGNpcGFjbGl0ZXN0a2V5b25lAAAA","emails":[{"email":"dev@example.com","verified":true},{"email":"work@example.com","verified":true}],"subkeys":[],"can_sign":true,"verified":true,"created_at":"2026-11-01T10:00:00Z","expires_at":"0001-01-01T00:00:00Z"}, + {"id":9,"primary_key_id":"","key_id":"4BB6D45482678CE3","public_key":"xsBNBGNpcGFjbGl0ZXN0a2V5dHdvAAAA","emails":[],"subkeys":[],"can_sign":false,"verified":false,"created_at":"2026-11-07T10:00:00Z","expires_at":"2027-11-07T10:00:00Z"} +]` + +func newOpts(reg *httpmock.Registry, ios *iostreams.IOStreams) *ListOptions { + return &ListOptions{ + IO: ios, + HTTPClient: &http.Client{Transport: reg}, + Host: "app.copia.io", + Token: "test-token", + Now: func() time.Time { return time.Date(2026, 11, 8, 10, 0, 0, 0, time.UTC) }, + } +} + +func TestListRun(t *testing.T) { + tests := []struct { + name string + tty bool + width int + body string + json []string + wantOut string + wantErrOut string + }{ + { + name: "without a terminal in gh's column order", + body: twoKeys, + wantOut: "dev@example.com, work@example.com\t3AA5C34371567BD2\txsBNBGNpcGFjbGl0ZXN0a2V5b25lAAAA\t2026-11-01T10:00:00Z\t0001-01-01T00:00:00Z\n" + + "\t4BB6D45482678CE3\txsBNBGNpcGFjbGl0ZXN0a2V5dHdvAAAA\t2026-11-07T10:00:00Z\t2027-11-07T10:00:00Z\n", + }, + { + name: "on a terminal with a header, the time in words and Never", + tty: true, + width: 200, + body: twoKeys, + wantOut: "EMAIL KEY ID PUBLIC KEY ADDED EXPIRES\n" + + "dev@example.com, work@example.com 3AA5C34371567BD2 xsBNBGNpcGFjbGl0ZXN0a2V5b25lAAAA 7 days ago Never\n" + + " 4BB6D45482678CE3 xsBNBGNpcGFjbGl0ZXN0a2V5dHdvAAAA 1 day ago 2027-11-07\n", + }, + { + name: "on a narrow terminal the public key is cut in the middle", + tty: true, + width: 72, + body: `[{"id":7,"key_id":"3AA5C34371567BD2","public_key":"xsBNBGNpcGFjbGl0ZXN0a2V5b25lAAAA","emails":[{"email":"a@b.c"}],"created_at":"2026-11-08T09:59:00Z","expires_at":"1970-01-01T00:00:00Z"}]`, + wantOut: "EMAIL KEY ID PUBLIC KEY ADDED EXPIRES\n" + + "a@b.c 3AA5C34371567BD2 xsBNBGNpcGF...V5b25lAAAA 1 minute ago Never\n", + }, + { + name: "no keys", + body: `[]`, + wantErrOut: "no GPG keys present in the Copia account\n", + }, + { + name: "no keys with --json prints an empty list", + body: `[]`, + json: []string{"id"}, + wantOut: "[]\n", + }, + { + name: "--json with the API's field names", + body: twoKeys, + json: validJSONFields, + wantOut: `[ + {"id":7,"key_id":"3AA5C34371567BD2","primary_key_id":"","emails":[{"email":"dev@example.com","verified":true},{"email":"work@example.com","verified":true}],"public_key":"xsBNBGNpcGFjbGl0ZXN0a2V5b25lAAAA","created_at":"2026-11-01T10:00:00Z","expires_at":"0001-01-01T00:00:00Z","verified":true,"can_sign":true}, + {"id":9,"key_id":"4BB6D45482678CE3","primary_key_id":"","emails":[],"public_key":"xsBNBGNpcGFjbGl0ZXN0a2V5dHdvAAAA","created_at":"2026-11-07T10:00:00Z","expires_at":"2027-11-07T10:00:00Z","verified":false,"can_sign":false} + ]`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + reg.Register( + httpmock.QueryMatcher("GET", "/api/v1/user/gpg_keys", url.Values{"page": {"1"}, "limit": {"50"}}), + httpmock.StringResponse(http.StatusOK, tt.body), + ) + + ios, _, stdout, stderr := iostreams.Test() + ios.SetStdoutTTY(tt.tty) + if tt.width > 0 { + ios.SetTerminalWidth(tt.width) + } + opts := newOpts(reg, ios) + opts.JSON = cmdutil.JSONFlags{Fields: tt.json} + + require.NoError(t, ListRun(opts)) + if tt.json != nil && tt.wantOut != "[]\n" { + assert.JSONEq(t, tt.wantOut, stdout.String()) + } else { + assert.Equal(t, tt.wantOut, stdout.String()) + } + assert.Equal(t, tt.wantErrOut, stderr.String()) + assert.Equal(t, "token test-token", reg.Requests[0].Header.Get("Authorization")) + }) + } +} + +func TestListRun_ReadsEveryPage(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + + var first []string + for i := 1; i <= 50; i++ { + first = append(first, fmt.Sprintf(`{"id":%d,"key_id":"K%d","public_key":"P%d","emails":[],"created_at":"2026-11-01T10:00:00Z","expires_at":"0001-01-01T00:00:00Z"}`, i, i, i)) + } + reg.Register( + httpmock.QueryMatcher("GET", "/api/v1/user/gpg_keys", url.Values{"page": {"1"}, "limit": {"50"}}), + httpmock.StringResponse(http.StatusOK, "["+strings.Join(first, ",")+"]"), + ) + reg.Register( + httpmock.QueryMatcher("GET", "/api/v1/user/gpg_keys", url.Values{"page": {"2"}, "limit": {"50"}}), + httpmock.StringResponse(http.StatusOK, `[{"id":51,"key_id":"LAST","public_key":"P51","emails":[],"created_at":"2026-11-01T10:00:00Z","expires_at":"0001-01-01T00:00:00Z"}]`), + ) + + ios, _, stdout, _ := iostreams.Test() + require.NoError(t, ListRun(newOpts(reg, ios))) + lines := strings.Split(strings.TrimSuffix(stdout.String(), "\n"), "\n") + assert.Len(t, lines, 51) + assert.True(t, strings.HasPrefix(lines[50], "\tLAST\t")) +} + +func TestListRun_HTTPError(t *testing.T) { + tests := []struct { + name string + body string + wantErr string + }{ + { + name: "with Gitea's message", + body: `{"message":"token does not have at least one of required scope(s): [read:user]"}`, + wantErr: "failed to list GPG keys (HTTP 403): token does not have at least one of required scope(s): [read:user]", + }, + { + name: "without a message", + body: ``, + wantErr: "failed to list GPG keys (HTTP 403)", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + reg.Register(httpmock.REST("GET", "/api/v1/user/gpg_keys"), httpmock.StringResponse(http.StatusForbidden, tt.body)) + + ios, _, stdout, _ := iostreams.Test() + err := ListRun(newOpts(reg, ios)) + require.EqualError(t, err, tt.wantErr) + assert.Empty(t, stdout.String()) + }) + } +} + +func TestTruncateMiddle(t *testing.T) { + assert.Equal(t, "abcdef", truncateMiddle(6, "abcdef")) + assert.Equal(t, "ab...ef", truncateMiddle(7, "abcdefghef")) + assert.Equal(t, "abc", truncateMiddle(3, "abcdefgh")) + assert.Equal(t, "ab...h", truncateMiddle(6, "abcdefgh")) +} + +func TestExpires(t *testing.T) { + assert.Equal(t, "Never", expires("0001-01-01T00:00:00Z")) + assert.Equal(t, "Never", expires("1970-01-01T00:00:00Z")) + assert.Equal(t, "Never", expires("1970-01-01T01:00:00+01:00")) + assert.Equal(t, "2027-11-07", expires("2027-11-07T10:00:00Z")) + assert.Equal(t, "soon", expires("soon")) +} + +func TestTimeAgo_KeepsAnUnparsableTime(t *testing.T) { + assert.Equal(t, "yesterday", timeAgo(time.Now(), "yesterday")) +} + +func TestNewCmdList(t *testing.T) { + ios, _, _, _ := iostreams.Test() + cmd := NewCmdList(&cmdutil.Factory{IOStreams: ios}) + assert.Equal(t, []string{"ls"}, cmd.Aliases) + assert.NotNil(t, cmd.Flags().Lookup("json")) + + cmd.SetArgs([]string{"extra"}) + cmd.SetOut(&strings.Builder{}) + cmd.SetErr(&strings.Builder{}) + assert.Error(t, cmd.Execute()) +} + +func TestNewCmdList_Runs(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + httpmock.ReplaceDefaultTransport(t, reg) + reg.Register(httpmock.REST("GET", "/api/v1/user/gpg_keys"), httpmock.StringResponse(http.StatusOK, twoKeys)) + + ios, _, stdout, _ := iostreams.Test() + cmd := NewCmdList(&cmdutil.Factory{IOStreams: ios, Host: "app.copia.io", Token: "flag-token"}) + cmd.SetArgs([]string{"--json", "id,key_id"}) + cmd.SetOut(&strings.Builder{}) + cmd.SetErr(&strings.Builder{}) + require.NoError(t, cmd.Execute()) + assert.JSONEq(t, `[{"id":7,"key_id":"3AA5C34371567BD2"},{"id":9,"key_id":"4BB6D45482678CE3"}]`, stdout.String()) + assert.Equal(t, "token flag-token", reg.Requests[0].Header.Get("Authorization")) +} diff --git a/pkg/cmd/repo/collaborator/add/add.go b/pkg/cmd/repo/collaborator/add/add.go new file mode 100644 index 0000000..8e91274 --- /dev/null +++ b/pkg/cmd/repo/collaborator/add/add.go @@ -0,0 +1,143 @@ +package add + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/url" + "regexp" + "slices" + "strings" + + "github.com/spf13/cobra" + "github.com/qubernetic/copia-cli/pkg/cmdutil" + "github.com/qubernetic/copia-cli/pkg/iostreams" +) + +// permissions are the values Gitea takes; it answers any other with 500. +var permissions = []string{"read", "write", "admin"} + +// loginPattern is the shape of a Gitea login. A login is a path segment of +// the request, so one that is not a login is refused before it is sent. +var loginPattern = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9_.-]*$`) + +// AddOptions holds all inputs for the repo collaborator add command. +type AddOptions struct { + IO *iostreams.IOStreams + HTTPClient *http.Client + Host string + Token string + Owner string + Repo string + Login string + Permission string +} + +type addRequest struct { + Permission string `json:"permission"` +} + +// NewCmdAdd creates the `copia-cli repo collaborator add` command. +func NewCmdAdd(f *cmdutil.Factory) *cobra.Command { + opts := &AddOptions{} + + cmd := &cobra.Command{ + Use: "add ", + Short: "Add a collaborator to a repository", + Long: `Add a user as a collaborator of a Copia repository with read, write or admin +permission (default write). For a user who is a collaborator already, the +permission is changed to the given one.`, + Args: cobra.ExactArgs(1), + Example: ` $ copia-cli repo collaborator add monalisa + $ copia-cli repo collaborator add monalisa --permission read + $ copia-cli repo collaborator add monalisa -p admin -R my-org/my-repo`, + RunE: func(cmd *cobra.Command, args []string) error { + opts.IO = f.IOStreams + opts.Login = args[0] + if err := validate(opts); err != nil { + return err + } + + host, token, err := f.ResolveAuth() + if err != nil { + return err + } + opts.Host = host + opts.Token = token + + owner, repo, err := f.ResolveRepo() + if err != nil { + return err + } + opts.Owner = owner + opts.Repo = repo + opts.HTTPClient = cmdutil.NewHTTPClient() + return AddRun(opts) + }, + } + + cmd.Flags().StringVarP(&opts.Permission, "permission", "p", "write", "Permission of the collaborator: {read|write|admin}") + + return cmd +} + +// ValidateLogin refuses a login that is not a Gitea login, so it never +// becomes a path segment of a request. +func ValidateLogin(login string) error { + if !loginPattern.MatchString(login) { + return fmt.Errorf("invalid login %q", login) + } + return nil +} + +// validate refuses a login or permission Gitea would not take. +func validate(opts *AddOptions) error { + if err := ValidateLogin(opts.Login); err != nil { + return err + } + if !slices.Contains(permissions, opts.Permission) { + return fmt.Errorf("invalid permission %q: use %s or %s", opts.Permission, strings.Join(permissions[:len(permissions)-1], ", "), permissions[len(permissions)-1]) + } + return nil +} + +func AddRun(opts *AddOptions) error { + if err := validate(opts); err != nil { + return err + } + + body, err := json.Marshal(addRequest{Permission: opts.Permission}) + if err != nil { + return err + } + u := fmt.Sprintf("https://%s/api/v1/repos/%s/%s/collaborators/%s", opts.Host, url.PathEscape(opts.Owner), url.PathEscape(opts.Repo), url.PathEscape(opts.Login)) + req, err := http.NewRequest("PUT", u, bytes.NewReader(body)) + if err != nil { + return err + } + req.Header.Set("Authorization", "token "+opts.Token) + req.Header.Set("Content-Type", "application/json") + + resp, err := opts.HTTPClient.Do(req) + if err != nil { + return fmt.Errorf("connecting to %s: %w", opts.Host, err) + } + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusNoContent { + message := cmdutil.ReadAPIMessage(resp.Body) + switch { + // Gitea answers an unknown user with 422 and "user ... does not + // exist [...]". + case resp.StatusCode == http.StatusUnprocessableEntity && (message == "" || strings.Contains(message, "does not exist")): + return fmt.Errorf("user %s not found", opts.Login) + case message != "": + return fmt.Errorf("failed to add collaborator (HTTP %d): %s", resp.StatusCode, message) + } + return fmt.Errorf("failed to add collaborator (HTTP %d)", resp.StatusCode) + } + + _, _ = fmt.Fprintf(opts.IO.Out, "Added %s to %s/%s with %s permission\n", opts.Login, opts.Owner, opts.Repo, opts.Permission) + return nil +} diff --git a/pkg/cmd/repo/collaborator/add/add_test.go b/pkg/cmd/repo/collaborator/add/add_test.go new file mode 100644 index 0000000..6f8a49c --- /dev/null +++ b/pkg/cmd/repo/collaborator/add/add_test.go @@ -0,0 +1,152 @@ +package add + +import ( + "errors" + "io" + "net/http" + "testing" + + "github.com/qubernetic/copia-cli/pkg/cmdutil" + "github.com/qubernetic/copia-cli/pkg/httpmock" + "github.com/qubernetic/copia-cli/pkg/iostreams" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const alicePath = "/api/v1/repos/my-org/my-repo/collaborators/alice" + +func runCmd(f *cmdutil.Factory, args ...string) error { + cmd := NewCmdAdd(f) + cmd.SetArgs(args) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + return cmd.Execute() +} + +// added answers 204 to a PUT that carries the token and wantBody. +func added(t *testing.T, wantBody string) httpmock.Responder { + return func(req *http.Request) (*http.Response, error) { + assert.Equal(t, "token test-token", req.Header.Get("Authorization")) + assert.Equal(t, "application/json", req.Header.Get("Content-Type")) + body, err := io.ReadAll(req.Body) + require.NoError(t, err) + assert.JSONEq(t, wantBody, string(body)) + return httpmock.StringResponse(http.StatusNoContent, "")(req) + } +} + +func TestNewCmdAdd(t *testing.T) { + tests := []struct { + name string + args []string + permission string + }{ + {name: "default", args: []string{"alice"}, permission: "write"}, + {name: "read", args: []string{"alice", "--permission", "read"}, permission: "read"}, + {name: "write", args: []string{"alice", "-p", "write"}, permission: "write"}, + {name: "admin", args: []string{"alice", "-p", "admin"}, permission: "admin"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + httpmock.ReplaceDefaultTransport(t, reg) + reg.Register(httpmock.REST("PUT", alicePath), added(t, `{"permission":"`+tt.permission+`"}`)) + + ios, _, stdout, stderr := iostreams.Test() + f := &cmdutil.Factory{IOStreams: ios, Host: "app.copia.io", Token: "test-token", Repo: "my-org/my-repo"} + + require.NoError(t, runCmd(f, tt.args...)) + assert.Equal(t, "Added alice to my-org/my-repo with "+tt.permission+" permission\n", stdout.String()) + assert.Empty(t, stderr.String()) + }) + } +} + +func TestNewCmdAdd_Refused(t *testing.T) { + tests := []struct { + name string + args []string + wantErr string + }{ + {name: "no login", args: []string{}, wantErr: "accepts 1 arg(s), received 0"}, + {name: "two logins", args: []string{"alice", "bob"}, wantErr: "accepts 1 arg(s), received 2"}, + {name: "owner permission", args: []string{"alice", "-p", "owner"}, wantErr: `invalid permission "owner": use read, write or admin`}, + {name: "upper case permission", args: []string{"alice", "-p", "Write"}, wantErr: `invalid permission "Write": use read, write or admin`}, + {name: "empty permission", args: []string{"alice", "-p", ""}, wantErr: `invalid permission "": use read, write or admin`}, + {name: "login with a slash", args: []string{"a/b"}, wantErr: `invalid login "a/b"`}, + {name: "dot dot", args: []string{".."}, wantErr: `invalid login ".."`}, + {name: "empty login", args: []string{""}, wantErr: `invalid login ""`}, + {name: "login with a control character", args: []string{"al\x1bice"}, wantErr: `invalid login "al\x1bice"`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + httpmock.ReplaceDefaultTransport(t, reg) + + ios, _, stdout, _ := iostreams.Test() + f := &cmdutil.Factory{IOStreams: ios, Host: "app.copia.io", Token: "test-token", Repo: "my-org/my-repo"} + + require.EqualError(t, runCmd(f, tt.args...), tt.wantErr) + assert.Empty(t, stdout.String()) + assert.Empty(t, reg.Requests) + }) + } +} + +func TestAddRun_Errors(t *testing.T) { + tests := []struct { + name string + respond httpmock.Responder + wantErr string + }{ + { + name: "unknown user", + respond: httpmock.StringResponse(http.StatusUnprocessableEntity, `{"message":"user redirect does not exist [name: alice]"}`), + wantErr: "user alice not found", + }, + { + name: "unknown user without a message", + respond: httpmock.StringResponse(http.StatusUnprocessableEntity, ``), + wantErr: "user alice not found", + }, + { + name: "other unprocessable entity", + respond: httpmock.StringResponse(http.StatusUnprocessableEntity, `{"message":"user is inactive"}`), + wantErr: "failed to add collaborator (HTTP 422): user is inactive", + }, + { + name: "missing scope", + respond: httpmock.StringResponse(http.StatusForbidden, `{"message":"token does not have at least one of required scope(s): [write:repository]"}`), + wantErr: "failed to add collaborator (HTTP 403): token does not have at least one of required scope(s): [write:repository]", + }, + { + name: "no message", + respond: httpmock.StringResponse(http.StatusInternalServerError, `oops`), + wantErr: "failed to add collaborator (HTTP 500)", + }, + { + name: "transport error", + respond: func(*http.Request) (*http.Response, error) { return nil, errors.New("boom") }, + wantErr: "connecting to app.copia.io", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + reg.Register(httpmock.REST("PUT", alicePath), tt.respond) + + ios, _, stdout, _ := iostreams.Test() + err := AddRun(&AddOptions{ + IO: ios, HTTPClient: &http.Client{Transport: reg}, + Host: "app.copia.io", Token: "test-token", + Owner: "my-org", Repo: "my-repo", + Login: "alice", Permission: "write", + }) + assert.ErrorContains(t, err, tt.wantErr) + assert.Empty(t, stdout.String()) + }) + } +} diff --git a/pkg/cmd/repo/collaborator/collaborator.go b/pkg/cmd/repo/collaborator/collaborator.go new file mode 100644 index 0000000..0770cb6 --- /dev/null +++ b/pkg/cmd/repo/collaborator/collaborator.go @@ -0,0 +1,26 @@ +package collaborator + +import ( + "github.com/spf13/cobra" + addCmd "github.com/qubernetic/copia-cli/pkg/cmd/repo/collaborator/add" + listCmd "github.com/qubernetic/copia-cli/pkg/cmd/repo/collaborator/list" + removeCmd "github.com/qubernetic/copia-cli/pkg/cmd/repo/collaborator/remove" + "github.com/qubernetic/copia-cli/pkg/cmdutil" +) + +// NewCmdCollaborator creates the `copia-cli repo collaborator` command group. +func NewCmdCollaborator(f *cmdutil.Factory) *cobra.Command { + cmd := &cobra.Command{ + Use: "collaborator ", + Short: "Manage repository collaborators", + Long: "Manage the collaborators of a Copia repository.", + } + + cmdutil.AddGroup(cmd, "General commands", + listCmd.NewCmdList(f), + addCmd.NewCmdAdd(f), + removeCmd.NewCmdRemove(f), + ) + + return cmd +} diff --git a/pkg/cmd/repo/collaborator/collaborator_test.go b/pkg/cmd/repo/collaborator/collaborator_test.go new file mode 100644 index 0000000..4d2a857 --- /dev/null +++ b/pkg/cmd/repo/collaborator/collaborator_test.go @@ -0,0 +1,24 @@ +package collaborator + +import ( + "testing" + + "github.com/qubernetic/copia-cli/pkg/cmdutil" + "github.com/stretchr/testify/assert" +) + +func TestNewCmdCollaborator_Subcommands(t *testing.T) { + cmd := NewCmdCollaborator(&cmdutil.Factory{}) + + assert.Equal(t, "collaborator ", cmd.Use) + + groups := map[string]string{} + for _, c := range cmd.Commands() { + groups[c.Name()] = c.GroupID + } + assert.Equal(t, map[string]string{ + "list": "General commands", + "add": "General commands", + "remove": "General commands", + }, groups) +} diff --git a/pkg/cmd/repo/collaborator/list/list.go b/pkg/cmd/repo/collaborator/list/list.go new file mode 100644 index 0000000..77b4593 --- /dev/null +++ b/pkg/cmd/repo/collaborator/list/list.go @@ -0,0 +1,135 @@ +package list + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "text/tabwriter" + + "github.com/spf13/cobra" + "github.com/qubernetic/copia-cli/pkg/cmdutil" + "github.com/qubernetic/copia-cli/pkg/iostreams" +) + +var validJSONFields = []string{"login", "full_name"} + +// ListOptions holds all inputs for the repo collaborator list command. +type ListOptions struct { + IO *iostreams.IOStreams + HTTPClient *http.Client + Host string + Token string + Owner string + Repo string + Limit int + JSON cmdutil.JSONFlags +} + +// Collaborator is one collaborator of a repository. It has no permission: +// Copia does not register Gitea's route for one collaborator's permission. +type Collaborator struct { + Login string `json:"login"` + FullName string `json:"full_name"` +} + +// NewCmdList creates the `copia-cli repo collaborator list` command. +func NewCmdList(f *cmdutil.Factory) *cobra.Command { + opts := &ListOptions{} + + cmd := &cobra.Command{ + Use: "list", + Short: "List collaborators of a repository", + Long: `List the collaborators of a Copia repository with their login and name. + +Use --limit to control how many collaborators are returned (default 30).`, + Aliases: []string{"ls"}, + Args: cobra.NoArgs, + Example: ` $ copia-cli repo collaborator list + $ copia-cli repo collaborator list -R my-org/my-repo --limit 100 + $ copia-cli repo collaborator list --json login,full_name`, + RunE: func(cmd *cobra.Command, args []string) error { + opts.IO = f.IOStreams + host, token, err := f.ResolveAuth() + if err != nil { + return err + } + opts.Host = host + opts.Token = token + + owner, repo, err := f.ResolveRepo() + if err != nil { + return err + } + opts.Owner = owner + opts.Repo = repo + opts.HTTPClient = cmdutil.NewHTTPClient() + return ListRun(opts) + }, + } + + cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum number of collaborators") + cmdutil.AddJSONFlags(cmd, &opts.JSON, validJSONFields) + + return cmd +} + +func decodeCollaborators(body []byte) ([]Collaborator, error) { + var users []Collaborator + err := json.Unmarshal(body, &users) + return users, err +} + +func ListRun(opts *ListOptions) error { + if err := cmdutil.ValidateLimit(opts.Limit); err != nil { + return err + } + + base := fmt.Sprintf("https://%s/api/v1/repos/%s/%s/collaborators", opts.Host, url.PathEscape(opts.Owner), url.PathEscape(opts.Repo)) + collaborators, err := cmdutil.FetchPages(opts.HTTPClient, base, opts.Token, opts.Limit, decodeCollaborators) + if err != nil { + var httpErr *cmdutil.HTTPError + if errors.As(err, &httpErr) { + return apiError("failed to list collaborators", httpErr.StatusCode, httpErr.Message) + } + return err + } + + if opts.JSON.IsJSON() { + return opts.JSON.Print(opts.IO.Out, collaborators) + } + + if len(collaborators) == 0 { + _, _ = fmt.Fprintf(opts.IO.ErrOut, "no collaborators found in %s/%s\n", opts.Owner, opts.Repo) + return nil + } + + if err := opts.IO.StartPager(); err != nil { + _, _ = fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err) + } + defer opts.IO.StopPager() + + if !opts.IO.IsStdoutTTY() { + for _, c := range collaborators { + _, _ = fmt.Fprintf(opts.IO.Out, "%s\t%s\n", c.Login, c.FullName) + } + return nil + } + + w := tabwriter.NewWriter(opts.IO.Out, 0, 0, 2, ' ', 0) + _, _ = fmt.Fprintln(w, "LOGIN\tNAME") + for _, c := range collaborators { + _, _ = fmt.Fprintf(w, "%s\t%s\n", c.Login, c.FullName) + } + return w.Flush() +} + +// apiError words a refusal of the API with its HTTP status and, when there +// is one, Gitea's message. +func apiError(what string, status int, message string) error { + if message != "" { + return fmt.Errorf("%s (HTTP %d): %s", what, status, message) + } + return fmt.Errorf("%s (HTTP %d)", what, status) +} diff --git a/pkg/cmd/repo/collaborator/list/list_test.go b/pkg/cmd/repo/collaborator/list/list_test.go new file mode 100644 index 0000000..0c1c071 --- /dev/null +++ b/pkg/cmd/repo/collaborator/list/list_test.go @@ -0,0 +1,239 @@ +package list + +import ( + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "testing" + + "github.com/qubernetic/copia-cli/pkg/cmdutil" + "github.com/qubernetic/copia-cli/pkg/httpmock" + "github.com/qubernetic/copia-cli/pkg/iostreams" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const collaboratorsPath = "/api/v1/repos/my-org/my-repo/collaborators" + +func runCmd(f *cmdutil.Factory, args ...string) error { + cmd := NewCmdList(f) + cmd.SetArgs(args) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + return cmd.Execute() +} + +func pageQuery(page, limit int) url.Values { + return url.Values{"page": {fmt.Sprint(page)}, "limit": {fmt.Sprint(limit)}} +} + +// usersJSON answers count collaborators user- and on. +func usersJSON(first, count int) string { + items := make([]string, count) + for i := range items { + n := first + i + items[i] = fmt.Sprintf(`{"id":%d,"login":"user-%d","full_name":"User %d"}`, n, n, n) + } + return "[" + strings.Join(items, ",") + "]" +} + +func newOpts(reg *httpmock.Registry, ios *iostreams.IOStreams, limit int) *ListOptions { + return &ListOptions{ + IO: ios, + HTTPClient: &http.Client{Transport: reg}, + Host: "app.copia.io", + Token: "test-token", + Owner: "my-org", + Repo: "my-repo", + Limit: limit, + } +} + +func TestNewCmdList(t *testing.T) { + tests := []struct { + name string + args []string + tty bool + want string + }{ + { + name: "no terminal", + want: "alice\tAlice A\nbob\t\n", + }, + { + name: "terminal", tty: true, + want: "LOGIN NAME\nalice Alice A\nbob \n", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + httpmock.ReplaceDefaultTransport(t, reg) + reg.Register( + httpmock.QueryMatcher("GET", collaboratorsPath, pageQuery(1, 30)), + httpmock.StringResponse(http.StatusOK, `[{"login":"alice","full_name":"Alice A"},{"login":"bob","full_name":""}]`), + ) + + ios, _, stdout, stderr := iostreams.Test() + ios.SetStdoutTTY(tt.tty) + f := &cmdutil.Factory{IOStreams: ios, Host: "app.copia.io", Token: "test-token", Repo: "my-org/my-repo"} + + require.NoError(t, runCmd(f, tt.args...)) + assert.Equal(t, tt.want, stdout.String()) + assert.Empty(t, stderr.String()) + }) + } +} + +func TestNewCmdList_Flags(t *testing.T) { + cmd := NewCmdList(&cmdutil.Factory{}) + assert.Equal(t, []string{"ls"}, cmd.Aliases) + flag := cmd.Flags().ShorthandLookup("L") + require.NotNil(t, flag) + assert.Equal(t, "limit", flag.Name) + assert.Equal(t, "30", flag.DefValue) + assert.Error(t, cmd.Args(cmd, []string{"extra"})) +} + +func TestListRun_Limit(t *testing.T) { + tests := []struct { + name string + limit int + pages [][3]int // page, page size asked, collaborators answered + want int + }{ + {name: "default limit", limit: 30, pages: [][3]int{{1, 30, 30}}, want: 30}, + {name: "past one page", limit: 80, pages: [][3]int{{1, 50, 50}, {2, 30, 30}}, want: 80}, + {name: "fewer than the limit", limit: 80, pages: [][3]int{{1, 50, 50}, {2, 30, 4}}, want: 54}, + {name: "limit of one", limit: 1, pages: [][3]int{{1, 1, 1}}, want: 1}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + first := 1 + for _, p := range tt.pages { + reg.Register( + httpmock.QueryMatcher("GET", collaboratorsPath, pageQuery(p[0], p[1])), + httpmock.StringResponse(http.StatusOK, usersJSON(first, p[2])), + ) + first += p[2] + } + + ios, _, stdout, _ := iostreams.Test() + require.NoError(t, ListRun(newOpts(reg, ios, tt.limit))) + assert.Equal(t, tt.want, strings.Count(stdout.String(), "\n")) + assert.Contains(t, stdout.String(), fmt.Sprintf("user-%d\tUser %d\n", tt.want, tt.want)) + }) + } +} + +func TestListRun_InvalidLimit(t *testing.T) { + ios, _, _, _ := iostreams.Test() + err := ListRun(&ListOptions{IO: ios, Limit: 0}) + assert.ErrorContains(t, err, "invalid limit") +} + +func TestListRun_JSON(t *testing.T) { + tests := []struct { + name string + users string + fields []string + jq string + want string + }{ + { + name: "all fields", + users: `[{"login":"alice","full_name":"Alice A","email":"alice@example.com"}]`, + fields: []string{"login", "full_name"}, + want: "[\n {\n \"full_name\": \"Alice A\",\n \"login\": \"alice\"\n }\n]\n", + }, + { + name: "jq", + users: `[{"login":"alice","full_name":"Alice A"}]`, + fields: []string{"login", "full_name"}, + jq: `.[] | .login + " " + .full_name`, + want: "alice Alice A\n", + }, + { + name: "no collaborators", + users: `[]`, + fields: []string{"login"}, + want: "[]\n", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + reg.Register(httpmock.REST("GET", collaboratorsPath), httpmock.StringResponse(http.StatusOK, tt.users)) + + ios, _, stdout, stderr := iostreams.Test() + opts := newOpts(reg, ios, 30) + opts.JSON = cmdutil.JSONFlags{Fields: tt.fields, JQ: tt.jq} + require.NoError(t, ListRun(opts)) + assert.Equal(t, tt.want, stdout.String()) + assert.Empty(t, stderr.String()) + }) + } +} + +func TestListRun_None(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + reg.Register(httpmock.REST("GET", collaboratorsPath), httpmock.StringResponse(http.StatusOK, `[]`)) + + ios, _, stdout, stderr := iostreams.Test() + require.NoError(t, ListRun(newOpts(reg, ios, 30))) + assert.Empty(t, stdout.String()) + assert.Equal(t, "no collaborators found in my-org/my-repo\n", stderr.String()) +} + +func TestListRun_Errors(t *testing.T) { + tests := []struct { + name string + list httpmock.Responder + wantErr string + }{ + { + name: "list refused with a message", + list: httpmock.StringResponse(http.StatusForbidden, `{"message":"token does not have at least one of required scope(s): [read:repository]"}`), + wantErr: "failed to list collaborators (HTTP 403): token does not have at least one of required scope(s): [read:repository]", + }, + { + name: "list refused without a message", + list: httpmock.StringResponse(http.StatusNotFound, ``), + wantErr: "failed to list collaborators (HTTP 404)", + }, + { + name: "list transport error", + list: func(*http.Request) (*http.Response, error) { return nil, errors.New("boom") }, + wantErr: "boom", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + reg.Register(httpmock.REST("GET", collaboratorsPath), tt.list) + + ios, _, stdout, _ := iostreams.Test() + err := ListRun(newOpts(reg, ios, 30)) + assert.ErrorContains(t, err, tt.wantErr) + assert.Empty(t, stdout.String()) + }) + } +} + +func TestNewCmdList_RefusesPermissionField(t *testing.T) { + // Copia has no route for one collaborator's permission. + httpmock.ReplaceDefaultTransport(t, &httpmock.Registry{}) + ios, _, _, _ := iostreams.Test() + f := &cmdutil.Factory{IOStreams: ios, Host: "app.copia.io", Token: "test-token", Repo: "my-org/my-repo"} + err := runCmd(f, "--json", "permission") + assert.ErrorContains(t, err, `unknown JSON field: "permission"`) +} diff --git a/pkg/cmd/repo/collaborator/remove/remove.go b/pkg/cmd/repo/collaborator/remove/remove.go new file mode 100644 index 0000000..7b285bc --- /dev/null +++ b/pkg/cmd/repo/collaborator/remove/remove.go @@ -0,0 +1,130 @@ +package remove + +import ( + "errors" + "fmt" + "net/http" + "net/url" + + "github.com/spf13/cobra" + collaboratoradd "github.com/qubernetic/copia-cli/pkg/cmd/repo/collaborator/add" + "github.com/qubernetic/copia-cli/pkg/cmdutil" + "github.com/qubernetic/copia-cli/pkg/iostreams" +) + +// RemoveOptions holds all inputs for the repo collaborator remove command. +type RemoveOptions struct { + IO *iostreams.IOStreams + HTTPClient *http.Client + Host string + Token string + Owner string + Repo string + Login string +} + +// NewCmdRemove creates the `copia-cli repo collaborator remove` command. +func NewCmdRemove(f *cmdutil.Factory) *cobra.Command { + opts := &RemoveOptions{} + var confirmed bool + + cmd := &cobra.Command{ + Use: "remove ", + Short: "Remove a collaborator from a repository", + Long: `Remove a user from the collaborators of a Copia repository. + +There is no prompt, so --yes is required.`, + Args: cobra.ExactArgs(1), + Example: ` $ copia-cli repo collaborator remove monalisa --yes + $ copia-cli repo collaborator remove monalisa -y -R my-org/my-repo`, + RunE: func(cmd *cobra.Command, args []string) error { + if !confirmed { + return errors.New("--yes required when not running interactively") + } + opts.IO = f.IOStreams + opts.Login = args[0] + if err := collaboratoradd.ValidateLogin(opts.Login); err != nil { + return err + } + + host, token, err := f.ResolveAuth() + if err != nil { + return err + } + opts.Host = host + opts.Token = token + + owner, repo, err := f.ResolveRepo() + if err != nil { + return err + } + opts.Owner = owner + opts.Repo = repo + opts.HTTPClient = cmdutil.NewHTTPClient() + return RemoveRun(opts) + }, + } + + cmd.Flags().BoolVarP(&confirmed, "yes", "y", false, "Skip the confirmation prompt") + + return cmd +} + +// RemoveRun checks with GET /repos/{owner}/{repo}/collaborators/{login} that +// the user is a collaborator and removes it with DELETE on the same path; +// Gitea answers 204 to a delete of a non-collaborator, so the check comes +// first. The command has checked --yes before. +func RemoveRun(opts *RemoveOptions) error { + if err := collaboratoradd.ValidateLogin(opts.Login); err != nil { + return err + } + u := fmt.Sprintf("https://%s/api/v1/repos/%s/%s/collaborators/%s", opts.Host, url.PathEscape(opts.Owner), url.PathEscape(opts.Repo), url.PathEscape(opts.Login)) + + status, message, err := send(opts, "GET", u) + if err != nil { + return err + } + switch { + case status == http.StatusNotFound: + return fmt.Errorf("%s is not a collaborator of %s/%s", opts.Login, opts.Owner, opts.Repo) + case status != http.StatusNoContent && message != "": + return fmt.Errorf("failed to check collaborator (HTTP %d): %s", status, message) + case status != http.StatusNoContent: + return fmt.Errorf("failed to check collaborator (HTTP %d)", status) + } + + status, message, err = send(opts, "DELETE", u) + if err != nil { + return err + } + switch { + case status != http.StatusNoContent && message != "": + return fmt.Errorf("failed to remove collaborator (HTTP %d): %s", status, message) + case status != http.StatusNoContent: + return fmt.Errorf("failed to remove collaborator (HTTP %d)", status) + } + + _, _ = fmt.Fprintf(opts.IO.Out, "Removed %s from %s/%s\n", opts.Login, opts.Owner, opts.Repo) + return nil +} + +// send makes an authenticated request without a body and returns the +// status and, for any status but 204, Gitea's message. +func send(opts *RemoveOptions, method, u string) (int, string, error) { + req, err := http.NewRequest(method, u, nil) + if err != nil { + return 0, "", err + } + req.Header.Set("Authorization", "token "+opts.Token) + + resp, err := opts.HTTPClient.Do(req) + if err != nil { + return 0, "", fmt.Errorf("connecting to %s: %w", opts.Host, err) + } + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode == http.StatusNoContent { + return resp.StatusCode, "", nil + } + return resp.StatusCode, cmdutil.ReadAPIMessage(resp.Body), nil +} diff --git a/pkg/cmd/repo/collaborator/remove/remove_test.go b/pkg/cmd/repo/collaborator/remove/remove_test.go new file mode 100644 index 0000000..c4d30f1 --- /dev/null +++ b/pkg/cmd/repo/collaborator/remove/remove_test.go @@ -0,0 +1,171 @@ +package remove + +import ( + "errors" + "io" + "net/http" + "testing" + + "github.com/qubernetic/copia-cli/pkg/cmdutil" + "github.com/qubernetic/copia-cli/pkg/httpmock" + "github.com/qubernetic/copia-cli/pkg/iostreams" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const alicePath = "/api/v1/repos/my-org/my-repo/collaborators/alice" + +func runCmd(f *cmdutil.Factory, args ...string) error { + cmd := NewCmdRemove(f) + cmd.SetArgs(args) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + return cmd.Execute() +} + +// noContent answers 204 to a request that carries the token. +func noContent(t *testing.T) httpmock.Responder { + return func(req *http.Request) (*http.Response, error) { + assert.Equal(t, "token test-token", req.Header.Get("Authorization")) + return httpmock.StringResponse(http.StatusNoContent, "")(req) + } +} + +func TestNewCmdRemove(t *testing.T) { + for _, yes := range []string{"--yes", "-y"} { + t.Run(yes, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + httpmock.ReplaceDefaultTransport(t, reg) + reg.Register(httpmock.REST("GET", alicePath), noContent(t)) + reg.Register(httpmock.REST("DELETE", alicePath), noContent(t)) + + ios, _, stdout, stderr := iostreams.Test() + f := &cmdutil.Factory{IOStreams: ios, Host: "app.copia.io", Token: "test-token", Repo: "my-org/my-repo"} + + require.NoError(t, runCmd(f, "alice", yes)) + assert.Equal(t, "Removed alice from my-org/my-repo\n", stdout.String()) + assert.Empty(t, stderr.String()) + }) + } +} + +func TestNewCmdRemove_Refused(t *testing.T) { + tests := []struct { + name string + args []string + wantErr string + }{ + {name: "no --yes", args: []string{"alice"}, wantErr: "--yes required when not running interactively"}, + {name: "no --yes before the login check", args: []string{"a/b"}, wantErr: "--yes required when not running interactively"}, + {name: "no login", args: []string{"--yes"}, wantErr: "accepts 1 arg(s), received 0"}, + {name: "two logins", args: []string{"alice", "bob", "--yes"}, wantErr: "accepts 1 arg(s), received 2"}, + {name: "login with a slash", args: []string{"a/b", "--yes"}, wantErr: `invalid login "a/b"`}, + {name: "dot dot", args: []string{"..", "--yes"}, wantErr: `invalid login ".."`}, + {name: "empty login", args: []string{"", "--yes"}, wantErr: `invalid login ""`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + httpmock.ReplaceDefaultTransport(t, reg) + + ios, _, stdout, _ := iostreams.Test() + f := &cmdutil.Factory{IOStreams: ios, Host: "app.copia.io", Token: "test-token", Repo: "my-org/my-repo"} + + require.EqualError(t, runCmd(f, tt.args...), tt.wantErr) + assert.Empty(t, stdout.String()) + assert.Empty(t, reg.Requests) + }) + } +} + +func TestRemoveRun_Errors(t *testing.T) { + tests := []struct { + name string + login string + host string + check httpmock.Responder + del httpmock.Responder + wantErr string + }{ + { + name: "not a collaborator", + check: httpmock.StringResponse(http.StatusNotFound, ``), + wantErr: "alice is not a collaborator of my-org/my-repo", + }, + { + name: "check refused with a message", + check: httpmock.StringResponse(http.StatusForbidden, `{"message":"token does not have at least one of required scope(s): [read:repository]"}`), + wantErr: "failed to check collaborator (HTTP 403): token does not have at least one of required scope(s): [read:repository]", + }, + { + name: "check refused without a message", + check: httpmock.StringResponse(http.StatusInternalServerError, `oops`), + wantErr: "failed to check collaborator (HTTP 500)", + }, + { + name: "transport error on check", + check: func(*http.Request) (*http.Response, error) { return nil, errors.New("boom") }, + wantErr: "connecting to app.copia.io", + }, + { + name: "delete refused with a message", + check: httpmock.StringResponse(http.StatusNoContent, ``), + del: httpmock.StringResponse(http.StatusForbidden, `{"message":"token does not have at least one of required scope(s): [write:repository]"}`), + wantErr: "failed to remove collaborator (HTTP 403): token does not have at least one of required scope(s): [write:repository]", + }, + { + name: "delete refused without a message", + check: httpmock.StringResponse(http.StatusNoContent, ``), + del: httpmock.StringResponse(http.StatusInternalServerError, ``), + wantErr: "failed to remove collaborator (HTTP 500)", + }, + { + name: "transport error on delete", + check: httpmock.StringResponse(http.StatusNoContent, ``), + del: func(*http.Request) (*http.Response, error) { return nil, errors.New("boom") }, + wantErr: "connecting to app.copia.io", + }, + { + name: "invalid host", + host: "bad\x7fhost", + wantErr: "invalid control character", + }, + { + name: "invalid login", + login: "a/b", + wantErr: `invalid login "a/b"`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + defer reg.Verify(t) + if tt.check != nil { + reg.Register(httpmock.REST("GET", alicePath), tt.check) + } + if tt.del != nil { + reg.Register(httpmock.REST("DELETE", alicePath), tt.del) + } + host := tt.host + if host == "" { + host = "app.copia.io" + } + login := tt.login + if login == "" { + login = "alice" + } + + ios, _, stdout, _ := iostreams.Test() + err := RemoveRun(&RemoveOptions{ + IO: ios, HTTPClient: &http.Client{Transport: reg}, + Host: host, Token: "test-token", + Owner: "my-org", Repo: "my-repo", + Login: login, + }) + assert.ErrorContains(t, err, tt.wantErr) + assert.Empty(t, stdout.String()) + }) + } +} diff --git a/pkg/cmd/repo/repo.go b/pkg/cmd/repo/repo.go index adfa8a9..0825514 100644 --- a/pkg/cmd/repo/repo.go +++ b/pkg/cmd/repo/repo.go @@ -4,6 +4,7 @@ import ( "github.com/spf13/cobra" archiveCmd "github.com/qubernetic/copia-cli/pkg/cmd/repo/archive" cloneCmd "github.com/qubernetic/copia-cli/pkg/cmd/repo/clone" + collaboratorCmd "github.com/qubernetic/copia-cli/pkg/cmd/repo/collaborator" createCmd "github.com/qubernetic/copia-cli/pkg/cmd/repo/create" deleteCmd "github.com/qubernetic/copia-cli/pkg/cmd/repo/delete" editCmd "github.com/qubernetic/copia-cli/pkg/cmd/repo/edit" @@ -41,6 +42,7 @@ func NewCmdRepo(f *cmdutil.Factory) *cobra.Command { forkCmd.NewCmdFork(f), setDefaultCmd.NewCmdSetDefault(f), syncCmd.NewCmdSync(f), + collaboratorCmd.NewCmdCollaborator(f), ) return cmd diff --git a/pkg/cmd/repo/repo_test.go b/pkg/cmd/repo/repo_test.go index f804f51..0286e30 100644 --- a/pkg/cmd/repo/repo_test.go +++ b/pkg/cmd/repo/repo_test.go @@ -28,7 +28,8 @@ func TestNewCmdRepo_Subcommands(t *testing.T) { "delete": "Targeted commands", "fork": "Targeted commands", "set-default": "Targeted commands", - "sync": "Targeted commands", + "sync": "Targeted commands", + "collaborator": "Targeted commands", }, groups) var titles []string diff --git a/pkg/cmdutil/apimessage.go b/pkg/cmdutil/apimessage.go new file mode 100644 index 0000000..7db16bb --- /dev/null +++ b/pkg/cmdutil/apimessage.go @@ -0,0 +1,40 @@ +package cmdutil + +import ( + "encoding/json" + "io" + "unicode/utf8" +) + +const ( + // MaxErrorBody is how much of an error response ReadAPIMessage reads. + MaxErrorBody = 64 << 10 + // MaxAPIMessage is the longest API message ReadAPIMessage returns, in + // bytes. + MaxAPIMessage = 512 +) + +// ReadAPIMessage returns the "message" of the JSON error body r, read up to +// MaxErrorBody bytes and cut to MaxAPIMessage bytes on a rune boundary, or +// "" when the body has none or is not JSON within that limit. A server can +// then not make copia-cli read or print an error of any size. +func ReadAPIMessage(r io.Reader) string { + data, err := io.ReadAll(io.LimitReader(r, MaxErrorBody)) + if err != nil { + return "" + } + var apiErr struct { + Message string `json:"message"` + } + if json.Unmarshal(data, &apiErr) != nil { + return "" + } + msg := apiErr.Message + if len(msg) > MaxAPIMessage { + msg = msg[:MaxAPIMessage] + for !utf8.ValidString(msg) { + msg = msg[:len(msg)-1] + } + } + return msg +} diff --git a/pkg/cmdutil/apimessage_test.go b/pkg/cmdutil/apimessage_test.go new file mode 100644 index 0000000..e8fce15 --- /dev/null +++ b/pkg/cmdutil/apimessage_test.go @@ -0,0 +1,39 @@ +package cmdutil + +import ( + "strings" + "testing" + "unicode/utf8" + + "github.com/stretchr/testify/assert" +) + +func TestReadAPIMessage(t *testing.T) { + tests := []struct { + name string + body string + want string + }{ + {name: "a message", body: `{"message":"Not Found","url":"x"}`, want: "Not Found"}, + {name: "no message", body: `{}`, want: ""}, + {name: "not JSON", body: `404 page not found`, want: ""}, + {name: "empty", body: ``, want: ""}, + {name: "a long message is cut", body: `{"message":"` + strings.Repeat("m", 10<<10) + `"}`, want: strings.Repeat("m", MaxAPIMessage)}, + // The body is read up to its limit only, so a message past it is + // not decoded at all. + {name: "a body past the limit", body: `{"message":"x","pad":"` + strings.Repeat("p", MaxErrorBody) + `"}`, want: ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, ReadAPIMessage(strings.NewReader(tt.body))) + }) + } +} + +func TestReadAPIMessage_CutsOnARuneBoundary(t *testing.T) { + // "é" is two bytes, so the cap falls inside the last rune. + got := ReadAPIMessage(strings.NewReader(`{"message":"a` + strings.Repeat("é", MaxAPIMessage) + `"}`)) + assert.LessOrEqual(t, len(got), MaxAPIMessage) + assert.True(t, utf8.ValidString(got)) + assert.Equal(t, MaxAPIMessage-1, len(got)) +} diff --git a/pkg/cmdutil/armor.go b/pkg/cmdutil/armor.go new file mode 100644 index 0000000..5f99a04 --- /dev/null +++ b/pkg/cmdutil/armor.go @@ -0,0 +1,44 @@ +package cmdutil + +import "strings" + +// ArmorKind is what CheckArmor finds in the armor headers of a key file. +type ArmorKind int + +const ( + // ArmorPublic: at least one armor header, and every one of them is the + // public key header. + ArmorPublic ArmorKind = iota + // ArmorPrivate: an armor header names a private or secret key. + ArmorPrivate + // ArmorOther: no armor header, or one that is neither. + ArmorOther +) + +// CheckArmor reads every line of content that holds "-----BEGIN ", also +// past its start. It is an allowlist: content is ArmorPublic only when it +// has such a line and each is exactly publicHeader (surrounding whitespace +// aside), so no other block, a private key of any format included, goes to +// the server with a public key. A header that names PRIVATE or SECRET, in +// any case and anywhere in the content, makes it ArmorPrivate. +func CheckArmor(content, publicHeader string) ArmorKind { + public, other := false, false + for _, line := range strings.Split(content, "\n") { + if !strings.Contains(line, "-----BEGIN ") { + continue + } + upper := strings.ToUpper(line) + if strings.Contains(upper, "PRIVATE") || strings.Contains(upper, "SECRET") { + return ArmorPrivate + } + if strings.TrimSpace(line) == publicHeader { + public = true + } else { + other = true + } + } + if public && !other { + return ArmorPublic + } + return ArmorOther +} diff --git a/pkg/cmdutil/armor_test.go b/pkg/cmdutil/armor_test.go new file mode 100644 index 0000000..1abffef --- /dev/null +++ b/pkg/cmdutil/armor_test.go @@ -0,0 +1,43 @@ +package cmdutil + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +const ( + gpgPublic = "-----BEGIN PGP PUBLIC KEY BLOCK-----" + publicKey = gpgPublic + "\n\nmDMEaS0ZRhYJKwYBBAHaRw8B\n=AbCd\n-----END PGP PUBLIC KEY BLOCK-----\n" +) + +func TestCheckArmor(t *testing.T) { + tests := []struct { + name string + content string + want ArmorKind + }{ + {name: "a public key", content: publicKey, want: ArmorPublic}, + {name: "two public keys", content: publicKey + publicKey, want: ArmorPublic}, + {name: "a public key with CRLF line ends", content: gpgPublic + "\r\n\r\nmDMEaS0Z\r\n-----END PGP PUBLIC KEY BLOCK-----\r\n", want: ArmorPublic}, + {name: "a PGP private key", content: "-----BEGIN PGP PRIVATE KEY BLOCK-----\nlFgE\n-----END PGP PRIVATE KEY BLOCK-----\n", want: ArmorPrivate}, + {name: "a legacy PGP secret key", content: "-----BEGIN PGP SECRET KEY BLOCK-----\nlFgE\n-----END PGP SECRET KEY BLOCK-----\n", want: ArmorPrivate}, + {name: "an OpenSSH private key", content: "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEA\n-----END OPENSSH PRIVATE KEY-----\n", want: ArmorPrivate}, + {name: "a PKCS#8 private key", content: "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIE\n-----END PRIVATE KEY-----\n", want: ArmorPrivate}, + {name: "an encrypted PKCS#8 private key", content: "-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIF\n-----END ENCRYPTED PRIVATE KEY-----\n", want: ArmorPrivate}, + {name: "an RSA private key", content: "-----BEGIN RSA PRIVATE KEY-----\nMIIE\n-----END RSA PRIVATE KEY-----\n", want: ArmorPrivate}, + {name: "a public key followed by a private key", content: publicKey + "-----BEGIN OPENSSH PRIVATE KEY-----\nb3Bl\n-----END OPENSSH PRIVATE KEY-----\n", want: ArmorPrivate}, + {name: "a private key header inside a line", content: publicKey + "x -----BEGIN EC PRIVATE KEY-----\n", want: ArmorPrivate}, + {name: "a lower-case secret header", content: "-----BEGIN pgp secret key block-----\n", want: ArmorPrivate}, + {name: "no armor", content: "mDMEaS0ZRhYJKwYBBAHaRw8BAQdA\n", want: ArmorOther}, + {name: "empty", content: "", want: ArmorOther}, + {name: "a signature", content: "-----BEGIN PGP SIGNATURE-----\niHUE\n-----END PGP SIGNATURE-----\n", want: ArmorOther}, + {name: "an SSH public key block", content: "-----BEGIN SSH2 PUBLIC KEY-----\nAAAA\n-----END SSH2 PUBLIC KEY-----\n", want: ArmorOther}, + {name: "a public key and a signature", content: publicKey + "-----BEGIN PGP SIGNATURE-----\niHUE\n", want: ArmorOther}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, CheckArmor(tt.content, gpgPublic)) + }) + } +} diff --git a/pkg/cmdutil/paginate.go b/pkg/cmdutil/paginate.go index 2610ae0..78c306c 100644 --- a/pkg/cmdutil/paginate.go +++ b/pkg/cmdutil/paginate.go @@ -15,9 +15,11 @@ import ( const MaxPageSize = 50 // HTTPError is returned by FetchPages when the API answers with a status -// other than 200. +// other than 200. Message is the message field of a JSON error body, or +// empty; Error leaves it out, so a caller decides whether to show it. type HTTPError struct { StatusCode int + Message string } func (e *HTTPError) Error() string { @@ -172,7 +174,7 @@ func getPage(client *http.Client, pageURL, token string) ([]byte, http.Header, e defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { - return nil, nil, &HTTPError{StatusCode: resp.StatusCode} + return nil, nil, &HTTPError{StatusCode: resp.StatusCode, Message: ReadAPIMessage(resp.Body)} } body, err := io.ReadAll(resp.Body) diff --git a/pkg/cmdutil/paginate_test.go b/pkg/cmdutil/paginate_test.go index c5912d6..1f0a8b3 100644 --- a/pkg/cmdutil/paginate_test.go +++ b/pkg/cmdutil/paginate_test.go @@ -178,6 +178,39 @@ func TestFetchPages_HTTPError(t *testing.T) { var httpErr *HTTPError require.ErrorAs(t, err, &httpErr) assert.Equal(t, http.StatusNotFound, httpErr.StatusCode) + assert.Empty(t, httpErr.Message) +} + +func TestFetchPages_HTTPErrorKeepsTheAPIMessage(t *testing.T) { + reg := &httpmock.Registry{} + reg.Register(httpmock.REST("GET", "/issues"), httpmock.StringResponse(http.StatusForbidden, `{"message":"token does not have at least one of required scope(s)","url":"x"}`)) + + _, err := FetchPages(&http.Client{Transport: reg}, pageURL, "test-token", 0, decodeItems) + var httpErr *HTTPError + require.ErrorAs(t, err, &httpErr) + assert.Equal(t, "API error (HTTP 403)", err.Error()) + assert.Equal(t, "token does not have at least one of required scope(s)", httpErr.Message) +} + +func TestFetchPages_HTTPErrorBoundsTheAPIMessage(t *testing.T) { + tests := []struct { + name string + body string + }{ + {name: "a 1 MiB body with a 100 KiB message", body: `{"message":"` + strings.Repeat("m", 100<<10) + `","pad":"` + strings.Repeat("p", 1<<20) + `"}`}, + {name: "a 10 KiB message", body: `{"message":"` + strings.Repeat("m", 10<<10) + `"}`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reg := &httpmock.Registry{} + reg.Register(httpmock.REST("GET", "/issues"), httpmock.StringResponse(http.StatusInternalServerError, tt.body)) + + _, err := FetchPages(&http.Client{Transport: reg}, pageURL, "test-token", 0, decodeItems) + var httpErr *HTTPError + require.ErrorAs(t, err, &httpErr) + assert.LessOrEqual(t, len(httpErr.Message), MaxAPIMessage) + }) + } } func TestFetchPages_DecodeError(t *testing.T) { diff --git a/test/integration/collaborator_test.go b/test/integration/collaborator_test.go new file mode 100644 index 0000000..46e7142 --- /dev/null +++ b/test/integration/collaborator_test.go @@ -0,0 +1,164 @@ +//go:build integration + +package integration + +import ( + "crypto/rand" + "encoding/hex" + "encoding/json" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/require" + + collaboratoradd "github.com/qubernetic/copia-cli/pkg/cmd/repo/collaborator/add" + collaboratorlist "github.com/qubernetic/copia-cli/pkg/cmd/repo/collaborator/list" + collaboratorremove "github.com/qubernetic/copia-cli/pkg/cmd/repo/collaborator/remove" + "github.com/qubernetic/copia-cli/pkg/cmdutil" +) + +// TestRepoCollaborator_AddAndList adds the test account itself to the run +// repository with read permission and finds it in repo collaborator list, +// which shows no permission: Copia does not register Gitea's route for one +// collaborator's permission. The collaborator goes with the run repository +// when TestMain deletes it. +func TestRepoCollaborator_AddAndList(t *testing.T) { + env := loadTestEnv(t) + + me := currentLogin(t, env) + + ios, out, _ := testIO() + err := collaboratoradd.AddRun(&collaboratoradd.AddOptions{ + IO: ios, HTTPClient: testHTTPClient(), + Host: env.Host, Token: env.Token, Owner: env.Owner, Repo: env.Repo, + Login: me, Permission: "read", + }) + require.True(t, err == nil, "repo collaborator add with read permission failed") + assertOutputContains(t, out.String(), " with read permission\n") + + // The add took effect: Gitea answers 204 for a collaborator. + status, _ := apiCall(t, env, "is collaborator", "GET", "/repos/"+env.Owner+"/"+env.Repo+"/collaborators/"+me, nil) + assertStatusCode(t, status, http.StatusNoContent) + + // The account is listed once, selected by its login in jq, so the + // output never holds the login. The error names the login, so only + // whether there is one is checked. + ios, out, _ = testIO() + err = collaboratorlist.ListRun(&collaboratorlist.ListOptions{ + IO: ios, HTTPClient: testHTTPClient(), + Host: env.Host, Token: env.Token, Owner: env.Owner, Repo: env.Repo, + Limit: 100, + JSON: cmdutil.JSONFlags{ + Fields: []string{"login"}, + JQ: `[.[] | select(.login == ` + jqString(me) + `)] | length`, + }, + }) + require.True(t, err == nil, "repo collaborator list --json failed") + assertOutputEqual(t, out.String(), "1\n") + + // Without a terminal: one line per collaborator, the login, a tab and + // the name. Checked with require.True, so the login is never printed. + ios, out, _ = testIO() + err = collaboratorlist.ListRun(&collaboratorlist.ListOptions{ + IO: ios, HTTPClient: testHTTPClient(), + Host: env.Host, Token: env.Token, Owner: env.Owner, Repo: env.Repo, + Limit: 100, + }) + require.True(t, err == nil, "repo collaborator list failed") + require.True(t, strings.Contains("\n"+out.String(), "\n"+me+"\t"), "repo collaborator list does not show the account") +} + +// TestRepoCollaboratorAdd_UnknownUser adds a login no account has. +func TestRepoCollaboratorAdd_UnknownUser(t *testing.T) { + env := loadTestEnv(t) + + // A random login, which no account has. + b := make([]byte, 8) + _, err := rand.Read(b) + require.NoError(t, err, "random login") + login := "it-nobody-" + hex.EncodeToString(b) + + ios, out, _ := testIO() + err = collaboratoradd.AddRun(&collaboratoradd.AddOptions{ + IO: ios, HTTPClient: testHTTPClient(), + Host: env.Host, Token: env.Token, Owner: env.Owner, Repo: env.Repo, + Login: login, Permission: "read", + }) + require.ErrorContains(t, err, "user "+login+" not found", "repo collaborator add of an unknown user") + assertOutputEmpty(t, out.String()) +} + +// jqString quotes s as a jq string literal. +func jqString(s string) string { + b, _ := json.Marshal(s) + return string(b) +} + +// TestRepoCollaborator_Remove adds the test account itself to the run +// repository, removes it with repo collaborator remove and no longer finds +// it in repo collaborator list. A second remove fails, since the account is +// no collaborator any more. +func TestRepoCollaborator_Remove(t *testing.T) { + env := loadTestEnv(t) + me := currentLogin(t, env) + + ios, _, _ := testIO() + err := collaboratoradd.AddRun(&collaboratoradd.AddOptions{ + IO: ios, HTTPClient: testHTTPClient(), + Host: env.Host, Token: env.Token, Owner: env.Owner, Repo: env.Repo, + Login: me, Permission: "read", + }) + require.True(t, err == nil, "repo collaborator add failed") + + // The success line names the login and the repository, so it is + // compared as a secret. + ios, out, _ := testIO() + err = collaboratorremove.RemoveRun(&collaboratorremove.RemoveOptions{ + IO: ios, HTTPClient: testHTTPClient(), + Host: env.Host, Token: env.Token, Owner: env.Owner, Repo: env.Repo, + Login: me, + }) + require.True(t, err == nil, "repo collaborator remove failed") + assertOutputEqualSecret(t, out.String(), "Removed "+me+" from "+env.Owner+"/"+env.Repo+"\n") + + // The remove took effect: Gitea answers 404 for a non-collaborator. + status, _ := apiCall(t, env, "is collaborator", "GET", "/repos/"+env.Owner+"/"+env.Repo+"/collaborators/"+me, nil) + assertStatusCode(t, status, http.StatusNotFound) + + ios, out, _ = testIO() + err = collaboratorlist.ListRun(&collaboratorlist.ListOptions{ + IO: ios, HTTPClient: testHTTPClient(), + Host: env.Host, Token: env.Token, Owner: env.Owner, Repo: env.Repo, + Limit: 100, + JSON: cmdutil.JSONFlags{ + Fields: []string{"login"}, + JQ: `[.[] | select(.login == ` + jqString(me) + `)] | length`, + }, + }) + require.True(t, err == nil, "repo collaborator list --json failed") + assertOutputEqual(t, out.String(), "0\n") + + // The error names the login, so only its fixed part is checked. + ios, out, _ = testIO() + err = collaboratorremove.RemoveRun(&collaboratorremove.RemoveOptions{ + IO: ios, HTTPClient: testHTTPClient(), + Host: env.Host, Token: env.Token, Owner: env.Owner, Repo: env.Repo, + Login: me, + }) + require.True(t, err != nil && strings.Contains(err.Error(), " is not a collaborator of "), "second repo collaborator remove did not fail as a non-collaborator") + assertOutputEmpty(t, out.String()) +} + +// currentLogin returns the login of the test account. +func currentLogin(t *testing.T, env testEnv) string { + t.Helper() + status, body := apiCall(t, env, "current user", "GET", "/user", nil) + assertStatusCode(t, status, http.StatusOK) + var me struct { + Login string `json:"login"` + } + require.NoError(t, json.Unmarshal(body, &me), "decode current user") + require.True(t, me.Login != "", "current user has a login") + return me.Login +} diff --git a/test/integration/gpgkey_test.go b/test/integration/gpgkey_test.go new file mode 100644 index 0000000..b5f78c1 --- /dev/null +++ b/test/integration/gpgkey_test.go @@ -0,0 +1,80 @@ +//go:build integration + +package integration + +import ( + "crypto/rand" + "encoding/hex" + "strings" + "testing" + + "github.com/stretchr/testify/require" + + gpgkeydelete "github.com/qubernetic/copia-cli/pkg/cmd/gpgkey/delete" + gpgkeylist "github.com/qubernetic/copia-cli/pkg/cmd/gpgkey/list" + "github.com/qubernetic/copia-cli/pkg/cmdutil" +) + +// Copia adds a GPG key only when one of its emails is a verified email of +// the account, and the tests never read the account's email, so no test +// adds a key: gpg-key add, and gpg-key delete of an existing key, are +// covered by their unit tests. + +func TestGPGKeyDelete_NotFound(t *testing.T) { + env := loadTestEnv(t) + + // A random key ID, which no key of the account has: the command reads + // every page of the list and refuses before any DELETE. + b := make([]byte, 8) + _, err := rand.Read(b) + require.NoError(t, err, "random key ID") + keyID := strings.ToUpper(hex.EncodeToString(b)) + + ios, out, _ := testIO() + err = gpgkeydelete.DeleteRun(&gpgkeydelete.DeleteOptions{ + IO: ios, HTTPClient: testHTTPClient(), + Host: env.Host, Token: env.Token, + KeyID: keyID, + }) + require.ErrorContains(t, err, "either the GPG key is not found or it is not owned by you", "gpg-key delete of an unknown key") + assertOutputEmpty(t, out.String()) + + // The list still has no key with that ID. + ios, out, _ = testIO() + err = gpgkeylist.ListRun(&gpgkeylist.ListOptions{ + IO: ios, HTTPClient: testHTTPClient(), + Host: env.Host, Token: env.Token, + JSON: cmdutil.JSONFlags{ + Fields: []string{"key_id"}, + JQ: `[.[] | select(.key_id == "` + keyID + `")] | length`, + }, + }) + require.NoError(t, err, "gpg-key list --json failed") + assertOutputEqual(t, out.String(), "0\n") +} + +func TestGPGKeyList_Run(t *testing.T) { + env := loadTestEnv(t) + + // Without a terminal: one line per key, or the no-keys message on + // standard error; either way no error. + ios, _, _ := testIO() + err := gpgkeylist.ListRun(&gpgkeylist.ListOptions{ + IO: ios, HTTPClient: testHTTPClient(), + Host: env.Host, Token: env.Token, + }) + require.NoError(t, err, "gpg-key list failed") + + // --json gives an array, also for an account without keys. + ios, out, _ := testIO() + err = gpgkeylist.ListRun(&gpgkeylist.ListOptions{ + IO: ios, HTTPClient: testHTTPClient(), + Host: env.Host, Token: env.Token, + JSON: cmdutil.JSONFlags{ + Fields: []string{"id", "key_id", "verified"}, + JQ: `type`, + }, + }) + require.NoError(t, err, "gpg-key list --json failed") + assertOutputEqual(t, out.String(), "array\n") +}