diff --git a/CHANGELOG.md b/CHANGELOG.md index b267266..775f0ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,68 @@ Notable changes, newest first. Release notes on GitHub list every commit; this file collects what users and scripts need to know. +## 0.26.0 (2026-11-07) + +### New + +- `norcube login` signs in through OAuth 2.0: the browser approves the + sign-in and hands the CLI a one-time code over `127.0.0.1`, which the CLI + exchanges with PKCE. The session's tokens no longer pass through the + dashboard page. `login --device` uses the same OAuth server. +- `norcube login --scopes backup.read,langsync.sync` limits a login to the + given scopes (the scopes CI tokens use; the default is `full`). The + login prints the scopes Norcube granted. Commands outside them exit with + code 5 (`insufficient_scope`) and the hint "This login is limited to …; + run `norcube login` for full access". A scope this release doesn't + know yet is still sent; Norcube Auth decides on it. +- `auth sessions list` has a SCOPES column (and `scopes` in JSON); + `whoami` and `auth status` show the login's scopes; `doctor` shows the + credential format and scopes and warns about the older format. +- `norcube logout` revokes the login's refresh token on Norcube (RFC 7009), + which ends its CLI session and removes it from Connected apps. A failure + on the server is reported, and the local sign-out happens anyway. +- `norcube login --force` ends the session it replaces on Norcube (the way + `logout` does) before storing the new one. If that fails, it warns and + signs in anyway. +- An account without an organization can sign in and use `whoami`, `org + list` and `org create`: Norcube Auth tokens are minted without an + organization. Product commands still need one. +- Fewer refreshes: a login refreshes one short-lived CLI token and + exchanges it per service and organization without the profile lock, so + parallel commands no longer queue behind each other. + +### Changes + +- `norcube upgrade` no longer links the deprecated `x/crypto/openpgp` + package (go-selfupdate 1.7.0). + +### Upgrading + +- A session from an older version moves to the new sign-in on its first + command, once, without signing in again (`auth status` and `doctor` only + describe the session and leave it as it is). A session made before + Norcube recorded CLI sessions can't be moved: the CLI asks for one + `norcube login`. +- After that move, an **older `norcube` binary** on the same machine must + sign in again: the session it knew was used up by the move. +- An older binary that keeps **its own copy** of the session's refresh + token (for example a copied credentials file) and presents it after the + move counts as a replayed token: Norcube then ends the session, which + signs the upgraded CLI out as well. Upgrade every `norcube` that shares a + session, or sign each in separately. +- Against a Norcube Auth that doesn't offer the OAuth sign-in yet, the CLI + keeps using the older sign-in for this release. CI tokens + (`NORCUBE_TOKEN`) are unchanged. + +### Changes for scripts + +- The credentials item of a profile has a new format (2): refresh token, + cached CLI access token, granted scopes and a format marker. Tokens per + service are no longer stored between commands. +- `login -o json` has `scopes`; `whoami -o json` and `auth status -o json` + have `scopes`, and `auth status` has `credentialFormat`. The `auth status` + and `auth sessions list` tables have a SCOPES column. + ## 0.25.0 (2026-11-06) ### New diff --git a/README.md b/README.md index 59d7544..cc91307 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,37 @@ and the Linux packages create it). Add `-o json` and `--query` to any command fo scripting, and `--org ` to target another organization for one command. +## Signing in + +`norcube login` opens the Norcube sign-in page in your browser. After you +approve the sign-in there, the browser hands the CLI a one-time code over +`127.0.0.1`, which the CLI exchanges for its session (OAuth 2.0 with PKCE: +the session's tokens never pass through the browser). The session is kept +in your OS keyring, per profile. + +```bash +norcube login # full access: everything you can do in the dashboard +norcube login --scopes backup.read,langsync.sync # only these scopes (the ones CI tokens use) +norcube login --device # approve on your phone or laptop (SSH, containers) +norcube auth sessions list # every login of your account, with its scopes +norcube logout # revoke the session on Norcube, then forget it here +``` + +- A login limited with `--scopes` refuses commands outside its scopes with + exit code 5 and says which login would allow them. Your own permissions + in each organization apply either way. +- Every login shows up under Account › CLI sessions and Account › + Connected apps in the dashboard. Revoking it there, or with + `norcube auth sessions revoke`, stops it at once. +- `norcube login --force` signs in again and ends the previous session on + Norcube. +- `norcube logout` revokes the login's refresh token on Norcube (RFC 7009), + so the session ends everywhere, and then removes it from this machine. If + Norcube can't be reached, it says so and signs out locally anyway. +- A session from an older `norcube` version moves to the new sign-in on its + first command, without signing in again. An older `norcube` binary on the + same machine then has to sign in again; see the [changelog](CHANGELOG.md). + ## In CI and on servers Create a CI token for the organization (scopes limit what it can do, and it diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9560bd7..f5ae874 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -33,7 +33,7 @@ maps them to stable codes and exit codes. | `internal/registry` | The service manifest (`services.yaml`, embedded): config key, product name, command name and aliases, OAuth audience, production endpoint, spec location, generated package. | | `internal/service` | `service.New[T]` resolves the target organization (explicit, `--org`/`NORCUBE_ORG`, a command default such as `.langsync.json`, then the profile), the endpoint, a token source and the shared transport, and returns the typed client. | | `internal/config`, `internal/resolve` | The config file (profiles, schema v2, migration) and which profile, endpoints, organization, credentials and output a command uses, each with its source. | -| `internal/auth`, `internal/credstore` | Browser login, the per-profile session (OS keyring or a 0600 file), the per-(audience, organization) access-token cache, and the refresh lock that keeps parallel commands from racing. | +| `internal/auth`, `internal/credstore` | Sign-in (OAuth browser and device flows, and the older flows for servers without them), the per-profile session (OS keyring or a 0600 file), the per-(audience, organization) token cache, and the refresh lock that keeps parallel commands from racing. See [Sign-in and tokens](#sign-in-and-tokens). | | `internal/transport` | The one HTTP client: connect and read timeouts, retries with backoff and `Retry-After`, proxy and CA bundle, User-Agent, and the redacting `--debug` trace. | | `internal/cmdutil`, `internal/output` | The result path: `--query` (JMESPath), the four output formats, pagination flags, `--wait` polling and `JobFailed`, `Confirm` and `Cancelled`, text and item input from files or stdin, safe file saves, renamed-command notes, and the command annotations (`annotations.go`: effect, flag enums, service) that `nrc commands` reads. | | `internal/clierr` | Error codes, exit codes and the JSON error shape. | @@ -47,6 +47,54 @@ prints the machine-readable command tree (schema in It reads only the tree, the annotations and the registry, never the network. +## Sign-in and tokens + +The CLI is a public, first-party OAuth 2.0 client of Norcube Auth +(`client_id` `norcube-cli`). Everything it needs is discovered from the +auth URL's RFC 8414 metadata (`/.well-known/oauth-authorization-server`), +cached for a day in the user cache directory. + +- **Browser sign-in** (`internal/auth/oauth.go`): authorization code with + PKCE (S256) and a random `state`, redirected to a loopback listener on + `127.0.0.1` and a random port (RFC 8252). The callback must carry the + `state` and the server's issuer (`iss`, RFC 9207) before the code is + exchanged. The authorization request names the scopes, the device's + hostname (`device_name`) and the CLI's User-Agent (`client_user_agent`) + for the consent screen and the session. +- **Device sign-in** (`internal/auth/device.go`): RFC 8628 against the + metadata's `device_authorization_endpoint`, polled at the token endpoint + (`authorization_pending`, `slow_down` adds five seconds, `access_denied`, + `expired_token`). +- **Tokens** (`internal/auth/oauthsession.go`): a sign-in gives a refresh + token and a 5-minute CLI access token, which no product accepts. Every + command exchanges it (RFC 8693) for a token per (audience, + organization; Norcube Auth's own `auth` audience also without one, for + an account that has none yet); exchanges use nothing up, run in parallel without any + lock and are cached in memory only. Refreshing rotates the refresh token, + so it runs under an in-process mutex plus a per-profile lock file, and + the rotated token is stored before the new access token is used. A + refused refresh re-reads the stored token once in case another process + rotated it meanwhile. +- **Credentials** (`internal/auth/keyring.go`): one item per profile. + Format 2 holds the refresh token, the cached CLI access token, the + granted scopes and a format marker; it fits the 2.5 KB Windows Credential + Manager limit, and a store that refuses it gets the blob without the + access token. Format 1 is the older sign-in (a refresh JWT that is + refreshed straight into per-service tokens, cached in the item too). It + is moved to format 2 once, under the lock, by a token exchange of the + refresh JWT; a token Norcube Auth won't move asks for one `norcube login`. +- **Errors**: a dead refresh token is `login_required` (exit 4), + `org_access_denied` is `permission_denied` (exit 5), and + `insufficient_scope` is `insufficient_scope` (exit 5) with a hint naming + the login's scopes. +- **Sign-out**: `logout` revokes the refresh token (RFC 7009); a format 1 + session uses the older sign-out endpoint. `login --force` ends the + session it replaces the same way, best effort. +- **Older servers**: when the metadata is missing or doesn't list the token + exchange grant, `login` uses the older sign-in (the web app's + `/cli-login` page and `/auth/cli/device/*`) and sessions refresh the + older way. CI tokens (`NORCUBE_TOKEN`) work as before. + ## Adding a service 1. **Manifest.** Add an entry to `internal/registry/services.yaml`: `key` @@ -120,7 +168,11 @@ secrets and the one-time setup. - `internal/cli` runs the real command tree in-process against a fake backend (`cli_test.go`) with a temporary config, cache and mocked - keyring. Golden files under `internal/cli/testdata/golden` pin every + keyring. `internal/auth/authtest` is a fake Norcube Auth OAuth server + (metadata, authorization redirect, code exchange, refresh with rotation + and reuse detection, token exchange, device flow, session upgrade, + revocation) for sign-in and token tests; a test "browser" follows the + authorization redirect to the CLI's loopback callback. Golden files under `internal/cli/testdata/golden` pin every output format; update them with `go test ./internal/cli -run TestGolden -update`. - Contract tests walk the tree: every command has an example, complete help text and an effect, nothing writes to stdout outside the result diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 07c2ebb..3dfd66a 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -458,15 +458,18 @@ themselves ([README, Verify a release](../README.md#verify-a-release)). ### P12. Authentication security model **Commitment.** -- **People sign in in the browser.** `nrc login` opens the dashboard, - the person approves while signed in, and the CLI receives its own CLI - session on a loopback listener bound to `127.0.0.1` with a random - `state`; only the dashboard's origin may call back. `--no-browser` - prints the URL; `--device` uses the device authorization flow (a short - code approved on any device). Nothing is pasted. +- **People sign in in the browser.** `nrc login` is a first-party OAuth + 2.0 client: the browser approves the sign-in and hands a one-time code + to a loopback listener on `127.0.0.1`, and the CLI exchanges it with + PKCE. The callback checks `state` and `iss`; a request with another + `state` is refused and the login keeps waiting. Metadata endpoints must + share the issuer's origin. `--no-browser` prints the URL; `--device` + uses the device authorization flow (a short code approved on any + device). `--scopes` limits a login. Nothing is pasted. - **Sessions are visible and revocable.** Each login is a named CLI - session (`nrc auth sessions list | revoke`, and in the dashboard); - `logout` ends it on Norcube Auth, `logout --all` for every profile. + session (`nrc auth sessions list | revoke`, and under Connected apps in + the dashboard); `logout` revokes it on Norcube Auth, `logout --all` for + every profile. - **One refresh token per profile, short-lived access tokens per (audience, organization).** Access tokens are minted per service and cached with an expiry computed from `expires_in` at receipt (immune to @@ -504,11 +507,6 @@ server that revokes on reuse), `keyring_concurrency_test.go`, `citoken_test.go`, `device_test.go`, `browser_test.go`, `session_check_test.go`, `logout_test.go`. -A first-party OAuth client design (authorization code with PKCE, scoped -logins with `--scopes`, sessions listed under Connected apps, RFC 7009 -revocation) was chosen on 2026-10-29 and is in development; until it -ships, the model above is the contract. - ### P13. One way to do each thing **Commitment.** Cross-cutting behaviour has exactly one implementation, diff --git a/go.mod b/go.mod index 819396f..0a35a57 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,7 @@ toolchain go1.26.10 require ( github.com/charmbracelet/huh v1.0.0 github.com/charmbracelet/lipgloss v1.1.0 - github.com/creativeprojects/go-selfupdate v1.5.2 + github.com/creativeprojects/go-selfupdate v1.7.0 github.com/getkin/kin-openapi v0.148.0 github.com/gofrs/flock v0.13.0 github.com/google/uuid v1.6.0 @@ -25,9 +25,10 @@ require ( ) require ( - code.gitea.io/sdk/gitea v0.22.1 // indirect - github.com/42wim/httpsig v1.2.3 // indirect - github.com/Masterminds/semver/v3 v3.4.0 // indirect + code.gitea.io/sdk/gitea v0.25.1 // indirect + github.com/42wim/httpsig v1.2.4 // indirect + github.com/Masterminds/semver/v3 v3.5.0 // indirect + github.com/ProtonMail/go-crypto v1.5.2 // indirect github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect github.com/atotto/clipboard v0.1.4 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect @@ -39,6 +40,7 @@ require ( github.com/charmbracelet/x/cellbuf v0.0.13 // indirect github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect github.com/charmbracelet/x/term v0.2.1 // indirect + github.com/cloudflare/circl v1.6.3 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.6 // indirect github.com/danieljoos/wincred v1.2.3 // indirect github.com/davidmz/go-pageant v1.0.2 // indirect @@ -48,11 +50,11 @@ require ( github.com/go-openapi/jsonpointer v0.22.5 // indirect github.com/go-openapi/swag/jsonname v0.25.5 // indirect github.com/godbus/dbus/v5 v5.2.2 // indirect - github.com/google/go-github/v74 v74.0.0 // indirect - github.com/google/go-querystring v1.1.0 // indirect + github.com/google/go-github/v86 v86.0.0 // indirect + github.com/google/go-querystring v1.2.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-retryablehttp v0.7.8 // indirect - github.com/hashicorp/go-version v1.8.0 // indirect + github.com/hashicorp/go-version v1.9.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect github.com/mattn/go-isatty v0.0.20 // indirect @@ -68,14 +70,14 @@ require ( github.com/rogpeppe/go-internal v1.16.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect - github.com/ulikunitz/xz v0.5.15 // indirect + github.com/ulikunitz/xz v0.5.17 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect - gitlab.com/gitlab-org/api/client-go v1.9.1 // indirect - go.yaml.in/yaml/v3 v3.0.4 // indirect + gitlab.com/gitlab-org/api/client-go v1.46.0 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/crypto v0.58.0 // indirect golang.org/x/exp v0.0.0-20250813145105-42675adae3e6 // indirect - golang.org/x/oauth2 v0.34.0 // indirect + golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/sys v0.49.0 // indirect golang.org/x/text v0.43.0 // indirect - golang.org/x/time v0.14.0 // indirect + golang.org/x/time v0.15.0 // indirect ) diff --git a/go.sum b/go.sum index 7e08e14..bd05717 100644 --- a/go.sum +++ b/go.sum @@ -1,11 +1,13 @@ -code.gitea.io/sdk/gitea v0.22.1 h1:7K05KjRORyTcTYULQ/AwvlVS6pawLcWyXZcTr7gHFyA= -code.gitea.io/sdk/gitea v0.22.1/go.mod h1:yyF5+GhljqvA30sRDreoyHILruNiy4ASufugzYg0VHM= -github.com/42wim/httpsig v1.2.3 h1:xb0YyWhkYj57SPtfSttIobJUPJZB9as1nsfo7KWVcEs= -github.com/42wim/httpsig v1.2.3/go.mod h1:nZq9OlYKDrUBhptd77IHx4/sZZD+IxTBADvAPI9G/EM= +code.gitea.io/sdk/gitea v0.25.1 h1:yywxWwoV+SdjHtbC6unBiXojWdZOtoHuGhEazEXeWuE= +code.gitea.io/sdk/gitea v0.25.1/go.mod h1:uDFWYBU8dgZsgOHwe6C/6olxvf8FHguNB3wW1i83fgg= +github.com/42wim/httpsig v1.2.4 h1:mI5bH0nm4xn7K18fo1K3okNDRq8CCJ0KbBYWyA6r8lU= +github.com/42wim/httpsig v1.2.4/go.mod h1:yKsYfSyTBEohkPik224QPFylmzEBtda/kjyIAJjh3ps= github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= -github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= -github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE= +github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/ProtonMail/go-crypto v1.5.2 h1:cucYnvqcY7UOXVD//mSyjeaPY0SSN3v5cDkYPxumINk= +github.com/ProtonMail/go-crypto v1.5.2/go.mod h1:/RaSu30DaKO4RY+XdV/ACcCcZkGr7AhUIduq5sjzzCo= github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk= github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ= github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= @@ -46,17 +48,17 @@ github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8 github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo= github.com/charmbracelet/x/xpty v0.1.2 h1:Pqmu4TEJ8KeA9uSkISKMU3f+C1F6OGBn8ABuGlqCbtI= github.com/charmbracelet/x/xpty v0.1.2/go.mod h1:XK2Z0id5rtLWcpeNiMYBccNNBrP2IJnzHI0Lq13Xzq4= +github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8= +github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4= github.com/cpuguy83/go-md2man/v2 v2.0.6 h1:XJtiaUW6dEEqVuZiMTn1ldk455QWwEIsMIJlo5vtkx0= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= -github.com/creativeprojects/go-selfupdate v1.5.2 h1:3KR3JLrq70oplb9yZzbmJ89qRP78D1AN/9u+l3k0LJ4= -github.com/creativeprojects/go-selfupdate v1.5.2/go.mod h1:BCOuwIl1dRRCmPNRPH0amULeZqayhKyY2mH/h4va7Dk= +github.com/creativeprojects/go-selfupdate v1.7.0 h1:hFqLlJHZLp2fZm91j+hdjT9EKRjOZ0b5M6bJAgTQwzg= +github.com/creativeprojects/go-selfupdate v1.7.0/go.mod h1:RVszRkQ0kVQB2hbqrsgrEl+sKGem5nR1qs8qdCicy+U= github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ= github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davidmz/go-pageant v1.0.2 h1:bPblRCh5jGU+Uptpz6LgMZGD5hJoOt7otgT454WvHn0= github.com/davidmz/go-pageant v1.0.2/go.mod h1:P2EDDnMqIwG5Rrp05dTRITj9z2zpGcD9efWSkTNKLIE= github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= @@ -81,23 +83,25 @@ github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ= github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= github.com/gofrs/flock v0.13.0 h1:95JolYOvGMqeH31+FC7D2+uULf6mG61mEZ/A8dRYMzw= github.com/gofrs/flock v0.13.0/go.mod h1:jxeyy9R1auM5S6JYDBhDt+E2TCo7DkratH4Pgi8P+Z0= -github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/go-github/v74 v74.0.0 h1:yZcddTUn8DPbj11GxnMrNiAnXH14gNs559AsUpNpPgM= -github.com/google/go-github/v74 v74.0.0/go.mod h1:ubn/YdyftV80VPSI26nSJvaEsTOnsjrxG3o9kJhcyak= -github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= -github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= +github.com/google/go-github/v86 v86.0.0 h1:S/6aANJhwRm8EQmGKVML3j41yq0h2BsTP8FnDkO7kcA= +github.com/google/go-github/v86 v86.0.0/go.mod h1:zKv1l4SwDXNFMGByi2FWkq71KwSXqj/eQRZuqtmcot8= +github.com/google/go-querystring v1.2.0 h1:yhqkPbu2/OH+V9BfpCVPZkNmUXhb2gBxJArfhIxNtP0= +github.com/google/go-querystring v1.2.0/go.mod h1:8IFJqpSRITyJ8QhQ13bmbeMBDfmeEJZD5A0egEOmkqU= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/graph-gophers/graphql-go v1.9.0 h1:yu0ucKHLc5qGpRwLYKIWtr9bOoxovkWasuBrPQwlHls= +github.com/graph-gophers/graphql-go v1.9.0/go.mod h1:23olKZ7duEvHlF/2ELEoSZaY1aNPfShjP782SOoNTyM= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48= github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw= -github.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4= -github.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA= +github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jmespath-community/go-jmespath v1.1.1 h1:bFikPhsi/FdmlZhVgSCd2jj1e7G/rw+zyQfyg5UF+L4= @@ -135,7 +139,6 @@ github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7ol github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= @@ -155,18 +158,19 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY= -github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/ulikunitz/xz v0.5.17 h1:flR0y/x1hgM8EGV1AW3Xll6T413G0glV8UfBwR617V4= +github.com/ulikunitz/xz v0.5.17/go.mod h1:H9Rt/W6/Qj27PGauhQc6nfCDy7vHpzsOThBSaYDoEhw= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs= github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0= -gitlab.com/gitlab-org/api/client-go v1.9.1 h1:tZm+URa36sVy8UCEHQyGGJ8COngV4YqMHpM6k9O5tK8= -gitlab.com/gitlab-org/api/client-go v1.9.1/go.mod h1:71yTJk1lnHCWcZLvM5kPAXzeJ2fn5GjaoV8gTOPd4ME= -go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +gitlab.com/gitlab-org/api/client-go v1.46.0 h1:YxBWFZIFYKcGESCb9fpkwzouo+apyB9pr/XTWzNoL24= +gitlab.com/gitlab-org/api/client-go v1.46.0/go.mod h1:FtgyU6g2HS5+fMhw6nLK96GBEEBx5MzntOiJWfIaiN8= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= @@ -176,8 +180,8 @@ golang.org/x/exp v0.0.0-20250813145105-42675adae3e6 h1:SbTAbRFnd5kjQXbczszQ0hdk3 golang.org/x/exp v0.0.0-20250813145105-42675adae3e6/go.mod h1:4QTo5u+SEIbbKW1RacMZq1YEfOBqeXa19JeshGi+zc4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw= -golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= +golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -195,10 +199,9 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= -golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= -golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= +golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= +golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= diff --git a/internal/api/auth.go b/internal/api/auth.go index ec510f3..7dfc090 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -100,6 +100,10 @@ type Session struct { ExpiresAt time.Time `json:"expires_at"` // Current marks the session the request's own token belongs to. Current bool `json:"current"` + // OAuthGrantID and Scopes describe an OAuth sign-in; both are null + // for the older sign-in, which always has full access. + OAuthGrantID *string `json:"oauth_grant_id,omitempty"` + Scopes []string `json:"scopes,omitempty"` } // SessionClient is what the session's CLI reported about itself; fields diff --git a/internal/auth/authtest/fakeauth.go b/internal/auth/authtest/fakeauth.go new file mode 100644 index 0000000..b77260d --- /dev/null +++ b/internal/auth/authtest/fakeauth.go @@ -0,0 +1,797 @@ +// Package authtest is a fake Norcube Auth for tests: the OAuth server the +// CLI signs in with (metadata, authorization redirect, code exchange, +// refresh with rotation and reuse detection, token exchange, device flow, +// session upgrade, revocation) plus the few account routes commands call +// right after a login. It keeps everything in memory and is safe for +// concurrent use. Only tests import it. +package authtest + +import ( + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "slices" + "strings" + "sync" + "sync/atomic" + "time" +) + +// Wire constants of the OAuth server. +// +// #nosec G101 -- OAuth grant and token type identifiers, not credentials. +const ( + ClientID = "norcube-cli" + GrantTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange" + GrantDeviceCode = "urn:ietf:params:oauth:grant-type:device_code" + TokenTypeAccess = "urn:ietf:params:oauth:token-type:access_token" + TokenTypeCLISession = "urn:norcube:params:oauth:token-type:cli-session" + // ReuseGrace: a refresh token rotated out less than this long ago is + // refused without ending the sign-in. + ReuseGrace = 10 * time.Second +) + +// Organizations the fake account belongs to. +const ( + HomeOrgID = "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d" + AcmeOrgID = "0b9d2b8e-1c1f-4c3e-9a51-6d1c2f9a7e01" + // OtherOrgID exists, but the account isn't a member. + OtherOrgID = "6f1e8a52-3d4b-4f7a-8c2e-9b0a1d2c3e4f" +) + +// scopeAudiences mirrors the server's catalog: which audiences a scope +// lets a sign-in be exchanged for. +var scopeAudiences = map[string][]string{ + "full": {"auth", "billing", "langsync-api", "snapdb-api", "prompthub", "domainradar", "cms-api", "monitor"}, + "org.read": {"auth"}, + "offline_access": nil, + "backup.read": {"snapdb-api"}, + "backup.write": {"snapdb-api"}, + "backup.verify": {"snapdb-api"}, + "domainradar.check": {"domainradar"}, + "langsync.read": {"langsync-api"}, + "langsync.sync": {"langsync-api"}, + "langsync.write": {"langsync-api"}, + "billing.read": {"billing"}, + "cms.read": {"cms-api"}, + "cms.write": {"cms-api"}, + "monitor.read": {"monitor"}, + "monitor.check": {"monitor"}, + "monitor.write": {"monitor"}, + "monitor.channels": {"monitor"}, + "monitor.statuspages": {"monitor"}, + "monitor.maintenance": {"monitor"}, +} + +// KnowsScope reports whether the fake's catalog has the scope. +func (s *Server) KnowsScope(scope string) bool { + _, ok := scopeAudiences[scope] + return ok +} + +// Grant is one sign-in (a CLI device). +type Grant struct { + ID string + Scopes []string + Revoked bool + // Refresh is the current refresh token; Access the current CLI + // access token. + Refresh string + Access string + // rotated maps refresh tokens rotated out to when. + rotated map[string]time.Time +} + +// Server is the fake. Set the knobs before the first request (or under +// Lock for a running test). +type Server struct { + *httptest.Server + + // OAuthOff makes the metadata 404 (an older Norcube Auth); NoExchange + // leaves the token exchange out of grant_types_supported. + OAuthOff bool + NoExchange bool + // NoDevice leaves the device endpoint out of the metadata. + NoDevice bool + // IssOff stops sending iss on the redirect (and says so). + IssOff bool + // WrongIss sends another issuer on the redirect. + WrongIss bool + // TokenEndpoint replaces the token endpoint the metadata names. + TokenEndpoint string + // Deny answers the authorization with access_denied. + Deny bool + // AccessTTL is the CLI access token's lifetime in seconds (299), + // ProductTTL the exchanged tokens' (300). + AccessTTL int + ProductTTL int + // Delay slows down refreshes and exchanges to widen race windows. + Delay time.Duration + // DeviceAnswers are the device polls' answers in order; after them + // the request is approved. + DeviceAnswers []string + // RevokeStatus, when set, is what /oauth/revoke answers. + RevokeStatus int + // NoDefaultOrg answers the sign-in with default_organization null. + NoDefaultOrg bool + // Clock replaces time.Now (grace checks). + Clock func() time.Time + + mu sync.Mutex + nextID int + codes map[string]*code + grants map[string]*Grant // by grant id + byAccess map[string]*Grant + // accessExp is when each CLI access token expires. + accessExp map[string]time.Time + byRT map[string]*Grant // current and rotated refresh tokens + product map[string]productToken + // legacy holds the older sign-in's refresh JWTs that may be upgraded + // (they have a session); a used one is kept in legacyUsed. + legacy map[string]bool + legacyUsed map[string]bool + // LegacyRefresh is the one refresh token the older cookie refresh + // accepts ("" for none). + LegacyRefresh string + device *deviceReq + + // Counters. + Authorizations int + CodeExchanges int + Refreshes int + Exchanges int + Upgrades int + UpgradeRefusals int + Reuses int + // GraceHits counts refresh tokens presented again within ReuseGrace: + // not a reuse, but in a race test a sign that two callers refreshed + // with the same token. + GraceHits int + Revocations []url.Values + SignOuts []url.Values + LegacyRefreshes int + DevicePolls int + // AuthorizeQuery and DeviceCodeForm are the last requests' values. + AuthorizeQuery url.Values + DeviceCodeForm url.Values + // RefreshTimes records when each refresh succeeded. + RefreshTimes []time.Time + + inflight atomic.Int32 + maxInflight atomic.Int32 +} + +type code struct { + challenge, redirect string + scopes []string +} + +type productToken struct { + audience, org string + scopes []string +} + +type deviceReq struct { + scopes []string + polls int + done bool +} + +// New starts a fake Norcube Auth. Close it when done. +func New() *Server { + s := &Server{ + AccessTTL: 299, + ProductTTL: 300, + codes: map[string]*code{}, + grants: map[string]*Grant{}, + byAccess: map[string]*Grant{}, + accessExp: map[string]time.Time{}, + byRT: map[string]*Grant{}, + product: map[string]productToken{}, + legacy: map[string]bool{}, legacyUsed: map[string]bool{}, + } + s.Server = httptest.NewServer(s) + return s +} + +// Lock and Unlock guard the knobs and counters while requests run. +func (s *Server) Lock() { s.mu.Lock() } +func (s *Server) Unlock() { s.mu.Unlock() } + +func (s *Server) now() time.Time { + if s.Clock != nil { + return s.Clock() + } + return time.Now() +} + +func (s *Server) id(prefix string) string { + s.nextID++ + return fmt.Sprintf("%s-%d", prefix, s.nextID) +} + +// jwt makes an unsigned token whose payload the CLI can read (exp). +func jwt(claims map[string]any) string { + h := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none"}`)) + p, _ := json.Marshal(claims) + return h + "." + base64.RawURLEncoding.EncodeToString(p) + ".sig" +} + +// NewGrant creates a sign-in directly (as if a login had happened) and +// returns it. No scopes means full. +func (s *Server) NewGrant(scopes ...string) *Grant { + s.mu.Lock() + defer s.mu.Unlock() + if len(scopes) == 0 { + scopes = []string{"full"} + } + return s.newGrant(normalize(append(scopes, "offline_access"))) +} + +func (s *Server) newGrant(scopes []string) *Grant { + g := &Grant{ID: s.id("grant"), Scopes: scopes, rotated: map[string]time.Time{}} + s.grants[g.ID] = g + s.issue(g) + return g +} + +// issue gives g a new refresh token and CLI access token. +func (s *Server) issue(g *Grant) { + if g.Refresh != "" { + g.rotated[g.Refresh] = s.now() + } + g.Refresh = "ory_rt_" + s.id("rt") + g.Access = jwt(map[string]any{ + "token_type": "cli_access", "grant_id": g.ID, "jti": s.id("at"), + "exp": s.now().Add(time.Duration(s.AccessTTL) * time.Second).Unix(), + }) + s.byRT[g.Refresh] = g + s.byAccess[g.Access] = g + s.accessExp[g.Access] = s.now().Add(time.Duration(s.AccessTTL) * time.Second) +} + +// AddLegacySession registers a refresh JWT of the older sign-in that has +// a session, so it can be upgraded (or refreshed the old way). +func (s *Server) AddLegacySession(refresh string) { + s.mu.Lock() + defer s.mu.Unlock() + s.legacy[refresh] = true + s.LegacyRefresh = refresh +} + +// Grant returns the grant a refresh token (current or rotated) belongs to. +func (s *Server) Grant(refresh string) *Grant { + s.mu.Lock() + defer s.mu.Unlock() + return s.byRT[refresh] +} + +// CurrentRefresh is the grant's current refresh token. +func (s *Server) CurrentRefresh(g *Grant) string { + s.mu.Lock() + defer s.mu.Unlock() + return g.Refresh +} + +// ExpireAccess makes the server refuse g's CLI access tokens issued so +// far, as if they had expired early. +func (s *Server) ExpireAccess(g *Grant) { + s.mu.Lock() + defer s.mu.Unlock() + for tok, owner := range s.byAccess { + if owner == g { + delete(s.byAccess, tok) + } + } +} + +// RevokeGrant ends a sign-in (session revoked in the dashboard). +func (s *Server) RevokeGrant(g *Grant) { + s.mu.Lock() + defer s.mu.Unlock() + g.Revoked = true +} + +// Rotate rotates g's refresh token as another process would. +func (s *Server) Rotate(g *Grant) string { + s.mu.Lock() + defer s.mu.Unlock() + s.issue(g) + return g.Refresh +} + +// Stats is a copy of the counters and the last requests' values. +type Stats struct { + Authorizations, CodeExchanges, Refreshes, Exchanges, Upgrades, UpgradeRefusals int + Reuses, GraceHits, LegacyRefreshes, DevicePolls int + Revocations, SignOuts []url.Values + AuthorizeQuery, DeviceCodeForm url.Values + RefreshTimes []time.Time +} + +// Stats returns the counters so far. +func (s *Server) Stats() Stats { + s.mu.Lock() + defer s.mu.Unlock() + return Stats{ + Authorizations: s.Authorizations, CodeExchanges: s.CodeExchanges, Refreshes: s.Refreshes, + Exchanges: s.Exchanges, Upgrades: s.Upgrades, UpgradeRefusals: s.UpgradeRefusals, + Reuses: s.Reuses, GraceHits: s.GraceHits, LegacyRefreshes: s.LegacyRefreshes, DevicePolls: s.DevicePolls, + Revocations: slices.Clone(s.Revocations), SignOuts: slices.Clone(s.SignOuts), + AuthorizeQuery: s.AuthorizeQuery, DeviceCodeForm: s.DeviceCodeForm, + RefreshTimes: slices.Clone(s.RefreshTimes), + } +} + +// Revoked reports whether g ended. +func (s *Server) Revoked(g *Grant) bool { + s.mu.Lock() + defer s.mu.Unlock() + return g.Revoked +} + +// MaxConcurrentExchanges is the most token exchanges seen in flight at +// once. +func (s *Server) MaxConcurrentExchanges() int { return int(s.maxInflight.Load()) } + +// Counts returns refreshes, exchanges and upgrades so far. +func (s *Server) Counts() (refreshes, exchanges, upgrades int) { + s.mu.Lock() + defer s.mu.Unlock() + return s.Refreshes, s.Exchanges, s.Upgrades +} + +func normalize(scopes []string) []string { + want := map[string]bool{"org.read": true} + for _, sc := range scopes { + want[sc] = true + } + var out []string + for _, sc := range []string{"full", "org.read", "offline_access", "backup.read", "backup.write", "backup.verify", + "domainradar.check", "langsync.read", "langsync.sync", "langsync.write", "billing.read", "cms.read", "cms.write", + "monitor.read", "monitor.check", "monitor.write", "monitor.channels", + "monitor.statuspages", "monitor.maintenance"} { + if !want[sc] || (want["full"] && sc != "full" && sc != "org.read" && sc != "offline_access") { + continue + } + out = append(out, sc) + } + return out +} + +func knownScopes(scopes []string) bool { + if len(scopes) == 0 { + return false + } + for _, sc := range scopes { + if _, ok := scopeAudiences[sc]; !ok { + return false + } + } + return true +} + +func allows(scopes []string, audience string) bool { + for _, sc := range scopes { + if slices.Contains(scopeAudiences[sc], audience) { + return true + } + } + return false +} + +func oauthErr(w http.ResponseWriter, status int, code, desc string) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]string{"error": code, "error_description": desc}) +} + +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/.well-known/oauth-authorization-server": + s.metadata(w, r) + case "/oauth/authorize": + s.authorize(w, r) + case "/oauth/token": + s.token(w, r) + case "/oauth/device/code": + s.deviceCode(w, r) + case "/oauth/revoke": + s.revoke(w, r) + case "/auth/cli/sign-out": + _ = r.ParseForm() + s.mu.Lock() + s.SignOuts = append(s.SignOuts, r.PostForm) + s.mu.Unlock() + w.WriteHeader(http.StatusNoContent) + case "/auth/me": + if s.bearer(w, r, "auth") { + fmt.Fprint(w, `{"id":"user-1","name":"Dev Eloper","email":"dev@example.com","avatarUrl":""}`) + } + case "/organizations": + if s.bearer(w, r, "auth") { + fmt.Fprintf(w, `[{"id":%q,"slug":"home","name":"Home","is_default":true},{"id":%q,"slug":"acme","name":"Acme Inc"}]`, HomeOrgID, AcmeOrgID) + } + case "/auth/me/sessions": + if s.bearer(w, r, "auth") { + fmt.Fprint(w, `[]`) + } + default: + http.NotFound(w, r) + } +} + +// bearer checks a product token for audience. Scoped tokens get 403 +// INSUFFICIENT_SCOPE when they're for another audience, like the +// products' own checks. +func (s *Server) bearer(w http.ResponseWriter, r *http.Request, audience string) bool { + w.Header().Set("Content-Type", "application/json") + tok := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + s.mu.Lock() + p, ok := s.product[tok] + s.mu.Unlock() + if !ok || p.audience != audience { + w.WriteHeader(http.StatusUnauthorized) + fmt.Fprint(w, `{"type":"UNAUTHORIZED","msg":"Unauthorized."}`) + return false + } + return true +} + +// ProductToken describes a token the fake minted, for assertions. +func (s *Server) ProductToken(tok string) (audience, org string, scopes []string, ok bool) { + s.mu.Lock() + defer s.mu.Unlock() + p, ok := s.product[tok] + return p.audience, p.org, p.scopes, ok +} + +func (s *Server) metadata(w http.ResponseWriter, _ *http.Request) { + s.mu.Lock() + defer s.mu.Unlock() + if s.OAuthOff { + w.WriteHeader(http.StatusNotFound) + return + } + grants := []string{"authorization_code", "refresh_token"} + if !s.NoDevice { + grants = append(grants, GrantDeviceCode) + } + if !s.NoExchange { + grants = append(grants, GrantTokenExchange) + } + m := map[string]any{ + "issuer": s.URL, + "authorization_endpoint": s.URL + "/oauth/authorize", + "token_endpoint": s.URL + "/oauth/token", + "registration_endpoint": s.URL + "/oauth/register", + "revocation_endpoint": s.URL + "/oauth/revoke", + "scopes_supported": []string{"org.read", "backup.read", "offline_access"}, + "response_types_supported": []string{"code"}, + "grant_types_supported": grants, + "code_challenge_methods_supported": []string{"S256"}, + "token_endpoint_auth_methods_supported": []string{"none"}, + "authorization_response_iss_parameter_supported": !s.IssOff, + } + if !s.NoDevice { + m["device_authorization_endpoint"] = s.URL + "/oauth/device/code" + } + if s.TokenEndpoint != "" { + m["token_endpoint"] = s.TokenEndpoint + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(m) +} + +// authorize plays the authorization endpoint and the consent page at +// once: it approves (or denies) and redirects back to the loopback +// callback. +func (s *Server) authorize(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + s.mu.Lock() + defer s.mu.Unlock() + s.Authorizations++ + s.AuthorizeQuery = q + redirect := q.Get("redirect_uri") + u, err := url.Parse(redirect) + if err != nil || u.Scheme != "http" || u.Hostname() != "127.0.0.1" || u.Path != "/callback" || u.Port() == "" { + http.Error(w, "redirect_uri must be http://127.0.0.1:/callback", http.StatusBadRequest) + return + } + if q.Get("client_id") != ClientID || q.Get("response_type") != "code" || + q.Get("code_challenge_method") != "S256" || q.Get("code_challenge") == "" { + http.Error(w, "bad authorization request", http.StatusBadRequest) + return + } + back := url.Values{"state": {q.Get("state")}} + switch { + case s.WrongIss: + back.Set("iss", "https://evil.example") + case !s.IssOff: + back.Set("iss", s.URL) + } + scopes := strings.Fields(q.Get("scope")) + switch { + case !knownScopes(scopes): + back.Set("error", "invalid_scope") + back.Set("error_description", "Unknown or missing scope.") + case s.Deny: + back.Set("error", "access_denied") + back.Set("error_description", "The person denied the sign-in.") + default: + c := s.id("code") + s.codes[c] = &code{challenge: q.Get("code_challenge"), redirect: redirect, scopes: normalize(scopes)} + back.Set("code", c) + } + u.RawQuery = back.Encode() + http.Redirect(w, r, u.String(), http.StatusFound) // #nosec G710 -- checked above: the loopback callback +} + +func (s *Server) signInResponse(w http.ResponseWriter, g *Grant) { + resp := map[string]any{ + "access_token": g.Access, "token_type": "bearer", "expires_in": s.AccessTTL, + "refresh_token": g.Refresh, "scope": strings.Join(g.Scopes, " "), + "default_organization": map[string]any{"id": HomeOrgID, "name": "Home", "slug": "home", "logo_url": nil}, + } + if s.NoDefaultOrg { + resp["default_organization"] = nil + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + _ = json.NewEncoder(w).Encode(resp) +} + +func (s *Server) token(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + f := r.PostForm + if f.Get("client_id") == "" && f.Get("grant_type") == "refresh_token" { + s.legacyRefresh(w, r) + return + } + if f.Get("client_id") != ClientID { + oauthErr(w, http.StatusUnauthorized, "invalid_client", "Unknown client.") + return + } + switch f.Get("grant_type") { + case "authorization_code": + s.codeExchange(w, f) + case "refresh_token": + s.refresh(w, f) + case GrantTokenExchange: + if f.Get("subject_token_type") == TokenTypeCLISession { + s.upgrade(w, f) + return + } + s.exchange(w, f) + case GrantDeviceCode: + s.devicePoll(w, f) + default: + oauthErr(w, http.StatusBadRequest, "unsupported_grant_type", "") + } +} + +func (s *Server) codeExchange(w http.ResponseWriter, f url.Values) { + s.mu.Lock() + defer s.mu.Unlock() + c, ok := s.codes[f.Get("code")] + delete(s.codes, f.Get("code")) + if !ok || c.redirect != f.Get("redirect_uri") { + oauthErr(w, http.StatusBadRequest, "invalid_grant", "Unknown code or redirect_uri mismatch.") + return + } + sum := sha256.Sum256([]byte(f.Get("code_verifier"))) + if base64.RawURLEncoding.EncodeToString(sum[:]) != c.challenge { + oauthErr(w, http.StatusBadRequest, "invalid_grant", "The PKCE code_verifier doesn't match the challenge.") + return + } + s.CodeExchanges++ + s.signInResponse(w, s.newGrant(c.scopes)) +} + +func (s *Server) refresh(w http.ResponseWriter, f url.Values) { + if s.Delay > 0 { + time.Sleep(s.Delay) + } + s.mu.Lock() + defer s.mu.Unlock() + rt := f.Get("refresh_token") + g, ok := s.byRT[rt] + switch { + case !ok || g.Revoked: + oauthErr(w, http.StatusBadRequest, "invalid_grant", "The refresh token is invalid.") + return + case rt != g.Refresh: + if at, ok := g.rotated[rt]; ok && s.now().Sub(at) < ReuseGrace { + s.GraceHits++ + oauthErr(w, http.StatusBadRequest, "invalid_grant", "The refresh token was just rotated.") + return + } + // Reuse: two parties hold the sign-in. End it. + s.Reuses++ + g.Revoked = true + oauthErr(w, http.StatusBadRequest, "invalid_grant", "Refresh token reuse.") + return + } + s.Refreshes++ + s.RefreshTimes = append(s.RefreshTimes, s.now()) + s.issue(g) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "access_token": g.Access, "token_type": "bearer", "expires_in": s.AccessTTL, + "refresh_token": g.Refresh, "scope": strings.Join(g.Scopes, " "), + }) +} + +func (s *Server) exchange(w http.ResponseWriter, f url.Values) { + n := s.inflight.Add(1) + defer s.inflight.Add(-1) + for { + m := s.maxInflight.Load() + if n <= m || s.maxInflight.CompareAndSwap(m, n) { + break + } + } + if s.Delay > 0 { + time.Sleep(s.Delay) + } + s.mu.Lock() + defer s.mu.Unlock() + if f.Get("subject_token_type") != TokenTypeAccess || f.Get("audience") == "" || f.Get("scope") != "" { + oauthErr(w, http.StatusBadRequest, "invalid_request", "Bad exchange.") + return + } + if !slices.Contains(scopeAudiences["full"], f.Get("audience")) { + oauthErr(w, http.StatusBadRequest, "invalid_target", "Unknown audience.") + return + } + // Only Norcube Auth's own tokens may come without an organization. + org, hasOrg := f.Get("organization_id"), f.Has("organization_id") + if (org == "" || !hasOrg) && (hasOrg || f.Get("audience") != "auth") { + oauthErr(w, http.StatusBadRequest, "invalid_request", "organization_id must be an organization id.") + return + } + // Like the real JWTs, every CLI access token of a live sign-in works + // until it expires. + g, ok := s.byAccess[f.Get("subject_token")] + if !ok || g.Revoked || !s.now().Before(s.accessExp[f.Get("subject_token")]) { + oauthErr(w, http.StatusBadRequest, "invalid_grant", "The access token is invalid or expired, or the sign-in was revoked.") + return + } + aud := f.Get("audience") + if !allows(g.Scopes, aud) { + oauthErr(w, http.StatusForbidden, "insufficient_scope", "This sign-in's scopes don't cover "+aud+".") + return + } + if org != "" && org != HomeOrgID && org != AcmeOrgID { + oauthErr(w, http.StatusForbidden, "org_access_denied", "You are not a member of the organization.") + return + } + s.Exchanges++ + tok := jwt(map[string]any{"aud": aud, "org": org, "jti": s.id("pt"), "exp": s.now().Add(time.Duration(s.ProductTTL) * time.Second).Unix()}) + var scopes []string + if !slices.Contains(g.Scopes, "full") { + for _, sc := range g.Scopes { + if slices.Contains(scopeAudiences[sc], aud) { + scopes = append(scopes, sc) + } + } + } + s.product[tok] = productToken{audience: aud, org: org, scopes: scopes} + resp := map[string]any{"access_token": tok, "issued_token_type": TokenTypeAccess, "token_type": "Bearer", "expires_in": s.ProductTTL} + if scopes != nil { + resp["scope"] = strings.Join(scopes, " ") + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(resp) +} + +func (s *Server) upgrade(w http.ResponseWriter, f url.Values) { + if s.Delay > 0 { + time.Sleep(s.Delay) + } + s.mu.Lock() + defer s.mu.Unlock() + if f.Get("audience") != "" || f.Get("scope") != "" { + oauthErr(w, http.StatusBadRequest, "invalid_request", "No audience or scope on an upgrade.") + return + } + tok := f.Get("subject_token") + if !s.legacy[tok] || s.legacyUsed[tok] { + s.UpgradeRefusals++ + oauthErr(w, http.StatusBadRequest, "invalid_grant", "The session can't be upgraded.") + return + } + s.legacyUsed[tok] = true + s.LegacyRefresh = "" + s.Upgrades++ + s.signInResponse(w, s.newGrant(normalize([]string{"full", "offline_access"}))) +} + +// legacyRefresh is the older cookie refresh (an older Norcube Auth). +func (s *Server) legacyRefresh(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + defer s.mu.Unlock() + c, err := r.Cookie("jds_refresh_token") + if err != nil || s.LegacyRefresh == "" || c.Value != s.LegacyRefresh { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusUnauthorized) + fmt.Fprint(w, `{"type":"unauthorized","msg":"Unauthorized."}`) + return + } + s.LegacyRefreshes++ + delete(s.legacy, s.LegacyRefresh) + s.LegacyRefresh = jwt(map[string]any{"sid": "sess-1", "jti": s.id("legacy")}) + s.legacy[s.LegacyRefresh] = true + aud, org := r.PostForm.Get("audience"), r.PostForm.Get("organization_id") + tok := jwt(map[string]any{"aud": aud, "org": org, "jti": s.id("pt"), "exp": s.now().Add(5 * time.Minute).Unix()}) + s.product[tok] = productToken{audience: aud, org: org} + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"access_token": tok, "refresh_token": s.LegacyRefresh, "token_type": "Bearer", "expires_in": 300}) +} + +func (s *Server) deviceCode(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + s.mu.Lock() + defer s.mu.Unlock() + s.DeviceCodeForm = r.PostForm + if r.PostForm.Get("client_id") != ClientID { + oauthErr(w, http.StatusUnauthorized, "invalid_client", "") + return + } + scopes := strings.Fields(r.PostForm.Get("scope")) + if !knownScopes(scopes) { + oauthErr(w, http.StatusBadRequest, "invalid_scope", "Unknown or missing scope.") + return + } + s.device = &deviceReq{scopes: normalize(scopes)} + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "device_code": "dc-oauth", "user_code": "WDJB-MJHT", + "verification_uri": "https://app.example/device", + "verification_uri_complete": "https://app.example/device?user_code=WDJB-MJHT", + "expires_in": 600, "interval": 5, + }) +} + +func (s *Server) devicePoll(w http.ResponseWriter, f url.Values) { + s.mu.Lock() + defer s.mu.Unlock() + s.DevicePolls++ + d := s.device + if d == nil || d.done || f.Get("device_code") != "dc-oauth" { + oauthErr(w, http.StatusBadRequest, "invalid_grant", "Unknown or already collected code.") + return + } + if d.polls < len(s.DeviceAnswers) { + answer := s.DeviceAnswers[d.polls] + d.polls++ + oauthErr(w, http.StatusBadRequest, answer, "") + return + } + d.done = true + s.signInResponse(w, s.newGrant(d.scopes)) +} + +func (s *Server) revoke(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + s.mu.Lock() + defer s.mu.Unlock() + s.Revocations = append(s.Revocations, r.PostForm) + if s.RevokeStatus != 0 { + oauthErr(w, s.RevokeStatus, "temporarily_unavailable", "Revocation failed; retry.") + return + } + if r.PostForm.Get("client_id") != ClientID { + oauthErr(w, http.StatusUnauthorized, "invalid_client", "") + return + } + // Current and rotated tokens alike end the grant. + if g, ok := s.byRT[r.PostForm.Get("token")]; ok { + g.Revoked = true + } + w.WriteHeader(http.StatusOK) +} diff --git a/internal/auth/browser.go b/internal/auth/browser.go index 2a4e63f..869163c 100644 --- a/internal/auth/browser.go +++ b/internal/auth/browser.go @@ -30,6 +30,12 @@ type CallbackPayload struct { RefreshExpiresIn int `json:"refreshExpiresIn"` User User `json:"user"` DefaultOrg Organization `json:"defaultOrganization"` + + // OAuth marks a session from the OAuth sign-in (format 2): the access + // token is a CLI access token, User is empty (the caller asks + // /auth/me), and Scopes are the granted scopes. + OAuth bool `json:"-"` + Scopes []string `json:"-"` } type User struct { @@ -56,7 +62,8 @@ type BrowserLoginOptions struct { NoBrowser bool } -// BrowserLogin runs the full browser-based login handshake: +// BrowserLogin runs the older browser-based login handshake, for a +// Norcube Auth without the OAuth sign-in (see OAuthLogin): // // 1. Bind a loopback HTTP server on a random localhost port. // 2. Open the user's browser to /cli-login?port=

