AttestoPhoenix.Interaction (AttestoPhoenix v5.0.0)

Copy Markdown View Source

Park an authorization request while the End-User authenticates or grants consent, and resume it afterwards.

When :authenticate_resource_owner has to send the End-User to a login page (no session, prompt=login, or an authentication older than max_age), the host needs a way back to the same authorization request. park/2 stores the request and returns a resume_id; the host redirects to its login page with that id and, once the End-User has authenticated, sends the browser to the authorization endpoint with ?resume=<resume_id> and nothing else.

def authenticate_resource_owner(conn, request, auth_opts) do
  case current_session(conn, auth_opts) do
    {:ok, subject} ->
      {:authenticated, subject}

    :login_needed ->
      case AttestoPhoenix.Interaction.park(conn, request) do
        {:ok, resume_id} -> {:halt, redirect(conn, to: "/login?resume=" <> resume_id)}
        {:error, _reason} -> {:error, :temporarily_unavailable}
      end
  end
end

When the store cannot take the request, park/2 returns {:error, reason}. Return {:error, :temporarily_unavailable} (or {:error, :server_error}) from either callback: the client receives that RFC 6749 §4.1.2.1 code by redirect.

What a resume does

The authorization endpoint takes the parked request out of the store and runs it as it would a fresh request with the same parameters: the client is loaded again, the request is validated again, the scope policy runs again. Authentication and consent are checked again. The host's :authenticate_resource_owner then receives auth_opts.resumed: true, auth_opts.parked_at and auth_opts.prompt_login_since (Unix seconds). When the original request included prompt=login, the returned auth_time must be at or after prompt_login_since. An older, missing or invalid time is a host contract violation: it is logged and returned as server_error. The host must supply an authentication satisfying the recorded bound. Both host callbacks can use request_params/1 to read the original parameters; conn.params still describes the HTTP request containing only resume.

From :consent, park with the authenticated OIDC sub and redirect to the host's consent page with an encrypted view_token/2 handle. On resume, use consent_decision/3 against the newly validated request and authenticated subject:

def consent(conn, request, subject) do
  case AttestoPhoenix.Interaction.consent_decision(conn, request, subject) do
    :allow ->
      {:consented, subject}

    :deny ->
      {:denied, :user_denied}

    nil ->
      case AttestoPhoenix.Interaction.park(conn, request, subject: subject.subject) do
        {:ok, resume_id} ->
          token = AttestoPhoenix.Interaction.view_token(conn, resume_id)
          {:halt, redirect(conn, to: "/consent?" <> URI.encode_query(%{"view" => token}))}

        {:error, _reason} ->
          {:error, :temporarily_unavailable}
      end
  end
end

The host consent controller reads the parked request without consuming it, and renders it only for the signed-in subject it was parked for:

def consent_page(conn, %{"view" => token}) do
  conn = put_resp_header(conn, "referrer-policy", "strict-origin")

  case get_session(conn, :subject) do
    subject_id when is_binary(subject_id) ->
      case AttestoPhoenix.Interaction.pending(conn, token, subject: subject_id) do
        {:ok, pending} ->
          render(conn, :consent, resume_id: pending.resume_id, request: pending.request)

        {:error, :invalid_resume} ->
          send_resp(conn, 400, "Invalid consent request")
      end

    _signed_out ->
      conn
      |> put_session(:return_to, current_path(conn))
      |> redirect(to: "/login")
  end
end

The page can be reloaded until the decision is recorded and the request resumes. With subject:, pending/3 returns the request only when it was parked for that subject, so one account on a shared browser is not shown a request parked by another; decide/4 refuses the mismatch as well. Without the option it answers the browser that parked the request whether or not anyone is signed in there, so the controller reads the host session first and always passes the subject it finds. A browser whose sign-in has ended goes to the host's sign-in with the consent URL as the return path. After sign-in the page renders again, for as long as the parked request has not expired (:interaction_ttl) and the browser binding is unchanged. Never store the decision POST as a return path. Both host routes need the fetched session, browser binding and configuration plugs. The endpoint supplies conn.secret_key_base to seal the handle; a route without it raises. Keep the resume id out of the consent URL, and set Referrer-Policy: strict-origin on the page.

A host using pairwise subject identifiers may need the client id before it can derive the signed-in user's subject. Pass a one-argument function as subject: to pending/3 and as subject_id to decide/4. The function receives the parked request's client id and returns the subject for that client. It runs only for a live entry found for this browser, after the cross-origin check in decide/4; its result must match the parked subject.

The page POSTs the resume id and Allow/Deny choice to a host handler with a fetched session, the AttestoPhoenix.Interaction.BrowserBinding plug and AttestoPhoenix.Plug.PutConfig, as on the authorization route. Read the current authenticated subject from the host session, never from the form:

