Attesto.Plug.Authenticate (Attesto v2.28.0)

Copy Markdown View Source

Authenticate a protected-resource request: verify the access token and, for a DPoP-bound or mTLS-bound token, the sender-constraint proof.

A thin wrapper over the pure verifiers (Attesto.Token, Attesto.DPoP, Attesto.MTLS). It does the HTTP-specific work - parsing the Authorization and DPoP headers, building the htu, computing the client-certificate thumbprint via a host callback, wiring the replay and nonce checks - then delegates every decision to the engine and assigns the verified claims onto the conn.

Options

  • :config (required) - an Attesto.Config, a zero-arity function, or an MFA tuple ({module, function} / {module, function, args}) returning one.

  • :verify - optional token-verification callback. It receives (config, token, verify_opts) and must return {:ok, claims} with a plain claims map, {:error, reason} for invalid_token, {:error, :insufficient_scope} for a 403 response, or {:error, {:temporarily_unavailable, reason}} / {:error, {:jwks_refresh_failed, reason}} for a generic 503 response. Function and MFA forms are accepted. Omit it to use Attesto.Token.verify/3. These tagged failures let a client-side resource server reuse this HTTP/DPoP/mTLS pipeline with a remote-issuer verifier without turning an issuer-key outage into a client error.

  • :required_scopes - scope strings named in the 403 challenge when a custom :verify callback returns {:error, :insufficient_scope}.

  • :replay_check - the DPoP :replay_check callback ((jti, ttl) -> :ok | {:error, :replay}), e.g. &Attesto.DPoP.ReplayCache.check_and_record/2. Required for DPoP: without it, RFC 9449 §11.1 replay rejection is off and a captured proof can be replayed within the iat window. This plug therefore fails closed - a DPoP request is rejected (401 invalid_dpop_proof, replay_check_unconfigured) unless :replay_check is wired, so an unprotected DPoP endpoint cannot silently ship. Bearer/mTLS requests are unaffected. A host that knowingly accepts unprotected DPoP sets dpop_replay_unprotected_acknowledged?: true to opt out.

  • :dpop_replay_unprotected_acknowledged? - set to true to allow DPoP requests through WITHOUT :replay_check, accepting that captured proofs are replayable. Off by default (fail closed).

  • :nonce_check - the DPoP :nonce_check callback ((nonce | nil) -> :ok | {:error, :use_dpop_nonce}).

  • :nonce_issue - a zero-arity function returning a fresh DPoP nonce for the use_dpop_nonce challenge (required if :nonce_check is set), e.g. &Attesto.DPoP.NonceStore.ETS.issue/0.

  • :cert_der - (conn -> der_binary | nil); the DER of the client certificate the TLS layer authenticated. TLS termination varies, so the host supplies it. When it returns a certificate, its RFC 8705 thumbprint is handed to Attesto.Token.verify/3.

  • :trusted_audiences - a non-empty list of trusted audience identifiers, or a one-arity resolver returning that list, forwarded unchanged to Attesto.Token.verify/3. Configure this per protected resource when it accepts RFC 8707 resource-audienced tokens. An explicit list or resolver replaces the configured-audience policy, so include config.audience when it should remain accepted. When absent, the configured single-audience behavior is unchanged. Resolver safety and fail-closed semantics are documented on Attesto.Token.verify/3.

  • :origin - the external origin of this resource server as clients address it, such as "https://api.example" or "https://api.example:8443": an https URL with a host, an optional port, and no path, userinfo, query, or fragment. The DPoP htu a proof must sign is then this origin followed by conn.request_path, and the request's scheme, Host header, and port are not used. Set it on every resource server that accepts DPoP-bound tokens; see "Choosing the DPoP target URI" below. Mutually exclusive with :htu.

  • :htu - (conn -> https_uri_string) building the request URI (without query/fragment) a DPoP proof must sign, for a resource server that answers on several origins or whose proxy rewrites the request path. Build it from configured origins, not from request headers. Mutually exclusive with :origin.

  • :credential_from_conn - optional fallback (conn -> {:ok, :bearer | :dpop, token} | :missing). Use this for host-owned credential channels such as first-party cookies. The standard Authorization header remains authoritative when present; this callback is consulted only when no usable header credential is present.

  • :bearer_methods - standard RFC 6750 Bearer-token presentation methods this resource server accepts. Allowed values are :header / "header" (RFC 6750 §2.1 Authorization: Bearer) and :body / "body" (RFC 6750 §2.2 form-body access_token). Defaults to [:header]. Add :body only when the protected-resource metadata advertises body support and the deployment accepts the logging, caching, retry, and replay risks of credentials in request bodies. The URI-query method is intentionally unsupported. This setting does not disable Authorization: DPoP, mTLS binding, or a host-owned :credential_from_conn fallback.

  • :claims_key - the conn.assigns key the verified claims are put under (default :attesto_claims).

  • :send_error, :www_authenticate, :no_store - optional transport hooks forwarded to Attesto.Plug.OAuthError so a host can keep its own JSON error envelope while Attesto owns the RFC status/challenge semantics.

  • :resource_metadata - the URL of this resource's protected-resource metadata (RFC 9728), or a (conn -> url) / MFA callback resolving it. The URL is advertised as a resource_metadata auth-param on every 401 WWW-Authenticate challenge (RFC 9728 §5.1) so a refused client can discover the authorization server.

  • :allow_http - permits an HTTP :resource_metadata URL for deliberate development use. Defaults to false.

    plug Attesto.Plug.Authenticate, config: &MyApp.Attesto.config/0, origin: "https://api.example", replay_check: &MyApp.DPoPReplay.check_and_record/2, cert_der: &MyApp.TLS.client_cert_der/1

