# `AttestoClient.ResourceServer`
[🔗](https://github.com/XukuLLC/attesto_client/blob/v2.26.0/lib/attesto_client/resource_server.ex#L1)

Verify JWT access tokens issued by a remote OAuth authorization server.

A resource server starts one supervised process per trusted issuer. The
process discovers the issuer's JWKS, retains a bounded key set, coordinates
refreshes, and permits a configured stale-key interval when a transient
upstream failure prevents refresh. Signature and claim verification happens
in the caller process; the server process only owns cache state and refresh
coordination.

The process is an `AttestoClient.Issuer` cache that also carries this
module's token policy, so there is one cache and one refresh logic for both.
Its name can be given as `issuer: {AttestoClient.Issuer, name}` to verify ID
Tokens from the same issuer against the same keys.

## Security properties

  * discovery metadata must report the configured issuer exactly;
  * metadata and JWKS are fetched only over HTTPS with redirects disabled;
  * signing algorithms are an explicit allowlist and are never learned from
    the presented token;
  * a `kid` selects exactly one eligible verification key, and RSA keys below
    2048 bits are rejected;
  * RFC 9068 `typ`, issuer, audience, time, identity, client, JWT ID, and scope
    claims are checked;
  * an unknown `kid` causes at most one coordinated refresh per cache
    generation and refresh interval, preventing request fan-out and random
    `kid` refresh storms;
  * stale keys are used only within the configured stale interval and only
    after transient transport, 429, or 5xx refresh failures; every refresh
    failure receives a retry cooldown so a persistent hard failure cannot
    make every token verification wait on the issuer;
  * DPoP and mTLS confirmation claims fail closed unless the matching verified
    proof-key or certificate thumbprint is supplied.

The module authenticates tokens and can require exact OAuth scope tokens. It
does not decide which subjects may perform an application action, map claims
to local users, or retain sessions; those remain application policy.

## Example

    children = [
      {AttestoClient.ResourceServer,
       name: MyApp.RemoteIssuer,
       issuer: "https://issuer.example",
       audience: "https://api.example",
       accepted_algs: ["PS256", "ES256"],
       fresh_ttl: :timer.minutes(5),
       stale_ttl: :timer.hours(1),
       refresh_retry_interval: :timer.seconds(5),
       max_response_bytes: 512 * 1024}
    ]

    :ok = AttestoClient.ResourceServer.warm(MyApp.RemoteIssuer)

    {:ok, claims} =
      AttestoClient.ResourceServer.verify(MyApp.RemoteIssuer, access_token,
        required_scopes: ["documents.read"]
      )

`fresh_ttl` and `stale_ttl` are milliseconds. `stale_ttl` starts when the
fresh interval ends. `refresh_retry_interval` avoids retrying a failed
upstream refresh on every request. During that interval, a transient failure
may use a still-valid stale snapshot; a hard failure or an exhausted stale
interval returns the remembered refresh error without another fetch. The
same applies before the first successful refresh: verification returns the
remembered error until the interval ends, while `warm/1` and `refresh/1`
still fetch.

`clock_skew_seconds` bounds how far in the future `iat` and `nbf` may lie,
and widens `:max_token_age_seconds`; it defaults to `60`.
`expiry_leeway_seconds` is how long past `exp` a token is still accepted
(RFC 7519 §4.1.4): an integer from `0` to `300`, default `0`, so an expired
token is rejected at `exp`. `AttestoClient.IDToken.verify/2` takes the same
two options with the same meanings.

`:outbound` names deliberate exceptions to the HTTPS and public-address
rules for the metadata and JWKS fetches: an issuer at a private address, or
a loopback `http` issuer in development. See `AttestoClient.Outbound`.
`:resolver` is a two-argument function used to resolve host names for those
fetches; every address it returns is screened the same way.

# `error`

```elixir
@type error() ::
  :invalid_token
  | :invalid_signature
  | :ambiguous_key
  | :weak_key
  | :unsupported_alg
  | :unsupported_critical_header
  | :unexpected_typ
  | :invalid_issuer
  | :invalid_audience
  | :expired
  | :not_yet_valid
  | :invalid_claims
  | :invalid_scope
  | :insufficient_scope
  | :subject_not_allowed
  | :client_not_allowed
  | :token_too_old
  | :token_lifetime_exceeded
  | :invalid_policy
  | :unsupported_confirmation
  | :dpop_proof_required
  | :dpop_proof_unexpected
  | :dpop_key_mismatch
  | :mtls_certificate_required
  | :mtls_certificate_mismatch
  | {:jwks_refresh_failed, term()}
```

# `jwks`

```elixir
@type jwks() :: %{optional(String.t()) =&gt; term()} | [map()] | map()
```

# `server`

```elixir
@type server() :: GenServer.server()
```

# `start_opt`

```elixir
@type start_opt() ::
  {:name, GenServer.name()}
  | {:issuer, String.t()}
  | {:audience, String.t() | [String.t()]}
  | {:accepted_algs, [Attesto.SigningAlg.alg()]}
  | {:well_known, AttestoClient.Discovery.well_known()}
  | {:metadata, map()}
  | {:jwks_uri, String.t()}
  | {:req_options, keyword()}
  | {:fresh_ttl, non_neg_integer()}
  | {:stale_ttl, non_neg_integer()}
  | {:unknown_kid_refresh_interval, non_neg_integer()}
  | {:refresh_retry_interval, non_neg_integer()}
  | {:refresh_timeout, pos_integer()}
  | {:clock_skew_seconds, non_neg_integer()}
  | {:expiry_leeway_seconds, 0..300}
  | {:max_jwks_keys, pos_integer()}
  | {:max_response_bytes, pos_integer()}
  | {:outbound, AttestoClient.Outbound.t()}
  | {:resolver,
     (charlist(), :inet | :inet6 -&gt;
        {:ok, [:inet.ip_address()]} | {:error, term()})}
```

# `verify_opt`

```elixir
@type verify_opt() ::
  {:required_scopes, [String.t()]}
  | {:allowed_subjects, [String.t()]}
  | {:allowed_client_ids, [String.t()]}
  | {:max_token_age_seconds, non_neg_integer()}
  | {:max_token_lifetime_seconds, pos_integer()}
  | {:now, integer() | DateTime.t()}
  | {:dpop_jkt, String.t()}
  | {:mtls_cert_thumbprint, String.t()}
```

# `child_spec`

# `ready?`

```elixir
@spec ready?(server()) :: boolean()
```

Return whether the verifier retains a currently usable key snapshot.

# `refresh`

```elixir
@spec refresh(server()) :: :ok | {:error, {:jwks_refresh_failed, term()}}
```

Force a metadata/JWKS refresh.

# `start_link`

```elixir
@spec start_link([start_opt()]) :: GenServer.on_start()
```

Start a supervised remote-issuer verifier.

# `verify`

```elixir
@spec verify(server(), String.t(), [verify_opt()]) :: {:ok, map()} | {:error, error()}
```

Verify a remote issuer's JWT access token.

`:required_scopes` is an optional list of exact RFC 6749 scope tokens. Every
listed scope must occur in the token's space-delimited `scope` claim.
`:allowed_subjects`, `:allowed_client_ids`, `:max_token_age_seconds`, and
`:max_token_lifetime_seconds` provide optional authentication policy bounds.
Sender-constrained tokens additionally require the verified `:dpop_jkt` or
`:mtls_cert_thumbprint` from the current request.

# `warm`

```elixir
@spec warm(server()) :: :ok | {:error, {:jwks_refresh_failed, term()}}
```

Warm the verifier by completing metadata/JWKS retrieval.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