def record_consent(conn, %{"resume" => resume_id, "decision" => choice}) do
  subject_id = get_session(conn, :subject)

  decision = case choice do
    "allow" -> :allow
    "deny" -> :deny
    _ -> nil
  end

  if decision in [:allow, :deny] and is_binary(subject_id) do
    case AttestoPhoenix.Interaction.decide(conn, resume_id, decision, subject_id) do
      :ok -> redirect(conn, to: "/oauth/authorize?" <> URI.encode_query(%{"resume" => resume_id}))
      {:error, :invalid_resume} -> send_resp(conn, 400, "Invalid consent request")
      {:error, :cross_origin} -> send_resp(conn, 403, "Cross-origin consent request")
    end
  else
    send_resp(conn, 400, "Invalid consent request")
  end
end

Use the host's configured authorization path and return with ?resume=<resume_id> only.

Cross-site request forgery: the resume id is a random synchronizer token, bound to the browser and subject and held server-side. decide/4 also requires exactly one Origin header equal to the configured issuer's origin. Missing, null, and other origins are refused before reading the store. A present Sec-Fetch-Site must be same-origin. Use same_origin_request?/1 in a host's logout-confirmation handler to apply the same rule. The consent page and handler can additionally run :protect_from_forgery; include the host's CSRF token when they do. Serve the page and handler from the issuer's origin, including in development. Set Referrer-Policy: strict-origin on the page so the browser can send its origin while keeping path and query out of Referer. The authorization endpoint itself accepts cross-site POST requests (OIDC Core §3.1.2.1).

The library ships no POST controller because the session, the subject and the page belong to the host. Protect the consent page against clickjacking with a Content-Security-Policy frame-ancestors directive appropriate for the host (for example, frame-ancestors 'none').

No separate AttestoPhoenix.ConsentGrant is needed for this flow. The decision lives on the single-use parked entry: its key binds it to the browser, decide/4 and consent_decision/3 bind it to the subject, and the stored consent binding hash binds it to the request. The accessor recomputes that hash from the resumed validated request, covering the client, redirect URI, effective scope, resource, PKCE challenge and method, claims, DPoP key, and authorization details (all AttestoPhoenix.ConsentGrant.binding/2 fields; RFC 6749 §4.1.1, §3.3). Nothing about the decision is in a cookie. Two consent pages in one browser have separate entries. Another decision before resume replaces the first without extending expiry. Re-parking always clears the decision; supply subject: again for a new consent page.

A resume id alone is not approval. A recorded Allow is not acted on by the library: the host's :consent reads it with consent_decision/3 and chooses whether to consent, deny, or park again, after the controller has loaded the client and run validation, scope policy and authentication. A recorded Deny is answered access_denied as soon as the resumed request is validated, before authentication and before :consent runs: refusing grants nothing, so a session that went stale against max_age on the consent page does not send the End-User to sign in again only to lose their Deny. A consent halt under prompt=none still becomes consent_required (OIDC Core §3.1.2.1, §3.1.2.6). Returning with the original query starts a fresh request, including a new prompt=login requirement (OIDC Core §3.1.2.1, §3.1.2.3, §3.1.2.4).

If a fresh prompt=login request passes authentication before parking in consent, prompt_login_since records the bound that check used: request arrival minus reauthentication_allowance_seconds/0. Resume accepts that same bound with no further allowance. A login detour parks before the check passes, so its bound is the real park time: auth_time >= parked_at. Re-parking retains the original parameters, first parked_at and first prompt_login_since, including a login resume parked again for consent. parked_at remains the real first park time for max_age_allowance/3. The host can reuse an authentication satisfying auth_opts.prompt_login_since on resume while honoring auth_opts.force_reauth. Never treat auth_opts.resumed alone as evidence of fresh authentication.

A parked request can be resumed once. It is bound to the browser that parked it through the host's :interaction_browser_binding callback ((conn -> binary)): a value that is stable for one browser and that another browser cannot present. Mount AttestoPhoenix.Interaction.BrowserBinding after :fetch_session and before the authorize route, and configure :interaction_browser_binding as &AttestoPhoenix.Interaction.BrowserBinding.binding/1. Preserve the value through login, including session renewal: Plug.Conn.configure_session(conn, renew: true) keeps session data; drop: true and Plug.Conn.clear_session/1 discard it (see AttestoPhoenix.Interaction.BrowserBinding for a sign-in that clears the session). Losing the value makes resume and pending/2 follow the wrong-browser refusal path. Only a hash of it is stored. The parked request is stored under a key derived from both the resume id and that hash, so a resume from a browser whose value differs finds nothing: it is refused and leaves the parked request in place for the browser that parked it. A leaked resume id alone cannot be used, or used up, from another browser.

resume cannot be combined with any other parameter. An unknown, expired, already used or wrong-browser resume is answered with a direct error page, never a redirect, since nothing about the request can be trusted.

