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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! `oidc_discover` (CONTRACT.md §12.1) — fetch, cache and single-flight the
//! OIDC discovery document.
//!
//! The cache is origin-keyed (normalized scheme+host+port, §12.3 rule 6), so
//! a document fetched from one origin can never be served for another. TTL
//! is at least [`MIN_DISCOVERY_TTL`] (5 minutes); concurrent callers for the
//! same (possibly cold) origin collapse into a single HTTP fetch via
//! [`tokio::sync::OnceCell::get_or_try_init`] — the same single-flight
//! primitive family CONTRACT.md §9 already prescribes for this language.

use crate::time::{Duration, Instant};
use std::collections::HashMap;
use std::sync::Arc;

use serde::{Deserialize, Serialize};
use tokio::sync::{OnceCell, RwLock};

use crate::AxiamError;
use crate::client::AxiamClient;

/// Path of the OIDC discovery document, relative to the client base URL.
pub const DISCOVERY_PATH: &str = "/.well-known/openid-configuration";

/// Minimum — and default — discovery-cache TTL. CONTRACT.md §12.3 rule 6
/// sets a floor of 5 minutes; a smaller configured value is raised to it.
pub const MIN_DISCOVERY_TTL: Duration = Duration::from_secs(300);

/// RFC 8705 §5 `mtls_endpoint_aliases` — the seven endpoints re-based on the
/// host that performs the mutual-TLS handshake (wire schema
/// `MtlsEndpointAliases`, contract 1.40; the seventh, CIBA's
/// `backchannel_authentication_endpoint`, contract 1.58).
///
/// A TLS listener decides whether to request a client certificate during the
/// handshake, before it has seen any HTTP, so "ask for a certificate on
/// `/oauth2/token` but not on `/oauth2/authorize`" is not something one
/// listener can do. A deployment wanting both runs two, and this object names
/// the second.
///
/// Only these seven are ever aliased. `authorization_endpoint` and
/// `end_session_endpoint` are front-channel and `jwks_uri` is public key
/// material, so CONTRACT.md §21.3 rule 2 forbids synthesising an alias for any
/// of them — sending a browser to an mTLS host raises a native
/// certificate-chooser dialog most users cannot answer. `issuer` is not an
/// endpoint and does not move either: §12.4 rule 3 still compares `iss`
/// against it by exact string.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
///
/// # Why every field is `Option`, though the schema marks all seven required
///
/// AXIAM builds all seven from one path through a shared macro, so a real AXIAM
/// deployment always publishes the complete set and this type accepts every
/// document it serves. Modelling them as required would additionally make a
/// *partial* object — which RFC 8705 §5 permits, and which another OP may well
/// serve — fail the whole discovery document, taking every §12 operation down
/// with it. That is the same mistake rule 2 point 1 names, one level in: the
/// shape of this member must never be why a client stops working. An absent
/// entry falls back to the top-level endpoint of the same name, exactly as an
/// absent object does.
pub struct MtlsEndpointAliases {
    /// The mTLS token endpoint — RFC 8705 §2 client authentication, and §3
    /// the mint of a certificate-bound token.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_endpoint: Option<String>,
    /// The mTLS userinfo endpoint — OIDC Core §5.3, reached with an access
    /// token that may carry `cnf`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub userinfo_endpoint: Option<String>,
    /// The mTLS revocation endpoint — RFC 7009 §2.1, which authenticates the
    /// client.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revocation_endpoint: Option<String>,
    /// The mTLS introspection endpoint — RFC 7662 §2.1, which authenticates
    /// the caller.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introspection_endpoint: Option<String>,
    /// The mTLS device authorization endpoint — RFC 8628 §3.1, which
    /// authenticates the client.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub device_authorization_endpoint: Option<String>,
    /// The mTLS pushed authorization request endpoint — RFC 9126 §2, which
    /// authenticates the client.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pushed_authorization_request_endpoint: Option<String>,
    /// The mTLS CIBA backchannel authentication endpoint — CIBA Core §7,
    /// which authenticates the client (the seventh alias, contract 1.58,
    /// §21.3.1).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backchannel_authentication_endpoint: Option<String>,
}