&state=. diff --git a/internal/auth/device.go b/internal/auth/device.go index 0745a31..e451fee 100644 --- a/internal/auth/device.go +++ b/internal/auth/device.go @@ -18,7 +18,10 @@ import ( // Device sign-in (OAuth 2.0 Device Authorization Grant, RFC 8628) for // machines without a usable browser: the CLI shows a short code, the // person approves it at /device on any device (a phone works), -// and the CLI receives the same session a browser login gives. +// and the CLI receives the same session a browser login gives. With +// Metadata it runs against the OAuth server (/oauth/device/code, polled +// at the token endpoint) and asks for Scopes; without, against the older +// /auth/cli/device endpoints. // DeviceClientID identifies the CLI to Norcube Auth's device endpoints. const DeviceClientID = "norcube-cli" @@ -39,6 +42,11 @@ type DeviceCode struct { type DeviceLoginOptions struct { AuthURL string HTTP *http.Client + // Metadata selects the OAuth device flow (it must support it, see + // Metadata.SupportsDevice); nil means the older flow. + Metadata *Metadata + // Scopes to ask for in the OAuth flow; empty means full. + Scopes []string // Hostname labels the session under Account › CLI sessions. Hostname string // OnCode is called once with the code to show the person. @@ -100,6 +108,10 @@ func DeviceLogin(ctx context.Context, opts DeviceLoginOptions) (*CallbackPayload payload, pollErr, err := pollDeviceToken(ctx, opts, code.DeviceCode) switch { case err != nil: + var fatal *fatalPollError + if errors.As(err, &fatal) { + return nil, fatal.err + } // A dropped connection or a 5xx: keep trying, more slowly, // while the code is valid. if ctx.Err() != nil { @@ -144,13 +156,26 @@ func requestDeviceCode(ctx context.Context, opts DeviceLoginOptions) (*DeviceCod if host == "" { host = deviceName() } - if host != "" { + endpoint := opts.AuthURL + "/auth/cli/device/code" + if opts.Metadata != nil { + endpoint = opts.Metadata.DeviceAuthorizationEndpoint + form.Set("scope", requestScope(opts.Scopes)) + form.Set("client_user_agent", truncate(transport.UserAgent())) + if host != "" { + form.Set("device_name", truncate(host)) + } + } else if host != "" { form.Set("hostname", truncate(host)) } - resp, raw, err := postForm(ctx, opts.HTTP, opts.AuthURL+"/auth/cli/device/code", form, true) + resp, raw, err := postForm(ctx, opts.HTTP, endpoint, form, true) if err != nil { return nil, fmt.Errorf("start device sign-in: %w", err) } + if opts.Metadata != nil && resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusTooManyRequests { + if oe := parseOAuthError(resp.StatusCode, raw); oe != nil { + return nil, oauthFailure("start device sign-in", oe) + } + } if resp.StatusCode != http.StatusOK { var body struct { Error string `json:"error"` @@ -187,14 +212,30 @@ func pollDeviceToken(ctx context.Context, opts DeviceLoginOptions, deviceCode st "device_code": {deviceCode}, "client_id": {DeviceClientID}, } + endpoint := opts.AuthURL + "/auth/cli/device/token" + if opts.Metadata != nil { + endpoint = opts.Metadata.TokenEndpoint + } // Not retried by the transport: the loop owns the pacing, and a poll // repeated behind its back would earn a slow_down. - resp, raw, err := postForm(ctx, opts.HTTP, opts.AuthURL+"/auth/cli/device/token", form, false) + resp, raw, err := postForm(ctx, opts.HTTP, endpoint, form, false) if err != nil { return nil, "", err } switch resp.StatusCode { case http.StatusOK: + if opts.Metadata != nil { + // The approved code is used up: asking again can't help. + var tr tokenEndpointResponse + if err := json.Unmarshal(raw, &tr); err != nil || tr.AccessToken == "" { + return nil, "", &fatalPollError{errors.New("device sign-in: Norcube Auth returned no session")} + } + p, err := signInPayload(&tr) + if err != nil { + return nil, "", &fatalPollError{err} + } + return p, "", nil + } var payload CallbackPayload if err := json.Unmarshal(raw, &payload); err != nil { return nil, "", fmt.Errorf("decode device sign-in: %w", err) @@ -214,6 +255,12 @@ func pollDeviceToken(ctx context.Context, opts DeviceLoginOptions, deviceCode st return nil, "", fmt.Errorf("device sign-in: %s", resp.Status) } +// fatalPollError ends the polling loop: retrying can't succeed. +type fatalPollError struct{ err error } + +func (e *fatalPollError) Error() string { return e.err.Error() } +func (e *fatalPollError) Unwrap() error { return e.err } + func postForm(ctx context.Context, httpc *http.Client, endpoint string, form url.Values, retryable bool) (*http.Response, []byte, error) { // #nosec G704 -- the Norcube Auth URL the user configured. req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode())) diff --git a/internal/auth/diagnose_test.go b/internal/auth/diagnose_test.go index 3238607..856e5dd 100644 --- a/internal/auth/diagnose_test.go +++ b/internal/auth/diagnose_test.go @@ -85,7 +85,7 @@ func TestRefusedExchangeIsDiagnosed(t *testing.T) { if tt.session { srv.current = "refresh-0" } - hs := httptest.NewServer(srv) + hs := httptest.NewServer(olderServer(srv)) defer hs.Close() prev := SetStore(fileStore{dir: t.TempDir()}) defer SetStore(prev) diff --git a/internal/auth/keyring.go b/internal/auth/keyring.go index e91800c..712330b 100644 --- a/internal/auth/keyring.go +++ b/internal/auth/keyring.go @@ -62,11 +62,33 @@ func storeFor(profile string) Store { return store } +// Credential formats. Format 1 (no "format" field) is the older sign-in: +// a refresh JWT of Norcube Auth's own sessions, refreshed straight into +// per-(audience, organization) tokens, which are cached in the blob too. +// Format 2 is the OAuth sign-in: the grant's refresh token, the cached +// 5-minute CLI access token and the granted scopes. Its per-service tokens +// are only cached in memory (see oauthsession.go), so the blob changes +// only on a refresh, under the profile's lock. +const ( + FormatLegacy = 1 + FormatOAuth = 2 +) + type credentials struct { + // Format is FormatOAuth for an OAuth sign-in; absent (0) means + // FormatLegacy, which is what CLI versions before it wrote. + Format int `json:"format,omitempty"` AuthURL string `json:"auth_url"` RefreshToken string `json:"refresh_token,omitempty"` - // Access caches access tokens by "|". + // Access caches access tokens by "|" + // (format 1 only). Access map[string]cachedAccess `json:"access,omitempty"` + // CLIAccess is the cached CLI access token (format 2), only good for + // the token exchange. + CLIAccess *cachedAccess `json:"cli_access,omitempty"` + // Scopes are the scopes Norcube Auth granted the sign-in (format 2), + // e.g. ["full", "org.read", "offline_access"]. + Scopes []string `json:"scopes,omitempty"` // legacy: read from an older CLI's per-auth-URL item, not yet saved // into the profile's own item. @@ -134,8 +156,16 @@ func loadCredentials(profile, api string) (*credentials, error) { return &credentials{AuthURL: api}, nil } -// saveCredentials writes the blob. A store that can't hold the access -// token cache (Windows caps items at 2.5 KB) gets the refresh token only. +func (c *credentials) format() int { + if c.Format == FormatOAuth { + return FormatOAuth + } + return FormatLegacy +} + +// saveCredentials writes the blob. A store that can't hold the cached +// access tokens (Windows caps items at 2.5 KB) gets the refresh token and +// scopes only; the next command mints new access tokens. func saveCredentials(profile string, c *credentials) error { b, err := json.Marshal(c) // #nosec G117 -- written to the credential store, which is where secrets belong if err != nil { @@ -143,9 +173,10 @@ func saveCredentials(profile string, c *credentials) error { } st := storeFor(profile) err = st.Set(profileKey(profile), string(b)) - if errors.Is(err, credstore.ErrTooBig) && len(c.Access) > 0 { + if errors.Is(err, credstore.ErrTooBig) && (len(c.Access) > 0 || c.CLIAccess != nil) { slim := *c slim.Access = nil + slim.CLIAccess = nil b, _ = json.Marshal(slim) // #nosec G117 -- see above err = st.Set(profileKey(profile), string(b)) } @@ -165,8 +196,9 @@ func saveCredentials(profile string, c *credentials) error { return nil } -// SaveRefreshToken stores the profile's refresh token for api. Cached -// access tokens of another auth URL are dropped. +// SaveRefreshToken stores the profile's refresh token for api as an older +// (format 1) sign-in. Cached access tokens of another auth URL are +// dropped, and so is an OAuth sign-in it replaces. func SaveRefreshToken(profile, api, token string) error { credsMu.Lock() defer credsMu.Unlock() @@ -174,10 +206,69 @@ func SaveRefreshToken(profile, api, token string) error { if err != nil { return err } + if c.format() == FormatOAuth { + c = &credentials{AuthURL: api, legacy: c.legacy} + forgetMemory(profile, api) + } c.RefreshToken = token return saveCredentials(profile, c) } +// SaveOAuthSession stores an OAuth sign-in (format 2) for the profile: +// its refresh token, the CLI access token that came with it and the +// granted scopes. It replaces whatever the profile had, older sign-in +// included. Callers hold the profile's lock. +func SaveOAuthSession(profile, api, refresh, cliAccess string, accessExpiresAt time.Time, scopes []string) error { + credsMu.Lock() + defer credsMu.Unlock() + old, err := loadCredentials(profile, api) + if err != nil { + return err + } + c := &credentials{ + Format: FormatOAuth, + AuthURL: api, + RefreshToken: refresh, + Scopes: scopes, + legacy: old.legacy, + } + if cliAccess != "" { + if accessExpiresAt.IsZero() { + accessExpiresAt = jwtExpiry(cliAccess) + } + c.CLIAccess = &cachedAccess{Token: cliAccess, ExpiresAt: accessExpiresAt} + } + forgetMemory(profile, api) + return saveCredentials(profile, c) +} + +// StoredSession describes what a profile has stored, without secrets. +type StoredSession struct { + // Format is FormatLegacy or FormatOAuth; 0 when nothing is stored. + Format int + // Scopes are the granted scopes of an OAuth sign-in (nil for the + // older sign-in, which always has full access). + Scopes []string + // CLIAccessExpiresAt is when the cached CLI access token expires + // (format 2; zero when none is cached). + CLIAccessExpiresAt time.Time +} + +// LoadSession describes the profile's stored session for api. +func LoadSession(profile, api string) (StoredSession, error) { + credsMu.RLock() + defer credsMu.RUnlock() + c, err := loadCredentials(profile, api) + if err != nil || c.RefreshToken == "" { + return StoredSession{}, err + } + s := StoredSession{Format: c.format(), Scopes: c.Scopes} + if c.CLIAccess != nil { + s.CLIAccessExpiresAt = c.CLIAccess.ExpiresAt + } + return s, nil +} + // LoadRefreshToken returns the profile's refresh token for api, or // ErrNotLoggedIn. func LoadRefreshToken(profile, api string) (string, error) { @@ -247,6 +338,7 @@ func DeleteCredentials(profile, api string) error { func DeleteCredentialsFrom(s Store, profile, api string) error { credsMu.Lock() defer credsMu.Unlock() + forgetMemory(profile, api) if err := s.Delete(profileKey(profile)); err != nil { return err } @@ -265,6 +357,9 @@ func HasCredentials(profile, api string) bool { // AccessExpiry returns when the profile's cached token for (audience, // org) expires; zero when none is cached. func AccessExpiry(profile, api, audience, orgID string) time.Time { + if a, ok := memGet(memKey(profile, api, audience, orgID)); ok { + return a.ExpiresAt + } _, exp, _ := loadAccess(profile, api, audience, orgID) return exp } diff --git a/internal/auth/main_test.go b/internal/auth/main_test.go new file mode 100644 index 0000000..ac1ebcf --- /dev/null +++ b/internal/auth/main_test.go @@ -0,0 +1,18 @@ +package auth + +import ( + "os" + "testing" +) + +// TestMain keeps the discovery cache out of the user's cache directory. +func TestMain(m *testing.M) { + dir, err := os.MkdirTemp("", "norcube-auth-test-") + if err != nil { + panic(err) + } + metadataCacheDir = dir + code := m.Run() + _ = os.RemoveAll(dir) + os.Exit(code) +} diff --git a/internal/auth/oauth.go b/internal/auth/oauth.go new file mode 100644 index 0000000..c66955f --- /dev/null +++ b/internal/auth/oauth.go @@ -0,0 +1,704 @@ +package auth + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "html" + "io" + "net" + "net/http" + "net/url" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/pkg/browser" + + "github.com/norcubeplatform/cli/internal/clierr" + "github.com/norcubeplatform/cli/internal/transport" +) + +// The CLI as an OAuth 2.0 client of Norcube Auth: a public, first-party +// client ("norcube-cli") that signs in with the authorization code flow +// and PKCE over a loopback redirect (RFC 8252), or with the device flow +// (RFC 8628). The sign-in yields a refresh token and a short-lived CLI +// access token, which is exchanged (RFC 8693) for a token per service and +// organization. Only a one-time, PKCE-bound code passes through the +// browser. + +// ClientID is the CLI's OAuth client id. +const ClientID = DeviceClientID + +// OAuth grant and token type identifiers. +// +// #nosec G101 -- identifiers, not credentials. +const ( + grantAuthorizationCode = "authorization_code" + grantRefreshToken = "refresh_token" + grantTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange" + + tokenTypeAccessToken = "urn:ietf:params:oauth:token-type:access_token" + // tokenTypeCLISession is a refresh JWT of the older CLI sign-in, + // exchanged once for an OAuth sign-in of the same session. + tokenTypeCLISession = "urn:norcube:params:oauth:token-type:cli-session" +) + +// Metadata is the part of Norcube Auth's RFC 8414 metadata the CLI uses. +type Metadata struct { + Issuer string `json:"issuer"` + AuthorizationEndpoint string `json:"authorization_endpoint"` + TokenEndpoint string `json:"token_endpoint"` + RevocationEndpoint string `json:"revocation_endpoint,omitempty"` + DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint,omitempty"` + GrantTypesSupported []string `json:"grant_types_supported,omitempty"` + CodeChallengeMethods []string `json:"code_challenge_methods_supported,omitempty"` + IssParameterSupported bool `json:"authorization_response_iss_parameter_supported,omitempty"` +} + +// SupportsCLISignIn reports whether the server signs the CLI in through +// OAuth: it advertises the token exchange the CLI needs for every +// command. Older servers don't, and the CLI keeps their older sign-in. +func (m *Metadata) SupportsCLISignIn() bool { + return m != nil && m.AuthorizationEndpoint != "" && m.TokenEndpoint != "" && + slices.Contains(m.GrantTypesSupported, grantTokenExchange) +} + +// SupportsDevice reports whether the server takes device sign-ins through +// OAuth. +func (m *Metadata) SupportsDevice() bool { + return m.SupportsCLISignIn() && m.DeviceAuthorizationEndpoint != "" && + slices.Contains(m.GrantTypesSupported, deviceGrantType) +} + +// ErrOAuthUnavailable: Norcube Auth has no OAuth sign-in for the CLI (an +// older server, or the OAuth server is switched off). The CLI then uses +// the older sign-in. +var ErrOAuthUnavailable = errors.New("the OAuth sign-in for the CLI is not available on this Norcube Auth") + +// metadataCacheTTL is how long a discovery answer is reused, on disk and +// in memory. A server without OAuth is asked again sooner, so a backend +// upgrade is picked up within the hour. +const ( + metadataCacheTTL = 24 * time.Hour + metadataNegativeCacheTTL = time.Hour +) + +type metadataEntry struct { + Metadata *Metadata `json:"metadata,omitempty"` + FetchedAt time.Time `json:"fetched_at"` +} + +var ( + metadataMu sync.Mutex + metadataCache = map[string]metadataEntry{} + // metadataCacheDir is where discovery answers are kept between runs; + // "" means the user cache directory. Tests set it. + metadataCacheDir string +) + +// Discover returns Norcube Auth's metadata for authURL, or +// ErrOAuthUnavailable when the server has no OAuth sign-in for the CLI. +// Answers are cached (24 hours, one hour for "unavailable") in memory and +// in the user cache directory, so commands don't pay a request for it. +// Network failures are returned as they are and never cached. +func Discover(ctx context.Context, httpc *http.Client, authURL string) (*Metadata, error) { + authURL = strings.TrimRight(authURL, "/") + if e, ok := cachedMetadata(authURL); ok { + if !e.Metadata.SupportsCLISignIn() { + return nil, ErrOAuthUnavailable + } + return e.Metadata, nil + } + m, err := fetchMetadata(ctx, httpc, authURL) + if err != nil && !errors.Is(err, ErrOAuthUnavailable) { + return nil, err + } + storeMetadata(authURL, metadataEntry{Metadata: m, FetchedAt: time.Now()}) + if err != nil { + return nil, err + } + return m, nil +} + +// ForgetMetadata drops the cached discovery answer for authURL. +func ForgetMetadata(authURL string) { + authURL = strings.TrimRight(authURL, "/") + metadataMu.Lock() + defer metadataMu.Unlock() + delete(metadataCache, authURL) + if p := metadataPath(authURL); p != "" { + _ = os.Remove(p) // #nosec G703 -- hashed name in the user's cache directory + } +} + +func fetchMetadata(ctx context.Context, httpc *http.Client, authURL string) (*Metadata, error) { + if httpc == nil { + httpc = transport.Default() + } + // #nosec G704 -- the Norcube Auth URL the user configured. + req, err := http.NewRequestWithContext(ctx, http.MethodGet, authURL+"/.well-known/oauth-authorization-server", nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + resp, err := httpc.Do(req) // #nosec G704 -- see above + if err != nil { + return nil, fmt.Errorf("read the OAuth metadata of Norcube Auth: %w", err) + } + defer resp.Body.Close() + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + switch { + case resp.StatusCode == http.StatusNotFound: + return nil, ErrOAuthUnavailable + case resp.StatusCode != http.StatusOK: + return nil, fmt.Errorf("read the OAuth metadata of Norcube Auth: status %d", resp.StatusCode) + } + var m Metadata + if err := json.Unmarshal(raw, &m); err != nil { + return nil, fmt.Errorf("read the OAuth metadata of Norcube Auth: %w", err) + } + // RFC 8414 §3.3: the issuer must be the URL the metadata was + // fetched for, or a server could pass off another's endpoints. + if !sameURL(m.Issuer, authURL) { + return nil, fmt.Errorf("the OAuth metadata of Norcube Auth names issuer %q, not %q; check the auth URL of this profile", m.Issuer, authURL) + } + // The endpoints must live on the issuer's own origin: the CLI sends + // its refresh token and codes there. + for name, ep := range map[string]string{ + "authorization_endpoint": m.AuthorizationEndpoint, + "token_endpoint": m.TokenEndpoint, + "revocation_endpoint": m.RevocationEndpoint, + "device_authorization_endpoint": m.DeviceAuthorizationEndpoint, + } { + if ep != "" && !sameOrigin(ep, m.Issuer) { + return nil, fmt.Errorf("the OAuth metadata of Norcube Auth puts %s at %q, outside %q", name, ep, m.Issuer) + } + } + if !m.SupportsCLISignIn() { + return &m, ErrOAuthUnavailable + } + if len(m.CodeChallengeMethods) > 0 && !slices.Contains(m.CodeChallengeMethods, "S256") { + return nil, errors.New("the OAuth server of Norcube Auth doesn't support PKCE S256") + } + return &m, nil +} + +// sameOrigin reports whether two URLs have the same scheme and host. +func sameOrigin(a, b string) bool { + ua, errA := url.Parse(a) + ub, errB := url.Parse(b) + return errA == nil && errB == nil && ua.Host != "" && + strings.EqualFold(ua.Scheme, ub.Scheme) && strings.EqualFold(ua.Host, ub.Host) +} + +func sameURL(a, b string) bool { + norm := func(s string) string { + u, err := url.Parse(strings.TrimRight(s, "/")) + if err != nil { + return s + } + u.Scheme, u.Host = strings.ToLower(u.Scheme), strings.ToLower(u.Host) + return u.String() + } + return a != "" && norm(a) == norm(b) +} + +func cachedMetadata(authURL string) (metadataEntry, bool) { + metadataMu.Lock() + defer metadataMu.Unlock() + fresh := func(e metadataEntry) bool { + ttl := metadataCacheTTL + if !e.Metadata.SupportsCLISignIn() { + ttl = metadataNegativeCacheTTL + } + age := time.Since(e.FetchedAt) + return age >= 0 && age < ttl + } + if e, ok := metadataCache[authURL]; ok && fresh(e) { + return e, true + } + p := metadataPath(authURL) + if p == "" { + return metadataEntry{}, false + } + b, err := os.ReadFile(p) // #nosec G304 -- hashed name in the user's cache directory + if err != nil { + return metadataEntry{}, false + } + var e metadataEntry + if json.Unmarshal(b, &e) != nil || !fresh(e) { + return metadataEntry{}, false + } + if e.Metadata != nil && !sameURL(e.Metadata.Issuer, authURL) { + return metadataEntry{}, false + } + metadataCache[authURL] = e + return e, true +} + +func storeMetadata(authURL string, e metadataEntry) { + metadataMu.Lock() + defer metadataMu.Unlock() + metadataCache[authURL] = e + p := metadataPath(authURL) + if p == "" { + return + } + b, err := json.Marshal(e) + if err != nil { + return + } + // Best effort: the cache only saves a request. + if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { // #nosec G703 -- the user's cache directory + return + } + tmp, err := os.CreateTemp(filepath.Dir(p), ".oauth-*") + if err != nil { + return + } + _, werr := tmp.Write(b) + cerr := tmp.Close() + if werr != nil || cerr != nil || os.Rename(tmp.Name(), p) != nil { // #nosec G703 -- see above + _ = os.Remove(tmp.Name()) // #nosec G703 -- see above + } +} + +func metadataPath(authURL string) string { + dir := metadataCacheDir + if dir == "" { + cache, err := os.UserCacheDir() + if err != nil { + return "" + } + dir = filepath.Join(cache, "norcube") + } + sum := sha256.Sum256([]byte(authURL)) + return filepath.Join(dir, "oauth-metadata-"+hex.EncodeToString(sum[:8])+".json") +} + +// --- token endpoint --- + +// tokenEndpointResponse is a token endpoint answer: the code exchange, +// device poll, refresh and session upgrade (cli_access token and refresh +// token), or a token exchange (a service token). +type tokenEndpointResponse struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + ExpiresIn int `json:"expires_in"` + RefreshToken string `json:"refresh_token,omitempty"` + Scope string `json:"scope,omitempty"` + IssuedTokenType string `json:"issued_token_type,omitempty"` + // DefaultOrganization comes with a sign-in (code exchange, device + // poll, upgrade); null when the person belongs to none. + DefaultOrganization *Organization `json:"default_organization,omitempty"` +} + +// OAuthError is an RFC 6749 §5.2 error answer of Norcube Auth's OAuth +// server. +type OAuthError struct { + Status int + Code string + Description string +} + +func (e *OAuthError) Error() string { + if e.Description != "" { + return fmt.Sprintf("%s: %s", e.Code, e.Description) + } + return fmt.Sprintf("%s (status %d)", e.Code, e.Status) +} + +// OAuth error codes the CLI acts on. +const ( + oauthInvalidGrant = "invalid_grant" + oauthInsufficientScope = "insufficient_scope" + oauthOrgAccessDenied = "org_access_denied" + oauthInvalidScope = "invalid_scope" + oauthInvalidTarget = "invalid_target" + oauthAccessDenied = "access_denied" + oauthTemporarilyUnavail = "temporarily_unavailable" + oauthServerError = "server_error" +) + +// postToken posts form to the token endpoint. It returns the answer, or +// the OAuth error the server sent, or err for transport failures and +// answers that aren't OAuth errors. retryable marks requests the +// transport may repeat (they use nothing up: token exchanges). +func postToken(ctx context.Context, httpc *http.Client, endpoint string, form url.Values, retryable bool) (*tokenEndpointResponse, *OAuthError, error) { + if httpc == nil { + httpc = transport.Default() + } + resp, raw, err := postForm(ctx, httpc, endpoint, form, retryable) + if err != nil { + return nil, nil, err + } + if resp.StatusCode == http.StatusOK { + var tr tokenEndpointResponse + if err := json.Unmarshal(raw, &tr); err != nil { + return nil, nil, fmt.Errorf("decode the token response: %w", err) + } + if tr.AccessToken == "" { + return nil, nil, errors.New("the token response has no access token") + } + return &tr, nil, nil + } + if oe := parseOAuthError(resp.StatusCode, raw); oe != nil { + return nil, oe, nil + } + e := &clierr.Error{ + Code: clierr.CodeForStatus(resp.StatusCode, ""), + Message: fmt.Sprintf("the token endpoint of Norcube Auth answered %s", resp.Status), + HTTPStatus: resp.StatusCode, + } + if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { + // Not an OAuth answer (a proxy, or no OAuth server behind + // /oauth/token): don't claim the session ended. + e.Code = clierr.CodeError + } + return nil, nil, e +} + +func parseOAuthError(status int, raw []byte) *OAuthError { + var body struct { + Error string `json:"error"` + Description string `json:"error_description"` + } + if json.Unmarshal(raw, &body) != nil || body.Error == "" { + return nil + } + return &OAuthError{Status: status, Code: body.Error, Description: body.Description} +} + +// oauthFailure turns an OAuth error of a sign-in step into a CLI error. +func oauthFailure(step string, oe *OAuthError) error { + e := &clierr.Error{ + Code: clierr.CodeError, + Message: fmt.Sprintf("%s: %s", step, oe.Error()), + HTTPStatus: oe.Status, + Err: oe, + } + if oe.Status >= 500 { + e.Code = clierr.CodeServerError + } + switch oe.Code { + case oauthInvalidScope: + e.Code = clierr.CodeUsage + e.Hint = "Valid scopes: " + strings.Join(LoginScopeNames(), ", ") + "." + case oauthInvalidGrant, oauthAccessDenied: + e.Code = clierr.CodeLoginRequired + case oauthTemporarilyUnavail, oauthServerError: + e.Code = clierr.CodeServerError + } + if oe.Status == http.StatusTooManyRequests { + e.Code = clierr.CodeRateLimited + e.Hint = "Too many sign-in requests from this network; wait a few minutes." + } + return e +} + +// signInPayload turns a sign-in's token response into the session a +// login stores. +func signInPayload(tr *tokenEndpointResponse) (*CallbackPayload, error) { + if tr.RefreshToken == "" { + return nil, errors.New("the sign-in response has no refresh token") + } + p := &CallbackPayload{ + AccessToken: tr.AccessToken, + RefreshToken: tr.RefreshToken, + AccessExpiresIn: tr.ExpiresIn, + Scopes: parseScope(tr.Scope), + OAuth: true, + } + if tr.DefaultOrganization != nil { + p.DefaultOrg = *tr.DefaultOrganization + } + return p, nil +} + +// --- browser sign-in: authorization code + PKCE over a loopback redirect --- + +// SignInWait is how long a sign-in waits for the browser: as long as +// Norcube Auth keeps the pending request (10 minutes), so an approval the +// server still accepts always finds the CLI listening. +const SignInWait = 10 * time.Minute + +// OAuthLoginOptions configures OAuthLogin. +type OAuthLoginOptions struct { + Metadata *Metadata + HTTP *http.Client + // Scopes to ask for (see ParseLoginScopes); empty means full. + Scopes []string + Timeout time.Duration + // BrowserOpenURL opens the authorization URL; the default browser + // by default. + BrowserOpenURL func(string) error + // OnURLReady is called with the authorization URL before the browser + // opens, for printing. + OnURLReady func(string) + // NoBrowser skips opening a browser: the caller prints the URL. + NoBrowser bool +} + +// OAuthLogin signs in through the browser: +// +// 1. Listen on 127.0.0.1 on a random port. +// 2. Open the authorization endpoint with PKCE (S256), a random state, +// the scopes, and the device's name and User-Agent for the consent +// screen and the session. +// 3. Norcube Auth redirects the browser to http://127.0.0.1:/callback +// with a code, the state and its issuer (RFC 9207), all checked. +// 4. Exchange the code with the PKCE verifier. +// +// The caller stores the returned session. +func OAuthLogin(ctx context.Context, opts OAuthLoginOptions) (*CallbackPayload, error) { + m := opts.Metadata + if !m.SupportsCLISignIn() { + return nil, ErrOAuthUnavailable + } + if opts.Timeout == 0 { + opts.Timeout = SignInWait + } + if opts.BrowserOpenURL == nil { + opts.BrowserOpenURL = browser.OpenURL + } + state, err := randomState() + if err != nil { + return nil, fmt.Errorf("generate state: %w", err) + } + verifier, challenge, err := newPKCE() + if err != nil { + return nil, fmt.Errorf("generate PKCE verifier: %w", err) + } + + // RFC 8252 §7.3: loopback IP literal, any port. IPv4 only, as the + // registered redirect URI names 127.0.0.1. + listener, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + return nil, fmt.Errorf("can't open a local port on 127.0.0.1 for the sign-in callback: %w. "+ + "Browser login needs IPv4 loopback; check that the loopback interface is up and that no firewall blocks local ports, or use `norcube login --device`", err) + } + redirectURI := fmt.Sprintf("http://127.0.0.1:%d/callback", listener.Addr().(*net.TCPAddr).Port) + + type result struct { + code string + err error + } + resultCh := make(chan result, 1) + deliver := func(r result) { + select { + case resultCh <- r: + default: // the first answer wins + } + } + // Single use: the first request with our state decides the login. A + // request without it (another local process or a web page probing the + // port) is refused and the login keeps waiting, so it can't be aborted + // from outside. + var answered atomic.Bool + mux := http.NewServeMux() + mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + code, err := checkCallback(r.URL.Query(), state, m) + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + if errors.Is(err, errCallbackState) { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, callbackPage("Not this sign-in", "This link doesn't belong to the sign-in in progress.")) + return + } + if !answered.CompareAndSwap(false, true) { + w.WriteHeader(http.StatusGone) + fmt.Fprint(w, callbackPage("Already used", "This sign-in link was already used. Return to the terminal.")) + return + } + if err != nil { + w.WriteHeader(http.StatusBadRequest) + // #nosec G705 -- callbackPage escapes everything it is given. + fmt.Fprint(w, callbackPage("Sign-in failed", err.Error()+". Return to the terminal for details.")) + deliver(result{err: err}) + return + } + fmt.Fprint(w, callbackPage("Signed in to Norcube CLI", "You can close this tab and return to the terminal.")) + deliver(result{code: code}) + }) + server := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second} + go func() { + if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) { + deliver(result{err: err}) + } + }() + defer func() { + shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _ = server.Shutdown(shutdownCtx) + }() + + authURL := authorizeURL(m.AuthorizationEndpoint, redirectURI, state, challenge, opts.Scopes) + if opts.OnURLReady != nil { + opts.OnURLReady(authURL) + } + // Open failure is not fatal: the user can copy the URL. + if !opts.NoBrowser { + _ = opts.BrowserOpenURL(authURL) + } + + timeoutCtx, cancel := context.WithTimeout(ctx, opts.Timeout) + defer cancel() + var res result + select { + case res = <-resultCh: + case <-timeoutCtx.Done(): + if errors.Is(timeoutCtx.Err(), context.DeadlineExceeded) && ctx.Err() == nil { + return nil, fmt.Errorf("login timed out after %s; re-run `norcube login`", opts.Timeout) + } + return nil, ctx.Err() + } + if res.err != nil { + return nil, res.err + } + + form := url.Values{ + "grant_type": {grantAuthorizationCode}, + "code": {res.code}, + "redirect_uri": {redirectURI}, + "client_id": {ClientID}, + "code_verifier": {verifier}, + } + // Not retried: a code is good for one exchange. + tr, oe, err := postToken(ctx, opts.HTTP, m.TokenEndpoint, form, false) + switch { + case err != nil: + return nil, fmt.Errorf("complete the sign-in: %w", err) + case oe != nil: + return nil, oauthFailure("complete the sign-in", oe) + } + return signInPayload(tr) +} + +// authorizeURL is the authorization request (RFC 6749 §4.1.1, PKCE, +// device details for the consent screen). +func authorizeURL(endpoint, redirectURI, state, challenge string, scopes []string) string { + u, err := url.Parse(endpoint) + if err != nil { + return endpoint + } + q := u.Query() + q.Set("response_type", "code") + q.Set("client_id", ClientID) + q.Set("redirect_uri", redirectURI) + q.Set("scope", requestScope(scopes)) + q.Set("state", state) + q.Set("code_challenge", challenge) + q.Set("code_challenge_method", "S256") + if host := deviceName(); host != "" { + q.Set("device_name", host) + } + q.Set("client_user_agent", truncate(transport.UserAgent())) + u.RawQuery = q.Encode() + return u.String() +} + +// errCallbackState: the callback doesn't carry this sign-in's state +// (possible CSRF). The login ignores it and keeps waiting. +var errCallbackState = errors.New("the sign-in callback's state did not match (possible CSRF)") + +// checkCallback validates the redirect: state first (anything without +// our state is refused, CSRF), then the issuer (RFC 9207, mix-up), then +// the outcome. +func checkCallback(q url.Values, state string, m *Metadata) (string, error) { + got := q.Get("state") + if got == "" || subtle.ConstantTimeCompare([]byte(got), []byte(state)) != 1 { + return "", errCallbackState + } + iss := q.Get("iss") + switch { + case iss != "" && !sameURL(iss, m.Issuer): + return "", fmt.Errorf("the sign-in callback came from issuer %q, not %q, sign-in aborted", iss, m.Issuer) + case iss == "" && m.IssParameterSupported: + return "", errors.New("the sign-in callback has no issuer although Norcube Auth sends one, sign-in aborted") + } + if e := q.Get("error"); e != "" { + oe := &OAuthError{Status: http.StatusBadRequest, Code: e, Description: q.Get("error_description")} + if e == oauthAccessDenied { + return "", &clierr.Error{Code: clierr.CodeLoginRequired, Message: "the sign-in was denied in the browser", Err: oe} + } + return "", oauthFailure("sign-in", oe) + } + code := q.Get("code") + if code == "" { + return "", errors.New("the sign-in callback has no code, sign-in aborted") + } + return code, nil +} + +func callbackPage(title, body string) string { + return "" + html.EscapeString(title) + + "

" + + html.EscapeString(title) + "

" + html.EscapeString(body) + "

" +} + +// newPKCE returns an RFC 7636 code verifier (43 characters from 32 random +// bytes) and its S256 challenge. +func newPKCE() (verifier, challenge string, err error) { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + return "", "", err + } + verifier = base64.RawURLEncoding.EncodeToString(b) + return verifier, pkceChallenge(verifier), nil +} + +func pkceChallenge(verifier string) string { + sum := sha256.Sum256([]byte(verifier)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +// --- revocation --- + +// RevokeRefreshToken signs an OAuth sign-in out on Norcube Auth (RFC 7009 +// revocation of its refresh token): the grant, its tokens and the CLI +// session end, also when the token was already rotated out. Norcube Auth +// answers 200 for unknown or already revoked tokens too; anything else is +// an error. Callers hold the profile's lock. +func RevokeRefreshToken(ctx context.Context, httpc *http.Client, authURL, refreshToken string) error { + if httpc == nil { + httpc = transport.Default() + } + ctx, cancel := context.WithTimeout(ctx, SignOutTimeout) + defer cancel() + endpoint := strings.TrimRight(authURL, "/") + "/oauth/revoke" + if m, err := Discover(ctx, httpc, authURL); err == nil && m.RevocationEndpoint != "" { + endpoint = m.RevocationEndpoint + } + form := url.Values{ + "token": {refreshToken}, + "token_type_hint": {"refresh_token"}, + "client_id": {ClientID}, + } + // Revoking twice is harmless, so the transport may retry. + resp, raw, err := postForm(ctx, httpc, endpoint, form, true) + if err != nil { + return fmt.Errorf("oauth/revoke: %w", err) + } + if resp.StatusCode/100 != 2 { + if oe := parseOAuthError(resp.StatusCode, raw); oe != nil { + return fmt.Errorf("oauth/revoke: %w", oe) + } + return fmt.Errorf("oauth/revoke: status %d", resp.StatusCode) + } + return nil +} diff --git a/internal/auth/oauth_race_test.go b/internal/auth/oauth_race_test.go new file mode 100644 index 0000000..d5b62ad --- /dev/null +++ b/internal/auth/oauth_race_test.go @@ -0,0 +1,171 @@ +package auth + +import ( + "context" + "fmt" + "os" + "os/exec" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/norcubeplatform/cli/internal/auth/authtest" +) + +// hammerOAuth asks for tokens of several services from n goroutines until +// the deadline, like hammer does for the older sign-in. +func hammerOAuth(api, lockDir string, n int, d time.Duration) (calls, failures int64, firstErr error) { + auds := []string{AudienceSnapDB, AudienceLangsync, AudienceDomainradar, AudienceAuth} + var c, f atomic.Int64 + var once sync.Once + deadline := time.Now().Add(d) + var wg sync.WaitGroup + for i := range n { + wg.Go(func() { + ts := NewTokenSource(api, auds[i%len(auds)], authtest.HomeOrgID) + ts.LockDir = lockDir + for time.Now().Before(deadline) { + c.Add(1) + if _, err := ts.Token(context.Background()); err != nil { + f.Add(1) + once.Do(func() { firstErr = err }) + } + time.Sleep(time.Millisecond) + } + }) + } + wg.Wait() + return c.Load(), f.Load(), firstErr +} + +const oauthHelperEnv = "NORCUBE_OAUTH_TOKEN_HELPER" + +// TestOAuthHelperProcess is the child side of TestOAuthRefreshAcrossProcesses. +func TestOAuthHelperProcess(t *testing.T) { + if os.Getenv(oauthHelperEnv) != "1" { + t.Skip("helper for TestOAuthRefreshAcrossProcesses") + } + SetStore(fileStore{dir: os.Getenv("STORE_DIR")}) + d, _ := time.ParseDuration(os.Getenv("DURATION")) + n, _ := strconv.Atoi(os.Getenv("GOROUTINES")) + calls, failures, err := hammerOAuth(os.Getenv("API"), os.Getenv("LOCK_DIR"), n, d) + fmt.Printf("RESULT calls=%d failures=%d err=%v\n", calls, failures, err) +} + +// Six processes with twenty goroutines each keep asking for tokens of +// four services while the CLI access token and the service tokens expire +// every second. Only the refresh rotates anything: exactly one refresh +// per expiry across all processes, and no refresh token presented twice. +func TestOAuthRefreshAcrossProcesses(t *testing.T) { + if testing.Short() { + t.Skip("multi-process test") + } + s := authtest.New() + defer s.Close() + // 31 s with the 30 s margin: each token is good for about a second. + s.AccessTTL, s.ProductTTL = 31, 31 + s.Delay = 20 * time.Millisecond + _ = discover(t, s) + + storeDir, lockDir := t.TempDir(), t.TempDir() + prev := SetStore(fileStore{dir: storeDir}) + defer SetStore(prev) + forgetMemory("", s.URL) + g := s.NewGrant() + if err := SaveOAuthSession("", s.URL, s.CurrentRefresh(g), "", time.Time{}, g.Scopes); err != nil { + t.Fatal(err) + } + + const ( + children = 5 + goroutines = 20 + duration = 3 * time.Second + ) + type result struct { + out []byte + err error + } + results := make(chan result, children) + for range children { + cmd := exec.Command(os.Args[0], "-test.run=^TestOAuthHelperProcess$", "-test.count=1", "-test.v") // #nosec G204 G702 -- re-runs this test binary + cmd.Env = append(os.Environ(), + oauthHelperEnv+"=1", + "API="+s.URL, + "STORE_DIR="+storeDir, + "LOCK_DIR="+lockDir, + "DURATION="+duration.String(), + "GOROUTINES="+strconv.Itoa(goroutines), + ) + go func() { + out, err := cmd.CombinedOutput() + results <- result{out, err} + }() + } + calls, failures, firstErr := hammerOAuth(s.URL, lockDir, goroutines, duration) + if failures != 0 { + t.Errorf("parent: %d of %d calls failed, first: %v", failures, calls, firstErr) + } + for range children { + r := <-results + if r.err != nil { + t.Fatalf("child failed: %v\n%s", r.err, r.out) + } + line := "" + for l := range strings.SplitSeq(string(r.out), "\n") { + if strings.HasPrefix(l, "RESULT ") { + line = l + } + } + if line == "" { + t.Fatalf("child printed no result:\n%s", r.out) + } + if !strings.Contains(line, " failures=0 ") { + t.Errorf("child: %s", line) + } + } + + st := s.Stats() + // GraceHits counts a stale token presented within the server's grace + // window, which a reuse check alone would not see. + if st.Reuses != 0 || st.GraceHits != 0 || s.Revoked(g) { + t.Fatalf("a rotated refresh token was presented again (%d reuses, %d within the grace window)", st.Reuses, st.GraceHits) + } + if n := st.Refreshes; n < 2 || n > 5 { + t.Fatalf("%d refreshes in %s with a ~1s token life; want one per expiry", n, duration) + } + for i := 1; i < len(st.RefreshTimes); i++ { + if gap := st.RefreshTimes[i].Sub(st.RefreshTimes[i-1]); gap < 800*time.Millisecond { + t.Fatalf("refreshes %d and %d only %v apart: a still-valid token was refreshed again", i-1, i, gap) + } + } + // Exchanges are per process and service, in parallel. + if s.MaxConcurrentExchanges() < 2 { + t.Fatalf("exchanges never overlapped (max %d in flight)", s.MaxConcurrentExchanges()) + } +} + +// Two processes upgrading the same older sign-in at once: one upgrade, +// the legacy token presented once. +func TestLegacyUpgradeOnceAcrossGoroutines(t *testing.T) { + s := authtest.New() + defer s.Close() + _ = discover(t, s) + prev := SetStore(fileStore{dir: t.TempDir()}) + defer SetStore(prev) + forgetMemory("", s.URL) + s.AddLegacySession("legacy-refresh") + if err := SaveRefreshToken("", s.URL, "legacy-refresh"); err != nil { + t.Fatal(err) + } + lockDir := t.TempDir() + _, failures, err := hammerOAuth(s.URL, lockDir, 30, 300*time.Millisecond) + if failures != 0 { + t.Fatalf("%d failures, first: %v", failures, err) + } + if st := s.Stats(); st.Upgrades != 1 || st.UpgradeRefusals != 0 || st.LegacyRefreshes != 0 { + t.Fatalf("upgrades %d refusals %d legacy refreshes %d", st.Upgrades, st.UpgradeRefusals, st.LegacyRefreshes) + } +} diff --git a/internal/auth/oauth_test.go b/internal/auth/oauth_test.go new file mode 100644 index 0000000..29945a3 --- /dev/null +++ b/internal/auth/oauth_test.go @@ -0,0 +1,842 @@ +package auth + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/zalando/go-keyring" + + "github.com/norcubeplatform/cli/internal/auth/authtest" + "github.com/norcubeplatform/cli/internal/clierr" + "github.com/norcubeplatform/cli/internal/credstore" + "github.com/norcubeplatform/cli/internal/registry" +) + +// browserFollows plays the browser: it opens the authorization URL and +// follows the redirect back to the CLI's loopback callback. +func browserFollows(t *testing.T) func(string) error { + t.Helper() + return func(u string) error { + go func() { + resp, err := http.Get(u) // #nosec G107 -- the test's own fake server + if err != nil { + return + } + _, _ = io.Copy(io.Discard, resp.Body) + _ = resp.Body.Close() + }() + return nil + } +} + +func discover(t *testing.T, s *authtest.Server) *Metadata { + t.Helper() + ForgetMetadata(s.URL) + m, err := Discover(context.Background(), s.Client(), s.URL) + if err != nil { + t.Fatal(err) + } + return m +} + +func oauthLogin(t *testing.T, s *authtest.Server, opts OAuthLoginOptions) (*CallbackPayload, error) { + t.Helper() + opts.Metadata = discover(t, s) + opts.HTTP = s.Client() + if opts.BrowserOpenURL == nil { + opts.BrowserOpenURL = browserFollows(t) + } + if opts.Timeout == 0 { + opts.Timeout = 5 * time.Second + } + return OAuthLogin(context.Background(), opts) +} + +func TestDiscover(t *testing.T) { + s := authtest.New() + defer s.Close() + m := discover(t, s) + if !m.SupportsCLISignIn() || !m.SupportsDevice() || !m.IssParameterSupported || m.RevocationEndpoint != s.URL+"/oauth/revoke" { + t.Fatalf("metadata: %+v", m) + } + + // Cached: the server going away doesn't matter. + s.Close() + if _, err := Discover(context.Background(), http.DefaultClient, s.URL); err != nil { + t.Fatalf("cached metadata not used: %v", err) + } +} + +func TestDiscoverWithoutOAuth(t *testing.T) { + for name, set := range map[string]func(*authtest.Server){ + "no metadata": func(s *authtest.Server) { s.OAuthOff = true }, + "no token exchange": func(s *authtest.Server) { s.NoExchange = true }, + } { + t.Run(name, func(t *testing.T) { + s := authtest.New() + defer s.Close() + set(s) + ForgetMetadata(s.URL) + if _, err := Discover(context.Background(), s.Client(), s.URL); !errors.Is(err, ErrOAuthUnavailable) { + t.Fatalf("got %v, want ErrOAuthUnavailable", err) + } + // The answer is cached too, for a shorter time. + s.Close() + if _, err := Discover(context.Background(), http.DefaultClient, s.URL); !errors.Is(err, ErrOAuthUnavailable) { + t.Fatalf("not cached: %v", err) + } + }) + } +} + +// RFC 8414 §3.3: metadata naming another issuer is refused, and network +// errors are not cached. +func TestDiscoverRejectsAnotherIssuer(t *testing.T) { + s := authtest.New() + defer s.Close() + ForgetMetadata(s.URL + "/") + other := "http://" + strings.Replace(strings.TrimPrefix(s.URL, "http://"), "127.0.0.1", "localhost", 1) + ForgetMetadata(other) + if _, err := Discover(context.Background(), s.Client(), other); err == nil || !strings.Contains(err.Error(), "names issuer") { + t.Fatalf("got %v", err) + } + if _, ok := cachedMetadata(other); ok { + t.Fatal("a refused answer was cached") + } +} + +func TestOAuthLogin(t *testing.T) { + s := authtest.New() + defer s.Close() + var shown string + p, err := oauthLogin(t, s, OAuthLoginOptions{OnURLReady: func(u string) { shown = u }}) + if err != nil { + t.Fatal(err) + } + if !p.OAuth || p.RefreshToken == "" || p.AccessToken == "" || p.AccessExpiresIn != 299 { + t.Fatalf("payload: %+v", p) + } + if strings.Join(p.Scopes, " ") != "full org.read offline_access" || p.DefaultOrg.Slug != "home" { + t.Fatalf("scopes %v, org %+v", p.Scopes, p.DefaultOrg) + } + q := s.Stats().AuthorizeQuery + if !strings.HasPrefix(shown, s.URL+"/oauth/authorize?") { + t.Errorf("printed URL %q", shown) + } + if q.Get("scope") != "full offline_access" || q.Get("client_id") != ClientID || q.Get("code_challenge_method") != "S256" { + t.Errorf("authorize query: %v", q) + } + if q.Get("client_user_agent") == "" || !strings.HasPrefix(q.Get("client_user_agent"), "norcube/") || q.Get("device_name") != deviceName() { + t.Errorf("device details: %v", q) + } + if len(q.Get("state")) != 64 || len(q.Get("code_challenge")) != 43 { + t.Errorf("state %q, challenge %q", q.Get("state"), q.Get("code_challenge")) + } + if n := s.Stats().CodeExchanges; n != 1 { + t.Fatalf("%d code exchanges", n) + } +} + +func TestOAuthLoginScopes(t *testing.T) { + s := authtest.New() + defer s.Close() + p, err := oauthLogin(t, s, OAuthLoginOptions{Scopes: []string{"backup.read", "langsync.sync"}}) + if err != nil { + t.Fatal(err) + } + if got := s.Stats().AuthorizeQuery.Get("scope"); got != "backup.read langsync.sync offline_access" { + t.Errorf("scope %q", got) + } + if DescribeScopes(p.Scopes) != "backup.read, langsync.sync" || ScopesFull(p.Scopes) { + t.Errorf("granted %v", p.Scopes) + } +} + +func TestPKCE(t *testing.T) { + v, c, err := newPKCE() + if err != nil { + t.Fatal(err) + } + if len(v) != 43 || strings.ContainsAny(v, "+/=") { + t.Errorf("verifier %q", v) + } + // RFC 7636 appendix B. + if got := pkceChallenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"); got != "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" { + t.Errorf("S256 challenge %q", got) + } + if c != pkceChallenge(v) { + t.Error("challenge doesn't match the verifier") + } +} + +// The callback must carry our state and the server's issuer; a browser +// sent there by anyone else, or a response from another server, is +// refused before any code is exchanged. +func TestOAuthLoginCallbackChecks(t *testing.T) { + cases := map[string]struct { + set func(*authtest.Server) + open func(t *testing.T) func(string) error + want string + }{ + "wrong issuer": {set: func(s *authtest.Server) { s.WrongIss = true }, want: "came from issuer"}, + "missing issuer": {set: func(s *authtest.Server) { s.IssOff = true }, want: ""}, + } + for name, c := range cases { + t.Run(name, func(t *testing.T) { + s := authtest.New() + defer s.Close() + if c.set != nil { + c.set(s) + } + opts := OAuthLoginOptions{} + if c.open != nil { + opts.BrowserOpenURL = c.open(t) + } + _, err := oauthLogin(t, s, opts) + if c.want == "" { + // A server that doesn't send iss (and says so) is fine. + if err != nil { + t.Fatalf("got %v", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), c.want) { + t.Fatalf("got %v, want %q", err, c.want) + } + if s.Stats().CodeExchanges != 0 { + t.Fatal("a code was exchanged after a failed check") + } + }) + } +} + +// A request to the callback without this sign-in's state (another local +// process, a page probing the port) is refused, and the login carries on +// with the real browser; a second answer after that is refused too. +func TestOAuthLoginIgnoresForeignCallbacks(t *testing.T) { + s := authtest.New() + defer s.Close() + follow := browserFollows(t) + var forged, late int + opts := OAuthLoginOptions{BrowserOpenURL: func(u string) error { + q, _ := url.Parse(u) + redirect := q.Query().Get("redirect_uri") + resp, err := http.Get(redirect + "?code=stolen&state=forged") // #nosec G107 -- loopback in a test + if err != nil { + return err + } + forged = resp.StatusCode + _ = resp.Body.Close() + if err := follow(u); err != nil { + return err + } + resp, err = http.Get(redirect + "?code=again&state=forged") // #nosec G107 -- loopback in a test + if err == nil { + late = resp.StatusCode + _ = resp.Body.Close() + } + return nil + }} + p, err := oauthLogin(t, s, opts) + if err != nil || p == nil { + t.Fatalf("login aborted by a foreign callback: %v", err) + } + if forged != http.StatusBadRequest { + t.Errorf("forged callback answered %d, want 400", forged) + } + if late != 0 && late != http.StatusBadRequest { + t.Errorf("late forged callback answered %d", late) + } + if n := s.Stats().CodeExchanges; n != 1 { + t.Errorf("%d code exchanges, want 1 (the real code)", n) + } +} + +// A server that advertises iss but leaves it out is refused. +func TestCheckCallbackRequiresAdvertisedIssuer(t *testing.T) { + m := &Metadata{Issuer: "https://auth.example", IssParameterSupported: true} + if _, err := checkCallback(url.Values{"state": {"s"}, "code": {"c"}}, "s", m); err == nil { + t.Fatal("missing iss accepted") + } + if code, err := checkCallback(url.Values{"state": {"s"}, "code": {"c"}, "iss": {"https://auth.example/"}}, "s", m); err != nil || code != "c" { + t.Fatalf("%q %v", code, err) + } +} + +func TestOAuthLoginErrors(t *testing.T) { + s := authtest.New() + defer s.Close() + s.Deny = true + _, err := oauthLogin(t, s, OAuthLoginOptions{}) + var ce *clierr.Error + if !errors.As(err, &ce) || ce.Code != clierr.CodeLoginRequired || !strings.Contains(err.Error(), "denied") { + t.Fatalf("denied: %v", err) + } + + s.Lock() + s.Deny = false + s.Unlock() + _, err = oauthLogin(t, s, OAuthLoginOptions{Scopes: []string{"nope.read"}}) + if !errors.As(err, &ce) || ce.Code != clierr.CodeUsage || !strings.Contains(err.Error(), "invalid_scope") { + t.Fatalf("invalid scope: %v", err) + } +} + +func TestOAuthLoginTimesOut(t *testing.T) { + s := authtest.New() + defer s.Close() + _, err := oauthLogin(t, s, OAuthLoginOptions{NoBrowser: true, Timeout: 50 * time.Millisecond}) + if err == nil || !strings.Contains(err.Error(), "timed out") { + t.Fatalf("got %v", err) + } +} + +func TestParseLoginScopes(t *testing.T) { + for in, want := range map[string]string{ + "": "full", + "full": "full", + "langsync.sync,backup.read": "backup.read langsync.sync", + "backup.read,full": "full", + "org.read,backup.read": "backup.read", + " backup.read , ": "backup.read", + // Unknown here but well-formed: sent, Norcube Auth decides. + "backup.delete,backup.read": "backup.read backup.delete", + "vault,backup.read,vault": "backup.read vault", + "backup.delete,full": "full", + } { + got, err := ParseLoginScopes(strings.Split(in, ",")) + if err != nil || strings.Join(got, " ") != want { + t.Errorf("%q: %v %v, want %q", in, got, err, want) + } + } + for _, bad := range []string{"Backup.Read", "backup.read.all", "backup read", "backup_read", "org.read", "offline_access,org.read"} { + if _, err := ParseLoginScopes(strings.Split(bad, ",")); err == nil { + t.Errorf("%q accepted", bad) + } + } +} + +func TestDeviceLoginOAuth(t *testing.T) { + s := authtest.New() + defer s.Close() + s.DeviceAnswers = []string{"authorization_pending", "slow_down", "authorization_pending"} + clock := &fakeClock{now: time.Unix(1_800_000_000, 0)} + p, err := DeviceLogin(context.Background(), DeviceLoginOptions{ + AuthURL: s.URL, HTTP: s.Client(), Metadata: discover(t, s), Scopes: []string{"backup.read"}, + Hostname: "build-box", sleep: clock.sleep, now: func() time.Time { return clock.now }, + }) + if err != nil { + t.Fatal(err) + } + if !p.OAuth || p.RefreshToken == "" || DescribeScopes(p.Scopes) != "backup.read" { + t.Fatalf("payload %+v", p) + } + f := s.Stats().DeviceCodeForm + if f.Get("scope") != "backup.read offline_access" || f.Get("device_name") != "build-box" || !strings.HasPrefix(f.Get("client_user_agent"), "norcube/") || f.Get("hostname") != "" { + t.Errorf("device code form: %v", f) + } + // 5s, 5s, then 10s after slow_down, 10s. + want := []time.Duration{5 * time.Second, 5 * time.Second, 10 * time.Second, 10 * time.Second} + if len(clock.sleeps) != len(want) { + t.Fatalf("sleeps %v, want %v", clock.sleeps, want) + } + for i := range want { + if clock.sleeps[i] != want[i] { + t.Fatalf("sleeps %v, want %v", clock.sleeps, want) + } + } +} + +func TestDeviceLoginOAuthEndings(t *testing.T) { + for answer, want := range map[string]error{"access_denied": ErrDeviceDenied, "expired_token": ErrDeviceExpired} { + t.Run(answer, func(t *testing.T) { + s := authtest.New() + defer s.Close() + s.DeviceAnswers = []string{answer} + clock := &fakeClock{now: time.Unix(1_800_000_000, 0)} + _, err := DeviceLogin(context.Background(), DeviceLoginOptions{ + AuthURL: s.URL, HTTP: s.Client(), Metadata: discover(t, s), + sleep: clock.sleep, now: func() time.Time { return clock.now }, + }) + var ce *clierr.Error + if !errors.Is(err, want) || !errors.As(err, &ce) || ce.ExitCode() != clierr.ExitAuth { + t.Fatalf("got %v", err) + } + }) + } + t.Run("invalid_scope", func(t *testing.T) { + s := authtest.New() + defer s.Close() + _, err := DeviceLogin(context.Background(), DeviceLoginOptions{ + AuthURL: s.URL, HTTP: s.Client(), Metadata: discover(t, s), Scopes: []string{"nope"}, + }) + var ce *clierr.Error + if !errors.As(err, &ce) || ce.Code != clierr.CodeUsage { + t.Fatalf("got %v", err) + } + }) +} + +// signedInOAuth stores an OAuth sign-in for the fake's new grant. +func signedInOAuth(t *testing.T, s *authtest.Server, scopes ...string) *authtest.Grant { + t.Helper() + keyring.MockInit() + forgetMemory("", s.URL) + g := s.NewGrant(scopes...) + if err := SaveOAuthSession("", s.URL, s.CurrentRefresh(g), "", time.Time{}, g.Scopes); err != nil { + t.Fatal(err) + } + return g +} + +func oauthSource(t *testing.T, s *authtest.Server, audience, org string) *TokenSource { + t.Helper() + ts := NewTokenSource(s.URL, audience, org) + ts.HTTP = s.Client() + ts.LockDir = t.TempDir() + return ts +} + +// One refresh, then one exchange per (audience, org); repeated calls +// come from memory, and the rotated refresh token is stored. +func TestOAuthTokenSource(t *testing.T) { + s := authtest.New() + defer s.Close() + g := signedInOAuth(t, s) + first := s.CurrentRefresh(g) + _ = discover(t, s) + + for range 3 { + for _, aud := range []string{AudienceSnapDB, AudienceLangsync, AudienceAuth} { + tok, err := oauthSource(t, s, aud, authtest.HomeOrgID).Token(context.Background()) + if err != nil { + t.Fatal(err) + } + if a, org, _, ok := s.ProductToken(tok); !ok || a != aud || org != authtest.HomeOrgID { + t.Fatalf("token for %s: %v %s %s", aud, ok, a, org) + } + } + } + if r, e, u := s.Counts(); r != 1 || e != 3 || u != 0 { + t.Fatalf("refreshes %d exchanges %d upgrades %d, want 1 3 0", r, e, u) + } + stored, _ := LoadRefreshToken("", s.URL) + if stored == first || stored != s.CurrentRefresh(g) { + t.Fatalf("stored refresh %q, server has %q (first %q)", stored, s.CurrentRefresh(g), first) + } + sess, _ := LoadSession("", s.URL) + if sess.Format != FormatOAuth || sess.CLIAccessExpiresAt.IsZero() || strings.Join(sess.Scopes, " ") != "full org.read offline_access" { + t.Fatalf("session %+v", sess) + } + if exp := AccessExpiry("", s.URL, AudienceSnapDB, authtest.HomeOrgID); exp.IsZero() { + t.Fatal("AccessExpiry doesn't see the in-memory token") + } +} + +func TestOAuthTokenErrors(t *testing.T) { + s := authtest.New() + defer s.Close() + _ = discover(t, s) + + t.Run("not a member", func(t *testing.T) { + signedInOAuth(t, s) + _, err := oauthSource(t, s, AudienceSnapDB, authtest.OtherOrgID).Token(context.Background()) + if !errors.Is(err, ErrOrgAccessDenied) { + t.Fatalf("got %v", err) + } + }) + t.Run("insufficient scope", func(t *testing.T) { + signedInOAuth(t, s, "backup.read") + _, err := oauthSource(t, s, AudienceLangsync, authtest.HomeOrgID).Token(context.Background()) + var se *ScopeError + if !errors.As(err, &se) || se.Audience != AudienceLangsync || DescribeScopes(se.Scopes) != "backup.read" { + t.Fatalf("got %v", err) + } + if _, err := oauthSource(t, s, AudienceSnapDB, authtest.HomeOrgID).Token(context.Background()); err != nil { + t.Fatalf("in scope: %v", err) + } + }) + t.Run("revoked", func(t *testing.T) { + g := signedInOAuth(t, s) + s.RevokeGrant(g) + _, err := oauthSource(t, s, AudienceSnapDB, authtest.HomeOrgID).Token(context.Background()) + if !errors.Is(err, ErrLoginRequired) || !strings.Contains(err.Error(), "ended this sign-in") { + t.Fatalf("got %v", err) + } + }) + t.Run("no organization", func(t *testing.T) { + signedInOAuth(t, s) + // Norcube Auth's own token needs none (organization_id omitted; + // the fake refuses an empty one)... + tok, err := oauthSource(t, s, AudienceAuth, "").Token(context.Background()) + if err != nil { + t.Fatalf("auth token without an organization: %v", err) + } + if aud, org, _, ok := s.ProductToken(tok); !ok || aud != AudienceAuth || org != "" { + t.Fatalf("token: %v %s %q", ok, aud, org) + } + // ...a product's does, and that's caught before any request. + _, err = oauthSource(t, s, AudienceSnapDB, "").Token(context.Background()) + if !clierr.IsUsage(err) { + t.Fatalf("product token without an organization: %v", err) + } + }) +} + +// A CLI access token the exchange refuses (expired early) costs one +// refresh, then the exchange is repeated. +func TestOAuthExchangeRetriesAfterRefresh(t *testing.T) { + s := authtest.New() + defer s.Close() + _ = discover(t, s) + g := signedInOAuth(t, s) + if _, err := oauthSource(t, s, AudienceSnapDB, authtest.HomeOrgID).Token(context.Background()); err != nil { + t.Fatal(err) + } + s.ExpireAccess(g) + if _, err := oauthSource(t, s, AudienceLangsync, authtest.HomeOrgID).Token(context.Background()); err != nil { + t.Fatal(err) + } + if r, e, _ := s.Counts(); r != 2 || e != 2 { + t.Fatalf("refreshes %d exchanges %d, want 2 2", r, e) + } +} + +// The refresh token this process read was rotated by another process +// meanwhile: the refused refresh reads the store again and uses the new one. +func TestOAuthRefreshReadsTheStoredTokenAgain(t *testing.T) { + s := authtest.New() + defer s.Close() + _ = discover(t, s) + g := signedInOAuth(t, s) + stale := s.CurrentRefresh(g) + // Another process refreshed: the server rotated, and its new token + // reaches the store only after this process read the old one. + fresh := s.Rotate(g) + c, _ := loadCreds("", s.URL) + if c.RefreshToken != stale { + t.Fatal("setup") + } + if err := SaveOAuthSession("", s.URL, fresh, "", time.Time{}, g.Scopes); err != nil { + t.Fatal(err) + } + ts := oauthSource(t, s, AudienceSnapDB, authtest.HomeOrgID) + tok, err := ts.refreshCLIAccess(context.Background(), c, true) + if err != nil || tok == "" { + t.Fatalf("got %q %v", tok, err) + } + if s.Stats().Reuses != 0 { + t.Fatal("the stale token counted as reuse") + } + if now, _ := LoadRefreshToken("", s.URL); now != s.CurrentRefresh(g) { + t.Fatal("the rotated token was not stored") + } +} + +// An older sign-in is moved to OAuth once; later calls use the OAuth +// sign-in and never present the legacy token again. +func TestLegacyUpgradeOnce(t *testing.T) { + keyring.MockInit() + s := authtest.New() + defer s.Close() + _ = discover(t, s) + s.AddLegacySession("legacy-refresh") + if err := SaveRefreshToken("", s.URL, "legacy-refresh"); err != nil { + t.Fatal(err) + } + for _, aud := range []string{AudienceSnapDB, AudienceLangsync, AudienceSnapDB} { + if _, err := oauthSource(t, s, aud, authtest.HomeOrgID).Token(context.Background()); err != nil { + t.Fatal(err) + } + } + if st := s.Stats(); st.Upgrades != 1 || st.UpgradeRefusals != 0 || st.LegacyRefreshes != 0 { + t.Fatalf("upgrades %d refusals %d legacy refreshes %d", st.Upgrades, st.UpgradeRefusals, st.LegacyRefreshes) + } + sess, _ := LoadSession("", s.URL) + if sess.Format != FormatOAuth || !ScopesFull(sess.Scopes) { + t.Fatalf("after upgrade: %+v", sess) + } +} + +// A token Norcube Auth won't upgrade (no session recorded, or ended) asks +// for one login; nothing is stored over it. +func TestLegacyUpgradeRefused(t *testing.T) { + keyring.MockInit() + s := authtest.New() + defer s.Close() + _ = discover(t, s) + if err := SaveRefreshToken("", s.URL, "sid-less"); err != nil { + t.Fatal(err) + } + _, err := oauthSource(t, s, AudienceSnapDB, authtest.HomeOrgID).Token(context.Background()) + if !errors.Is(err, ErrLoginRequired) || !strings.Contains(err.Error(), "sign in once more") { + t.Fatalf("got %v", err) + } + if sess, _ := LoadSession("", s.URL); sess.Format != FormatLegacy { + t.Fatalf("format %d", sess.Format) + } +} + +// Against a Norcube Auth without the OAuth sign-in the older refresh +// keeps working and nothing is upgraded. +func TestLegacyFallback(t *testing.T) { + keyring.MockInit() + s := authtest.New() + defer s.Close() + s.OAuthOff = true + ForgetMetadata(s.URL) + s.AddLegacySession("legacy-refresh") + if err := SaveRefreshToken("", s.URL, "legacy-refresh"); err != nil { + t.Fatal(err) + } + if _, err := oauthSource(t, s, AudienceSnapDB, authtest.HomeOrgID).Token(context.Background()); err != nil { + t.Fatal(err) + } + if st := s.Stats(); st.Upgrades != 0 || st.LegacyRefreshes != 1 { + t.Fatalf("upgrades %d legacy refreshes %d", st.Upgrades, st.LegacyRefreshes) + } + if sess, _ := LoadSession("", s.URL); sess.Format != FormatLegacy { + t.Fatalf("format %d", sess.Format) + } +} + +// Exchanges take no lock: with another process holding the profile's +// lock (a refresh in progress), a token is still minted from the cached +// CLI access token. +func TestExchangeNeedsNoLock(t *testing.T) { + s := authtest.New() + defer s.Close() + _ = discover(t, s) + signedInOAuth(t, s) + ts := oauthSource(t, s, AudienceSnapDB, authtest.HomeOrgID) + if _, err := ts.Token(context.Background()); err != nil { + t.Fatal(err) + } + unlock, err := LockProfile(context.Background(), ts.LockDir, "", s.URL, 0) + if err != nil { + t.Fatal(err) + } + defer unlock() + other := oauthSource(t, s, AudienceLangsync, authtest.HomeOrgID) + other.LockDir, other.LockTimeout = ts.LockDir, 100*time.Millisecond + if _, err := other.Token(context.Background()); err != nil { + t.Fatalf("the exchange waited for the lock: %v", err) + } +} + +// Many goroutines asking for tokens of several services at once: one +// refresh, exchanges in parallel, one per (service, org). +func TestConcurrentOAuthTokens(t *testing.T) { + s := authtest.New() + defer s.Close() + s.Delay = 30 * time.Millisecond + _ = discover(t, s) + signedInOAuth(t, s) + lockDir := t.TempDir() + auds := []string{AudienceSnapDB, AudienceLangsync, AudienceDomainradar, AudienceBilling, AudienceAuth} + errs := make(chan error, 50) + for i := range 50 { + go func() { + ts := NewTokenSource(s.URL, auds[i%len(auds)], authtest.HomeOrgID) + ts.HTTP, ts.LockDir = s.Client(), lockDir + _, err := ts.Token(context.Background()) + errs <- err + }() + } + for range 50 { + if err := <-errs; err != nil { + t.Fatal(err) + } + } + st := s.Stats() + if st.Refreshes != 1 || st.Exchanges != len(auds) || st.Reuses != 0 || st.GraceHits != 0 { + t.Fatalf("refreshes %d exchanges %d reuses %d grace hits %d; want 1 %d 0 0", st.Refreshes, st.Exchanges, st.Reuses, st.GraceHits, len(auds)) + } + if s.MaxConcurrentExchanges() < 2 { + t.Fatalf("exchanges ran one at a time (max %d in flight)", s.MaxConcurrentExchanges()) + } +} + +// limitedStore caps values like the Windows Credential Manager. +type limitedStore struct { + fileStore + max int +} + +func (l limitedStore) Set(key, value string) error { + if len(value) > l.max { + return credstore.ErrTooBig + } + return l.fileStore.Set(key, value) +} + +// A format 2 blob with tokens of realistic size fits the 2560-byte +// Windows limit; one that doesn't keeps the refresh token and scopes. +func TestOAuthCredentialsFitTheWindowsKeyring(t *testing.T) { + st := limitedStore{fileStore{dir: t.TempDir()}, 2560} + prev := SetStore(st) + defer SetStore(prev) + const api = "https://auth.api.example.com" + refresh := "ory_rt_" + strings.Repeat("r", 43) + "." + strings.Repeat("s", 43) + // An RS256 JWT with the cli_access claims is about 1.1 KB. + access := strings.Repeat("a", 36) + "." + strings.Repeat("p", 520) + "." + strings.Repeat("s", 342) + scopes := []string{"backup.read", "backup.write", "backup.verify", "domainradar.check", "langsync.read", "langsync.sync", + "langsync.write", "billing.read", "cms.read", "cms.write", "org.read", "offline_access"} + if err := SaveOAuthSession("", api, refresh, access, time.Now().Add(5*time.Minute), scopes); err != nil { + t.Fatal(err) + } + c, _ := loadCreds("", api) + if c.CLIAccess == nil || c.CLIAccess.Token != access || c.RefreshToken != refresh || len(c.Scopes) != len(scopes) { + t.Fatalf("not stored whole: %+v", c) + } + raw, _ := st.Get(profileKey("")) + var probe map[string]any + if json.Unmarshal([]byte(raw), &probe) != nil || probe["format"] != float64(FormatOAuth) { + t.Fatalf("format marker missing: %s", raw) + } + + huge := strings.Repeat("x", 3000) + if err := SaveOAuthSession("", api, refresh, huge, time.Now().Add(5*time.Minute), scopes); err != nil { + t.Fatal(err) + } + c, _ = loadCreds("", api) + if c.CLIAccess != nil || c.RefreshToken != refresh || c.format() != FormatOAuth || len(c.Scopes) != len(scopes) { + t.Fatalf("slimmed blob: %+v", c) + } +} + +func TestRevokeRefreshToken(t *testing.T) { + s := authtest.New() + defer s.Close() + _ = discover(t, s) + g := s.NewGrant("full") + rt := s.CurrentRefresh(g) + if err := RevokeRefreshToken(context.Background(), s.Client(), s.URL, rt); err != nil { + t.Fatal(err) + } + f := s.Stats().Revocations[0] + if f.Get("token") != rt || f.Get("client_id") != ClientID || f.Get("token_type_hint") != "refresh_token" || !s.Revoked(g) { + t.Fatalf("revocation %v, revoked %v", f, s.Revoked(g)) + } + s.Lock() + s.RevokeStatus = http.StatusServiceUnavailable + s.Unlock() + if err := RevokeRefreshToken(context.Background(), s.Client(), s.URL, rt); err == nil { + t.Fatal("a failed revocation reported success") + } +} + +// Metadata naming an endpoint outside the issuer's origin is refused, so a +// tampered answer can't send the refresh token elsewhere. +func TestDiscoverRejectsForeignEndpoint(t *testing.T) { + s := authtest.New() + defer s.Close() + s.TokenEndpoint = "https://elsewhere.example/oauth/token" + ForgetMetadata(s.URL) + if _, err := Discover(context.Background(), s.Client(), s.URL); err == nil || !strings.Contains(err.Error(), "outside") { + t.Fatalf("got %v", err) + } +} + +// A cached token endpoint that has moved answers without OAuth: the +// metadata is fetched again and the refresh goes to the new endpoint. +func TestOAuthTokenSourceRediscoversMovedEndpoint(t *testing.T) { + s := authtest.New() + defer s.Close() + signedInOAuth(t, s) + s.TokenEndpoint = s.URL + "/moved/token" + _ = discover(t, s) + s.Lock() + s.TokenEndpoint = "" + s.Unlock() + + if _, err := oauthSource(t, s, AudienceSnapDB, authtest.HomeOrgID).Token(context.Background()); err != nil { + t.Fatal(err) + } + if r, e, _ := s.Counts(); r != 1 || e != 1 { + t.Fatalf("refreshes %d exchanges %d, want 1 1", r, e) + } + if e, ok := cachedMetadata(s.URL); !ok || e.Metadata.TokenEndpoint != s.URL+"/oauth/token" { + t.Fatal("the moved endpoint is still cached") + } +} + +// A full sign-in reaches every service the CLI can call. A product added +// to the registry without its audience on the fake (or the server) fails +// here. +func TestFullSignInCoversEveryService(t *testing.T) { + s := authtest.New() + defer s.Close() + signedInOAuth(t, s) + _ = discover(t, s) + services := registry.Callable() + if len(services) == 0 { + t.Fatal("no callable services") + } + for _, svc := range services { + tok, err := oauthSource(t, s, svc.Audience, authtest.HomeOrgID).Token(context.Background()) + if err != nil { + t.Errorf("%s: %v", svc.Command, err) + continue + } + if a, _, _, ok := s.ProductToken(tok); !ok || a != svc.Audience { + t.Errorf("%s: token for %q (valid %v), want %q", svc.Command, a, ok, svc.Audience) + } + } +} + +// Every scope `login --scopes` offers is one the server knows, and a +// Monitor scope gets a token for Monitor only. +func TestLoginScopesAreKnownAndLimit(t *testing.T) { + s := authtest.New() + defer s.Close() + for _, ls := range LoginScopes { + if !s.KnowsScope(ls.Name) { + t.Errorf("--scopes offers %s, which the fake's catalog doesn't have", ls.Name) + } + } + + signedInOAuth(t, s, "monitor.read") + _ = discover(t, s) + tok, err := oauthSource(t, s, AudienceMonitor, authtest.HomeOrgID).Token(context.Background()) + if err != nil { + t.Fatal(err) + } + if a, _, _, ok := s.ProductToken(tok); !ok || a != AudienceMonitor { + t.Fatalf("token for %q (valid %v)", a, ok) + } + if _, err := oauthSource(t, s, AudienceSnapDB, authtest.HomeOrgID).Token(context.Background()); err == nil { + t.Fatal("a monitor.read sign-in got a Backup token") + } +} + +// With KeepLegacy an older sign-in stays as it is even when Norcube Auth +// offers the OAuth sign-in: the older refresh is used instead. +func TestKeepLegacyDoesNotUpgrade(t *testing.T) { + keyring.MockInit() + s := authtest.New() + defer s.Close() + ForgetMetadata(s.URL) + s.AddLegacySession("legacy-refresh") + if err := SaveRefreshToken("", s.URL, "legacy-refresh"); err != nil { + t.Fatal(err) + } + ts := oauthSource(t, s, AudienceSnapDB, authtest.HomeOrgID) + ts.KeepLegacy = true + if _, err := ts.Token(context.Background()); err != nil { + t.Fatal(err) + } + if st := s.Stats(); st.Upgrades != 0 || st.LegacyRefreshes != 1 { + t.Fatalf("upgrades %d legacy refreshes %d", st.Upgrades, st.LegacyRefreshes) + } + if sess, _ := LoadSession("", s.URL); sess.Format != FormatLegacy { + t.Fatalf("format %d", sess.Format) + } +} diff --git a/internal/auth/oauthsession.go b/internal/auth/oauthsession.go new file mode 100644 index 0000000..bc9c675 --- /dev/null +++ b/internal/auth/oauthsession.go @@ -0,0 +1,438 @@ +package auth + +import ( + "context" + "errors" + "fmt" + "net/url" + "strings" + "sync" + "time" + + "github.com/norcubeplatform/cli/internal/clierr" +) + +// Tokens of an OAuth sign-in (credentials format 2): +// +// - The refresh token and the 5-minute CLI access token live in the +// profile's credentials. Refreshing rotates the refresh token, so it +// happens under the in-process mutex and the per-profile lock file, +// and the rotated token is saved before the new access token is used. +// - The CLI access token is exchanged (RFC 8693) for a token per +// (service, organization). Exchanges use nothing up, so they run in +// parallel without the lock, and their tokens are cached in memory +// only: writing them back to the credential store without the lock +// could overwrite a refresh token another process just rotated. + +// memCache holds the exchanged tokens of this process. +var memCache = struct { + sync.Mutex + m map[string]cachedAccess +}{m: map[string]cachedAccess{}} + +func memPrefix(profile, api string) string { return profileName(profile) + "\x00" + api + "\x00" } + +func memKey(profile, api, audience, orgID string) string { + return memPrefix(profile, api) + audience + "\x00" + orgID +} + +func memGet(key string) (cachedAccess, bool) { + memCache.Lock() + defer memCache.Unlock() + a, ok := memCache.m[key] + return a, ok +} + +func memPut(key string, a cachedAccess) { + memCache.Lock() + defer memCache.Unlock() + memCache.m[key] = a +} + +// forgetMemory drops the profile's exchanged tokens (sign-in, sign-out). +func forgetMemory(profile, api string) { + prefix := memPrefix(profile, api) + memCache.Lock() + defer memCache.Unlock() + for k := range memCache.m { + if strings.HasPrefix(k, prefix) { + delete(memCache.m, k) + } + } +} + +// flights coalesces concurrent exchanges for the same key into one. +var flights = struct { + sync.Mutex + m map[string]*flight +}{m: map[string]*flight{}} + +type flight struct { + done chan struct{} + tok string + err error +} + +func coalesce(ctx context.Context, key string, fn func() (string, error)) (string, error) { + flights.Lock() + if f, ok := flights.m[key]; ok { + flights.Unlock() + select { + case <-f.done: + return f.tok, f.err + case <-ctx.Done(): + return "", ctx.Err() + } + } + f := &flight{done: make(chan struct{})} + flights.m[key] = f + flights.Unlock() + + f.tok, f.err = fn() + flights.Lock() + delete(flights.m, key) + flights.Unlock() + close(f.done) + return f.tok, f.err +} + +// refreshSems serializes this process's refreshes per profile; the lock +// file does it across processes. +var refreshSems sync.Map + +func refreshSem(profile, api string) chan struct{} { + s, _ := refreshSems.LoadOrStore(memPrefix(profile, api), make(chan struct{}, 1)) + return s.(chan struct{}) +} + +// ScopeError: the sign-in is limited by `login --scopes` and its scopes +// don't cover the service. Match it with errors.As. +type ScopeError struct { + Audience string + // Scopes are the sign-in's granted scopes. + Scopes []string +} + +func (e *ScopeError) Error() string { + return fmt.Sprintf("the scopes of this login (%s) don't cover %s", DescribeScopes(e.Scopes), ServiceName(e.Audience)) +} + +// ServiceName names an audience for messages. +func ServiceName(audience string) string { + switch audience { + case AudienceAuth: + return "Norcube Auth" + case AudienceBilling: + return "Billing" + case AudienceSnapDB: + return "Backup" + case AudienceLangsync: + return "LangSync" + case AudienceDomainradar: + return "DomainRadar" + case AudiencePrompthub: + return "PromptHub" + case AudienceCMS: + return "CMS" + } + return audience +} + +// errSubjectRejected: the token exchange refused the CLI access token +// (expired early, or the sign-in ended). A refresh tells which. +var errSubjectRejected = errors.New("the CLI access token was refused") + +// errSessionReplaced: the profile's stored sign-in changed kind while +// this command waited for the lock (a login of the older kind). +var errSessionReplaced = errors.New("the profile's sign-in changed while this command ran; run it again") + +// endedSignIn is the answer to a refresh token Norcube Auth no longer +// accepts. +func endedSignIn() error { + return fmt.Errorf("%w: Norcube Auth ended this sign-in (revoked, signed out elsewhere, or unused for 30 days)", ErrLoginRequired) +} + +func loadCreds(profile, api string) (*credentials, error) { + credsMu.RLock() + defer credsMu.RUnlock() + return loadCredentials(profile, api) +} + +func saveCreds(profile string, c *credentials) error { + credsMu.Lock() + defer credsMu.Unlock() + return saveCredentials(profile, c) +} + +func (t *TokenSource) memKey() string { return memKey(t.Profile, t.APIBase, t.Audience, t.OrgID) } + +// memCached returns this process's exchanged token for (audience, org) +// when it has more than expiryMargin of life left. +func (t *TokenSource) memCached() (string, bool) { + a, ok := memGet(t.memKey()) + if !ok || a.Token == "" || a.ExpiresAt.Sub(t.clock()) < expiryMargin { + return "", false + } + return a.Token, true +} + +// oauthToken returns a token for (audience, org) of an OAuth sign-in. +func (t *TokenSource) oauthToken(ctx context.Context) (string, error) { + // Only Norcube Auth's own tokens may be minted without an + // organization (the account, its organizations, org create). + if t.OrgID == "" && t.Audience != AudienceAuth { + return "", clierr.Usage(fmt.Errorf("a token for %s needs an organization. Run `norcube org use ` or pass --org ", ServiceName(t.Audience))) + } + return coalesce(ctx, t.memKey(), func() (string, error) { + if tok, ok := t.memCached(); ok { + return tok, nil + } + access, err := t.cliAccess(ctx, "") + if err != nil { + return "", err + } + tok, err := t.exchange(ctx, access) + if errors.Is(err, errSubjectRejected) { + // Expired in flight, or the sign-in ended: a refresh + // tells which. + if access, err = t.cliAccess(ctx, access); err != nil { + return "", err + } + if tok, err = t.exchange(ctx, access); errors.Is(err, errSubjectRejected) { + return "", endedSignIn() + } + } + return tok, err + }) +} + +// validCLIAccess returns c's CLI access token when it has more than +// expiryMargin of life left and isn't stale (the one just refused). +func validCLIAccess(c *credentials, stale string, now time.Time) (string, bool) { + if c.format() != FormatOAuth || c.CLIAccess == nil || c.CLIAccess.Token == "" || c.CLIAccess.Token == stale { + return "", false + } + if c.CLIAccess.ExpiresAt.Sub(now) < expiryMargin { + return "", false + } + return c.CLIAccess.Token, true +} + +func (t *TokenSource) storedCLIAccess(stale string) (string, bool) { + c, err := loadCreds(t.Profile, t.APIBase) + if err != nil { + return "", false + } + return validCLIAccess(c, stale, t.clock()) +} + +// cliAccess returns a CLI access token, refreshing the sign-in when the +// stored one is about to expire or is stale. +func (t *TokenSource) cliAccess(ctx context.Context, stale string) (string, error) { + if tok, ok := t.storedCLIAccess(stale); ok { + return tok, nil + } + sem := refreshSem(t.Profile, t.APIBase) + select { + case sem <- struct{}{}: + case <-ctx.Done(): + return "", ctx.Err() + } + defer func() { <-sem }() + // Another goroutine may have refreshed while we waited. + if tok, ok := t.storedCLIAccess(stale); ok { + return tok, nil + } + unlock, err := LockProfile(ctx, t.LockDir, t.Profile, t.APIBase, t.LockTimeout) + if err != nil { + return "", err + } + defer unlock() + // Read the refresh token only now, under the lock: a value read + // before it may already have been rotated away by another process. + c, err := loadCreds(t.Profile, t.APIBase) + if err != nil { + return "", fmt.Errorf("%w: %v", ErrLoginRequired, err) + } + switch { + case c.RefreshToken == "": + return "", ErrNotLoggedIn + case c.format() != FormatOAuth: + return "", errSessionReplaced + } + if tok, ok := validCLIAccess(c, stale, t.clock()); ok { + return tok, nil + } + return t.refreshCLIAccess(ctx, c, true) +} + +// tokenEndpoint is the OAuth server's token endpoint: from the (cached) +// metadata, else the path every Norcube Auth serves it at. +func (t *TokenSource) tokenEndpoint(ctx context.Context) string { + if m, err := Discover(ctx, t.HTTP, t.APIBase); err == nil { + return m.TokenEndpoint + } + return strings.TrimRight(t.APIBase, "/") + "/oauth/token" +} + +// postTokenRediscovering posts to the token endpoint. When the answer +// isn't OAuth at all (the cached metadata names an endpoint that moved), +// it drops the cached metadata and, if discovery now names another +// endpoint, sends the request there once. The request was not processed +// by an OAuth server, so nothing (such as a refresh token) was used up. +func (t *TokenSource) postTokenRediscovering(ctx context.Context, form url.Values, retryable bool) (*tokenEndpointResponse, *OAuthError, error) { + endpoint := t.tokenEndpoint(ctx) + tr, oe, err := postToken(ctx, t.HTTP, endpoint, form, retryable) + if !notOAuthAnswer(err) { + return tr, oe, err + } + ForgetMetadata(t.APIBase) + if fresh := t.tokenEndpoint(ctx); fresh != endpoint { + return postToken(ctx, t.HTTP, fresh, form, retryable) + } + return tr, oe, err +} + +// notOAuthAnswer reports whether err is an HTTP answer that isn't an +// OAuth response (not a transport failure). +func notOAuthAnswer(err error) bool { + var ce *clierr.Error + return errors.As(err, &ce) && ce.HTTPStatus != 0 +} + +// refreshCLIAccess rotates the refresh token. Must be called under the +// profile's lock. On invalid_grant it reads the stored refresh token once +// more: if it changed meanwhile (another process rotated it), that one is +// used instead of declaring the sign-in ended. Norcube Auth refuses a +// token rotated out less than 10 seconds ago without ending the session, +// so presenting the old one by mistake is harmless within that grace. +func (t *TokenSource) refreshCLIAccess(ctx context.Context, c *credentials, retry bool) (string, error) { + form := url.Values{ + "grant_type": {grantRefreshToken}, + "refresh_token": {c.RefreshToken}, + "client_id": {ClientID}, + } + received := t.clock() + // Not retried by the transport: a repeated refresh would present a + // token the first attempt may already have rotated. + tr, oe, err := t.postTokenRediscovering(ctx, form, false) + if err != nil { + return "", fmt.Errorf("refresh the sign-in: %w", err) + } + if oe != nil { + if oe.Code != oauthInvalidGrant { + return "", oauthFailure("refresh the sign-in", oe) + } + if retry { + if now, err := loadCreds(t.Profile, t.APIBase); err == nil && now.format() == FormatOAuth && + now.RefreshToken != "" && now.RefreshToken != c.RefreshToken { + if tok, ok := validCLIAccess(now, "", t.clock()); ok { + return tok, nil + } + return t.refreshCLIAccess(ctx, now, false) + } + } + return "", endedSignIn() + } + next := *c + if tr.RefreshToken != "" { + next.RefreshToken = tr.RefreshToken + } + next.CLIAccess = &cachedAccess{Token: tr.AccessToken, ExpiresAt: expiresAt(received, tr.ExpiresIn, tr.AccessToken)} + if scopes := parseScope(tr.Scope); len(scopes) > 0 { + next.Scopes = scopes + } + if err := saveCreds(t.Profile, &next); err != nil { + // The presented refresh token is used up: without the new one + // the next command can't refresh. Say so now. + return "", fmt.Errorf("persist rotated refresh token: %w", err) + } + return tr.AccessToken, nil +} + +func expiresAt(received time.Time, expiresIn int, token string) time.Time { + if expiresIn > 0 { + return received.Add(time.Duration(expiresIn) * time.Second) + } + return jwtExpiry(token) +} + +// exchange trades the CLI access token for a token for (audience, org) +// and caches it in memory. +func (t *TokenSource) exchange(ctx context.Context, access string) (string, error) { + form := url.Values{ + "grant_type": {grantTokenExchange}, + "client_id": {ClientID}, + "subject_token": {access}, + "subject_token_type": {tokenTypeAccessToken}, + "audience": {t.Audience}, + } + if t.OrgID != "" { + form.Set("organization_id", t.OrgID) + } + received := t.clock() + // An exchange uses nothing up, so the transport may retry it. + tr, oe, err := t.postTokenRediscovering(ctx, form, true) + if err != nil { + return "", fmt.Errorf("get a token for %s: %w", ServiceName(t.Audience), err) + } + if oe != nil { + switch oe.Code { + case oauthInvalidGrant: + return "", errSubjectRejected + case oauthOrgAccessDenied: + return "", &OrgAccessError{Org: t.orgLabel()} + case oauthInsufficientScope: + var scopes []string + if c, err := loadCreds(t.Profile, t.APIBase); err == nil { + scopes = c.Scopes + } + return "", &ScopeError{Audience: t.Audience, Scopes: scopes} + case oauthInvalidTarget: + return "", fmt.Errorf("no tokens for %q from Norcube Auth (%s); is this norcube version too new for it?", t.Audience, oe.Error()) + } + return "", oauthFailure("get a token for "+ServiceName(t.Audience), oe) + } + memPut(t.memKey(), cachedAccess{Token: tr.AccessToken, ExpiresAt: expiresAt(received, tr.ExpiresIn, tr.AccessToken)}) + return tr.AccessToken, nil +} + +// upgradeLegacy moves an older sign-in (format 1) to OAuth, once: Norcube +// Auth uses up its refresh JWT and links a full grant to the same CLI +// session, so nobody signs in again. Must be called under the profile's +// lock. A token Norcube Auth won't move (the session ended, or the token +// predates recorded CLI sessions) asks for one new sign-in. +func (t *TokenSource) upgradeLegacy(ctx context.Context, m *Metadata, refresh string) error { + form := url.Values{ + "grant_type": {grantTokenExchange}, + "client_id": {ClientID}, + "subject_token": {refresh}, + "subject_token_type": {tokenTypeCLISession}, + } + received := t.clock() + // Not retried: the refresh JWT is used up by the first attempt. + tr, oe, err := postToken(ctx, t.HTTP, m.TokenEndpoint, form, false) + if err != nil { + return fmt.Errorf("move this sign-in to the OAuth sign-in: %w", err) + } + if oe != nil { + if oe.Code == oauthInvalidGrant { + return fmt.Errorf("%w: Norcube Auth couldn't move this sign-in to the new sign-in (the session ended, or it was made before Norcube recorded CLI sessions); sign in once more", ErrLoginRequired) + } + return oauthFailure("move this sign-in to the OAuth sign-in", oe) + } + if tr.RefreshToken == "" { + return errors.New("move this sign-in to the OAuth sign-in: the response has no refresh token") + } + if err := SaveOAuthSession(t.Profile, t.APIBase, tr.RefreshToken, tr.AccessToken, + expiresAt(received, tr.ExpiresIn, tr.AccessToken), parseScope(tr.Scope)); err != nil { + return fmt.Errorf("persist the upgraded sign-in: %w", err) + } + return nil +} + +// isLimitedScope reports whether err is a ScopeError. +func isLimitedScope(err error) bool { + var se *ScopeError + return errors.As(err, &se) +} diff --git a/internal/auth/refresh_race_test.go b/internal/auth/refresh_race_test.go index aecffbe..e86c179 100644 --- a/internal/auth/refresh_race_test.go +++ b/internal/auth/refresh_race_test.go @@ -151,7 +151,7 @@ func TestRefreshAcrossProcesses(t *testing.T) { } // expires_in 31 with the 30s margin: each token is good for ~1s. srv := &rotatingServer{expiresIn: 31, current: "refresh-0"} - hs := httptest.NewServer(srv) + hs := httptest.NewServer(olderServer(srv)) defer hs.Close() storeDir, lockDir := t.TempDir(), t.TempDir() @@ -228,7 +228,7 @@ func TestRefreshAcrossProcesses(t *testing.T) { // exchange, not one each. func TestConcurrentFirstTokenExchangesOnce(t *testing.T) { srv := &rotatingServer{expiresIn: 300, current: "refresh-0"} - hs := httptest.NewServer(srv) + hs := httptest.NewServer(olderServer(srv)) defer hs.Close() prev := SetStore(fileStore{dir: t.TempDir()}) defer SetStore(prev) @@ -249,14 +249,14 @@ func TestConcurrentFirstTokenExchangesOnce(t *testing.T) { // whose JWT exp looks past (a local clock running fast) is still reused. func TestExpiryUsesExpiresInNotLocalClockVsJWT(t *testing.T) { var exchanges atomic.Int32 - hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hs := httptest.NewServer(olderServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { exchanges.Add(1) _ = json.NewEncoder(w).Encode(map[string]any{ // exp claim already in the past by the local clock "access_token": fakeJWT(t, time.Now().Add(-time.Hour)), "expires_in": 300, }) - })) + }))) defer hs.Close() prev := SetStore(fileStore{dir: t.TempDir()}) defer SetStore(prev) diff --git a/internal/auth/scopes.go b/internal/auth/scopes.go new file mode 100644 index 0000000..23ea220 --- /dev/null +++ b/internal/auth/scopes.go @@ -0,0 +1,160 @@ +package auth + +import ( + "fmt" + "regexp" + "slices" + "strings" +) + +// Scopes of a CLI sign-in. A sign-in has full access (everything the person +// can do in the dashboard) unless `login --scopes` named a subset. Norcube +// Auth always adds org.read (the account and its organizations) and keeps +// offline_access (the refresh token); the person's own permissions apply on +// every call either way. +const ( + ScopeFull = "full" + ScopeOrgRead = "org.read" + ScopeOfflineAccess = "offline_access" +) + +// LoginScope is a scope `login --scopes` accepts. +type LoginScope struct { + Name string + Description string +} + +// LoginScopes mirrors the scope catalog of Norcube Auth for CLI sign-ins, +// minus the two scopes every sign-in carries anyway (org.read, +// offline_access). The server is the authority: it refuses an unknown +// scope with invalid_scope. A well-formed scope missing here (one Norcube +// Auth added after this release) is still sent, so it only misses the +// description and completion. +var LoginScopes = []LoginScope{ + {ScopeFull, "Everything you can do in the dashboard (the default)"}, + {"backup.read", "View backups: data sources, backup jobs, restore checks and policies"}, + {"backup.write", "Run backups, plus everything backup.read allows"}, + {"backup.verify", "Run restore checks, plus everything backup.read allows"}, + {"domainradar.check", "Run single and bulk DomainRadar checks and read the results"}, + {"langsync.read", "View namespaces, terms, translations, languages and the glossary"}, + {"langsync.sync", "Run `langsync sync`: push source terms and pull translations"}, + {"langsync.write", "Add and edit terms and translations, translate missing values"}, + {"billing.read", "View billing status, usage, invoices and the subscription"}, + {"cms.read", "View CMS sites, content, schema and media"}, + {"cms.write", "Edit CMS content and media, plus everything cms.read allows"}, + {"monitor.read", "View monitors, check results, uptime, incidents and alert channels"}, + {"monitor.check", "Run a monitor's check now, plus everything monitor.read allows"}, + {"monitor.write", "Create, change and delete monitors and acknowledge incidents, plus everything monitor.read allows"}, + {"monitor.channels", "Create, change and delete alert channels and send test alerts, plus everything monitor.read allows"}, + {"monitor.statuspages", "Create, publish and delete status pages and post incidents on them, plus everything monitor.read allows"}, + {"monitor.maintenance", "Schedule, change and cancel maintenance windows, plus everything monitor.read allows"}, +} + +// scopeShape is what a Norcube scope looks like: product or product.action. +var scopeShape = regexp.MustCompile(`^[a-z]+(\.[a-z]+)?$`) + +// LoginScopeNames lists the scopes `login --scopes` accepts. +func LoginScopeNames() []string { + out := make([]string, 0, len(LoginScopes)) + for _, s := range LoginScopes { + out = append(out, s.Name) + } + return out +} + +// ParseLoginScopes validates the scopes given to `login --scopes` and +// returns the ones to ask for: the known ones in catalog order, then the +// well-formed ones this release doesn't know, as given (Norcube Auth +// decides on those). Nothing means full. org.read and offline_access are +// dropped (every sign-in carries them), and full absorbs the rest. A +// malformed scope is an error naming the valid ones. +func ParseLoginScopes(values []string) ([]string, error) { + want := map[string]bool{} + var unknown []string + for _, v := range values { + v = strings.TrimSpace(v) + switch { + case v == "": + continue + case v == ScopeOrgRead || v == ScopeOfflineAccess: + // Implicit; asking for them changes nothing. + want[v] = true + continue + case !slices.Contains(LoginScopeNames(), v): + if !scopeShape.MatchString(v) { + return nil, fmt.Errorf("invalid scope %q; valid scopes: %s", v, strings.Join(LoginScopeNames(), ", ")) + } + if !slices.Contains(unknown, v) { + unknown = append(unknown, v) + } + } + want[v] = true + } + if len(want) == 0 { + return []string{ScopeFull}, nil + } + if want[ScopeFull] { + return []string{ScopeFull}, nil + } + var out []string + for _, s := range LoginScopes { + if want[s.Name] { + out = append(out, s.Name) + } + } + out = append(out, unknown...) + if len(out) == 0 { + return nil, fmt.Errorf("--scopes needs at least one scope besides %s and %s, which every sign-in has; valid scopes: %s", + ScopeOrgRead, ScopeOfflineAccess, strings.Join(LoginScopeNames(), ", ")) + } + return out, nil +} + +// requestScope is the scope parameter of a sign-in asking for scopes: +// the scopes plus offline_access, so the CLI gets a refresh token. +func requestScope(scopes []string) string { + if len(scopes) == 0 { + scopes = []string{ScopeFull} + } + return strings.Join(append(slices.Clone(scopes), ScopeOfflineAccess), " ") +} + +// ScopesFull reports whether a sign-in's granted scopes include full +// access. A sign-in without recorded scopes (the older sign-in) has full +// access too. +func ScopesFull(granted []string) bool { + return len(granted) == 0 || slices.Contains(granted, ScopeFull) +} + +// LimitedScopes are a scoped sign-in's scopes as the person asked for +// them: without the implicit org.read and offline_access. Empty for a +// full sign-in. +func LimitedScopes(granted []string) []string { + if ScopesFull(granted) { + return nil + } + var out []string + for _, s := range granted { + if s != ScopeOrgRead && s != ScopeOfflineAccess { + out = append(out, s) + } + } + return out +} + +// DescribeScopes reads like "full" or "backup.read, backup.write". +func DescribeScopes(granted []string) string { + if ScopesFull(granted) { + return ScopeFull + } + limited := LimitedScopes(granted) + if len(limited) == 0 { + return ScopeOrgRead + } + return strings.Join(limited, ", ") +} + +// parseScope splits a space-separated OAuth scope parameter. +func parseScope(s string) []string { + return strings.Fields(s) +} diff --git a/internal/auth/tokens.go b/internal/auth/tokens.go index 67f36c8..d58ce65 100644 --- a/internal/auth/tokens.go +++ b/internal/auth/tokens.go @@ -41,9 +41,15 @@ const ( // the rest of the CLI should ask for "give me a token I can use right now." // // It is safe for concurrent use, and refreshes are serialized across -// processes too: the server rotates the refresh token on every exchange -// and rejects the old one, so two exchanges racing with the same refresh +// processes too: the server rotates the refresh token on every refresh +// and rejects the old one, so two refreshes racing with the same refresh // token would sign the user out. +// +// An OAuth sign-in (credentials format 2) refreshes only its CLI access +// token under the lock and exchanges it per (audience, organization) +// without it; see oauthsession.go. An older sign-in (format 1) refreshes +// straight into each token, under the lock, and is moved to OAuth on its +// first refresh when Norcube Auth offers it. type TokenSource struct { // Profile names whose credentials are used ("" is the default profile). Profile string @@ -67,6 +73,11 @@ type TokenSource struct { // OrgLabel names OrgID in error messages (its slug); defaults to the id. OrgLabel string + // KeepLegacy leaves an older sign-in (format 1) as it is instead of + // moving it to the OAuth sign-in on first use. For diagnostics such + // as doctor, which must not change the profile they describe. + KeepLegacy bool + // LockDir holds the cross-process refresh lock files. Empty means // locks/ next to the config file. LockDir string @@ -122,10 +133,20 @@ func (t *TokenSource) CheckSession(ctx context.Context) (SessionState, error) { if !HasCredentials(t.Profile, t.APIBase) { return SessionNone, nil } - _, err := t.Token(ctx) + var err error + if s, _ := LoadSession(t.Profile, t.APIBase); s.Format == FormatOAuth && t.OrgID == "" { + // No organization to exchange for: a CLI access token (cached, + // or from a refresh) proves the sign-in works. + _, err = t.cliAccess(ctx, "") + } else { + _, err = t.Token(ctx) + } switch { case err == nil: return SessionActive, nil + case isLimitedScope(err): + // The exchange checks the sign-in before its scopes. + return SessionActive, nil case errors.Is(err, ErrOrgAccessDenied): // Norcube Auth checks the session before the organization, so a // refused organization means the session itself is alive. @@ -187,9 +208,27 @@ func (t *TokenSource) Token(ctx context.Context) (string, error) { if t.Static != "" { return t.Static, nil } - if tok, ok := t.cached(); ok { + if tok, ok := t.memCached(); ok { return tok, nil } + c, err := loadCreds(t.Profile, t.APIBase) + if err == nil && c.format() == FormatOAuth && c.RefreshToken != "" { + return t.oauthToken(ctx) + } + tok, upgraded, err := t.legacyToken(ctx) + if upgraded { + return t.oauthToken(ctx) + } + return tok, err +} + +// legacyToken is Token for an older sign-in (format 1). upgraded reports +// that the profile now holds an OAuth sign-in (moved by this call, or +// by another process meanwhile), which the caller then uses. +func (t *TokenSource) legacyToken(ctx context.Context) (tok string, upgraded bool, err error) { + if tok, ok := t.cached(); ok { + return tok, false, nil + } // In-process: one refresh at a time; the others wait and then find // the fresh token in the cache. @@ -197,50 +236,66 @@ func (t *TokenSource) Token(ctx context.Context) (string, error) { select { case t.sem <- struct{}{}: case <-ctx.Done(): - return "", ctx.Err() + return "", false, ctx.Err() } defer func() { <-t.sem }() if tok, ok := t.cached(); ok { - return tok, nil + return tok, false, nil } // Cross-process: every token of this profile shares one refresh // token, so every refresh for the profile takes the same lock. unlock, err := LockProfile(ctx, t.LockDir, t.Profile, t.APIBase, t.LockTimeout) if err != nil { - return "", err + return "", false, err } defer unlock() // Another process may have refreshed while we waited for the lock. if tok, ok := t.cached(); ok { - return tok, nil + return tok, false, nil } // Read the refresh token only now, under the lock: a value read // before it may already have been rotated away by another process. - refresh, err := LoadRefreshToken(t.Profile, t.APIBase) - if err != nil { - if errors.Is(err, ErrNotLoggedIn) { - return "", err + c, err := loadCreds(t.Profile, t.APIBase) + switch { + case err != nil: + return "", false, fmt.Errorf("%w: %v", ErrLoginRequired, err) + case c.RefreshToken == "": + return "", false, ErrNotLoggedIn + case c.format() == FormatOAuth: + // Another process moved it to OAuth (or signed in) meanwhile. + return "", true, nil + } + refresh := c.RefreshToken + + // Move the sign-in to OAuth once, when Norcube Auth offers it. Without + // an answer from the metadata (an older server, or the network), the + // older refresh below keeps working and the move waits. + if !t.KeepLegacy { + if m, derr := Discover(ctx, t.HTTP, t.APIBase); derr == nil { + if err := t.upgradeLegacy(ctx, m, refresh); err != nil { + return "", false, err + } + return "", true, nil } - return "", fmt.Errorf("%w: %v", ErrLoginRequired, err) } received := t.clock() tr, err := t.exchangeRefresh(ctx, refresh, t.Audience, t.OrgID) if err != nil { if errors.Is(err, errOrgRefused) { - return "", &OrgAccessError{Org: t.orgLabel()} + return "", false, &OrgAccessError{Org: t.orgLabel()} } if errors.Is(err, ErrLoginRequired) { - return "", t.diagnose(ctx, refresh, err) + return "", false, t.diagnose(ctx, refresh, err) } - return "", err + return "", false, err } if err := t.saveExchange(tr, received, t.Audience, t.OrgID); err != nil { - return "", err + return "", false, err } - return tr.AccessToken, nil + return tr.AccessToken, false, nil } // diagnose runs after an exchange for OrgID was refused with a bare 401. diff --git a/internal/auth/tokens_test.go b/internal/auth/tokens_test.go index f770c93..424d9c9 100644 --- a/internal/auth/tokens_test.go +++ b/internal/auth/tokens_test.go @@ -46,7 +46,7 @@ func TestTokenUsesCachedAccessToken(t *testing.T) { func TestTokenRefreshesAndPersistsRotation(t *testing.T) { keyring.MockInit() access := "" - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + srv := httptest.NewServer(olderServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/oauth/token" { t.Errorf("unexpected path %s", r.URL.Path) } @@ -58,7 +58,7 @@ func TestTokenRefreshesAndPersistsRotation(t *testing.T) { "access_token": access, "refresh_token": "rotated-refresh", }) - })) + }))) defer srv.Close() access = fakeJWT(t, time.Now().Add(time.Hour)) @@ -99,10 +99,10 @@ func TestTokenMissingRefreshIsLoginRequired(t *testing.T) { func TestTokenRejectedRefreshIsLoginRequired(t *testing.T) { keyring.MockInit() - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + srv := httptest.NewServer(olderServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusUnauthorized) fmt.Fprint(w, `{"msg":"refresh token revoked"}`) - })) + }))) defer srv.Close() if err := SaveRefreshToken("", srv.URL, "revoked"); err != nil { @@ -114,9 +114,9 @@ func TestTokenRejectedRefreshIsLoginRequired(t *testing.T) { t.Fatalf("expected ErrLoginRequired on 401, got %v", err) } // A transient 500 must NOT read as login-required. - srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + srv2 := httptest.NewServer(olderServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusInternalServerError) - })) + }))) defer srv2.Close() if err := SaveRefreshToken("", srv2.URL, "fine"); err != nil { t.Fatal(err) @@ -145,3 +145,15 @@ func newTestSource(t *testing.T, api string) *TokenSource { ts.LockDir = t.TempDir() return ts } + +// olderServer plays a Norcube Auth without the OAuth sign-in for the CLI: +// its metadata is missing, so the older sign-in stays in use. +func olderServer(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/.well-known/oauth-authorization-server" { + http.NotFound(w, r) + return + } + h.ServeHTTP(w, r) + }) +} diff --git a/internal/cli/authcmd.go b/internal/cli/authcmd.go index c929023..2a36dc1 100644 --- a/internal/cli/authcmd.go +++ b/internal/cli/authcmd.go @@ -49,6 +49,11 @@ type authStatus struct { User string `json:"user,omitempty" yaml:"user,omitempty"` Organization string `json:"organization,omitempty" yaml:"organization,omitempty"` AccessExpiresAt *time.Time `json:"accessExpiresAt,omitempty" yaml:"accessExpiresAt,omitempty"` + // CredentialFormat is the stored login's format: 1 for the older + // sign-in, 2 for the OAuth sign-in; absent when nothing is stored. + CredentialFormat int `json:"credentialFormat,omitempty" yaml:"credentialFormat,omitempty"` + // Scopes are the stored login's scopes (see whoami), or a CI token's. + Scopes []string `json:"scopes,omitempty" yaml:"scopes,omitempty"` // CIToken describes the CI token in NORCUBE_TOKEN / --token-file, when // the invocation uses one (learned from its exchanges). CIToken *ciTokenStatus `json:"ciToken,omitempty" yaml:"ciToken,omitempty"` @@ -90,6 +95,9 @@ A cached access token that hasn't expired counts as "yes" without a request: it was minted from the session within the last few minutes. --offline skips the check and only looks at what is stored locally. +SCOPES is what the login may do: full, or the scopes ` + "`norcube login --scopes`" + ` +limited it to (a CI token's scopes when one is in use). + Exits with 4 when the profile can't be used ("no" or "revoked/expired"), so scripts can check before they start: ` + "`norcube auth status >/dev/null || norcube login`" + `. @@ -140,13 +148,20 @@ exits 0.`, } } if err := cmdutil.Print(cmd, output.Table[authStatus]{ - Headers: []string{"PROFILE", "ENVIRONMENT", "SIGNED IN", "USER", "ORGANIZATION", "STORE", "TOKEN EXPIRES"}, + Headers: []string{"PROFILE", "ENVIRONMENT", "SIGNED IN", "USER", "ORGANIZATION", "SCOPES", "STORE", "TOKEN EXPIRES"}, Rows: func(s authStatus) []string { exp := "-" if s.AccessExpiresAt != nil { exp = output.When(*s.AccessExpiresAt) } - return []string{s.Profile, s.Environment, signedInLabel(s), orDash(s.User), orDash(s.Organization), s.CredentialStore, exp} + scopes := "-" + switch { + case s.CIToken != nil: + scopes = strings.Join(s.Scopes, ", ") + case s.Scopes != nil: + scopes = auth.DescribeScopes(s.Scopes) + } + return []string{s.Profile, s.Environment, signedInLabel(s), orDash(s.User), orDash(s.Organization), orDash(scopes), s.CredentialStore, exp} }, Items: rows, }); err != nil { @@ -209,6 +224,10 @@ func statusOf(r *resolve.Result) authStatus { default: s.cfg = cfg s.SignedIn = auth.HasCredentials(cfg.Profile, cfg.Auth) + if st, err := auth.LoadSession(cfg.Profile, cfg.Auth); err == nil { + s.CredentialFormat = st.Format + } + s.Scopes = loginScopes(cfg) s.setAccessExpiry() } return s @@ -221,6 +240,12 @@ func (s *authStatus) setAccessExpiry() { } if exp := auth.AccessExpiry(s.cfg.Profile, s.cfg.Auth, auth.AudienceAuth, s.cfg.ActiveOrg.ID); !exp.IsZero() { s.AccessExpiresAt = &exp + return + } + // An OAuth sign-in caches only its CLI access token between commands. + if st, err := auth.LoadSession(s.cfg.Profile, s.cfg.Auth); err == nil && !st.CLIAccessExpiresAt.IsZero() { + exp := st.CLIAccessExpiresAt + s.AccessExpiresAt = &exp } } @@ -292,6 +317,7 @@ func checkCIToken(ctx context.Context, ci *auth.CIExchanger, s *authStatus) { case info != nil: sort.Strings(info.Scopes) s.CIToken = info + s.Scopes = info.Scopes s.Session, s.SignedIn = auth.SessionActive, true s.User = "CI token · " + info.Name exp := info.ExpiresAt @@ -319,6 +345,9 @@ func checkSession(ctx context.Context, flags *clictx.Flags, cfg *config.Config) ts.Profile = cfg.Profile ts.HTTP = httpc ts.ProbeOrgID = cfg.ActiveOrg.ID + // auth status and doctor describe the sign-in; they must not move + // an older one to OAuth. + ts.KeepLegacy = true ctx, cancel := context.WithTimeout(ctx, sessionCheckTimeout) defer cancel() return ts.CheckSession(ctx) diff --git a/internal/cli/doctor.go b/internal/cli/doctor.go index 92b069c..cd1e0f7 100644 --- a/internal/cli/doctor.go +++ b/internal/cli/doctor.go @@ -127,6 +127,12 @@ func runDoctor(ctx context.Context, flags *clictx.Flags, offline bool) []doctorC add("config", checkFail, err.Error()) return checks } + if !offline { + // Diagnose against Norcube Auth as it is now: the next command + // discovers its OAuth endpoints afresh instead of reusing a cached + // answer that may be what's wrong. + auth.ForgetMetadata(cfg.Auth) + } if org := res.Org.Value; org != "" { add("organization", checkOK, fmt.Sprintf("%s (from %s)", org, res.Org.Source)) } else { @@ -212,8 +218,20 @@ func credentialCheck(flags *clictx.Flags, res *resolve.Result, cfg *config.Confi c.Status, c.Detail = checkWarn, "no OS keyring here; sessions fall back to the file store" } } - if !auth.HasCredentials(cfg.Profile, cfg.Auth) && c.Status == checkOK && res.Credentials.Value != resolve.CredentialTokenFile && res.Credentials.Value != config.CredentialEnv { + if res.Credentials.Value == resolve.CredentialTokenFile || res.Credentials.Value == config.CredentialEnv || c.Status == checkFail { + return c + } + st, err := auth.LoadSession(cfg.Profile, cfg.Auth) + switch { + case err != nil: + c.Status, c.Detail = checkFail, c.Detail+"; reading the stored session failed: "+err.Error() + case st.Format == 0: c.Detail += "; no session stored" + case st.Format == auth.FormatOAuth: + c.Detail += fmt.Sprintf("; OAuth sign-in (format %d), scopes %s", st.Format, auth.DescribeScopes(st.Scopes)) + default: + c.Status = checkWarn + c.Detail += fmt.Sprintf("; older sign-in (format %d), full access. The next command moves it to the OAuth sign-in when Norcube Auth offers it; an older norcube on this machine then has to sign in again", st.Format) } return c } @@ -356,18 +374,25 @@ func sessionAndTokenChecks(ctx context.Context, flags *clictx.Flags, cfg *config return append(out, doctorCheck{"tokens", checkSkip, "no organization to mint tokens for"}) } services := registry.Callable() - // One at a time: every mint rotates the profile's one refresh token. + // One at a time: with the older sign-in every mint rotates the + // profile's one refresh token. for _, s := range services { c := doctorCheck{Check: "token " + s.Command} ts, err := flags.TokenSource(cfg, s.Audience, org.ID) if err == nil { + // doctor describes the sign-in; it must not move it to OAuth. + ts.KeepLegacy = true tctx, cancel := context.WithTimeout(ctx, sessionCheckTimeout) _, err = ts.Token(tctx) cancel() } - if err != nil { + var scopeErr *auth.ScopeError + switch { + case errors.As(err, &scopeErr): + c.Status, c.Detail = checkSkip, "this login's scopes ("+auth.DescribeScopes(scopeErr.Scopes)+") don't cover this service" + case err != nil: c.Status, c.Detail = checkFail, err.Error() - } else { + default: c.Status, c.Detail = checkOK, fmt.Sprintf("%s in %s", s.Audience, orgLabel(config.Organization{ID: org.ID, Slug: org.Slug})) } out = append(out, c) diff --git a/internal/cli/doctor_test.go b/internal/cli/doctor_test.go index ff12fee..ca80e36 100644 --- a/internal/cli/doctor_test.go +++ b/internal/cli/doctor_test.go @@ -38,7 +38,12 @@ func TestDoctorHealthyProfile(t *testing.T) { if err != nil { t.Fatalf("doctor failed on a healthy setup: %v (%v)", err, checks) } - for _, name := range []string{"cli version", "config file", "profile", "organization", "credentials", "clock", "session", "endpoint auth", "endpoint langsync", "token backup", "token langsync", "token domainradar"} { + // The fake Norcube Auth has no OAuth sign-in, so the session stays an + // older one, which doctor flags. + if c := checks["credentials"]; c.Status != checkWarn || !strings.Contains(c.Detail, "older sign-in (format 1)") { + t.Errorf("credentials: %s (%s)", c.Status, c.Detail) + } + for _, name := range []string{"cli version", "config file", "profile", "organization", "clock", "session", "endpoint auth", "endpoint langsync", "token backup", "token langsync", "token domainradar"} { c, ok := checks[name] if !ok { t.Errorf("no %q check", name) diff --git a/internal/cli/errors.go b/internal/cli/errors.go index d79744c..de39cc2 100644 --- a/internal/cli/errors.go +++ b/internal/cli/errors.go @@ -31,6 +31,15 @@ func Describe(err error) *clierr.Error { if err == nil { return nil } + var scopeErr *auth.ScopeError + if errors.As(err, &scopeErr) { + return &clierr.Error{ + Code: clierr.CodeInsufficientScope, + Message: scopeErr.Error(), + Hint: limitedLoginHint(scopeErr.Scopes), + Err: err, + } + } var ce *clierr.Error if errors.As(err, &ce) { out := *ce @@ -44,6 +53,11 @@ func Describe(err error) *clierr.Error { (out.Code == clierr.CodePermissionDenied || out.Code == clierr.CodeInsufficientScope) { out.Hint = ciRefusalHint } + if !usingCIToken && out.Hint == "" && out.Code == clierr.CodeInsufficientScope { + if scopes := selectedLoginScopes(); scopes != nil { + out.Hint = limitedLoginHint(scopes) + } + } return &out } @@ -75,6 +89,28 @@ func Describe(err error) *clierr.Error { return e } +// limitedLoginHint explains a refusal under a login limited by --scopes. +func limitedLoginHint(scopes []string) string { + return fmt.Sprintf("This login is limited to %s; run `%s` for full access.", auth.DescribeScopes(scopes), LoginCommand()) +} + +// selectedAuthURL is the running command's auth URL, for +// selectedLoginScopes. +var selectedAuthURL string + +// selectedLoginScopes are the scopes of the running command's login when +// --scopes limited it; nil for a full login or none. +func selectedLoginScopes() []string { + if selectedAuthURL == "" { + return nil + } + s, err := auth.LoadSession(selectedProfile, selectedAuthURL) + if err != nil || s.Format != auth.FormatOAuth || auth.ScopesFull(s.Scopes) { + return nil + } + return s.Scopes +} + // usingCIToken is set when the running command authenticates with a CI // token (NORCUBE_TOKEN or --token-file), so a refusal can say why. var usingCIToken bool diff --git a/internal/cli/golden_test.go b/internal/cli/golden_test.go index e075a96..62226e1 100644 --- a/internal/cli/golden_test.go +++ b/internal/cli/golden_test.go @@ -29,9 +29,9 @@ var update = flag.Bool("update", false, "rewrite the golden files") var goldenData = map[string]string{ // #nosec G101 -- API fixtures, no credentials "GET /auth/me": `{"id":"user-1","name":"Dev Eloper","email":"dev@example.com","avatarUrl":""}`, "GET /auth/me/sessions": `[ - {"id":"sess-1","kind":"cli","hostname":"dev-laptop","client":{"name":"norcube","version":"0.17.0","os":"darwin","arch":"arm64"},"ip_address":"203.0.113.24","created_at":"2026-10-16T09:00:00Z","last_used_at":"2026-10-28T11:42:00Z","expires_at":"2026-11-27T11:42:00Z","current":true}, - {"id":"sess-2","kind":"cli","hostname":"ci-runner-04","client":{"name":"norcube","version":"0.16.0","os":"linux","arch":"amd64"},"ip_address":"198.51.100.7","created_at":"2026-09-28T08:00:00Z","last_used_at":"2026-10-27T03:10:00Z","expires_at":"2026-11-26T03:10:00Z","current":false}, - {"id":"sess-3","kind":"cli","hostname":null,"client":{"name":null,"version":null,"os":null,"arch":null},"ip_address":null,"created_at":"2026-08-29T10:00:00Z","last_used_at":"2026-10-19T10:00:00Z","expires_at":"2026-11-18T10:00:00Z","current":false} + {"id":"sess-1","kind":"cli","hostname":"dev-laptop","client":{"name":"norcube","version":"0.17.0","os":"darwin","arch":"arm64"},"ip_address":"203.0.113.24","created_at":"2026-10-16T09:00:00Z","last_used_at":"2026-10-28T11:42:00Z","expires_at":"2026-11-27T11:42:00Z","current":true,"oauth_grant_id":"6a1f0c7e-2b3d-4e5f-8a9b-0c1d2e3f4a5b","scopes":["full","org.read","offline_access"]}, + {"id":"sess-2","kind":"cli","hostname":"ci-runner-04","client":{"name":"norcube","version":"0.16.0","os":"linux","arch":"amd64"},"ip_address":"198.51.100.7","created_at":"2026-09-28T08:00:00Z","last_used_at":"2026-10-27T03:10:00Z","expires_at":"2026-11-26T03:10:00Z","current":false,"oauth_grant_id":"7b2e1d8f-3c4e-4f6a-9b0c-1d2e3f4a5b6c","scopes":["backup.read","langsync.sync","org.read","offline_access"]}, + {"id":"sess-3","kind":"cli","hostname":null,"client":{"name":null,"version":null,"os":null,"arch":null},"ip_address":null,"created_at":"2026-08-29T10:00:00Z","last_used_at":"2026-10-19T10:00:00Z","expires_at":"2026-11-18T10:00:00Z","current":false,"oauth_grant_id":null,"scopes":null} ]`, "GET /iam/ci-tokens": `[ {"id":"0b7a4c8e-2d3f-4a1b-9c6d-5e4f3a2b1c0d","name":"GitHub Actions deploy","preview":"x7Kq","scopes":["langsync.sync"],"created_by":"user-1","created_at":"2026-10-01T09:00:00Z","expires_at":"2026-12-30T09:00:00Z","last_used_at":"2026-10-28T11:42:00Z","last_used_ip":"203.0.113.24","revoked_at":null,"revoked_by":null,"status":"active"}, diff --git a/internal/cli/login.go b/internal/cli/login.go index a2b9e9f..2934fb1 100644 --- a/internal/cli/login.go +++ b/internal/cli/login.go @@ -2,7 +2,11 @@ package cli import ( "context" + "errors" "fmt" + "io" + "net/http" + "slices" "strings" "time" @@ -22,23 +26,32 @@ import ( func newLoginCmd() *cobra.Command { var force, noBrowser, device bool + var scopes []string cmd := &cobra.Command{ Use: "login", Annotations: cmdutil.Writes(), Short: "Sign in to Norcube via your browser", - Long: `Opens a Norcube login page in your default browser. After you sign in there, -the CLI receives a session over a one-shot localhost callback. The session -is stored for the selected profile (--profile, NORCUBE_PROFILE or the -default profile) in your operating system's keyring (Keychain / Secret -Service / Windows Credential Manager), or in a file when no keyring is -available. + Long: `Opens the Norcube sign-in page in your default browser. After you approve +the sign-in there, the browser hands the CLI a one-time code over a localhost +callback (127.0.0.1), which the CLI exchanges for its session (OAuth 2.0 with +PKCE). The session is stored for the selected profile (--profile, +NORCUBE_PROFILE or the default profile) in your operating system's keyring +(Keychain / Secret Service / Windows Credential Manager), or in a file when +no keyring is available. Logging in to a profile that doesn't exist yet creates it. Its organization is --org when given, else the profile's organization, else your default organization. -With --no-browser the CLI only prints the login URL. Open it in any -browser on this machine; the page hands the session back to the CLI over +By default the login can do everything you can do in the dashboard. With +--scopes it is limited to the scopes you list, the same scopes CI tokens +use (for example --scopes backup.read,langsync.sync); commands outside them +fail with exit code 5. Your own permissions in each organization apply +either way. Every login shows up under Account › CLI sessions and Connected +apps in the dashboard, where you can revoke it. + +With --no-browser the CLI only prints the sign-in URL. Open it in any +browser on this machine; the page hands the code back to the CLI over 127.0.0.1. With --device you approve the sign-in on any other device instead, such as @@ -49,6 +62,7 @@ started yourself: Norcube never asks you for one.`, Example: ` norcube login norcube login --profile client-acme norcube login --org acme + norcube login --scopes backup.read,langsync.sync norcube login --device norcube login --no-browser norcube login --force`, @@ -57,23 +71,61 @@ started yourself: Norcube never asks you for one.`, if device && noBrowser { return clierr.Usage(fmt.Errorf("--device and --no-browser can't be combined: --device never opens a browser")) } - return runLogin(cmd, force, noBrowser, device) + wanted, err := auth.ParseLoginScopes(scopes) + if err != nil { + return clierr.Usage(fmt.Errorf("--scopes: %w", err)) + } + return runLogin(cmd, loginOptions{ + force: force, noBrowser: noBrowser, device: device, + scopes: wanted, scopesSet: cmd.Flags().Changed("scopes"), + }) }, } - cmd.Flags().BoolVar(&force, "force", false, "Re-authenticate even if a valid session already exists") + cmd.Flags().BoolVar(&force, "force", false, "Re-authenticate even if a valid session already exists; the previous session is ended on Norcube") cmd.Flags().BoolVar(&noBrowser, "no-browser", false, "Print the login URL instead of opening a browser") cmd.Flags().BoolVar(&device, "device", false, "Approve the sign-in on another device (phone, laptop) with a short code; for SSH and headless machines") + cmd.Flags().StringSliceVar(&scopes, "scopes", nil, "Limit the login to these scopes, comma-separated (default full: everything you can do in the dashboard); one of "+strings.Join(auth.LoginScopeNames(), ", ")) + _ = cmd.RegisterFlagCompletionFunc("scopes", completeLoginScopes) return cmd } -// browserLogin and deviceLogin run the sign-in handshakes; tests replace -// them. +// completeLoginScopes completes the last of the comma-separated scopes. +func completeLoginScopes(_ *cobra.Command, _ []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { + prefix := "" + if i := strings.LastIndex(toComplete, ","); i >= 0 { + prefix = toComplete[:i+1] + } + used := strings.Split(prefix, ",") + var out []cobra.Completion + for _, s := range auth.LoginScopes { + if slices.Contains(used, s.Name) { + continue + } + out = append(out, prefix+s.Name+"\t"+s.Description) + } + return out, cobra.ShellCompDirectiveNoFileComp | cobra.ShellCompDirectiveNoSpace +} + +type loginOptions struct { + force, noBrowser, device bool + // scopes to ask for (ParseLoginScopes); scopesSet when --scopes was + // given. + scopes []string + scopesSet bool +} + +// The sign-in handshakes and the metadata lookup; tests replace them. var ( browserLogin = auth.BrowserLogin + oauthLogin = auth.OAuthLogin deviceLogin = auth.DeviceLogin + discoverAuth = auth.Discover + // openBrowser opens the sign-in page; nil means the default browser. + openBrowser func(string) error ) -func runLogin(cmd *cobra.Command, force, noBrowser, device bool) error { +func runLogin(cmd *cobra.Command, o loginOptions) error { + force, noBrowser, device := o.force, o.noBrowser, o.device flags := clictx.Get(cmd) res, err := flags.Resolve() if err != nil { @@ -117,17 +169,44 @@ func runLogin(cmd *cobra.Command, force, noBrowser, device bool) error { fmt.Fprintln(cmd.ErrOrStderr(), "Your previous session ended (revoked or expired); signing in again.") } + httpc, err := flags.HTTPClient() + if err != nil { + return err + } + // The OAuth sign-in when Norcube Auth offers it, else the older one + // (an older server). The answer is cached, so the commands after the + // login don't ask again. + auth.ForgetMetadata(authURL) + meta, err := discoverAuth(cmd.Context(), httpc, authURL) + switch { + case errors.Is(err, auth.ErrOAuthUnavailable): + meta = nil + if o.scopesSet { + return clierr.Usage(fmt.Errorf("--scopes needs the OAuth sign-in, which %s doesn't offer yet; sign in without --scopes", authURL)) + } + case err != nil: + return err + } + var payload *auth.CallbackPayload - if device { - payload, err = runDeviceLogin(cmd, flags, authURL) - } else { + switch { + case device && meta != nil && meta.SupportsDevice(): + payload, err = runDeviceLogin(cmd, httpc, authURL, meta, o.scopes) + case device: + if o.scopesSet { + return clierr.Usage(fmt.Errorf("--scopes with --device needs the OAuth device sign-in, which %s doesn't offer yet", authURL)) + } + payload, err = runDeviceLogin(cmd, httpc, authURL, nil, nil) + case meta != nil: + payload, err = runOAuthBrowserLogin(cmd, httpc, meta, noBrowser, o.scopes) + default: payload, err = runBrowserLogin(cmd, webApp, noBrowser) } if err != nil { return err } - if err := storeSession(cmd.Context(), cfg.Profile, authURL, payload); err != nil { + if err := storeSession(cmd.Context(), cmd.ErrOrStderr(), cfg.Profile, authURL, payload); err != nil { return err } @@ -139,6 +218,20 @@ func runLogin(cmd *cobra.Command, force, noBrowser, device bool) error { } org = config.Organization{ID: found.ID, Slug: found.Slug, Name: found.Name} } + if payload.OAuth { + // The OAuth sign-in doesn't say who signed in: ask. Norcube + // Auth tokens need no organization, so this works for an + // account without one too. + client, err := flags.AuthClient(cfg, org.ID) + if err != nil { + return err + } + me, err := client.GetMe(cmd.Context()) + if err != nil { + return fmt.Errorf("signed in, but reading your account failed: %w", err) + } + payload.User = auth.User{ID: me.ID, Name: me.Name, Email: me.Email} + } err = flags.UpdateProfile(func(p *config.Profile) error { if !res.ProfileDefined { @@ -153,17 +246,26 @@ func runLogin(cmd *cobra.Command, force, noBrowser, device bool) error { } msg := fmt.Sprintf("Signed in as %s (%s).\nActive organization: %s.", payload.User.Name, payload.User.Email, orgLabel(org)) + if org.ID == "" { + msg = fmt.Sprintf("Signed in as %s (%s).\nYour account has no organization yet: create one with `norcube org create ` or in the dashboard.", payload.User.Name, payload.User.Email) + } if cfg.Profile != config.DefaultProfileName { msg += fmt.Sprintf("\nProfile: %s.", cfg.Profile) } - return cmdutil.Print(cmd, output.Done{ - Message: msg, - Value: loginResult{ - Profile: cfg.Profile, - User: userRef{ID: payload.User.ID, Name: payload.User.Name, Email: payload.User.Email}, - Organization: orgRefOf(org), - }, - }) + result := loginResult{ + Profile: cfg.Profile, + User: userRef{ID: payload.User.ID, Name: payload.User.Name, Email: payload.User.Email}, + Organization: orgRefOf(org), + } + if payload.OAuth { + result.Scopes = payload.Scopes + if auth.ScopesFull(payload.Scopes) { + msg += "\nAccess: full (everything you can do in the dashboard)." + } else { + msg += fmt.Sprintf("\nAccess: limited to %s. Run `%s` without --scopes for full access.", auth.DescribeScopes(payload.Scopes), LoginCommand()) + } + } + return cmdutil.Print(cmd, output.Done{Message: msg, Value: result}) } // checkLoginTarget refuses to sign an existing profile in to another @@ -219,24 +321,52 @@ func newProfileEnvironment(res *resolve.Result) (string, map[string]string) { // storeSession saves the login's refresh token (and its first access // token) under the profile's credential lock. -func storeSession(ctx context.Context, profile, authURL string, payload *auth.CallbackPayload) error { +// +// A session it replaces (login --force) is ended on Norcube Auth first, +// the way logout ends it, so it doesn't linger under CLI sessions and +// Connected apps. That is best effort: a failure is a warning and the new +// session is stored anyway. +func storeSession(ctx context.Context, stderr io.Writer, profile, authURL string, payload *auth.CallbackPayload) error { unlock, err := auth.LockProfile(ctx, "", profile, authURL, 0) if err != nil { return err } defer unlock() - if err := auth.SaveRefreshToken(profile, authURL, payload.RefreshToken); err != nil { - return fmt.Errorf("store refresh token: %w", err) - } + endReplacedSession(ctx, stderr, profile, authURL) var accessExp time.Time if payload.AccessExpiresIn > 0 { accessExp = time.Now().Add(time.Duration(payload.AccessExpiresIn) * time.Second) } + if payload.OAuth { + if err := auth.SaveOAuthSession(profile, authURL, payload.RefreshToken, payload.AccessToken, accessExp, payload.Scopes); err != nil { + return fmt.Errorf("store the session: %w", err) + } + return nil + } + if err := auth.SaveRefreshToken(profile, authURL, payload.RefreshToken); err != nil { + return fmt.Errorf("store refresh token: %w", err) + } // Cache failure is non-fatal: the next command mints a new token. _ = auth.SaveAccessTokenUntil(profile, authURL, auth.AudienceAuth, "", payload.AccessToken, accessExp) return nil } +// endReplacedSession ends the profile's stored session on Norcube Auth +// before a login replaces it. Callers hold the profile's lock. +func endReplacedSession(ctx context.Context, stderr io.Writer, profile, authURL string) { + old, err := auth.LoadRefreshToken(profile, authURL) + if err != nil || old == "" { + return + } + end := endServerSession + if s, _ := auth.LoadSession(profile, authURL); s.Format == auth.FormatOAuth { + end = revokeServerSession + } + if err := end(ctx, authURL, old); err != nil { + fmt.Fprintf(stderr, "Warning: couldn't end the previous session on the server (%v). It expires after 30 days unused, or revoke it under Account › CLI sessions in the dashboard.\n", err) + } +} + // wantedLoginOrg is the organization the login should select: --org or // NORCUBE_ORG, else the profile's organization; "" means the account's // default. @@ -245,12 +375,13 @@ func wantedLoginOrg(res *resolve.Result) string { } // resolveLoginOrg finds the wanted organization among the user's, using -// the access token the login just stored. +// the session the login just stored. func resolveLoginOrg(ctx context.Context, flags *clictx.Flags, cfg *config.Config, payload *auth.CallbackPayload, want string) (api.Organization, error) { defaultOrg := api.Organization{ID: payload.DefaultOrg.ID, Slug: payload.DefaultOrg.Slug, Name: payload.DefaultOrg.Name} if o, ok := orgs.Find([]api.Organization{defaultOrg}, want); ok { return o, nil } + // Norcube Auth tokens need no organization. client, err := flags.AuthClient(cfg, "") if err != nil { return api.Organization{}, err @@ -280,44 +411,67 @@ type loginResult struct { Profile string `json:"profile" yaml:"profile"` User userRef `json:"user" yaml:"user"` Organization *orgRef `json:"organization" yaml:"organization"` + // Scopes are the scopes Norcube Auth granted (OAuth sign-in only). + Scopes []string `json:"scopes,omitempty" yaml:"scopes,omitempty"` } -// runBrowserLogin signs in through the web app in a browser on this -// machine (the default). +// runOAuthBrowserLogin signs in through Norcube Auth's authorization +// page in a browser on this machine (the default). +func runOAuthBrowserLogin(cmd *cobra.Command, httpc *http.Client, meta *auth.Metadata, noBrowser bool, scopes []string) (*auth.CallbackPayload, error) { + out := cmd.ErrOrStderr() + if !noBrowser { + fmt.Fprintln(out, "Opening the Norcube sign-in page in your browser…") + } + return oauthLogin(cmd.Context(), auth.OAuthLoginOptions{ + Metadata: meta, + HTTP: httpc, + Scopes: scopes, + Timeout: auth.SignInWait, + NoBrowser: noBrowser, + BrowserOpenURL: openBrowser, + OnURLReady: loginURLPrinter(out, noBrowser), + }) +} + +func loginURLPrinter(out io.Writer, noBrowser bool) func(string) { + return func(url string) { + if noBrowser { + fmt.Fprintf(out, "Open this URL in a browser on this machine to sign in:\n %s\n", url) + } else { + fmt.Fprintf(out, "If your browser didn't open, visit:\n %s\n", url) + } + fmt.Fprintln(out, "Waiting for you to finish signing in (Ctrl-C to cancel)…") + } +} + +// runBrowserLogin signs in through the web app's older sign-in page, +// for a Norcube Auth without the OAuth sign-in. func runBrowserLogin(cmd *cobra.Command, webApp string, noBrowser bool) (*auth.CallbackPayload, error) { out := cmd.ErrOrStderr() if !noBrowser { fmt.Fprintf(out, "Opening %s in your browser…\n", webApp+"/cli-login") } return browserLogin(cmd.Context(), auth.BrowserLoginOptions{ - WebApp: webApp, - Timeout: 5 * time.Minute, - NoBrowser: noBrowser, - OnURLReady: func(url string) { - if noBrowser { - fmt.Fprintf(out, "Open this URL in a browser on this machine to sign in:\n %s\n", url) - } else { - fmt.Fprintf(out, "If your browser didn't open, visit:\n %s\n", url) - } - fmt.Fprintln(out, "Waiting for you to finish signing in (Ctrl-C to cancel)…") - }, + WebApp: webApp, + Timeout: 5 * time.Minute, + NoBrowser: noBrowser, + OnURLReady: loginURLPrinter(out, noBrowser), }) } // runDeviceLogin signs in with a code approved on another device -// (RFC 8628). The code, the page and, when the terminal can show one, a QR -// code go to stderr; a countdown runs while it waits. -func runDeviceLogin(cmd *cobra.Command, flags *clictx.Flags, authURL string) (*auth.CallbackPayload, error) { - httpc, err := flags.HTTPClient() - if err != nil { - return nil, err - } +// (RFC 8628), through the OAuth server when meta is set. The code, the +// page and, when the terminal can show one, a QR code go to stderr; a +// countdown runs while it waits. +func runDeviceLogin(cmd *cobra.Command, httpc *http.Client, authURL string, meta *auth.Metadata, scopes []string) (*auth.CallbackPayload, error) { out := cmd.ErrOrStderr() tty := term.IsTerminal(out) waiting := false payload, err := deviceLogin(cmd.Context(), auth.DeviceLoginOptions{ - AuthURL: authURL, - HTTP: httpc, + AuthURL: authURL, + HTTP: httpc, + Metadata: meta, + Scopes: scopes, OnCode: func(c auth.DeviceCode) { fmt.Fprintf(out, "To sign in, open this page on any device (your phone works) and enter the code:\n\n %s\n\n %s\n\n", c.VerificationURI, c.UserCode) if c.VerificationURIComplete != "" && term.Color(out) { diff --git a/internal/cli/logout.go b/internal/cli/logout.go index 724da40..2c3fef1 100644 --- a/internal/cli/logout.go +++ b/internal/cli/logout.go @@ -18,15 +18,22 @@ import ( "github.com/norcubeplatform/cli/internal/resolve" ) -// endServerSession ends the CLI session on Norcube Auth when logging out. -// A variable so tests can observe or replace the call. -var endServerSession = func(ctx context.Context, authURL, refreshToken string) error { - return auth.EndServerSession(ctx, nil, authURL, refreshToken) -} +// endServerSession ends an older sign-in's CLI session on Norcube Auth +// when logging out; revokeServerSession revokes an OAuth sign-in (RFC +// 7009), which ends its grant and CLI session. Variables so tests can +// observe or replace the calls. +var ( + endServerSession = func(ctx context.Context, authURL, refreshToken string) error { + return auth.EndServerSession(ctx, nil, authURL, refreshToken) + } + revokeServerSession = func(ctx context.Context, authURL, refreshToken string) error { + return auth.RevokeRefreshToken(ctx, nil, authURL, refreshToken) + } +) // serverSignOutWarning is printed when the session couldn't be ended on the // server. Logging out still succeeds: the local credentials are gone. -const serverSignOutWarning = "Warning: couldn't end the session on the server (%v). It expires after 30 days unused, or revoke it under Account › CLI sessions.\n" +const serverSignOutWarning = "Warning: couldn't end the session on the server (%v). It expires after 30 days unused, or revoke it under Account › CLI sessions in the dashboard.\n" func newLogoutCmd() *cobra.Command { var all bool @@ -34,9 +41,10 @@ func newLogoutCmd() *cobra.Command { Use: "logout", Annotations: cmdutil.Writes(), Short: "Sign out: end the session on Norcube and forget it locally", - Long: `Ends the selected profile's CLI session on Norcube Auth, so its refresh -token stops working everywhere, then removes the session (refresh and access -tokens) from the credential store and forgets its signed-in user. If the + Long: `Ends the selected profile's CLI session on Norcube Auth (it revokes the +login's refresh token), so the session stops working everywhere and leaves +Account › CLI sessions and Connected apps, then removes the session (refresh +and access tokens) from the credential store and forgets its signed-in user. If the server can't be reached, the local sign-out still happens and a warning says so; the session then expires after 30 days unused, or you revoke it under Account › CLI sessions in the dashboard. The profile itself, with its @@ -94,8 +102,12 @@ func logoutProfile(ctx context.Context, stderr io.Writer, profile, authURL strin defer unlock() if endServer { if tok, err := auth.LoadRefreshToken(profile, authURL); err == nil && tok != "" { + end := endServerSession + if s, _ := auth.LoadSession(profile, authURL); s.Format == auth.FormatOAuth { + end = revokeServerSession + } ok := true - if err := endServerSession(ctx, authURL, tok); err != nil { + if err := end(ctx, authURL, tok); err != nil { ok = false fmt.Fprintf(stderr, serverSignOutWarning, err) } diff --git a/internal/cli/oauth_login_test.go b/internal/cli/oauth_login_test.go new file mode 100644 index 0000000..ded98e4 --- /dev/null +++ b/internal/cli/oauth_login_test.go @@ -0,0 +1,453 @@ +package cli + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "strings" + "testing" + + "github.com/norcubeplatform/cli/internal/auth" + "github.com/norcubeplatform/cli/internal/auth/authtest" + "github.com/norcubeplatform/cli/internal/clierr" + "github.com/norcubeplatform/cli/internal/config" +) + +const oauthProfile = "p-oauth" + +// oauthEnv starts a fake Norcube Auth with the OAuth sign-in, a profile +// using it (not signed in), and a "browser" that approves the sign-in by +// following the authorization redirect back to the CLI. +func oauthEnv(t *testing.T) *authtest.Server { + t.Helper() + s := authtest.New() + t.Cleanup(s.Close) + isolatedConfig(t, func(f *config.File) { + f.DefaultProfile = oauthProfile + p := f.Profile(oauthProfile) + p.Environment = config.EnvCustom + p.Endpoints = map[string]string{config.ServiceAuth: s.URL} + p.SetActiveOrg(config.Organization{ID: authtest.HomeOrgID, Slug: "home", Name: "Home"}) + }) + auth.ForgetMetadata(s.URL) + t.Cleanup(func() { _ = auth.DeleteCredentials(oauthProfile, s.URL) }) + prev := openBrowser + openBrowser = func(u string) error { + go func() { + resp, err := http.Get(u) // #nosec G107 -- the test's fake server + if err == nil { + _, _ = io.Copy(io.Discard, resp.Body) + _ = resp.Body.Close() + } + }() + return nil + } + t.Cleanup(func() { openBrowser = prev }) + return s +} + +func TestOAuthLogin(t *testing.T) { + s := oauthEnv(t) + stdout, stderr, err := run(t, "login", "-o", "json") + if err != nil { + t.Fatalf("login: %v\n%s", err, stderr) + } + var res loginResult + if err := json.Unmarshal([]byte(stdout), &res); err != nil { + t.Fatalf("%v\n%s", err, stdout) + } + if res.User.Email != "dev@example.com" || res.Organization == nil || res.Organization.Slug != "home" || + strings.Join(res.Scopes, " ") != "full org.read offline_access" { + t.Fatalf("login result: %+v", res) + } + if !strings.Contains(stderr, "Opening the Norcube sign-in page") || !strings.Contains(stderr, s.URL+"/oauth/authorize?") { + t.Errorf("stderr:\n%s", stderr) + } + sess, _ := auth.LoadSession(oauthProfile, s.URL) + if sess.Format != auth.FormatOAuth { + t.Fatalf("stored format %d", sess.Format) + } + + out, _, err := run(t, "whoami") + if err != nil || !strings.Contains(out, "Access: full") || !strings.Contains(out, "dev@example.com") { + t.Fatalf("whoami: %v\n%s", err, out) + } + out, _, err = run(t, "auth", "status", "-o", "json") + if err != nil || !strings.Contains(out, `"credentialFormat": 2`) || !strings.Contains(out, `"session": "active"`) { + t.Fatalf("auth status: %v\n%s", err, out) + } + + // Signed in already: no second sign-in. + out, _, err = run(t, "login") + if err != nil || !strings.Contains(out, "Already signed in") { + t.Fatalf("second login: %v %q", err, out) + } + if n := s.Stats().CodeExchanges; n != 1 { + t.Fatalf("%d code exchanges", n) + } +} + +func TestOAuthLoginWithScopes(t *testing.T) { + s := oauthEnv(t) + out, stderr, err := run(t, "login", "--scopes", "backup.read") + if err != nil { + t.Fatalf("login: %v\n%s", err, stderr) + } + if !strings.Contains(out, "Access: limited to backup.read.") { + t.Errorf("login output:\n%s", out) + } + if got := s.Stats().AuthorizeQuery.Get("scope"); got != "backup.read offline_access" { + t.Errorf("asked for %q", got) + } + + // In scope: a Backup token. Out of scope: exit 5 and how to fix it. + if _, _, err := run(t, "auth", "token", "--audience", "backup"); err != nil { + t.Fatalf("token in scope: %v", err) + } + _, _, err = run(t, "auth", "token", "--audience", "langsync") + e := Describe(err) + if e.Code != clierr.CodeInsufficientScope || e.ExitCode() != clierr.ExitAccess || + e.Hint != "This login is limited to backup.read; run `norcube login` for full access." { + t.Fatalf("out of scope: %+v (%v)", e, err) + } + + out, _, err = run(t, "auth", "status") + if err != nil || !strings.Contains(out, "SCOPES") || !strings.Contains(out, "backup.read") { + t.Fatalf("auth status: %v\n%s", err, out) + } + out, _, err = run(t, "whoami", "-o", "json") + if err != nil || !strings.Contains(out, `"backup.read"`) { + t.Fatalf("whoami: %v\n%s", err, out) + } +} + +// A product's own scope refusal under a limited login gets the same hint. +func TestScopeRefusalHintUnderLimitedLogin(t *testing.T) { + s := oauthEnv(t) + if _, stderr, err := run(t, "login", "--scopes", "backup.read,langsync.sync"); err != nil { + t.Fatalf("login: %v\n%s", err, stderr) + } + selectedProfile, selectedAuthURL = oauthProfile, s.URL + t.Cleanup(func() { selectedAuthURL = "" }) + e := Describe(&clierr.Error{Code: clierr.CodeInsufficientScope, Message: "insufficient scope", HTTPStatus: http.StatusForbidden}) + if e.Hint != "This login is limited to backup.read, langsync.sync; run `norcube login` for full access." { + t.Fatalf("hint %q", e.Hint) + } +} + +func TestLoginScopesValidation(t *testing.T) { + s := oauthEnv(t) + _, _, err := run(t, "login", "--scopes", "backup.read,Backup/Delete") + if !clierr.IsUsage(err) || !strings.Contains(err.Error(), `invalid scope "Backup/Delete"`) || !strings.Contains(err.Error(), "langsync.sync") { + t.Fatalf("got %v", err) + } + if s.Stats().Authorizations != 0 { + t.Fatal("a sign-in started despite the bad scope") + } +} + +// A well-formed scope this release doesn't know goes to Norcube Auth, +// which is the authority; its invalid_scope is a usage error. +func TestLoginScopesUnknownGoesToServer(t *testing.T) { + s := oauthEnv(t) + _, _, err := run(t, "login", "--scopes", "backup.read,backup.delete") + var ce *clierr.Error + if !errors.As(err, &ce) || ce.Code != clierr.CodeUsage || !strings.Contains(err.Error(), "invalid_scope") { + t.Fatalf("got %v", err) + } + if s.Stats().Authorizations != 1 { + t.Fatalf("authorizations %d, want 1 (the server decides)", s.Stats().Authorizations) + } +} + +func TestLoginScopesCompletion(t *testing.T) { + got, _ := completeLoginScopes(nil, nil, "backup.read,") + if len(got) == 0 || !strings.HasPrefix(got[0], "backup.read,full\t") { + t.Fatalf("got %v", got) + } + for _, c := range got { + if strings.HasPrefix(c, "backup.read,backup.read") { + t.Fatalf("offered a scope already given: %v", got) + } + } +} + +// Against a Norcube Auth without the OAuth sign-in, login uses the older +// one, and --scopes is refused. +func TestLoginFallsBackToTheOlderSignIn(t *testing.T) { + s := oauthEnv(t) + s.Lock() + s.NoExchange = true + s.Unlock() + calls := 0 + prev := browserLogin + browserLogin = func(context.Context, auth.BrowserLoginOptions) (*auth.CallbackPayload, error) { + calls++ + return &auth.CallbackPayload{ + AccessToken: testJWT(auth.AudienceAuth, ""), RefreshToken: "legacy-refresh", AccessExpiresIn: 300, + User: auth.User{ID: "user-1", Name: "Dev", Email: "dev@example.com"}, + DefaultOrg: auth.Organization{ID: authtest.HomeOrgID, Slug: "home", Name: "Home"}, + }, nil + } + t.Cleanup(func() { browserLogin = prev }) + + if _, _, err := run(t, "login", "--scopes", "backup.read"); !clierr.IsUsage(err) || !strings.Contains(err.Error(), "needs the OAuth sign-in") { + t.Fatalf("--scopes on an older server: %v", err) + } + out, stderr, err := run(t, "login") + if err != nil { + t.Fatalf("login: %v\n%s", err, stderr) + } + if calls != 1 || strings.Contains(out, "Access:") || s.Stats().Authorizations != 0 { + t.Fatalf("calls %d, authorizations %d, output:\n%s", calls, s.Stats().Authorizations, out) + } + if sess, _ := auth.LoadSession(oauthProfile, s.URL); sess.Format != auth.FormatLegacy { + t.Fatalf("format %d", sess.Format) + } +} + +func TestOAuthDeviceLoginPassesScopes(t *testing.T) { + oauthEnv(t) + var got auth.DeviceLoginOptions + prev := deviceLogin + deviceLogin = func(ctx context.Context, opts auth.DeviceLoginOptions) (*auth.CallbackPayload, error) { + got = opts + return nil, &clierr.Error{Code: clierr.CodeLoginRequired, Message: auth.ErrDeviceDenied.Error(), Err: auth.ErrDeviceDenied} + } + t.Cleanup(func() { deviceLogin = prev }) + _, _, err := run(t, "login", "--device", "--scopes", "langsync.sync") + if !errors.Is(err, auth.ErrDeviceDenied) { + t.Fatalf("got %v", err) + } + if got.Metadata == nil || !got.Metadata.SupportsDevice() || strings.Join(got.Scopes, ",") != "langsync.sync" { + t.Fatalf("device options: %+v", got) + } +} + +// logout revokes an OAuth sign-in's refresh token (RFC 7009) instead of +// the older sign-out endpoint, then forgets it; a failed revocation is +// reported, and the local sign-out happens anyway. +func TestOAuthLogout(t *testing.T) { + s := oauthEnv(t) + if _, stderr, err := run(t, "login"); err != nil { + t.Fatalf("login: %v\n%s", err, stderr) + } + rt, _ := auth.LoadRefreshToken(oauthProfile, s.URL) + g := s.Grant(rt) + out, _, err := run(t, "logout", "-o", "json") + if err != nil { + t.Fatal(err) + } + if res := logoutJSON(t, out); res.ServerSessionEnded == nil || !*res.ServerSessionEnded { + t.Fatalf("logout result: %s", out) + } + st := s.Stats() + if len(st.Revocations) != 1 || st.Revocations[0].Get("token") != rt || len(st.SignOuts) != 0 || !s.Revoked(g) { + t.Fatalf("revocations %v, sign-outs %v", st.Revocations, st.SignOuts) + } + if auth.HasCredentials(oauthProfile, s.URL) { + t.Fatal("credentials kept") + } + + if _, stderr, err := run(t, "login", "--force"); err != nil { + t.Fatalf("login: %v\n%s", err, stderr) + } + s.Lock() + s.RevokeStatus = http.StatusServiceUnavailable + s.Unlock() + out, stderr, err := run(t, "logout", "-o", "json") + if err != nil { + t.Fatal(err) + } + if res := logoutJSON(t, out); res.ServerSessionEnded == nil || *res.ServerSessionEnded { + t.Fatalf("logout result after a failed revocation: %s", out) + } + if !strings.Contains(stderr, "couldn't end the session on the server") { + t.Errorf("stderr: %s", stderr) + } + if auth.HasCredentials(oauthProfile, s.URL) { + t.Fatal("credentials kept after a failed revocation") + } +} + +// An older sign-in moves to OAuth on its first command, once, and doctor +// reports the format before and after. +func TestOlderSignInUpgradesOnce(t *testing.T) { + s := oauthEnv(t) + s.AddLegacySession("legacy-refresh") + if err := auth.SaveRefreshToken(oauthProfile, s.URL, "legacy-refresh"); err != nil { + t.Fatal(err) + } + checks, _ := doctorReport(t, "--offline") + if c := checks["credentials"]; c.Status != checkWarn || !strings.Contains(c.Detail, "older sign-in (format 1)") { + t.Fatalf("doctor before: %+v", c) + } + for range 2 { + if out, stderr, err := run(t, "whoami"); err != nil || !strings.Contains(out, "Access: full") { + t.Fatalf("whoami: %v\n%s%s", err, out, stderr) + } + } + st := s.Stats() + if st.Upgrades != 1 || st.UpgradeRefusals != 0 || st.LegacyRefreshes != 0 || st.Refreshes != 0 { + t.Fatalf("upgrades %d refusals %d legacy refreshes %d refreshes %d", st.Upgrades, st.UpgradeRefusals, st.LegacyRefreshes, st.Refreshes) + } + checks, _ = doctorReport(t, "--offline") + if c := checks["credentials"]; c.Status != checkOK || !strings.Contains(c.Detail, "OAuth sign-in (format 2), scopes full") { + t.Fatalf("doctor after: %+v", c) + } +} + +// A sign-in Norcube Auth won't move (no recorded session) asks for one +// login, exit 4. +func TestOlderSignInThatCantUpgradeAsksForLogin(t *testing.T) { + s := oauthEnv(t) + if err := auth.SaveRefreshToken(oauthProfile, s.URL, "sid-less"); err != nil { + t.Fatal(err) + } + _, _, err := run(t, "whoami") + if e := Describe(err); e.ExitCode() != clierr.ExitAuth || !strings.Contains(err.Error(), "sign in once more") { + t.Fatalf("got %v (exit %d)", err, e.ExitCode()) + } +} + +func TestDoctorWithLimitedLogin(t *testing.T) { + s := oauthEnv(t) + if _, stderr, err := run(t, "login", "--scopes", "backup.read"); err != nil { + t.Fatalf("login: %v\n%s", err, stderr) + } + for _, key := range []string{config.ServiceSnapDB, config.ServiceLangsync, config.ServiceDomainradar, config.ServiceBilling} { + t.Setenv(config.ServiceEnvVar(key), s.URL) + } + checks, _ := doctorReport(t) + if c := checks["credentials"]; c.Status != checkOK || !strings.Contains(c.Detail, "scopes backup.read") { + t.Errorf("credentials: %+v", c) + } + if c := checks["token backup"]; c.Status != checkOK { + t.Errorf("token backup: %+v", c) + } + if c := checks["token langsync"]; c.Status != checkSkip || !strings.Contains(c.Detail, "don't cover") { + t.Errorf("token langsync: %+v", c) + } +} + +func TestGoldenLoginHelp(t *testing.T) { + out, _, err := run(t, "login", "--help") + if err != nil { + t.Fatal(err) + } + checkGolden(t, "help-login.txt", out, "http://no-server.invalid") +} + +// An account without an organization still signs in: /auth/me and the +// organization list need no organization; product commands do. +func TestOAuthLoginWithoutOrganization(t *testing.T) { + s := oauthEnv(t) + s.Lock() + s.NoDefaultOrg = true + s.Unlock() + isolatedConfig(t, func(f *config.File) { + f.DefaultProfile = oauthProfile + p := f.Profile(oauthProfile) + p.Environment = config.EnvCustom + p.Endpoints = map[string]string{config.ServiceAuth: s.URL} + }) + out, stderr, err := run(t, "login") + if err != nil { + t.Fatalf("login: %v\n%s", err, stderr) + } + if !strings.Contains(out, "Signed in as Dev Eloper (dev@example.com)") || !strings.Contains(out, "norcube org create") { + t.Fatalf("login output:\n%s", out) + } + if out, _, err := run(t, "whoami"); err != nil || !strings.Contains(out, "dev@example.com") { + t.Fatalf("whoami: %v\n%s", err, out) + } + if out, _, err := run(t, "org", "list"); err != nil || !strings.Contains(out, "acme") { + t.Fatalf("org list: %v\n%s", err, out) + } + _, _, err = run(t, "auth", "token", "--audience", "backup") + if !clierr.IsUsage(err) { + t.Fatalf("product token without an organization: %v", err) + } +} + +// login --force ends the session it replaces on the server, the way +// logout does: revocation for an OAuth sign-in, the older sign-out for an +// older one. A failure warns and the new login goes ahead. +func TestLoginForceEndsThePreviousSession(t *testing.T) { + t.Run("oauth", func(t *testing.T) { + s := oauthEnv(t) + if _, stderr, err := run(t, "login"); err != nil { + t.Fatalf("login: %v\n%s", err, stderr) + } + old, _ := auth.LoadRefreshToken(oauthProfile, s.URL) + g := s.Grant(old) + if _, stderr, err := run(t, "login", "--force"); err != nil { + t.Fatalf("login --force: %v\n%s", err, stderr) + } + st := s.Stats() + if len(st.Revocations) != 1 || st.Revocations[0].Get("token") != old || !s.Revoked(g) || len(st.SignOuts) != 0 { + t.Fatalf("revocations %v, sign-outs %v", st.Revocations, st.SignOuts) + } + if now, _ := auth.LoadRefreshToken(oauthProfile, s.URL); now == old || now == "" { + t.Fatal("the new session was not stored") + } + + // The server fails: a warning, and the new session anyway. + s.Lock() + s.RevokeStatus = http.StatusServiceUnavailable + s.Unlock() + prev, _ := auth.LoadRefreshToken(oauthProfile, s.URL) + _, stderr, err := run(t, "login", "--force") + if err != nil { + t.Fatalf("login --force with a failing server: %v\n%s", err, stderr) + } + if !strings.Contains(stderr, "couldn't end the previous session") { + t.Errorf("stderr: %s", stderr) + } + if now, _ := auth.LoadRefreshToken(oauthProfile, s.URL); now == prev || now == "" { + t.Fatal("the new session was not stored after a failed revocation") + } + }) + t.Run("older sign-in", func(t *testing.T) { + s := oauthEnv(t) + s.AddLegacySession("legacy-refresh") + if err := auth.SaveRefreshToken(oauthProfile, s.URL, "legacy-refresh"); err != nil { + t.Fatal(err) + } + if _, stderr, err := run(t, "login", "--force"); err != nil { + t.Fatalf("login --force: %v\n%s", err, stderr) + } + st := s.Stats() + if len(st.SignOuts) != 1 || st.SignOuts[0].Get("refresh_token") != "legacy-refresh" || len(st.Revocations) != 0 { + t.Fatalf("sign-outs %v, revocations %v", st.SignOuts, st.Revocations) + } + if sess, _ := auth.LoadSession(oauthProfile, s.URL); sess.Format != auth.FormatOAuth { + t.Fatalf("format %d", sess.Format) + } + }) +} + +// doctor describes an older sign-in without moving it to OAuth, so the +// profile is the same after the report as before. +func TestDoctorKeepsTheOlderSignIn(t *testing.T) { + s := oauthEnv(t) + s.AddLegacySession("legacy-refresh") + if err := auth.SaveRefreshToken(oauthProfile, s.URL, "legacy-refresh"); err != nil { + t.Fatal(err) + } + checks, err := doctorReport(t) + if err != nil { + t.Fatalf("doctor: %v (%v)", err, checks) + } + if c := checks["credentials"]; !strings.Contains(c.Detail, "format 1") { + t.Errorf("credentials: %s (%s)", c.Status, c.Detail) + } + if st := s.Stats(); st.Upgrades != 0 { + t.Errorf("doctor moved the sign-in to OAuth (%d upgrades)", st.Upgrades) + } + if sess, _ := auth.LoadSession(oauthProfile, s.URL); sess.Format != auth.FormatLegacy { + t.Errorf("format %d after doctor, want the older one", sess.Format) + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 85699cf..74ca3b5 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -53,8 +53,10 @@ func NewRootCmd() *cobra.Command { return err } selectedOutput = flags.Output + selectedAuthURL = "" if res, err := flags.Resolve(); err == nil { selectedProfile = res.Profile.Value + selectedAuthURL = res.Endpoints[config.ServiceAuth].Value // --profile or NORCUBE_PROFILE picked it; the hint then // names it even when it is the default. selectedProfileExplicit = !strings.HasPrefix(res.Profile.Source, "default") diff --git a/internal/cli/sessions.go b/internal/cli/sessions.go index bcee07d..1e1a66e 100644 --- a/internal/cli/sessions.go +++ b/internal/cli/sessions.go @@ -7,6 +7,7 @@ import ( "github.com/spf13/cobra" "github.com/norcubeplatform/cli/internal/api" + "github.com/norcubeplatform/cli/internal/auth" "github.com/norcubeplatform/cli/internal/clictx" "github.com/norcubeplatform/cli/internal/clierr" "github.com/norcubeplatform/cli/internal/cmdutil" @@ -21,8 +22,10 @@ func newAuthSessionsCmd() *cobra.Command { Short: "List and revoke the CLI sessions of your account", Long: `Every ` + "`norcube login`" + ` creates a CLI session for your account. These commands list them and end the ones you don't use or don't recognize, the -same as Account › CLI sessions in the dashboard. Revoking a session stops -its refresh token at once; the CLI on that machine has to sign in again.`, +same as Account › CLI sessions in the dashboard. SCOPES is what the login may +do: full, or the scopes it was limited to with ` + "`norcube login --scopes`" + `. +Revoking a session stops its refresh token at once; the CLI on that machine +has to sign in again.`, } cmd.AddCommand(newAuthSessionsListCmd(), newAuthSessionsRevokeCmd()) return cmd @@ -46,7 +49,7 @@ func newAuthSessionsListCmd() *cobra.Command { return err } return cmdutil.Print(cmd, output.Table[api.Session]{ - Headers: []string{"CURRENT", "DEVICE", "CLIENT", "LAST USED", "IP", "ID"}, + Headers: []string{"CURRENT", "DEVICE", "CLIENT", "SCOPES", "LAST USED", "IP", "ID"}, Rows: func(s api.Session) []string { current := " " if s.Current { @@ -56,6 +59,7 @@ func newAuthSessionsListCmd() *cobra.Command { current, orDash(cmdutil.Deref(s.Hostname)), sessionClientLabel(s.Client), + auth.DescribeScopes(s.Scopes), output.When(s.LastUsedAt), orDash(cmdutil.Deref(s.IPAddress)), s.ID, diff --git a/internal/cli/testdata/golden/auth-sessions-list.json b/internal/cli/testdata/golden/auth-sessions-list.json index 42b0343..92c0f51 100644 --- a/internal/cli/testdata/golden/auth-sessions-list.json +++ b/internal/cli/testdata/golden/auth-sessions-list.json @@ -13,7 +13,13 @@ "created_at": "2026-10-16T09:00:00Z", "last_used_at": "2026-10-28T11:42:00Z", "expires_at": "2026-11-27T11:42:00Z", - "current": true + "current": true, + "oauth_grant_id": "6a1f0c7e-2b3d-4e5f-8a9b-0c1d2e3f4a5b", + "scopes": [ + "full", + "org.read", + "offline_access" + ] }, { "id": "sess-2", @@ -29,7 +35,14 @@ "created_at": "2026-09-28T08:00:00Z", "last_used_at": "2026-10-27T03:10:00Z", "expires_at": "2026-11-26T03:10:00Z", - "current": false + "current": false, + "oauth_grant_id": "7b2e1d8f-3c4e-4f6a-9b0c-1d2e3f4a5b6c", + "scopes": [ + "backup.read", + "langsync.sync", + "org.read", + "offline_access" + ] }, { "id": "sess-3", diff --git a/internal/cli/testdata/golden/auth-sessions-list.tsv b/internal/cli/testdata/golden/auth-sessions-list.tsv index 9878849..bcb5409 100644 --- a/internal/cli/testdata/golden/auth-sessions-list.tsv +++ b/internal/cli/testdata/golden/auth-sessions-list.tsv @@ -1,3 +1,3 @@ -* dev-laptop norcube 0.17.0 (darwin/arm64) 2026-10-28T11:42:00Z 203.0.113.24 sess-1 - ci-runner-04 norcube 0.16.0 (linux/amd64) 2026-10-27T03:10:00Z 198.51.100.7 sess-2 - 2026-10-19T10:00:00Z sess-3 +* dev-laptop norcube 0.17.0 (darwin/arm64) full 2026-10-28T11:42:00Z 203.0.113.24 sess-1 + ci-runner-04 norcube 0.16.0 (linux/amd64) backup.read, langsync.sync 2026-10-27T03:10:00Z 198.51.100.7 sess-2 + full 2026-10-19T10:00:00Z sess-3 diff --git a/internal/cli/testdata/golden/auth-sessions-list.txt b/internal/cli/testdata/golden/auth-sessions-list.txt index 98c2c24..e6c0b25 100644 --- a/internal/cli/testdata/golden/auth-sessions-list.txt +++ b/internal/cli/testdata/golden/auth-sessions-list.txt @@ -1,4 +1,4 @@ -CURRENT DEVICE CLIENT LAST USED IP ID -* dev-laptop norcube 0.17.0 (darwin/arm64) 2026-10-28 13:42 203.0.113.24 sess-1 - ci-runner-04 norcube 0.16.0 (linux/amd64) 2026-10-27 05:10 198.51.100.7 sess-2 - - - 2026-10-19 12:00 - sess-3 +CURRENT DEVICE CLIENT SCOPES LAST USED IP ID +* dev-laptop norcube 0.17.0 (darwin/arm64) full 2026-10-28 13:42 203.0.113.24 sess-1 + ci-runner-04 norcube 0.16.0 (linux/amd64) backup.read, langsync.sync 2026-10-27 05:10 198.51.100.7 sess-2 + - - full 2026-10-19 12:00 - sess-3 diff --git a/internal/cli/testdata/golden/auth-sessions-list.yaml b/internal/cli/testdata/golden/auth-sessions-list.yaml index 5cfb1db..0db9ff4 100644 --- a/internal/cli/testdata/golden/auth-sessions-list.yaml +++ b/internal/cli/testdata/golden/auth-sessions-list.yaml @@ -11,6 +11,11 @@ ip_address: 203.0.113.24 kind: cli last_used_at: "2026-10-28T11:42:00Z" + oauth_grant_id: 6a1f0c7e-2b3d-4e5f-8a9b-0c1d2e3f4a5b + scopes: + - full + - org.read + - offline_access - client: arch: amd64 name: norcube @@ -24,6 +29,12 @@ ip_address: 198.51.100.7 kind: cli last_used_at: "2026-10-27T03:10:00Z" + oauth_grant_id: 7b2e1d8f-3c4e-4f6a-9b0c-1d2e3f4a5b6c + scopes: + - backup.read + - langsync.sync + - org.read + - offline_access - client: arch: null name: null diff --git a/internal/cli/testdata/golden/help-login.txt b/internal/cli/testdata/golden/help-login.txt new file mode 100644 index 0000000..2b6ced8 --- /dev/null +++ b/internal/cli/testdata/golden/help-login.txt @@ -0,0 +1,63 @@ +Opens the Norcube sign-in page in your default browser. After you approve +the sign-in there, the browser hands the CLI a one-time code over a localhost +callback (127.0.0.1), which the CLI exchanges for its session (OAuth 2.0 with +PKCE). The session is stored for the selected profile (--profile, +NORCUBE_PROFILE or the default profile) in your operating system's keyring +(Keychain / Secret Service / Windows Credential Manager), or in a file when +no keyring is available. + +Logging in to a profile that doesn't exist yet creates it. Its +organization is --org when given, else the profile's organization, else +your default organization. + +By default the login can do everything you can do in the dashboard. With +--scopes it is limited to the scopes you list, the same scopes CI tokens +use (for example --scopes backup.read,langsync.sync); commands outside them +fail with exit code 5. Your own permissions in each organization apply +either way. Every login shows up under Account › CLI sessions and Connected +apps in the dashboard, where you can revoke it. + +With --no-browser the CLI only prints the sign-in URL. Open it in any +browser on this machine; the page hands the code back to the CLI over +127.0.0.1. + +With --device you approve the sign-in on any other device instead, such as +your phone or laptop: the CLI shows a short code and a page to enter it on +(and a QR code when the terminal can show one). Use it over SSH, in a +container or on any machine without a browser. Only approve a code you +started yourself: Norcube never asks you for one. + +Usage: + norcube login [flags] + +Examples: + norcube login + norcube login --profile client-acme + norcube login --org acme + norcube login --scopes backup.read,langsync.sync + norcube login --device + norcube login --no-browser + norcube login --force + +Flags: + --device Approve the sign-in on another device (phone, laptop) with a short code; for SSH and headless machines + --force Re-authenticate even if a valid session already exists; the previous session is ended on Norcube + -h, --help help for login + --no-browser Print the login URL instead of opening a browser + --scopes strings Limit the login to these scopes, comma-separated (default full: everything you can do in the dashboard); one of full, backup.read, backup.write, backup.verify, domainradar.check, langsync.read, langsync.sync, langsync.write, billing.read, cms.read, cms.write, monitor.read, monitor.check, monitor.write, monitor.channels, monitor.statuspages, monitor.maintenance + +Global Flags: + --auth-url string Override the auth service base URL, same as --endpoint-url auth=URL (env: NORCUBE_AUTH_URL) + --cli-connect-timeout int Seconds to wait for a connection, 0 for no limit (env: NORCUBE_CONNECT_TIMEOUT) (default 10) + --cli-read-timeout int Seconds to wait for each API response, 0 for no limit (env: NORCUBE_READ_TIMEOUT) (default 60) + --debug Print every HTTP request and response to stderr, with credentials redacted (env: NORCUBE_DEBUG=1) + --endpoint-url stringArray Override a service endpoint, service=url (repeatable; services: auth, web_app, snapdb, langsync, domainradar, billing, monitor, prompthub) + --max-attempts int Attempts for a request that hit throttling or a transient failure, 1 disables retries (env: NORCUBE_MAX_ATTEMPTS) (default 3) + --no-color Disable color and styling (env: NO_COLOR, CLICOLOR=0) + --no-pager Disable automatic paging of long table output (env: $PAGER controls the pager, default: less) + --org string Run this command against a specific organization, id or slug (env: NORCUBE_ORG) + -o, --output string Output format: table | json | yaml | text | id (env: NORCUBE_OUTPUT) (default "table") + --profile string Use a named profile from the config file (env: NORCUBE_PROFILE) + --query string JMESPath expression applied to the result before it is printed, e.g. "[?status=='failed'].jobId" + --token-file string Read an access token from this file instead of the profile's credentials (env: NORCUBE_TOKEN holds one directly) + --web-app string Override the web app base URL used for browser login (env: NORCUBE_WEB_APP) diff --git a/internal/cli/testdata/golden/whoami.json b/internal/cli/testdata/golden/whoami.json index a724e4c..ea593a8 100644 --- a/internal/cli/testdata/golden/whoami.json +++ b/internal/cli/testdata/golden/whoami.json @@ -11,5 +11,8 @@ }, "profile": "default", "environment": "custom", - "api": "http://backend" + "api": "http://backend", + "scopes": [ + "full" + ] } diff --git a/internal/cli/testdata/golden/whoami.tsv b/internal/cli/testdata/golden/whoami.tsv index cb81527..2d7c1eb 100644 --- a/internal/cli/testdata/golden/whoami.tsv +++ b/internal/cli/testdata/golden/whoami.tsv @@ -1 +1 @@ -Dev Eloper user-1 home (a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d) default (custom) http://backend +Dev Eloper user-1 home (a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d) full default (custom) http://backend diff --git a/internal/cli/testdata/golden/whoami.txt b/internal/cli/testdata/golden/whoami.txt index 7487ba5..4582da7 100644 --- a/internal/cli/testdata/golden/whoami.txt +++ b/internal/cli/testdata/golden/whoami.txt @@ -1,5 +1,6 @@ User: Dev Eloper User ID: user-1 Active org: home (a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d) +Access: full Profile: default (custom) API: http://backend diff --git a/internal/cli/testdata/golden/whoami.yaml b/internal/cli/testdata/golden/whoami.yaml index 65dbde9..eff7bb4 100644 --- a/internal/cli/testdata/golden/whoami.yaml +++ b/internal/cli/testdata/golden/whoami.yaml @@ -5,6 +5,8 @@ organization: name: Home slug: home profile: default +scopes: + - full user: email: dev@example.com id: user-1 diff --git a/internal/cli/whoami.go b/internal/cli/whoami.go index 4bd3cea..bdd9e71 100644 --- a/internal/cli/whoami.go +++ b/internal/cli/whoami.go @@ -5,8 +5,10 @@ import ( "github.com/spf13/cobra" + "github.com/norcubeplatform/cli/internal/auth" "github.com/norcubeplatform/cli/internal/clictx" "github.com/norcubeplatform/cli/internal/cmdutil" + "github.com/norcubeplatform/cli/internal/config" "github.com/norcubeplatform/cli/internal/output" ) @@ -44,6 +46,7 @@ func newWhoamiCmd() *cobra.Command { Profile: cfg.Profile, Environment: cfg.Environment, API: cfg.Auth, + Scopes: loginScopes(cfg), } active := "(none — run `norcube org use `)" if res.Organization != nil { @@ -53,6 +56,7 @@ func newWhoamiCmd() *cobra.Command { {Name: "User", Value: fmt.Sprintf("%s <%s>", me.Name, me.Email)}, {Name: "User ID", Value: me.ID}, {Name: "Active org", Value: active}, + {Name: "Access", Value: accessLabel(res.Scopes)}, {Name: "Profile", Value: fmt.Sprintf("%s (%s)", cfg.Profile, cfg.Environment)}, {Name: "API", Value: cfg.Auth}, }}) @@ -66,4 +70,31 @@ type whoamiResult struct { Profile string `json:"profile" yaml:"profile"` Environment string `json:"environment" yaml:"environment"` API string `json:"api" yaml:"api"` + // Scopes are the login's scopes: ["full"] for the older sign-in, + // what Norcube Auth granted for an OAuth sign-in, absent for a static + // access token. + Scopes []string `json:"scopes,omitempty" yaml:"scopes,omitempty"` +} + +// loginScopes are the scopes of cfg's stored login (see whoamiResult). +func loginScopes(cfg *config.Config) []string { + s, err := auth.LoadSession(cfg.Profile, cfg.Auth) + switch { + case err != nil || s.Format == 0: + return nil + case s.Format == auth.FormatLegacy || len(s.Scopes) == 0: + return []string{auth.ScopeFull} + } + return s.Scopes +} + +// accessLabel reads like "full" or "limited to backup.read, langsync.sync". +func accessLabel(scopes []string) string { + switch { + case scopes == nil: + return "-" + case auth.ScopesFull(scopes): + return auth.ScopeFull + } + return "limited to " + auth.DescribeScopes(scopes) } diff --git a/internal/transport/debug.go b/internal/transport/debug.go index 3b15e9b..ff2c04f 100644 --- a/internal/transport/debug.go +++ b/internal/transport/debug.go @@ -127,12 +127,18 @@ func redactHeader(name, value string) string { // signatures. func sensitiveKey(key string) bool { k := strings.ToLower(key) - for _, part := range []string{"token", "secret", "password", "apikey", "api_key", "signature", "credential", "authorization", "cookie", "sig"} { + for _, part := range []string{"token", "secret", "password", "apikey", "api_key", "signature", "credential", "authorization", "cookie", "sig", "verifier"} { if strings.Contains(k, part) { return true } } - return k == "code" || k == "x-amz-security-token" + // OAuth codes (authorization code, device_code) are one-time + // credentials; user_code is the short code the person types, shown + // on screen anyway, and the only *_code that isn't secret. + if k == "user_code" { + return false + } + return k == "code" || strings.HasSuffix(k, "_code") || k == "x-amz-security-token" } // RedactURL returns u as a string with credential query values replaced, diff --git a/internal/transport/debug_test.go b/internal/transport/debug_test.go index c68a521..cd53060 100644 --- a/internal/transport/debug_test.go +++ b/internal/transport/debug_test.go @@ -27,8 +27,9 @@ func TestDebugTraceRedactsCredentials(t *testing.T) { if err != nil { t.Fatal(err) } - form := url.Values{"grant_type": {"refresh_token"}, "refresh_token": {"form-secret"}, "audience": {"snapdb-api"}} - req, _ := http.NewRequest(http.MethodPost, srv.URL+"/oauth/token?token=query-secret&page=2", strings.NewReader(form.Encode())) + form := url.Values{"grant_type": {"refresh_token"}, "refresh_token": {"form-secret"}, "audience": {"snapdb-api"}, + "code": {"code-secret"}, "device_code": {"devicecode-secret"}, "code_verifier": {"verifier-secret"}, "user_code": {"WDJB-MJHT"}} + req, _ := http.NewRequest(http.MethodPost, srv.URL+"/oauth/token?token=query-secret&page=2&code_challenge=challenge-ok", strings.NewReader(form.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Authorization", "Bearer header-secret") req.Header.Set("Cookie", "jds_refresh_token=cookie-secret") @@ -42,12 +43,16 @@ func TestDebugTraceRedactsCredentials(t *testing.T) { _ = resp.Body.Close() out := trace.String() - for _, secret := range []string{"header-secret", "cookie-secret", "key-secret", "form-secret", "query-secret", "at-secret", "rt-secret", "sig-secret", "pw-secret"} { + for _, secret := range []string{"header-secret", "cookie-secret", "key-secret", "form-secret", "query-secret", "at-secret", "rt-secret", "sig-secret", "pw-secret", + "code-secret", "devicecode-secret", "verifier-secret"} { if strings.Contains(out, secret) { t.Errorf("trace leaks %q:\n%s", secret, out) } } - for _, want := range []string{"--> #1 POST", "Authorization: Bearer [REDACTED]", "page=2", "audience=snapdb-api", "<-- #1 200 OK", "request-id=req-42", `"expires_in":300`, "X-Amz-Expires=60"} { + // The PKCE challenge is public (a hash); the user code is shown on + // screen anyway and is what a support request needs. + for _, want := range []string{"--> #1 POST", "Authorization: Bearer [REDACTED]", "page=2", "audience=snapdb-api", "<-- #1 200 OK", "request-id=req-42", `"expires_in":300`, "X-Amz-Expires=60", + "code_challenge=challenge-ok", "user_code=WDJB-MJHT"} { if !strings.Contains(out, want) { t.Errorf("trace lacks %q:\n%s", want, out) } diff --git a/scripts/govulncheck.sh b/scripts/govulncheck.sh index 6511acd..bc32ca6 100755 --- a/scripts/govulncheck.sh +++ b/scripts/govulncheck.sh @@ -4,13 +4,8 @@ set -euo pipefail # Accepted advisories: ID, then why it is accepted and what removes it. -accepted=( - # golang.org/x/crypto/openpgp is deprecated with no fix. It is linked - # only through github.com/creativeprojects/go-selfupdate's init; the CLI - # never verifies or creates PGP data. Goes away when `norcube upgrade` - # stops using go-selfupdate. - GO-2026-5932 -) +# None at the moment. +accepted=() json=$(go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 -format json ./...) @@ -20,7 +15,7 @@ reachable=$(jq -r 'select(.finding != null and .finding.trace[0].function != nul failed=0 for id in $reachable; do - if printf '%s\n' "${accepted[@]}" | grep -qx "$id"; then + if printf '%s\n' ${accepted[@]+"${accepted[@]}"} | grep -qx "$id"; then echo "accepted: $id" else echo "reachable vulnerability: $id (https://pkg.go.dev/vuln/$id)"