axiam-sdk 1.2.2

Official Rust client SDK for AXIAM IAM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! Pushed Authorization Requests — CONTRACT.md §26 (RFC 9126).
//!
//! PAR moves the authorization request off the browser. Instead of putting
//! `scope`, `redirect_uri`, `state` and the PKCE challenge into a URL the user
//! agent carries, the client POSTs them straight to AXIAM over an authenticated
//! back channel and puts an opaque `request_uri` in the redirect. What travels
//! through the browser is then a random string that cannot be edited into
//! meaning something else.
//!
//! A §12 extension, not a replacement: `oidc_exchange` afterwards is unchanged.

use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::AxiamError;
use crate::Sensitive;
use crate::client::AxiamClient;
use crate::oidc::authorize::{
    AuthorizationRequest, CODE_CHALLENGE_METHOD_S256, IDP_HINT_PARAM, compute_code_challenge,
    normalize_scope, validate_idp_hint,
};
use crate::oidc::discovery::OidcConfiguration;
use crate::oidc::exchange::oauth2_error_or_fallback;

/// The result of [`AxiamClient::oidc_par`] (CONTRACT.md §26.1).
///
/// The server answered **201** — RFC 9126 §2.2 specifies Created, and a success
/// predicate written `== 200` would treat every successful push as a failure.
///
/// `state`, `nonce` and `code_verifier` are carried straight through from the
/// [`AuthorizationRequest`] that was pushed: §26.2 rule 1 forbids a second
/// generator, and rule 6 wants exactly one `code_verifier` so there is no
/// second place for the two to disagree.
#[derive(Debug, Clone)]
pub struct PushedAuthorizationRequest {
    /// Where to redirect the user agent.
    ///
    /// Carries **exactly** `client_id`, `request_uri` and the `tenant_id` this
    /// push was made under. Not `response_type`, not `redirect_uri`, not
    /// `scope`, not `state` — the server refuses a request that mixes a
    /// `request_uri` with inline authorization parameters rather than merging
    /// them, because merging is where parameter confusion lives (§26.2
    /// rule 2).
    ///
    /// `tenant_id` is not one of those parameters: it is AXIAM's tenant
    /// routing parameter, never part of the pushed body, and
    /// `/oauth2/authorize` reads it to route a browser that has no session yet
    /// — which is every browser arriving here. It is sent unconditionally
    /// rather than copied from the advertised endpoint, because a multi-tenant
    /// deployment that configures no default tenant serves a discovery
    /// document with no tenant in it at all. See [`AxiamClient::oidc_par`]'s
    /// implementation for the full argument.
    pub url: String,
    /// The opaque, single-use handle.
    ///
    /// [`Sensitive`] per §26.5: short-lived and single-use are both reasons it
    /// gets treated as harmless, but between the push and the redirect it is a
    /// bearer handle to a fully-formed authorization request, and a log line is
    /// the wrong place for it to sit for the length of that window.
    pub request_uri: Sensitive<String>,
    /// The handle's lifetime in seconds. Not advisory (§26.2 rule 3).
    pub expires_in: i64,
    /// The value to compare against the `state` the IdP returns.
    pub state: String,
    /// The value that must equal the ID token's `nonce` claim.
    pub nonce: String,
    /// The PKCE verifier to pass into `oidc_exchange` — the same one
    /// `oidc_begin` produced.
    pub code_verifier: Sensitive<String>,
}

