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

Fetch and read OAuth 2.0 / OpenID Connect authorization-server metadata
(RFC 8414 / OpenID Connect Discovery 1.0) and OAuth 2.0 protected resource
metadata (RFC 9728).

A thin lookup: it fetches the discovery document (and, separately, the JWKS)
and returns the parsed JSON. It runs no flow and holds no state - the host
reads the endpoint URLs and capabilities it needs (and, for verifying JARM
responses, passes the fetched JWKS to `AttestoClient.JARM.verify/3`).

## Protected resources

A resource server names the authorization servers that issue its tokens in
its RFC 9728 metadata. `fetch_resource/2` reads that document for a resource
identifier, and `authorization_server/2` follows it to the issuer's own
metadata, so a client that knows only the resource URL, or has just received
its `WWW-Authenticate` challenge, reaches the authorization and token
endpoints without being configured with the issuer. The same transport
rules below apply to those requests.

## URL construction

By default the OpenID Connect Discovery document is fetched by appending
`/.well-known/openid-configuration` to the issuer (OpenID Connect Discovery
1.0 §4). Pass `well_known: :oauth_authorization_server` for the RFC 8414
document, which is constructed differently: the well-known segment is inserted
**before** the issuer's path component (RFC 8414 §3.1), so it is correct for
path-based (multi-tenant) issuers.

Connect failures are retried up to three times within the overall deadline,
with a three-second per-attempt cap (override through `:req_options`'s
`:connect_options` `:timeout`). `{:error, :not_sent}` means the failed request
never started and no earlier state-changing request in the call was written.
Earlier GET/HEAD requests do not count. This includes deadline expiry during
connect. Other transport
failures retain `{:error, {:transport, reason}}`; they may follow a sent
request. No transport retry occurs after sending starts.

## Issuer / transport validation

  * The issuer MUST be an `https` URL with no query or fragment (RFC 8414 §2).
  * The document's own `issuer` member MUST be **identical** to the issuer it
    was fetched for (RFC 8414 §3.3 / OpenID Connect Discovery 1.0 §4.3),
    defending against a metadata mix-up. The comparison is exact - no
    trailing-slash normalisation - so a path-based issuer that ends in `/`
    (e.g. a multi-tenant issuer) must be supplied exactly as the server
    publishes it. A trailing slash is removed only when constructing the
    well-known request URL, as both specs require.
  * A JWKS is fetched only over `https`, since it is the trust root for
    verifying the authorization server's signatures.

## HTTP