/// The OIDC Discovery 1.0 metadata document served by
/// `GET /.well-known/openid-configuration` (wire schema
/// `OidcDiscoveryDocument`). Every field is required by the server's schema.
///
/// `issuer` is the **authoritative** issuer for ID-token validation
/// (CONTRACT.md §12.4 rule 3). It may legitimately differ from the client's
/// base URL when AXIAM runs behind a proxy, so this SDK never rejects a
/// document on an issuer/base-URL mismatch (§12.3 rule 6). Likewise
/// `jwks_uri` is read from here rather than hardcoded.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OidcConfiguration {
    /// The authorization server's issuer identifier — the value an ID
    /// token's `iss` claim must equal exactly.
    pub issuer: String,
    /// The authorization endpoint `oidc_begin` builds its redirect URL from.
    pub authorization_endpoint: String,
    /// The token endpoint used by `oidc_exchange`, `oidc_refresh` and
    /// `login_client_credentials`.
    pub token_endpoint: String,
    /// The userinfo endpoint. Advertised by the server but deliberately NOT
    /// called by any SDK (§12.3 rule 5).
    pub userinfo_endpoint: String,
    /// URI of the JWKS document whose keys verify ID-token signatures
    /// (§12.4 rule 2).
    pub jwks_uri: String,
    /// The RFC 7009 revocation endpoint used by `revoke`.
    pub revocation_endpoint: String,
    /// The RFC 7662 introspection endpoint used by `introspect`.
    pub introspection_endpoint: String,
    /// OAuth2 `response_type` values the server supports.
    pub response_types_supported: Vec<String>,
    /// Subject identifier types the server supports.
    pub subject_types_supported: Vec<String>,
    /// ID-token signing algorithms the server advertises. Informational
    /// only: §12.4 rule 1 pins verification to `EdDSA` regardless of what
    /// appears here.
    pub id_token_signing_alg_values_supported: Vec<String>,
    /// Scopes the server supports.
    pub scopes_supported: Vec<String>,
    /// Client-authentication methods the token endpoint supports
    /// (`client_secret_post`, §12.1 note 3).
    pub token_endpoint_auth_methods_supported: Vec<String>,
    /// Claims the server may include in an ID token.
    pub claims_supported: Vec<String>,
    /// Grant types the token endpoint supports.
    pub grant_types_supported: Vec<String>,

    /// RFC 8414 §2 / RFC 7636 §4.3 — the PKCE transformations the server
    /// accepts (contract 1.42, §21.5). AXIAM publishes `["S256"]`, and its
    /// authorization endpoint refuses `plain`.
    ///
    /// `Option` even though the server's own schema marks it required, and
    /// the contract row is why: *"RFC 8414 defines no default for this
    /// member, so its **absence** does not mean `S256`"*. `None` means the
    /// document did not say — which is what a pre-1.42 AXIAM and most
    /// third-party OPs will give this SDK — and is not the same answer as
    /// `Some(vec![])`. Modelling it required would refuse documents this
    /// SDK accepts today.
    #[serde(default)]
    pub code_challenge_methods_supported: Option<Vec<String>>,

    /// RFC 8414 §2 — the JWS algorithms the token endpoint accepts on a
    /// `private_key_jwt` client assertion (contract 1.42, §21.5). AXIAM
    /// publishes the same three as `dpop_signing_alg_values_supported`
    /// (`PS256`, `ES256`, `EdDSA`); FAPI 2.0 §5.3.1.1 is why they are one
    /// profile.
    ///
    /// `Option` for [`Self::code_challenge_methods_supported`]'s reason.
    #[serde(default)]
    pub token_endpoint_auth_signing_alg_values_supported: Option<Vec<String>>,

    /// RFC 8414 §2 — the client-authentication methods the revocation
    /// endpoint accepts (contract 1.60, §21.5): the token endpoint's list.
    ///
    /// `None` for a server before 1.0.0, which omits all four contract 1.60
    /// members; RFC 8414 then reads it as `client_secret_basic` alone. Like
    /// [`Self::token_endpoint_auth_methods_supported`] it describes the
    /// deployment: `revoke` keeps authenticating with the method this client
    /// was configured with either way (§12.1 rules 3 and 4).
    #[serde(default)]
    pub revocation_endpoint_auth_methods_supported: Option<Vec<String>>,

    /// RFC 8414 §2 — the client-authentication methods the introspection
    /// endpoint accepts (contract 1.60, §21.5): the token endpoint's list
    /// without `none`. `Option`, and informational only, for the reason
    /// [`Self::revocation_endpoint_auth_methods_supported`] gives.
    #[serde(default)]
    pub introspection_endpoint_auth_methods_supported: Option<Vec<String>>,

    /// RFC 8414 §2 — the JWS algorithms the revocation endpoint accepts on a
    /// `private_key_jwt` assertion (contract 1.60, §21.5); equal to
    /// [`Self::token_endpoint_auth_signing_alg_values_supported`] at AXIAM.
    #[serde(default)]
    pub revocation_endpoint_auth_signing_alg_values_supported: Option<Vec<String>>,

    /// RFC 8414 §2 — the JWS algorithms the introspection endpoint accepts on
    /// a `private_key_jwt` assertion (contract 1.60, §21.5).
    #[serde(default)]
    pub introspection_endpoint_auth_signing_alg_values_supported: Option<Vec<String>>,

    /// RFC 8628 device authorization endpoint, used by
    /// [`crate::client::AxiamClient::device_authorize`] (§14.1).
    ///
    /// `Option` because a server that does not implement the device grant
    /// does not advertise it, and because this document may come from a
    /// non-AXIAM OP. Its absence is an error at call time, never a cue to
    /// build the URL by concatenation.
    #[serde(default)]
    pub device_authorization_endpoint: Option<String>,

    /// RFC 9126 pushed authorization request endpoint, used by
    /// [`crate::client::AxiamClient::oidc_par`] (§26.1).
    ///
    /// `Option` for the same reason as the two around it, and with the same
    /// rule: its absence is an error at call time, never a cue to build
    /// `<issuer>/oauth2/par` by concatenation.
    #[serde(default)]
    pub pushed_authorization_request_endpoint: Option<String>,

    /// CIBA Core §4 backchannel authentication endpoint, used by
    /// [`crate::client::AxiamClient::ciba_initiate`] (§33.1). `Option`, and its
    /// absence is an error at call time, as for the two above.
    #[serde(default)]
    pub backchannel_authentication_endpoint: Option<String>,

    /// The CIBA delivery modes the **server** supports (`["poll", "ping"]`).
    /// A statement about the deployment: which mode a client uses is its
    /// registration's answer (§21.5).
    #[serde(default)]
    pub backchannel_token_delivery_modes_supported: Option<Vec<String>>,

    /// Always `false` at AXIAM: no `user_code` is ever sent (§33.3 rule 3).
    #[serde(default)]
    pub backchannel_user_code_parameter_supported: Option<bool>,

    /// The algorithms a signed CIBA request may use (`PS256`, `ES256`,
    /// `EdDSA`). The one a client signs with is the one it registered.
    #[serde(default)]
    pub backchannel_authentication_request_signing_alg_values_supported: Option<Vec<String>>,

    /// OIDC RP-Initiated Logout 1.0 `end_session_endpoint`, used by
    /// [`crate::client::AxiamClient::logout_url`] (§12.7.2 rule 1).
    ///
    /// `Option` for the same reason, and the rule is stricter here: §12.7.2
    /// rule 1 forbids synthesising this URL from the issuer. Code that
    /// concatenates works against AXIAM and breaks against every other OP
    /// the same application is pointed at.
    #[serde(default)]
    pub end_session_endpoint: Option<String>,

    /// Whether the OP sends back-channel logout tokens.
    #[serde(default)]
    pub backchannel_logout_supported: Option<bool>,

    /// Whether those logout tokens carry `sid`. AXIAM always sends it.
    #[serde(default)]
    pub backchannel_logout_session_supported: Option<bool>,

    /// RFC 8705 §5 endpoint aliases for a deployment that terminates mutual
    /// TLS on a host other than the issuer's own (contract 1.40, §21.3
    /// rule 2).
    ///
    /// `Option`, and **`None` means "no separate host", not "mTLS
    /// unsupported"**: a deployment running `client_auth = optional` on one
    /// listener serves both populations at the conventional endpoints and
    /// correctly publishes nothing here. A client treating absence as an
    /// error would refuse the most common mTLS topology AXIAM ships. The
    /// server omits the key rather than serialising `null`, and
    /// `skip_serializing_if` keeps this type's own output the same shape.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mtls_endpoint_aliases: Option<MtlsEndpointAliases>,
}

