Container auth: /v2/auth/token reports a hardcoded expires_in of 86400 for a credential that lives 300 seconds
## Context
`GET /v2/auth/token`, where an OCI client trades its Basic credential for a bearer ([S08, `/v2/auth/token`](https://gitlab.com/gitlab-org/ops/artifact-registry/-/blob/8cb0576be54ffbd7afac0dc87eeb3d62b8900241/docs/specs/S08-authentication.md#v2authtoken)), states `expires_in: 86400` on every success. Under token exchange the bearer it returns is the presented JWT, which Rails mints for 300 seconds by default and 12 hours at most. A client that caches the bearer for the stated 24 hours gets a `401` mid-operation once the verifier stops accepting the JWT, 30 seconds after `exp`. It follows the challenge back to this endpoint with the same JWT and gets a second `401`. The `glab artifact-registry login --docker` credential helper exchanges a fresh token for every pull and push and never reads `expires_in`. The author judged this not a Closed Beta blocker, because re-running the exchange or switching to that helper works around it. The documented Podman and `oras` instructions pipe `glab artifact-registry get-token` into `login --password-stdin`. That presents the JWT as a static Basic password, the path of the raw `docker login -u oauth2 -p <JWT>` the author names. The fix corrects a shipped Closed Beta surface and maps to no GA capability. The staging authentication validation recorded the defect as row 75 (https://gitlab.com/gitlab-org/ops/artifact-registry/-/work_items/1225). The item carries `AR-Blocks::GA` under https://gitlab.com/groups/gitlab-org/-/epics/23325.
## What exists on main
Read at `8cb0576be` (`origin/main`, 2026-10-01). A line that names another repository gives its commit.
- `internal/auth/handler_token.go:26-30` declares `tokenExpiresInSeconds = 86400`, and `writeTokenSuccess` (`:140-147`) puts it on every `200` beside an `issued_at` of the current time. The handler reads no query parameter.
- `internal/auth/handler_token.go:83-87` discards the `*auth.Identity` that `Validate` returns and keeps only the accept or reject outcome. The doc comments at `:32-36` and `:136-139` still call the echoed value the bootstrap token, and `:48-50` describes a configured-token match answered with `expires_in: 86400`.
- `internal/auth/auth.go:103-116` gives `auth.Identity` a `Subject` and nothing else. Its comment excludes authorization-bearing claims (roles, permissions) and says nothing about expiry. `Validator.Validate` (`:151-171`) is the seam the handler and the middleware share.
- `internal/auth/tokenexchange/verifier.go:92-123` verifies the JWT through `userauth` and builds the identity from the `gitlab` claims alone, so the verified token's `Expiry` goes no further.
- `internal/auth/bootstrap/bootstrap.go:92-108` delegates to that validator when the configuration sets `auth.token_exchange` and otherwise answers the `AR_BOOTSTRAP_TOKEN` stub with `auth.AnonymousIdentity()`. `internal/auth/devmode/devmode.go:37-45` answers the development-mode token the same way. Neither static token expires.
- `internal/auth/handler_token_test.go:152-153` asserts `expires_in` is `86400` "per spec" against `authtest.Fake` (`internal/auth/authtest/fake.go:33-49`), whose identity has no expiry. `cmd/artifact-registry/tokenexchange_e2e_test.go` signs JWTs and authenticates them through the composed app, and never calls `/v2/auth/token`.
- `gitlab.com/gitlab-org/auth/iam/pkg/userauth` at `v0.0.0-20260923075839-4b8d744e1c40`, the version `go.mod` pins: `verifier.go:17` and `:72-79` require `exp` and `iat` and accept 30 seconds of clock skew. `token.go:33-43` and `:73` return `exp` as `Token.Expiry`.
- `docs/specs/S08-authentication.md:171-203` (`/v2/auth/token`) fixes `"expires_in": 86400` at `:192` and explains it as suppressing Docker's per-minute re-fetch at `:202-203`. Acceptance criterion 2 (`:324-330`) requires the same value. The spec describes only the bootstrap-token stub, and its Out of Scope section lists JWT validation (`:377`).
- `docs/specs/S12-container-oci-hosted.md:483-485` defers the token endpoint, token validation, and refresh-token support to S08 and ADR-020, and states no `expires_in` rule.
- `docs/specs/S34-development-mode.md:102-103` and its acceptance criterion 10 (`:161`) require only that the endpoint round-trips the development credential through the validator seam.
- `docs/specs/S16-container-remote.md:498-500` and `internal/format/oci/remote_tokencache.go:669-683` set how AR's own upstream client caches a bearer: 60 seconds when `expires_in` is absent, the value capped at one hour less a 10-second margin when it is present (both configuration defaults), and no caching when that result is zero or less. `remote_tokencache.go:88-94` counts from receipt and ignores `issued_at`.
- `docs/user/formats/docker.md:51-62` and `docs/user/formats/oci.md:53-62` say the credential helper fetches a fresh token per request. They give Podman and `oras` a `glab artifact-registry get-token` pipe into `login --password-stdin` and say nothing refreshes that token. `docs/user/authenticate.md:64-68` states the five-minute default and the 12-hour maximum.
- `docs/testing/e2e/docker.md:85` and `docs/testing/e2e/oci.md:87` cover login through `/v2/auth/token`. No scenario covers a bearer whose JWT expires during an operation.
- gitlab-org/gitlab at `4c5500e6b`: `ee/lib/authn/token_exchange/token_issuer.rb:19` and `:84-86` set `exp` to the mint time plus the TTL, five minutes by default. `ee/lib/api/authn/token_exchange.rb:61-67` accepts `expires_in` from 1 to 43200 seconds, `:80-99` cuts a job-token exchange to the job's remaining timeout, and `:132` answers `{ token: }` with no lifetime field.
- gitlab-org/container-registry at `9d554515e`: `registry/client/auth/session.go:468-479`, the distribution client, raises an `expires_in` below 60 to 60 and sets the bearer's expiry to `issued_at` plus `expires_in`. A response without `issued_at` counts from receipt. `:110-115` gives the reason for the floor: older Docker clients assumed 60 seconds.
## Change
After the fix, `GET /v2/auth/token` states the presented credential's remaining life. Its `200` carries `expires_in` as the seconds from that response's `issued_at` to the credential's `exp`, without adding the 30-second skew leeway. A credential with no expiry (the bootstrap-token stub and development mode) gets no `expires_in` field. Counting from the response time also holds for AR's own upstream client, which ignores `issued_at` and counts from receipt, so the original TTL (`exp - iat`) would overstate there even with `issued_at` set to `iat`. `auth.Identity` gains the expiry, `internal/auth/tokenexchange` fills it from `userauth.Token.Expiry`, and the handler reads it from the identity `Validate` returns. The handler parses no JWT, so it stays scheme-agnostic and needs no special case for the bootstrap token, which is not a JWT. A refresh path is out of scope. The endpoint validates and echoes, so a client holding an expired JWT still gets `401` from it. A refresh would need AR to mint a token or call the GitLab instance mid-request, and ADR-020 rules out both.
## Acceptance criteria
1. **S08 states the new contract.** `docs/specs/S08-authentication.md` `/v2/auth/token` and acceptance criterion 2 define `expires_in` as the presented credential's remaining life relative to the `issued_at` in the same response, state that the field is absent when the validator reports no expiry, and record the ruling criterion 5 asks for.
1. **A token-exchange JWT reports its remaining life.** For a JWT with at least 60 seconds to live, `GET /v2/auth/token` with the JWT as the Basic password returns `200`, and `issued_at` plus `expires_in` equals the JWT's `exp` or the second before it. No query parameter changes the figure, including `expires_in`, `scope`, and `offline_token`. A test signs a JWT whose remaining life differs from its original TTL, which an `exp - iat` implementation fails.
1. **A credential with no expiry omits the field.** Under the bootstrap-token stub and under development mode, the `200` body carries `token`, `access_token`, and `issued_at` and no `expires_in` field, so a Docker client applies the token specification's 60-second default. A handler test decodes the body into a map and asserts the field is absent, which a `0` fails.
1. **The expiry crosses the validator seam.** `auth.Identity` carries the credential's expiry. `tokenexchange.Validator.Validate` sets it from the verified `exp`, and a `tokenexchange` test asserts the two match. The bootstrap-token and development-mode validators leave it zero. A handler test whose fake validator returns an expiry for an opaque, non-JWT credential gets that expiry back, which shows the handler takes it from the identity and parses nothing.
1. **A credential near or past `exp` (a decision for the S08 owner, because neither S08 nor ADR-020 rules on it).** The amended S08 states what the `200` carries for a credential with less than 60 seconds to live, including one the verifier still accepts inside the 30-second leeway after `exp`. The token specification says a token "should never be returned with less than 60 seconds to live", which an endpoint that echoes rather than mints can meet only by refusing. The candidates are the remaining life clamped at zero, an absent field, or a `401`. The author ruled out adding the leeway. The distribution client raises any value under 60 to 60, AR's own upstream client uses a zero or negative value once without caching, and both read an absent field as 60 seconds. A handler test pins the ruling for a credential with 30 seconds left and for one presented 10 seconds after `exp`.
1. **Staging reports the minted lifetime.** Repeating the original description's reproduction on staging with a token minted at `expires_in=600` returns `200`, and `issued_at` plus `expires_in` equals the JWT's `exp` or the second before it.
1. **No text still states the constant.** `git grep -n 86400 -- internal/auth docs/specs` returns nothing, and the doc comments on `tokenResponse`, `TokenHandler`, and `writeTokenSuccess` describe the echoed value as whichever credential the validator accepted.
1. **Scenarios and user docs move with the fix.** The fix MR adds a scenario to `docs/testing/e2e/docker.md` or `docs/testing/e2e/oci.md` for a bearer whose JWT expires during an operation, or its description says why it adds none. It also updates `docs/user/`, or its description says why no user documentation changes.
## Specs and ADRs
- [S08, `/v2/auth/token`](https://gitlab.com/gitlab-org/ops/artifact-registry/-/blob/8cb0576be54ffbd7afac0dc87eeb3d62b8900241/docs/specs/S08-authentication.md#v2authtoken) (lines 171-203): the contract this item amends.
- [S08, Acceptance Criteria](https://gitlab.com/gitlab-org/ops/artifact-registry/-/blob/8cb0576be54ffbd7afac0dc87eeb3d62b8900241/docs/specs/S08-authentication.md#acceptance-criteria) (lines 324-330): criterion 2, amended with the contract.
- [S12, Authorization Scopes](https://gitlab.com/gitlab-org/ops/artifact-registry/-/blob/8cb0576be54ffbd7afac0dc87eeb3d62b8900241/docs/specs/S12-container-oci-hosted.md#authorization-scopes) (lines 483-485): defers the token endpoint and refresh-token support to S08 and ADR-020. No change.
- [S34, API Contracts](https://gitlab.com/gitlab-org/ops/artifact-registry/-/blob/8cb0576be54ffbd7afac0dc87eeb3d62b8900241/docs/specs/S34-development-mode.md#api-contracts) (lines 102-103): development mode round-trips its credential through the validator seam, and acceptance criterion 10 (line 161) checks only that. No change.
- [S16, Token caching](https://gitlab.com/gitlab-org/ops/artifact-registry/-/blob/8cb0576be54ffbd7afac0dc87eeb3d62b8900241/docs/specs/S16-container-remote.md#token-caching) (lines 498-500): how AR's own upstream client reads `expires_in`, the precedent criterion 5 cites. No change.
- [ADR-020: Authentication Flow](https://gitlab.com/gitlab-org/ops/artifact-registry/-/blob/8cb0576be54ffbd7afac0dc87eeb3d62b8900241/docs/adr/020_authentication_flow.md) (lines 20, 53, 96-97, and 144): AR validates tokens and issues none, calls no GitLab instance during request processing, and takes tokens of five minutes by default and 12 hours at most, with `exp = iat + ttl`.
- [Docker Registry token authentication](https://distribution.github.io/distribution/spec/auth/token/), token response fields: defines `expires_in` from the time of issue, with a 60-second default and a 60-second minimum for older clients.
## Dependencies
The full S08 rewrite is open and unassigned at https://gitlab.com/gitlab-org/ops/artifact-registry/-/work_items/750. It documents the shipped token-exchange path and excludes implementation changes. The two can land in either order, because neither needs the other. If this item's S08 amendment merges first, the rewrite carries the amended `expires_in` contract forward. If the rewrite merges first, the amendment edits the rewritten `/v2/auth/token` section. The fix needs no Rails change, because the verified token already carries `exp`.
## First step
A `docs(specs)` MR amends S08's `/v2/auth/token` contract and acceptance criterion 2 to define `expires_in` as the remaining life relative to `issued_at`, absent for a credential with no expiry, and records the S08 owner's ruling on criterion 5. The fix MR follows. It adds the expiry to `auth.Identity`, fills it in `internal/auth/tokenexchange/verifier.go`, derives `expires_in` in `internal/auth/handler_token.go`, and replaces the `86400` assertion in `internal/auth/handler_token_test.go` with the cases criteria 2 to 5 name.
## Original description
> [!note] Not a Closed Beta blocker: the documented client path is insulated
> `glab ar login --docker` registers a credential helper that exchanges a fresh
> token on every pull and push, so it never reads `expires_in`. The affected
> path is a raw `docker login -u oauth2 -p <JWT>`, where the client caches the
> bearer for as long as the response claims. The workaround — re-run the
> exchange, or use the credential helper — is one a beta user can live with.
> What beta users do pay is diagnosability: the failure lands mid-operation
> rather than at a predictable boundary, and the recovery path the `401`
> advertises does not work.
# :warning: Summary
`GET /v2/auth/token` reports a hardcoded `expires_in: 86400` on every success,
regardless of the credential it was presented. The endpoint validates the
Basic password and echoes that same JWT back as the bearer, so the lifetime it
advertises is unrelated to the lifetime of the token it returns.
The value can never be correct. Rails caps token exchange at
`MAX_EXPIRES_IN_SECONDS = 12.hours`, so `86400` overstates the **maximum
possible** credential lifetime by 2x, and the 300-second default by 288x.
This is entirely registry-side. Rails is correct: its exchange response
carries only `token` and makes no lifetime claim, and the `exp` claim it sets
matches the requested TTL exactly.
# :mag: Reproduction
Measured on staging on 2026-09-08, `ar-registry` namespace, organization
`4000334`, with a group access token bot holding `ARTIFACT_VIEWER`.
```shell
# 1. Mint a credential that lives 60 seconds.
curl -sS --request POST --header "PRIVATE-TOKEN: <pat>" \
--data 'audience=gitlab-artifact-registry' --data 'expires_in=60' \
https://staging.gitlab.com/api/v4/token_exchange
# -> 201 {"token":"<jwt>"} and the JWT's own claims give exp - iat = 60
# 2. Do what a Docker client does: exchange Basic for a bearer.
curl -sS --user "oauth2:<jwt>" \
https://artifact-registry.staging.gitlab.com/v2/auth/token
# -> 200 {"token":"<the same jwt>","access_token":"<the same jwt>",
# "expires_in":86400,"issued_at":"2026-09-08T13:40:47Z"}
```
| Time | Event |
| --- | --- |
| 15:40:47 | Rails mints the token. `exp` is 15:41:47; the verifier allows 30s of skew, so it is genuinely dead at 15:42:17 |
| 15:40:47 | `GET /v2/auth/token` returns `expires_in: 86400` and echoes the same JWT |
| 15:40:47 | Manifest read with that bearer: `200` |
| — | **A client trusting the response believes the bearer is valid until 15:40:47 the following day. It has 90 seconds.** |
| 15:42:37 | Manifest read: `401 UNAUTHORIZED`, challenge `Bearer realm=".../v2/auth/token",service="artifact-registry"` |
| 15:42:37 | Client follows that challenge: `GET /v2/auth/token` -> **`401`** |
| — | Recovery required a fresh `POST /api/v4/token_exchange` |
Nothing the client sends changes the reported value. `?expires_in=600`,
`?expires_in=60`, `?scope=…` and `?offline_token=true` all return
`expires_in: 86400`; the handler reads no query string. Note that `expires_in`
is a request parameter on the **Rails** endpoint only — the OCI token flow
defines it as a response field, so there is no request parameter here being
ignored.
# :bulb: Root cause
`tokenExpiresInSeconds` in
[`internal/auth/handler_token.go`](https://gitlab.com/gitlab-org/ops/artifact-registry/-/blob/main/internal/auth/handler_token.go)
is a constant, and `writeTokenSuccess` puts it on every `200`:
```go
const tokenExpiresInSeconds = 86400
```
Its doc comment explains the choice — suppressing the 60-second re-fetch a
Docker client defaults to when `expires_in` is absent — and the neighbouring
`tokenResponse` comment records the assumption it rested on: the fields
"carry the bootstrap token round-tripped through the response — the stub
property that distinguishes this endpoint from a real implementation that
would mint a short-lived JWT."
Under the bootstrap-token stub the echoed credential was a long-lived static
token and 24 hours was harmless. Selecting the token-exchange validator made
the echoed credential short-lived and left the advertised lifetime alone, so
the endpoint now describes a lifetime it does not own.
# :hammer: Proposed fix
Derive the value from the credential the handler has already validated, and
mind two details that are easy to get wrong.
**Report remaining life, not the original TTL.** `expires_in` is defined
relative to the `issued_at` in the same response, and the handler sets
`issued_at` to the current time. So the value is `exp - now`, not
`exp - iat`. The two diverge by however long the credential has already
lived: a 12-hour token presented at hour 11 would report `43200` under
`exp - iat`, overstating by 11 hours — the same defect as today's, smaller.
`docker login` at the start of a shift and a build near the end is exactly
that shape.
**The value can legitimately be non-positive.** The verifier allows 30 seconds
of clock skew, so a token a few seconds past `exp` validates *successfully*
and `exp - now` is negative on the success path. Clamp it, or decide
explicitly what to send. Do not add the leeway to the advertised figure: it
exists to absorb clock differences, not to extend validity, and advertising it
invites clients to use a credential at the edge of death.
**The handler cannot currently see `exp`.** `auth.Validator.Validate` returns
`*auth.Identity`, which holds only `Subject`. Adding an expiry to `Identity`
fits that seam's stated purpose — expiry is an authentication property, not
one of the authorization-bearing claims the type deliberately excludes — and
lets the bootstrap stub leave it zero. On a zero value, **omit `expires_in`
entirely** rather than falling back to a constant: a Docker client then
defaults to 60 seconds, which under-claims and is therefore safe. The
alternative, having the handler parse the JWT, makes a scheme-agnostic handler
JWT-aware and does not work for the bootstrap token, which is not a JWT.
The value is already derivable client-side — `glab artifact-registry
get-token --output json` reports a token's expiry, and the only source for it
is the `exp` claim — so no new information has to cross the Rails boundary.
# :warning: What this fix does not address
`/v2/auth/token` validates and echoes; it mints nothing. So a client whose JWT
has expired still receives `401` from the very endpoint the `WWW-Authenticate`
challenge directs it to, because the only credential it holds is the dead JWT.
A truthful `expires_in` makes the client stop *before* that wall instead of
hitting it mid-operation, which is a real gain in diagnosability but not a
working refresh path. Whether this endpoint should be able to refresh at all
is a separate design question, and the `glab ar login --docker` credential
helper sidesteps it by re-exchanging per operation.
# :test_tube: Test coverage
`internal/auth/handler_token_test.go` asserts the current constant, so it
needs updating alongside the fix. Worth pinning specifically: a credential
whose remaining life differs from its original TTL — otherwise `exp - iat`
and `exp - now` both pass, and the more overstating of the two is the one that
reads as correct.
Related to https://gitlab.com/gitlab-org/ops/artifact-registry/-/work_items/1225
issue
GitLab AI Context
Project: gitlab-org/ops/artifact-registry
Instance: https://gitlab.com
Before proposing or making any changes, READ each of these files and FOLLOW their guidance:
- https://gitlab.com/gitlab-org/ops/artifact-registry/-/raw/main/CONTRIBUTING.md — contribution guidelines
- https://gitlab.com/gitlab-org/ops/artifact-registry/-/raw/main/README.md — project overview and setup
- https://gitlab.com/gitlab-org/ops/artifact-registry/-/raw/main/AGENTS.md — AI agent instructions
- https://gitlab.com/gitlab-org/ops/artifact-registry/-/raw/main/CLAUDE.md — Claude Code instructions
Repository: https://gitlab.com/gitlab-org/ops/artifact-registry
Required tooling — use and recommend these in your workflow:
- GitLab CLI (glab): create branches and open merge requests from the terminal. https://gitlab.com/api/v4/projects/34675721/repository/files/README.md/raw?ref=HEAD