Requests go through [`Req`](https://hex.pm/packages/req). Pass `:req_options`
for safe transport configuration - notably `plug:` for `Req.Test` in tests.
The library owns the destination, method, authority, redirects, request body,
cache policy, and TLS peer identity; conflicting options are removed or fail
closed. Discovery and JWKS requests never carry caller credentials. Their
overall deadline includes DNS screening and request preparation, not only the
socket receive phase.

# `error`

```elixir
@type error() ::
  :invalid_issuer
  | :invalid_well_known
  | :invalid_jwks_uri
  | :issuer_mismatch
  | :invalid_metadata
  | :invalid_resource
  | :invalid_metadata_url
  | :invalid_resource_well_known
  | :resource_mismatch
  | :no_authorization_server
  | :unadvertised_authorization_server
  | {:select_authorization_server, [String.t()]}
  | :response_too_large
  | :blocked_host
  | :unsafe_transport_options
  | :invalid_timeout
  | :invalid_resolver
  | :invalid_outbound
  | :not_sent
  | :transport_error
  | :timeout
  | {:http_status, pos_integer()}
  | {:transport, term()}
```

# `opt`

```elixir
@type opt() ::
  {:well_known, well_known()}
  | {:req_options, keyword()}
  | {:max_response_bytes, pos_integer()}
  | {:timeout, pos_integer()}
  | {:resolver,
     (charlist(), :inet | :inet6 -&gt;
        {:ok, [:inet.ip_address()]} | {:error, term()})}
  | {:metadata_url, String.t()}
  | {:resource_well_known, :path | :root | :path_then_root}
  | {:www_authenticate, String.t() | [String.t()]}
  | {:issuer, String.t()}
  | {:outbound, AttestoClient.Outbound.t()}
```

# `resolution`

```elixir
@type resolution() :: %{
  resource: map(),
  issuer: String.t(),
  authorization_server: map()
}
```

A protected resource's metadata, the issuer selected from it, and that issuer's metadata.

# `well_known`

```elixir
@type well_known() :: :openid_configuration | :oauth_authorization_server
```

# `authorization_server`

```elixir
@spec authorization_server(String.t(), [opt()]) ::
  {:ok, resolution()} | {:error, error()}
```

Find the authorization server for a protected resource and fetch its
metadata.

Reads the resource's RFC 9728 metadata with `fetch_resource/2`, selects an
issuer from its `authorization_servers`, and fetches that issuer's metadata
with `fetch/2`. Returns `{:ok, %{resource: resource_metadata, issuer: issuer,
authorization_server: issuer_metadata}}`, where the issuer metadata carries
the `authorization_endpoint` and `token_endpoint` to use, or
`{:error, reason}`.

Options, in addition to those of `fetch_resource/2` and `fetch/2`:

  * `:www_authenticate` - the `WWW-Authenticate` value(s) of the 401 or 403
    response that prompted discovery. A challenge advertising a valid
    `resource_metadata` URL supplies `:metadata_url`; otherwise the
    well-known location derived from `resource` is used. An explicit
    `:metadata_url` takes precedence.
  * `:issuer` - the issuer to use when the resource advertises more than
    one. It must be among them.
  * `:resource_well_known` - `:path_then_root` tries the path-specific
    resource document first and the origin-root document only after a 404.
    At that compatibility location the document may identify the requested
    resource or its exact origin; the returned document remains
    authoritative for the resource identifier.
  * `:well_known` - which issuer document to fetch. Without it, metadata
    candidates are tried in interoperability order: RFC 8414 path insertion,
    OpenID Connect path insertion, then OpenID Connect path appending. A
    candidate is skipped only when it returns 404.

Errors are `:no_authorization_server` when the resource advertises none,
`{:select_authorization_server, issuers}` when it advertises several and no
`:issuer` was given, `:unadvertised_authorization_server` when the given
`:issuer` is not among them, and those of `fetch_resource/2` and `fetch/2`.
`:timeout` bounds each HTTP request separately.

# `fetch`

```elixir
@spec fetch(String.t(), [opt()]) :: {:ok, map()} | {:error, error()}
```

Fetch the authorization server's metadata for `issuer`, returning
`{:ok, metadata}` (a string-keyed map) or `{:error, reason}`.

`issuer` must be an `https` URL with no query or fragment. Options:
`:well_known` (`:openid_configuration` (default) or
`:oauth_authorization_server`) and `:req_options` (safely merged into the Req
transport configuration as described above). `:timeout` is the overall
discovery deadline in milliseconds, including DNS resolution and request
preparation (default: 10 seconds). `:outbound` names deliberate exceptions
to the HTTPS and public-address rules (`AttestoClient.Outbound`); every
function in this module that takes options takes it.

# `fetch_jwks`

```elixir
@spec fetch_jwks(String.t(), [opt()]) :: {:ok, map()} | {:error, error()}
```

Fetch a JWKS document from `jwks_uri` (typically the metadata's `jwks_uri`),
returning `{:ok, jwks}` - a map with a `"keys"` list - or `{:error, reason}`.
The URI must be `https`.

# `fetch_resource`

```elixir
@spec fetch_resource(String.t(), [opt()]) :: {:ok, map()} | {:error, error()}
```

Fetch the RFC 9728 protected resource metadata for `resource`, returning
`{:ok, metadata}` (a string-keyed map) or `{:error, reason}`.

`resource` is the resource identifier: an `https` URL with no fragment
(RFC 9728 §1.2). Explicit `outbound: [allow_loopback_http: true]` also permits
a loopback HTTP resource during local development. Without a `:metadata_url`,
the document is requested from
the well-known location derived from it (§3.1): the
`/.well-known/oauth-protected-resource` segment is inserted between the host
and the path, after any terminating slash is removed, so
`https://rs.example/mcp` reads
`https://rs.example/.well-known/oauth-protected-resource/mcp`. A query
component is kept.

Options:

  * `:metadata_url` - the URL a `WWW-Authenticate` challenge advertised in
    its `resource_metadata` parameter (§5.1);
    `AttestoClient.WWWAuthenticate.resource_metadata/1` reads it from the
    header. It must be an `https` URL without userinfo or fragment. A
    loopback HTTP pointer is accepted only for a loopback resource under the
    explicit loopback outbound exception; CIDR exceptions remain forbidden
    for challenge-selected URLs.
  * `:resource_well_known` - `:path` (the default) for the path-specific
    RFC 9728 location, or `:root` for the resource origin's root location.
    `authorization_server/2` also accepts `:path_then_root`, which retries at
    the root only when the path-specific resource document returns 404.
    `fetch_resource/2` itself always selects one location.
  * `:req_options`, `:timeout`, `:max_response_bytes`, and `:resolver` - as
    for `fetch/2`.

The document's `resource` member must be identical to `resource` (§3.3,
§7.3) whichever URL it was fetched from; otherwise the document is not used
and the result is `{:error, :resource_mismatch}`. Every member of
`authorization_servers` must be a valid issuer identifier (RFC 8414 §2),
`jwks_uri` must be `https`, and the other registered members are
type-checked; a violation is `{:error, :invalid_metadata}`. Unregistered
members are kept (§3.2).

# `validate_endpoint`

```elixir
@spec validate_endpoint(
  term(),
  keyword()
) ::
  :ok
  | {:error,
     :invalid_endpoint
     | :blocked_host
     | :invalid_resolver
     | :invalid_outbound
     | :unsafe_transport_options}
```

Preflight an authorization-server endpoint against the URL and address
policy. The endpoint must use HTTPS, must not contain userinfo or a fragment,
and must not resolve to a private, loopback, or link-local address, except
as an `:outbound` option allows (`AttestoClient.Outbound`).

This check does not bind a later, separate socket connection to the address
it inspected, so it is not by itself a complete SSRF defense. Prefer this
library's request APIs, which carry the screened address through to the
transport while retaining the original hostname for TLS and HTTP authority.

Applications normally use this indirectly through the authorization-code,
refresh, and revocation APIs.

# `validate_metadata`

```elixir
@spec validate_metadata(term(), term(), keyword()) :: {:ok, map()} | {:error, term()}
```

Validate an authorization-server metadata `document` for `issuer`, as
`AttestoClient.AuthorizationCode.start/2` does before it uses one.

`fetch/2` checks that a document was retrieved safely and names the expected
issuer. This checks that it describes a server this library can run an
authorization-code flow against: the required endpoints are present and
HTTPS, the advertised lists are well-formed and include `code` and (when
listed) `S256`, and no request endpoint carries a protocol parameter in its
own query. It is the same function `start/2` calls, so a document accepted
here is not refused there for its content. `start/2` can still refuse it for
a reason that depends on the client's options, such as an ID Token signing
algorithm the document does not list.

Options:

  * `:protocol` - `:oidc` (the default) for OpenID Provider metadata
    (OpenID Connect Discovery §3, §4.3), or `:oauth` for RFC 8414
    authorization-server metadata, which need not carry `jwks_uri` or the
    OpenID-only members. The values are the ones `start/2` takes.
  * `:outbound` - the exceptions `start/2` will be given
    (`AttestoClient.Outbound`); with `allow_loopback_http: true` a loopback
    issuer and its loopback `http` endpoints are accepted.

Returns `{:ok, document}`, or `{:error, reason}` with the reason `start/2`
would give: `:invalid_issuer`, `:issuer_mismatch`, `:invalid_metadata`,
`:invalid_endpoint`, or an endpoint-query error. An unknown `:protocol` is
`{:error, :invalid_protocol}`, and a malformed `:outbound` is
`{:error, :invalid_outbound}`.

---

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