/// Normalize a base URL to its cache key: lowercased scheme and host with
/// the port always explicit (§12.3 rule 6). `https://IAM.example.com/` and
/// `https://iam.example.com:443/x` therefore share one key, while
/// `http://iam.example.com` gets its own.
pub(crate) fn normalize_origin(url: &url::Url) -> String {
    let scheme = url.scheme().to_ascii_lowercase();
    let host = url.host_str().unwrap_or_default().to_ascii_lowercase();
    let default_port = match scheme.as_str() {
        "https" => 443,
        "http" => 80,
        _ => 0,
    };
    let port = url.port().unwrap_or(default_port);
    format!("{scheme}://{host}:{port}")
}

struct CacheEntry {
    cell: OnceCell<OidcConfiguration>,
    created_at: Instant,
}

/// Origin-keyed discovery cache with single-flight fetching (CONTRACT.md
/// §12.3 rule 6). Not process-global: owned per [`AxiamClient`] instance, so
/// it is never shared across tenants or clients.
pub(crate) struct DiscoveryCache {
    entries: RwLock<HashMap<String, Arc<CacheEntry>>>,
    ttl: Duration,
}

impl DiscoveryCache {
    /// `ttl` is clamped up to [`MIN_DISCOVERY_TTL`] — §12.3 rule 6 forbids a
    /// smaller value.
    pub(crate) fn new(ttl: Duration) -> Self {
        Self {
            entries: RwLock::new(HashMap::new()),
            ttl: ttl.max(MIN_DISCOVERY_TTL),
        }
    }