max_age

A request with max_age normally allows reauthentication_allowance_seconds/0 beyond max_age for the trip back from the login page. On a resumed request that interval is replaced by an exact rule: an authentication performed at or after the request was parked satisfies max_age (the End-User re-authenticated for this request); one performed before it must still be within max_age now. max_age=0 on a resumed request therefore requires an authentication at or after the park.

Upgrading from 4.10

Return :auth_time (Unix seconds) from :authenticate_resource_owner. Send the browser to login when auth_opts.force_reauth is true or the existing authentication exceeds auth_opts.max_age, and return the new authentication time (OIDC Core §3.1.2.1, §3.1.2.3). Use park/resume to preserve the request across login and consent; on resume, use the bounds above to decide whether the authentication already satisfies this request.

Storage

Parked requests live in the configured :par_store, under a key no pushed authorization request can have, for :interaction_ttl seconds (default 600, at most 3600). Pushed request_uri requests remain governed by :par_ttl when shorter than :interaction_ttl. The store must implement atomic take/1, and atomic replace/2 only when using decide/4. The bundled stores expire the rows as they do pushed requests (the Ecto store through the sweeper); on the default ETS store, parked requests have their own table and count bounded by :interaction_max_entries (default 8_192), separate from :par_max_entries, and park/3 enforces :par_max_record_bytes for every store. Because anonymous /authorize requests can hold interaction slots up to :interaction_ttl, public deployments should rate-limit /authorize per source.

Summary

Functions

The decision recorded on the resumed request, if it still matches the authenticated subject and validated request's consent binding.

Record :allow or :deny on a live parked request for the current browser and authenticated OIDC subject_id. A later call replaces the decision.

The interval beyond max_age a resumed request is allowed, given the authentication time the host returned (see "max_age" above).

Store the authorization request being processed on conn and return the identifier that resumes it.

Read a parked request through an encrypted view token for the current browser.

The interactive allowance, in seconds, for a fresh authorization request.

The authorization parameters used as input to request validation.

Whether key is in the key space parked requests use. The authorization endpoint refuses such a value as a request_uri.

Whether a browser POST came from a page on the configured issuer's origin.

Take the request parked under resume_id for the browser on conn.

Encrypt a resume id for the host consent URL, without exposing the form's synchronizer token. The handle expires after :interaction_ttl seconds.

Types

parked()

@type parked() :: %{
  params: map(),
  client_id: String.t(),
  parked_at: integer(),
  prompt_login_since: integer(),
  subject: String.t() | nil,
  consent_binding: String.t() | nil,
  consent_decision: String.t() | nil
}

Functions

decide(conn, resume_id, decision, subject_id)

@spec decide(
  Plug.Conn.t(),
  String.t(),
  :allow | :deny,
  String.t() | (String.t() -> term())
) ::
  :ok | {:error, :invalid_resume | :cross_origin}

Record :allow or :deny on a live parked request for the current browser and authenticated OIDC subject_id. A later call replaces the decision.

Returns {:error, :invalid_resume} without changing the entry for a wrong browser or subject, an entry parked without subject:, or an unknown, expired or taken id. Replacement retains the entry's original expiry and cannot recreate a taken entry.

Returns {:error, :cross_origin}, before reading the store, when the request's Sec-Fetch-Site header is present and not same-origin, or its Origin header is missing, null, or differs from the issuer's origin. A browser with no binding value, such as one that never parked a request, gets {:error, :invalid_resume}.

subject_id also accepts a one-argument function receiving the parked request's client id and returning the subject for that client. It is called only after the cross-origin check and after a live entry has been found for this browser. As with a directly supplied subject, only a non-empty binary equal to the parked subject passes; nil, an empty string, a non-binary or another subject returns {:error, :invalid_resume} without changing the entry. Exceptions raised by the function propagate.

Call from the host's browser POST handler, using the current subject from its session. Raises ArgumentError when :interaction_browser_binding is not configured or the configured :par_store has no replace/2.

max_age_allowance(parked_at, auth_time, now)

@spec max_age_allowance(integer(), term(), integer()) :: non_neg_integer()

The interval beyond max_age a resumed request is allowed, given the authentication time the host returned (see "max_age" above).

An authentication at or after parked_at gets the time since the park, which always satisfies max_age; anything else gets zero.

park(conn, request, opts \\ [])

@spec park(Plug.Conn.t(), Attesto.AuthorizationRequest.t(), keyword()) ::
  {:ok, String.t()} | {:error, term()}

Store the authorization request being processed on conn and return the identifier that resumes it.

request is the validated request the host callback received. Call this from :authenticate_resource_owner (or :consent), where conn still carries the authorization request's parameters.