Choosing the DPoP target URI

RFC 9449 §4.3 binds a proof to the URI of the request it was made for, so that a proof sent to one server cannot be replayed to another. That holds only if the URI a proof is compared against names this server whatever the request says, so :origin or :htu is required whenever DPoP is enabled. Without a pinned target URI, conn.host comes from the client's Host header and the scheme and port can differ behind a TLS-terminating proxy, so a resource server with no pin refuses to start unless DPoP is disabled (by omitting :replay_check without dpop_replay_unprotected_acknowledged?: true).

Set :origin to the origin clients use. Use :htu instead when the resource server answers on several origins or behind a path-rewriting proxy.

Summary

Functions

Whether a plug built from opts can accept a DPoP-scheme request.

Classify an OAuth HTTP error response (status and decoded body map) into a bounded telemetry outcome atom.

Resolve the expected DPoP htu from conn and plug opts without consulting Host.

Validate and normalize plug options.

Compute the expected DPoP htu by joining a pinned origin and request_path.

Parse an HTTP Authorization header value into {:ok, :bearer | :dpop, token} or :malformed. Trims whitespace around the credential.

Token verification failure descriptions corresponding to sender-constraint mismatches.

Functions

accepts_dpop?(opts)

@spec accepts_dpop?(keyword()) :: boolean()

Whether a plug built from opts can accept a DPoP-scheme request.

It can when :replay_check is a 2-arity function or dpop_replay_unprotected_acknowledged?: true is set. Without either, every DPoP request is refused with replay_check_unconfigured, so the resource accepts Bearer (and mTLS-bound) tokens only.

Resource metadata uses this to decide whether to advertise dpop_signing_alg_values_supported (RFC 9728 §2), so the advertisement and the plug's behavior come from the same rule.

classify_refusal(status, body)

@spec classify_refusal(integer(), term()) :: atom()

Classify an OAuth HTTP error response (status and decoded body map) into a bounded telemetry outcome atom.

expected_htu(conn, opts)

@spec expected_htu(
  Plug.Conn.t(),
  keyword()
) :: {:ok, String.t()} | {:error, :invalid_http_uri}

Resolve the expected DPoP htu from conn and plug opts without consulting Host.

normalize_options(opts, init_opts \\ [])

@spec normalize_options(keyword(), keyword()) :: keyword()

Validate and normalize plug options.

Wrapper plugs that enforce their own boot-time DPoP origin policy and inject :htu per request (such as AttestoMCP.Plug.Authenticate) pass require_dpop_pin?: false so initialization still validates every option without requiring a static :origin or literal :htu callback up front.

origin_htu(origin, request_path)

@spec origin_htu(String.t(), String.t()) :: String.t()

Compute the expected DPoP htu by joining a pinned origin and request_path.

parse_authorization(value)

@spec parse_authorization(term()) :: {:ok, :bearer | :dpop, String.t()} | :malformed

Parse an HTTP Authorization header value into {:ok, :bearer | :dpop, token} or :malformed. Trims whitespace around the credential.

sender_constraint_reasons()

@spec sender_constraint_reasons() :: [String.t()]

Token verification failure descriptions corresponding to sender-constraint mismatches.