Attesto.RefreshToken (Attesto v2.28.0)

Copy Markdown View Source

Refresh-token issuance and rotation with reuse detection (RFC 6749 §6 / §10.4, OAuth 2.0 Security BCP).

Each refresh token is single-use: presenting it (rotate/3) consumes it and mints a successor in the same family. A short idempotency window (10 seconds by default) lets the same client retry the just-consumed parent after a lost response and receive the same successor. The parent expiry remains authoritative: a cached successor is never returned after the consumed parent expires, even when the persisted retry deadline is later. Outside the intersection of those two fixed deadlines, or when the retry does not match the original client and binding or requests scope or resource outside the grant, a rotated token is a captured-token signal and the entire family is revoked so neither the attacker nor the victim can continue, forcing a fresh authorization.

A refresh request may name a subset of the granted scope (RFC 6749 §6) and resource set (RFC 8707 §2.2). The subset applies to the access token minted from the returned context only. The successor refresh token keeps exactly the presented token's scope and resource set, so a later refresh can obtain the full grant again.

This module is pure logic over a Attesto.RefreshStore; the store provides the atomic family-level rotate/4 transaction on which reuse detection depends (see that behaviour's moduledoc). Token records use hashes, except that a positive rotation-grace window necessarily retains the plaintext successor until the window closes so the same credential can be returned after a lost response. That retry state is credential-equivalent and MUST be protected as described by Attesto.RefreshStore.rotate/4.

A consumed token presented under another client

The client check has two outcomes, and which one applies depends on whether the presented token has already been rotated.

A token that has not been rotated and is presented with the wrong :client_id fails with :client_mismatch and is left untouched. Nothing is consumed and nothing is revoked, so a misrouted request costs the real client nothing.

A token that has already been rotated is different. Presenting it again is reuse, and reuse revokes the family (RFC 9700 §4.14.2) whichever client the request names. The client is not consulted first, on purpose:

  • For a public client there is no credential behind client_id. Whoever holds a leaked consumed token can name the owning client as easily as any other, so refusing a replay "from another client" would stop nothing.
  • For a confidential client, a consumed token arriving under a different client is the signal reuse detection exists for: the token has left the party it was issued to. Revoking the family is the intended response.

The consequence is that anyone who obtains a consumed refresh token can end that family, and the legitimate client has to authorize again. That is the cost RFC 9700 accepts for detecting theft. It is bounded to the one family, and it needs a token that has leaked. An issuer mismatch is the one case checked first: a consumed token sent to a different issuer of a multi-issuer deployment fails with :issuer_mismatch and revokes nothing, because that is routing, not a leak.

:ttl bounds inactivity between refreshes. An optional :family_ttl on initial issuance also fixes an absolute family deadline, which every successor inherits. Rotation and lost-response retries cannot extend it (RFC 10017 §6.3.2.3).

DPoP binding

A refresh token can be bound to a DPoP key (its issuing context carries a :dpop_jkt). Rotation then requires the caller to present the matching :dpop_jkt (the thumbprint of the key in the token-request's DPoP proof); an unbound token must be rotated without one - presenting a proof for an unbound token is :dpop_proof_unexpected. That fail-closed matrix mirrors Attesto.Token. It does NOT match Attesto.AuthorizationCode, which permits an unbound code to be redeemed alongside a token-request proof (the proof there binds the new access token, not the code); rotation is deliberately the stricter of the two.

An attested client's verified Client Instance Key is bound independently as :attestation_jkt. Every rotation and retry requires that same instance key, even when its DPoP key differs. An unbound legacy token rejects a presented instance key; its original binding cannot be reconstructed after issuance.

Issuer binding

A host that may share a refresh store across authorization-server issuers can pass the issuing server's exact :issuer in the initial context. Passing that server's identifier as the :issuer option to rotate/3 then requires an exact match before an unconsumed token can be claimed. If the caller supplies an expected issuer for a legacy token that has no issuer binding, rotation fails closed with :issuer_mismatch and leaves the token usable by a caller applying the correct legacy policy. Omitting the option preserves compatibility for existing callers and families.

The marker is stored under a core-reserved string key inside :claims, so stores that serialize this established JSON field preserve it without a schema migration. Host claims cannot set that key. Returned rotation context exposes the verified value as top-level :issuer and removes the reserved entry before handing :claims back to the host.

Summary

Types

Context for issuing an initial refresh token.

Functions

Issue a refresh token for context and persist it via store.

Rotate a presented refresh token: consume it and mint its successor.

Types

context()

@type context() :: %{
  :subject => String.t(),
  optional(:scope) => [String.t()],
  optional(:resource) => [String.t()],
  optional(:acr) => String.t() | nil,
  optional(:auth_time) => non_neg_integer() | nil,
  optional(:client_id) => String.t(),
  optional(:issuer) => String.t(),
  optional(:dpop_jkt) => String.t() | nil,
  optional(:attestation_jkt) => String.t() | nil,
  optional(:claims) => map()
}

Context for issuing an initial refresh token.

:dpop_jkt is optional because the host must classify the client before issuing the token: RFC 9449 §5 requires DPoP-bound refresh tokens for public clients and prohibits DPoP binding for confidential clients. When this context is passed through Attesto.AuthorizationCode.issue_refresh_and_finalize/6 for a DPoP-bound authorization grant, nil is the confidential-client choice and the grant's exact JKT is the public-client choice; a different JKT is rejected. Core does not determine the client class.

issue_error()

@type issue_error() ::
  :invalid_subject
  | :invalid_scope
  | :invalid_resource
  | :invalid_client_id
  | :invalid_issuer
  | :invalid_dpop_jkt
  | :invalid_attestation_jkt
  | :invalid_claims
  | :invalid_acr
  | :invalid_auth_time
  | :family_revoked

issued()

@type issued() :: %{
  token: String.t(),
  family_id: String.t(),
  generation: non_neg_integer(),
  expires_at: non_neg_integer()
}

rotate_error()

@type rotate_error() ::
  :invalid_grant
  | :reuse_detected
  | :grant_revoked
  | :temporarily_unavailable
  | :expired
  | :client_required
  | :client_mismatch
  | :issuer_mismatch
  | :invalid_scope
  | :invalid_target
  | :dpop_proof_required
  | :dpop_proof_unexpected
  | :dpop_binding_mismatch
  | :attestation_proof_required
  | :attestation_proof_unexpected
  | :attestation_binding_mismatch

rotated()

@type rotated() :: %{
  token: String.t(),
  family_id: String.t(),
  generation: non_neg_integer(),
  expires_at: non_neg_integer(),
  context: map()
}

Functions

issue(store, context, opts \\ [])

@spec issue(module(), context(), keyword()) ::
  {:ok, issued()} | {:error, issue_error()}

Issue a refresh token for context and persist it via store.

context MUST carry :subject; optional :scope (list, default []), :client_id, :issuer (the exact authorization-server issuer), :dpop_jkt (binds the token to a DPoP key), :attestation_jkt (the verified Client Instance Key), and :claims (a lossless, string-keyed I-JSON object of host context; persisted numbers are exact-range integers, not floats).

Options: :ttl (idle seconds, default 14 days), :family_ttl (optional positive seconds, fixing the entire family's maximum lifetime), and :now. The family deadline is stored as :family_expires_at in the canonical context and caps the initial token as well as every successor. Public issuance always starts a fresh family at generation 0; only rotate/3 can create a later generation, through the store's atomic rotation transaction.

Returns {:ok, %{token, family_id, generation}} with the plaintext token to hand the client (only its hash is stored), or {:error, reason} on malformed context. A store may very rarely return {:error, :family_revoked} if a freshly generated family identifier collides with one of its retained revocation markers.

rotate(store, presented_token, opts \\ [])

@spec rotate(module(), String.t(), keyword()) ::
  {:ok, rotated()} | {:error, rotate_error()}

Rotate a presented refresh token: consume it and mint its successor.

On success returns {:ok, %{token, family_id, generation, context}} where token is the new refresh token, generation is the successor's generation, and context is the grant context to mint this request's access token from: its :scope and :resource are the values resolved from the :scope and :resource options below. The new refresh token itself keeps the presented token's full scope and resource set.

If the presented token was already rotated, an immediate retry by the same client and binding returns the original successor within :rotation_grace_seconds, with a context for the retry's own requested scope and resource; otherwise the whole family is revoked and {:error, :reuse_detected} is returned. Other failures include :invalid_grant (unknown token), :expired, :grant_revoked, :temporarily_unavailable, :client_mismatch, :issuer_mismatch, :invalid_scope, :invalid_target, and the DPoP binding errors.

Options:

  • :now - clock override.
  • :dpop_jkt - the presented proof's thumbprint (for DPoP-bound tokens).
  • :attestation_jkt - the authenticated Client Instance Key thumbprint, required for an attestation-bound family independently of its DPoP key.
  • :client_id - the authenticated presenting client. When the token was issued with a client_id, rotation is fail-closed: it MUST present a matching one (:client_required if absent, :client_mismatch if wrong), closing token substitution across clients (RFC 6749 §6 / §10.4). Pass allow_missing_client_id?: true to opt out. A token issued without a client binding skips the check.
  • :issuer - the authorization server expected to have issued this refresh family. When supplied, it must exactly match the bounded HTTPS issuer saved at issuance. A different issuer, or a legacy token with no issuer binding, returns :issuer_mismatch without consuming an unconsumed token or revoking a consumed token's family. Omitting this option preserves legacy behavior.
  • :scope - a requested scope list. MUST be a subset of the token's granted scope; the returned context then carries the requested scope for the access token, while the successor refresh token keeps the full granted scope (RFC 6749 §6). A request for any scope not granted is :invalid_scope (no escalation). Omitted, context carries the full granted scope.
  • :resource - a requested resource list. MUST be a subset of the token's granted resource set; the returned context then carries the requested resources for the access token's audience, while the successor stays bound to the full set (RFC 8707 §2.2). A resource not granted is :invalid_target. Omitted, context carries the full granted set.
  • :ttl - lifetime for the successor.
  • :rotation_grace_seconds - non-negative integer idempotency window for an immediate retry of the just-rotated token. Defaults to 10; set 0 for strict reuse revocation. The window is fixed when the successor is issued: a later call may shorten it, but cannot extend it.

Recoverable failures (:client_mismatch, :issuer_mismatch, :invalid_scope, :expired, the DPoP binding errors) are checked on a non-consuming read before the token is claimed, so they do NOT burn the token: a client that, say, retries with a corrected DPoP proof succeeds rather than tripping reuse detection. Issuer mismatch is also checked before retry/reuse handling for an already-consumed token, so a request routed to a different issuer cannot revoke the legitimate issuer's family. An already-consumed token is accepted only when its complete successor state proves it is the same request inside the fixed retry window.

The parent claim, child insert, and retry-state persistence are one atomic Attesto.RefreshStore.rotate/4 operation. Simultaneous matching requests therefore coalesce on the winner's complete committed successor instead of observing a partially rotated family.

A store's documented {:error, :invalid_rotation} result means validation rejected the proposed transition before committing any mutation. It is reported as {:error, :temporarily_unavailable} with revocation: :not_attempted; adapters MUST use that result only when they can prove the transaction rolled back. Callback exceptions or ambiguous unexpected returns still trigger family cleanup because they may have committed.

When the store implements Attesto.RefreshStore.with_family_lock/2, retry recovery re-reads the parent and successor under the same family lock as rotation and revocation. A revocation that wins the lock prevents recovery. This does not make the later network response atomic with revocation or invalidate access tokens already minted.

A get/1 exception or contract violation emits the operational [:attesto, :refresh_token, :rotation_state_failed] event with operation: :lookup. The original callback exception or constant contract error is preserved. If a malformed returned record still binds the presented token hash to a non-empty family ID, that family is revoked before the contract error is raised; an untrusted or absent family is never used for cleanup.