/// Arguments to [`AxiamClient::oidc_par`].
///
/// Not `Clone`: it owns the [`AuthorizationRequest`], which is not `Clone`
/// either because it carries the PKCE verifier — one verifier, one login, and
/// a type that cannot be duplicated is one fewer way to get that wrong.
#[derive(Debug)]
pub struct OidcParParams {
    /// What `oidc_begin` returned. Its `url` is replaced by
    /// [`PushedAuthorizationRequest::url`].
    pub request: AuthorizationRequest,
    /// The relying party's redirect URI — the same value that will be sent at
    /// `oidc_exchange` (§26.2 rule 6).
    pub redirect_uri: String,
    /// Requested scope. `openid` is added when absent, exactly as `oidc_begin`
    /// does.
    pub scope: Option<String>,
    /// Tenant UUID override for the mandatory `?tenant_id=` query parameter
    /// (§12.1 note 2).
    pub tenant_id: Option<Uuid>,
    /// The discovery document; fetched via `oidc_discover` when `None`.
    pub configuration: Option<OidcConfiguration>,
    /// RFC 9449 §10 `dpop_jkt` — the RFC 7638 SHA-256 thumbprint of the key
    /// the client will prove possession of at the token endpoint
    /// (contract 1.42).
    ///
    /// Binds the authorization code to that key at push time, so a code
    /// intercepted in the browser cannot be redeemed by anyone else. §10.1
    /// makes this one of two carriers an AS supporting both PAR and DPoP must
    /// accept; the other is a `DPoP` proof header on this same request, and
    /// when both arrive the server requires them to agree.
    ///
    /// Caller-supplied, because this SDK verifies DPoP proofs but does not
    /// generate them (CONTRACT.md §21.9). A caller holding the key computes
    /// the value with [`crate::token::jwk_thumbprint_s256`] over its public
    /// JWK — the same function the resource-server half uses for check 10, so
    /// the two halves cannot disagree about what a thumbprint is.
    ///
    /// Omitted from the pushed form entirely when `None`; §12.1 forbids
    /// sending an empty value for an absent optional field.
    pub dpop_jkt: Option<String>,
}

#[derive(Serialize)]
struct ParForm<'a> {
    client_id: &'a str,
    response_type: &'a str,
    redirect_uri: &'a str,
    scope: &'a str,
    state: &'a str,
    nonce: &'a str,
    code_challenge: &'a str,
    code_challenge_method: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    client_secret: Option<&'a str>,
    /// RFC 9449 §10 — absent, not empty, when the caller pins no key.
    #[serde(skip_serializing_if = "Option::is_none")]
    dpop_jkt: Option<&'a str>,
    /// Contract 1.65 (§26.2 rule 8): the provider hint rides the pushed body,
    /// exactly once, and never the redirect. Absent when `oidc_begin` was
    /// given none.
    #[serde(skip_serializing_if = "Option::is_none")]
    axiam_idp_hint: Option<&'a str>,
}

impl std::fmt::Debug for ParForm<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ParForm")
            .field("client_id", &self.client_id)
            .field("response_type", &self.response_type)
            .field("redirect_uri", &self.redirect_uri)
            .field("scope", &self.scope)
            .field("state", &self.state)
            .field("nonce", &self.nonce)
            .field("code_challenge", &self.code_challenge)
            .field("code_challenge_method", &self.code_challenge_method)
            .field(
                "client_secret",
                &self.client_secret.map(|_| "[REDACTED]").unwrap_or("None"),
            )
            // A public-key thumbprint, not a secret: it is published in the
            // token's `cnf.jkt` and in every proof's header.
            .field("dpop_jkt", &self.dpop_jkt)
            .field("axiam_idp_hint", &self.axiam_idp_hint)
            .finish()
    }
}

#[derive(Deserialize)]
struct PushedAuthorizationWire {
    request_uri: String,
    expires_in: i64,
}

/// The first `axiam_idp_hint` of an `oidc_begin` URL, if any.
fn idp_hint_of(authorization_url: &str) -> Option<String> {
    url::Url::parse(authorization_url).ok().and_then(|u| {
        u.query_pairs()
            .find(|(k, _)| k == IDP_HINT_PARAM)
            .map(|(_, v)| v.into_owned())
    })
}