Parking a resumed request preserves its original parameters and first parked_at and prompt_login_since. A first park after a successful fresh prompt=login check saves its arrival-minus-allowance bound; a park before that check uses the park time. Each park issues a new single-use identifier bound to the browser; the consumed identifier cannot be reused.

Pass subject: subject_id (a non-empty OIDC sub) to bind a subsequent decide/4 call to that subject and this validated request. Re-parking never carries over a consent decision, even when the subject is supplied again.

Raises ArgumentError when the configuration cannot park a request: no :interaction_browser_binding, a :par_store without take/1, or a callback that returns no usable browser value.

pending(conn, token, opts \\ [])

@spec pending(Plug.Conn.t(), term(), keyword()) ::
  {:ok, map()} | {:error, :invalid_resume}

Read a parked request through an encrypted view token for the current browser.

Returns {:ok, pending} with :resume_id, :client_id, :request, :subject, :parked_at and :consent_decision (nil, "allow" or "deny"). The request is rebuilt through authorization validation and scope policy, as on resume. Reads never consume or extend the entry, including a decided entry that has not yet resumed.

Pass subject: subject_id, the subject in the host session, to read only a request parked for that subject, as a consent page does. When the option is present, only a non-empty binary equal to the parked subject passes. nil from a signed-out session, an empty string, a non-binary, another subject, or an entry parked without subject: returns {:error, :invalid_resume}. An option other than :subject raises ArgumentError.

:subject also accepts a one-argument function receiving the parked request's client id and returning the subject for that client. It is called only after a live entry has been found for this browser. Its return value is checked exactly as a directly supplied subject; exceptions propagate.

Without the option, the entry is returned to the browser that parked it whether or not anyone is signed in there. That suits a sign-in page that names the client; never render a consent page from it without comparing :subject with the subject in the host session.

Invalid, expired, consumed or wrong-browser handles and request rebuild failures return {:error, :invalid_resume}. Requires conn.secret_key_base; raises ArgumentError naming that value when it is missing.

reauthentication_allowance_seconds()

@spec reauthentication_allowance_seconds() :: non_neg_integer()

The interactive allowance, in seconds, for a fresh authorization request.

The controller allows this interval beyond max_age, or before request arrival for prompt=login (OpenID Connect Core §3.1.2.1, §3.1.2.3). prompt=none gets no allowance. Resumes use the recorded prompt_login_since for prompt=login, with no further allowance, and the real parked_at for max_age_allowance/3. Hosts must still perform reauthentication.

request_params(conn)

@spec request_params(Plug.Conn.t()) :: map()

The authorization parameters used as input to request validation.

On a resumed request, returns the original parked parameters. Otherwise, fetches the query parameters and merges the already parsed body parameters over them, excluding router path parameters. An unfetched body contributes no parameters; the host pipeline must parse request bodies before dispatch.

For PAR, returns the front-channel parameters, including request_uri, rather than the pushed parameters. The controller resolves that reference again on each resume and consumes it only on completion (RFC 9126 §2.3). Signed Request Objects are likewise left encoded. Use the validated request argument for protocol fields and policy decisions.

Available to both :authenticate_resource_owner and :consent; callers need not read private connection fields or the resume-only conn.params.

reserved_key?(key)

@spec reserved_key?(term()) :: boolean()

Whether key is in the key space parked requests use. The authorization endpoint refuses such a value as a request_uri.

same_origin_request?(conn)

@spec same_origin_request?(Plug.Conn.t()) :: boolean()

Whether a browser POST came from a page on the configured issuer's origin.

True when the request carries exactly one Origin header naming the issuer's origin and, if it carries Sec-Fetch-Site, exactly one with the value same-origin. An absent Origin, Origin: null and any other origin are false. The request's Host and forwarded headers play no part.

decide/4 applies this rule before it reads the interaction store or calls a subject function. A host's logout-confirmation POST handler can call it to apply the same rule. Like decide/4, it needs the configuration plug on the route.

take(config, conn, resume_id)

@spec take(AttestoPhoenix.Config.t(), Plug.Conn.t(), term()) ::
  {:ok, parked()} | {:error, :invalid_resume}

Take the request parked under resume_id for the browser on conn.

Returns {:ok, parked} with the original parameters, client id, park and login times, and subject, consent_binding, consent_decision (each nil when absent), or {:error, :invalid_resume} when the id is unknown, expired or already used, the browser value does not match, or the configuration cannot resume. The lookup key includes the browser value, so a wrong browser's lookup finds no entry and consumes nothing. A found entry is consumed.

view_token(conn, resume_id)

@spec view_token(Plug.Conn.t(), String.t()) :: String.t()

Encrypt a resume id for the host consent URL, without exposing the form's synchronizer token. The handle expires after :interaction_ttl seconds.

Requires conn.secret_key_base, supplied by the Phoenix endpoint; raises ArgumentError if it is missing or the resume id is invalid.