    /// Fetch (or reuse a cached/in-flight) document for `origin_key`.
    /// Concurrent callers for the same cold origin share one `fetcher` call.
    pub(crate) async fn get<F, Fut>(
        &self,
        origin_key: &str,
        fetcher: F,
    ) -> Result<OidcConfiguration, AxiamError>
    where
        F: FnOnce() -> Fut,
        Fut: std::future::Future<Output = Result<OidcConfiguration, AxiamError>>,
    {
        // Fast path: an existing, still-fresh entry (initialized or another
        // caller's in-flight fetch) — no write lock needed.
        {
            let entries = self.entries.read().await;
            if let Some(entry) = entries.get(origin_key)
                && entry.created_at.elapsed() < self.ttl
            {
                let entry = Arc::clone(entry);
                drop(entries);
                let doc = entry.cell.get_or_try_init(fetcher).await?;
                return Ok(doc.clone());
            }
        }

        // Slow path: no fresh entry yet. Acquire the write lock and either
        // reuse an entry a racing writer already inserted, or create a new
        // one — this keeps a burst of cold-start callers to exactly one
        // fresh `CacheEntry`, and therefore (via `get_or_try_init` below)
        // exactly one HTTP fetch.
        let entry = {
            let mut entries = self.entries.write().await;
            let fresh = entries
                .get(origin_key)
                .is_some_and(|e| e.created_at.elapsed() < self.ttl);
            if !fresh {
                entries.insert(
                    origin_key.to_string(),
                    Arc::new(CacheEntry {
                        cell: OnceCell::new(),
                        created_at: Instant::now(),
                    }),
                );
            }
            Arc::clone(
                entries
                    .get(origin_key)
                    .expect("just inserted or already fresh"),
            )
        };

        let doc = entry.cell.get_or_try_init(fetcher).await?;
        Ok(doc.clone())
    }
}

impl AxiamClient {
    /// `GET /.well-known/openid-configuration` (CONTRACT.md §12.1) — fetch
    /// the OIDC discovery document, cached per origin with a ≥5-minute TTL
    /// and single-flight de-duplication of concurrent calls (§12.3 rule 6).
    ///
    /// The document's own `issuer` is authoritative for ID-token validation
    /// and may legitimately differ from the client's base URL behind a
    /// proxy, so a mismatch is never treated as an error.
    pub async fn oidc_discover(&self) -> Result<OidcConfiguration, AxiamError> {
        let origin_key = normalize_origin(self.base_url());
        let url = self
            .base_url()
            .join(DISCOVERY_PATH)
            .map_err(|e| AxiamError::Network {
                message: format!("invalid discovery URL: {e}"),
                source: None,
            })?;
        let http = self.http().clone();

        self.oidc_discovery_cache()
            .get(&origin_key, move || async move {
                let response = http
                    .get(url)
                    .send()
                    .await
                    .map_err(|e| AxiamError::Network {
                        message: format!("oidc discovery request failed: {e}"),
                        source: Some(Box::new(e)),
                    })?;
                if !response.status().is_success() {
                    let status = response.status().as_u16();
                    let message = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "no response body".to_string());
                    return Err(AxiamError::from_http_status(status, message));
                }
                response
                    .json::<OidcConfiguration>()
                    .await
                    .map_err(|e| AxiamError::Network {
                        message: format!("failed to parse discovery document: {e}"),
                        source: Some(Box::new(e)),
                    })
            })
            .await
    }
}

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

    #[test]
    fn normalize_origin_lowercases_and_fills_default_port() {
        let a = url::Url::parse("https://IAM.example.com/").unwrap();
        let b = url::Url::parse("https://iam.example.com:443/x").unwrap();
        assert_eq!(normalize_origin(&a), normalize_origin(&b));

        let c = url::Url::parse("http://iam.example.com").unwrap();
        assert_ne!(normalize_origin(&a), normalize_origin(&c));
    }

    /// A scheme with no IANA default port (the `_ => 0` arm) still yields a
    /// stable, distinct origin key rather than colliding with `https`.
    #[test]
    fn normalize_origin_handles_a_scheme_with_no_default_port() {
        let explicit = url::Url::parse("ftp://iam.example.com:2121/").unwrap();
        assert_eq!(normalize_origin(&explicit), "ftp://iam.example.com:2121");

        let implicit = url::Url::parse("ftp://iam.example.com/").unwrap();
        assert_eq!(normalize_origin(&implicit), "ftp://iam.example.com:0");
        assert_ne!(
            normalize_origin(&implicit),
            normalize_origin(&url::Url::parse("https://iam.example.com/").unwrap())
        );
    }
}