impl AxiamClient {
    /// `POST /oauth2/par` (CONTRACT.md §26.1) — push the authorization request
    /// over the back channel and get an opaque handle to redirect with.
    ///
    /// **Required for a FAPI 2.0 client**: `profile: "fapi2"` refuses a
    /// registration that does not set `require_par`, so such a client cannot
    /// authorize any other way (§21.1).
    ///
    /// Not retried on a `5xx` or a transport failure — it is a POST that
    /// creates server state, so it falls outside §16.2's read-only eligibility
    /// exactly as `oidc_exchange` does. The safe recovery is a fresh push,
    /// which costs one round trip and cannot double-consume anything (§26.2
    /// rule 4).
    pub async fn oidc_par(
        &self,
        params: OidcParParams,
    ) -> Result<PushedAuthorizationRequest, AxiamError> {
        self.ensure_open()?;

        let configuration = match params.configuration {
            Some(c) => c,
            None => self.oidc_discover().await?,
        };
        let tenant_id = self.resolve_oidc_tenant_id(params.tenant_id).await?;
        let client_id = self.oidc_client_id_or_err()?.to_string();

        let endpoint = self
            .mtls_preferred_opt(
                &configuration,
                |a| a.pushed_authorization_request_endpoint.as_deref(),
                configuration
                    .pushed_authorization_request_endpoint
                    .as_deref(),
            )?
            .ok_or_else(|| {
                AxiamError::auth(
                    "the authorization server's discovery document advertises no \
                     pushed_authorization_request_endpoint: this server does not support \
                     RFC 9126 (CONTRACT.md §26.1)",
                )
            })?;
        let url = self.oidc_endpoint_url(endpoint, tenant_id)?;

        // §26.2 rule 1: everything below was computed by `oidc_begin`. There is
        // no second generator here, and there must not be — two sources for
        // `state` or the PKCE pair are two things that can disagree.
        let scope = normalize_scope(params.scope.as_deref());
        let code_challenge = compute_code_challenge(params.request.code_verifier.expose());
        let client_secret = self.oidc_client_secret().map(|s| s.expose().clone());

        // §26.2 rule 8: `oidc_begin` computed the request, so the hint it put
        // in the URL is carried over like `state` and the PKCE pair; there is
        // no second source for it. The redirect built below still carries
        // none.
        let idp_hint = idp_hint_of(&params.request.url);
        if let Some(hint) = &idp_hint {
            validate_idp_hint("oidc_par", hint)?;
        }

        let form = ParForm {
            client_id: &client_id,
            response_type: "code",
            redirect_uri: &params.redirect_uri,
            scope: &scope,
            state: &params.request.state,
            nonce: &params.request.nonce,
            code_challenge: &code_challenge,
            code_challenge_method: CODE_CHALLENGE_METHOD_S256,
            client_secret: client_secret.as_deref(),
            dpop_jkt: params.dpop_jkt.as_deref(),
            axiam_idp_hint: idp_hint.as_deref(),
        };

        let response = self
            .idp_form_post(url)
            .form(&form)
            .send()
            .await
            .map_err(|e| AxiamError::Network {
                message: format!("pushed authorization request failed: {e}"),
                source: Some(Box::new(e)),
            })?;

        // 201, not 200. RFC 9126 §2.2 specifies Created, and this is the one
        // thing an implementation of this section gets wrong: a success
        // predicate written `== 200` treats every successful push as a failure
        // while passing every other assertion.
        if !response.status().is_success() {
            return Err(oauth2_error_or_fallback(response).await);
        }

        let wire: PushedAuthorizationWire =
            response.json().await.map_err(|e| AxiamError::Network {
                message: format!("failed to parse pushed authorization response: {e}"),
                source: Some(Box::new(e)),
            })?;

        // §26.2 rule 2: exactly two *authorization* parameters. The server
        // REFUSES a request carrying both a `request_uri` and any inline
        // authorization parameter rather than merging them: an attacker
        // supplies the inline value they want and lets the pushed copy satisfy
        // whichever check reads the other one. Re-adding them "for
        // compatibility" restores the attack.
        //
        // `tenant_id` is the one parameter that accompanies them, and it is
        // not an exception to that rule — it is outside it. `/oauth2/authorize`
        // reads `tenant_id` **only** for a request that carries no
        // authenticated principal, which is every browser arriving on a PAR
        // redirect: it has not logged in yet, that is what the redirect is
        // for. Without it the server cannot look up the client whose
        // `browser_sso` registration decides how to answer, and replies `401`
        // instead of a sign-in page.
        //
        // It is sent from the tenant this push was made under, NOT copied from
        // the advertised endpoint. Contract 1.42 publishes
        // `authorization_endpoint` already scoped as `…?tenant_id=<uuid>`, but
        // only when the discovery document describes one tenant — and
        // `oidc_discover` fetches `/.well-known/openid-configuration` with no
        // tenant of its own, so a multi-tenant deployment that configures no
        // `oauth2_default_tenant_id` serves a BARE document. Carrying over only
        // what the document happened to publish fixes the scoped case and
        // leaves that one at the same `401`. The tenant resolved above is
        // authoritative for both: it is a `Uuid` (§12.3 rule 4 refused
        // anything else, client-side, before any wire call) and it is the
        // tenant whose `request_uri` this redirect is about to present.
        //
        // This cannot produce the confusion rule 2 exists to prevent.
        // `tenant_id` is AXIAM's tenant routing parameter, not an OAuth2
        // authorization request parameter, and it is never part of the pushed
        // body — §12.1 note 2 makes it a query parameter on the push itself —
        // so there is no pushed copy for a query-string copy to contradict.
        // Sending it to a non-AXIAM OP is harmless and already this SDK's
        // posture: `oidc_endpoint_url` appends `tenant_id` unconditionally to
        // every `/oauth2/*` endpoint the document advertises, and RFC 6749
        // §3.1 requires an authorization server to ignore a parameter it does
        // not recognise.
        //
        // Everything else the endpoint's query might carry is still dropped,
        // including a `tenant_id` that disagrees: rule 2 caps what may
        // accompany a `request_uri`, and the resolved tenant is the one this
        // request was actually made under.
        let advertised = url::Url::parse(&configuration.authorization_endpoint).map_err(|e| {
            AxiamError::Network {
                message: format!("invalid authorization_endpoint in discovery document: {e}"),
                source: None,
            }
        })?;

        let mut target = advertised;
        target.set_query(None);
        target
            .query_pairs_mut()
            .append_pair("tenant_id", &tenant_id.to_string())
            .append_pair("client_id", &client_id)
            .append_pair("request_uri", &wire.request_uri);

        Ok(PushedAuthorizationRequest {
            url: target.to_string(),
            request_uri: Sensitive::new(wire.request_uri),
            expires_in: wire.expires_in,
            state: params.request.state,
            nonce: params.request.nonce,
            code_verifier: params.request.code_verifier,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // §12.3 rule 4: a confidential client's secret travels in the PAR form, so
    // the form's `Debug` must not render it. The other eight fields stay
    // visible — every one of them is about to appear in a redirect URL or in
    // the server's own logs, and a form that renders as nothing but
    // `[REDACTED]` is a form nobody can debug.
    #[test]
    fn par_form_debug_redacts_only_the_client_secret() {
        let rendered = format!(
            "{:?}",
            ParForm {
                client_id: "client-abc",
                response_type: "code",
                redirect_uri: "https://rp.example/callback",
                scope: "openid profile",
                state: "state-value",
                nonce: "nonce-value",
                code_challenge: "challenge-value",
                code_challenge_method: CODE_CHALLENGE_METHOD_S256,
                client_secret: Some("super-secret-value"),
                dpop_jkt: None,
                axiam_idp_hint: None,
            }
        );
        assert!(!rendered.contains("super-secret-value"), "{rendered}");
        assert!(rendered.contains("[REDACTED]"), "{rendered}");
        for visible in [
            "client-abc",
            "https://rp.example/callback",
            "openid profile",
            "state-value",
            "nonce-value",
            "challenge-value",
            CODE_CHALLENGE_METHOD_S256,
        ] {
            assert!(
                rendered.contains(visible),
                "{visible} missing from {rendered}"
            );
        }
    }

    // A public client has no secret, and the render says `None` rather than
    // `[REDACTED]` — the two are different facts and a reader of the log needs
    // to be able to tell them apart.
    #[test]
    fn par_form_debug_distinguishes_a_public_client_from_a_redacted_secret() {
        let rendered = format!(
            "{:?}",
            ParForm {
                client_id: "client-abc",
                response_type: "code",
                redirect_uri: "https://rp.example/callback",
                scope: "openid",
                state: "state-value",
                nonce: "nonce-value",
                code_challenge: "challenge-value",
                code_challenge_method: CODE_CHALLENGE_METHOD_S256,
                client_secret: None,
                dpop_jkt: Some("0ZcOCORZNYy-DWpqq30jZyJGHTN0d2HglBV3uiguA4I"),
                axiam_idp_hint: None,
            }
        );
        assert!(rendered.contains("None"), "{rendered}");
        assert!(!rendered.contains("[REDACTED]"), "{rendered}");
        // RFC 9449 §10 `dpop_jkt` is a PUBLIC key thumbprint — it is published
        // in the token's `cnf.jkt` and in the header of every proof. Redacting
        // it would cost the one field that makes a DPoP push debuggable while
        // protecting nothing.
        assert!(
            rendered.contains("0ZcOCORZNYy-DWpqq30jZyJGHTN0d2HglBV3uiguA4I"),
            "{rendered}"
        );
    }
}