alibi-plugins 0.11.0

Built-in authentication plugins and API metadata for Alibi
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! RFC 7523 authentication using registered asymmetric client keys and durable replay claims.
use super::{OAuthProviderPlugin, credentials::Credentials};
use alibi_core::endpoint::{EndpointError, EndpointResponse};
use alibi_core::store::OAuthClient;
use alibi_core::utils::json::{JsValue, parse_value};
use alibi_core::{AuthContext, AuthError, AuthResult, AuthSchema};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use serde_json::Value;
use sha2::{Digest as _, Sha256};

const ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
const SIGNATURE_ERROR: &str = "client assertion signature verification failed";
fn denied<T>(status: u16, description: &str) -> AuthResult<Result<T, EndpointResponse>> {
    Ok(Err(super::clients::status_protocol_error(
        status,
        "invalid_client",
        description,
    )?))
}
fn decode(value: &str) -> Option<JsValue> {
    let bytes = URL_SAFE_NO_PAD.decode(value.trim_end_matches('=')).ok()?;
    let text = String::from_utf8(bytes).ok()?;
    let parsed = parse_value(text.strip_prefix('\u{feff}').unwrap_or(&text)).ok()?;
    parsed.is_object().then_some(parsed)
}
/// Admission hook run on the looked-up client before any key is fetched or
/// the `jti` is consumed.
pub(super) type ClientCheck = fn(&OAuthProviderPlugin, &OAuthClient) -> Option<(u16, &'static str)>;
pub(super) async fn verify<S: AuthSchema>(
    body: &Value,
    ctx: &AuthContext<S>,
    provider: &OAuthProviderPlugin,
    endpoint_url: &str,
) -> AuthResult<Result<Credentials, EndpointResponse>> {
    Ok(Box::pin(verify_client(
        body,
        ctx,
        provider,
        endpoint_url,
        false,
        None,
    ))
    .await?
    .map(|(credentials, _)| credentials))
}
/// Verify a client assertion and return the client record the signature was
/// checked against. With `endpoint_only`, the issuer is not an accepted
/// audience, so an assertion minted for another endpoint cannot be redirected.
pub(super) async fn verify_client<S: AuthSchema>(
    body: &Value,
    ctx: &AuthContext<S>,
    provider: &OAuthProviderPlugin,
    endpoint_url: &str,
    endpoint_only: bool,
    check: Option<ClientCheck>,
) -> AuthResult<Result<(Credentials, OAuthClient), EndpointResponse>> {
    let assertion = body
        .get("client_assertion")
        .and_then(Value::as_str)
        .unwrap_or_default();
    let assertion_type = body
        .get("client_assertion_type")
        .and_then(Value::as_str)
        .unwrap_or_default();
    if assertion.is_empty() || assertion_type.is_empty() {
        return denied(
            400,
            "client_assertion and client_assertion_type must both be provided",
        );
    }
    if assertion_type != ASSERTION_TYPE {
        return denied(400, "unsupported client_assertion_type");
    }
    let parts = assertion.split('.').collect::<Vec<_>>();
    let Some(header) = parts
        .first()
        .and_then(|part| decode(part))
        .filter(|_| matches!(parts.len(), 3 | 5))
    else {
        return denied(400, "malformed client assertion: invalid JWT header");
    };
    let alg = header
        .get("alg")
        .and_then(JsValue::as_str)
        .unwrap_or_default();
    if !super::super::oauth::PRIVATE_KEY_JWT_SIGNING_ALGORITHMS.contains(&alg) {
        let value = header
            .get("alg")
            .map(JsValue::coerce_string)
            .transpose()
            .unwrap_or_default()
            .unwrap_or_else(|| "undefined".into());
        return denied(
            400,
            &format!("unsupported assertion signing algorithm: {value}"),
        );
    }
    let Some(payload) = parts
        .get(1)
        .and_then(|part| decode(part))
        .filter(|_| parts.len() == 3)
    else {
        return denied(400, "malformed client assertion: invalid JWT payload");
    };
    let client_id = payload
        .get("sub")
        .filter(|value| !matches!(value, JsValue::Null))
        .or_else(|| payload.get("iss"));
    let Some(client_id) = client_id
        .filter(|value| value.is_truthy())
        .and_then(JsValue::as_str)
    else {
        return denied(
            400,
            "client assertion must contain sub or iss claim identifying the client",
        );
    };
    if body
        .get("client_id")
        .and_then(Value::as_str)
        .is_some_and(|id| !id.is_empty() && id != client_id)
    {
        return denied(400, "client_id in body does not match assertion sub/iss");
    }
    let Some(client) = provider.get_client(ctx, client_id).await? else {
        return denied(400, "client not found");
    };
    if client.metadata.get("disabled") == Some(&Value::Bool(true)) {
        return denied(400, "client is disabled");
    }
    if client
        .metadata
        .get("token_endpoint_auth_method")
        .and_then(Value::as_str)
        != Some("private_key_jwt")
    {
        return denied(
            400,
            "client is not registered for private_key_jwt authentication",
        );
    }
    if let Some((status, description)) = check.and_then(|check| check(provider, &client)) {
        return denied(status, description);
    }
    let mut jwks = match super::client_jwks::get(ctx, provider, &client).await? {
        Ok(jwks) => jwks,
        Err(description) => return denied(400, description),
    };
    let metadata = provider.metadata(ctx)?;
    let mut audiences = vec![endpoint_url];
    if !endpoint_only {
        audiences.push(
            metadata
                .get("issuer")
                .and_then(Value::as_str)
                .unwrap_or_default(),
        );
    }
    let mut signature = signature_result(&header, &jwks, alg, assertion);
    if signature == SignatureResult::NoMatchingKey
        && let Some(refreshed) = super::client_jwks::refetch(provider, &client).await?
    {
        jwks = refreshed;
        signature = signature_result(&header, &jwks, alg, assertion);
    }
    if signature != SignatureResult::Valid || !claims_valid(&payload, client_id, &audiences) {
        return denied(401, SIGNATURE_ERROR);
    }
    let expected_audience = audiences
        .iter()
        .copied()
        .find(|aud| audience_contains(&payload, aud))
        .unwrap_or_default();
    if let Err(error) = consume_client_assertion(
        ctx,
        &provider.config,
        &format!("private_key_jwt:{client_id}"),
        &payload,
        expected_audience,
    )
    .await
    {
        if let Some(body) = error.body {
            return Ok(Err(
                EndpointResponse::error(error.error).with_error_body(*body)
            ));
        }
        return Err(error.error);
    }
    Ok(Ok((
        Credentials {
            client_id: client_id.into(),
            secret: String::new(),
            method: "private_key_jwt".into(),
            pre_verified: true,
            confirmation: None,
        },
        client,
    )))
}
/// Check assertion hygiene and atomically consume its durable replay identifier.
///
/// Callers must verify the signature and establish the client identity first.
/// This helper does not authenticate a client or require a registered client row.
/// Namespace the identifier by authentication method and client to isolate proofs.
///
/// # Errors
/// Returns protocol errors for audience, lifetime, missing or reused identifiers;
/// database failures retain their original error.
pub async fn consume_client_assertion<S: AuthSchema>(
    ctx: &AuthContext<S>,
    config: &super::OAuthProviderConfig,
    namespace: &str,
    payload: &JsValue,
    expected_audience: &str,
) -> Result<(), EndpointError> {
    if !audience_contains(payload, expected_audience) {
        return Err(consumption_error(
            "client assertion aud does not match the endpoint",
        ));
    }
    if let Some(description) = lifetime_error(payload, config.assertion_max_lifetime) {
        return Err(consumption_error(&description));
    }
    let exp = payload
        .get("exp")
        .and_then(JsValue::as_f64)
        .unwrap_or_default();
    let jti = payload
        .get("jti")
        .and_then(JsValue::as_str)
        .unwrap_or_default();
    if jti.is_empty() {
        return Err(consumption_error("client assertion must include jti claim"));
    }
    let digest = Sha256::digest(format!("{namespace}:{jti}"));
    let id = deterministic_id(digest.get(..24).unwrap_or_default(), ctx);
    #[expect(
        clippy::cast_possible_truncation,
        reason = "ECMAScript Date truncates fractional milliseconds"
    )]
    let expires_at = chrono::DateTime::from_timestamp_millis((exp * 1000.0).trunc() as i64)
        .ok_or_else(|| AuthError::internal("Invalid assertion expiration"))?;
    if !ctx
        .database
        .claim_oauth_client_assertion(&id, expires_at)
        .await?
    {
        return Err(consumption_error(
            "client assertion jti has already been used",
        ));
    }
    Ok(())
}
/// Encode a digest as a primary key the configured id strategy keeps: a
/// version 5 UUID under `uuid`, otherwise the unpadded base64url digest.
/// Serial ids cannot hold a derived id, so single use is not enforced there.
fn deterministic_id<S: AuthSchema>(digest: &[u8], ctx: &AuthContext<S>) -> String {
    if matches!(
        ctx.config.advanced.database.generate_id,
        Some(alibi_core::config::DatabaseIdStrategy::Uuid)
    ) {
        let mut bytes = digest.get(..16).unwrap_or_default().to_vec();
        if let Some(byte) = bytes.get_mut(6) {
            *byte = (*byte & 0x0f) | 0x50;
        }
        if let Some(byte) = bytes.get_mut(8) {
            *byte = (*byte & 0x3f) | 0x80;
        }
        let hex = bytes.iter().fold(String::new(), |mut hex, byte| {
            use std::fmt::Write as _;
            _ = write!(hex, "{byte:02x}");
            hex
        });
        return format!(
            "{}-{}-{}-{}-{}",
            hex.get(..8).unwrap_or_default(),
            hex.get(8..12).unwrap_or_default(),
            hex.get(12..16).unwrap_or_default(),
            hex.get(16..20).unwrap_or_default(),
            hex.get(20..).unwrap_or_default()
        );
    }
    if ctx.config.advanced.database.serial_ids() {
        static WARNED: std::sync::Once = std::sync::Once::new();
        WARNED.call_once(|| {
            tracing::warn!(
                "Single-use checks (such as SAML assertion IDs, DPoP proofs, and private_key_jwt assertions) need string ids and are not enforced with `advanced.database.generateId: \"serial\"`."
            );
        });
    }
    URL_SAFE_NO_PAD.encode(digest)
}
fn consumption_error(description: &str) -> EndpointError {
    EndpointError {
        error: AuthError::Api {
            status: 400,
            code: None,
            message: String::new(),
        },
        headers: None,
        body: Some(Box::new(JsValue::from(
            serde_json::json!({"error":"invalid_client","error_description":description}),
        ))),
        body_absent: false,
    }
}
fn audience_contains(payload: &JsValue, expected: &str) -> bool {
    let aud = payload.get("aud");
    aud.and_then(JsValue::as_str) == Some(expected)
        || aud
            .and_then(JsValue::as_array)
            .is_some_and(|values| values.iter().any(|value| value.as_str() == Some(expected)))
}
fn claims_valid(payload: &JsValue, client_id: &str, audiences: &[&str]) -> bool {
    if payload.get("iss").and_then(JsValue::as_str) != Some(client_id)
        || payload.get("sub").and_then(JsValue::as_str) != Some(client_id)
    {
        return false;
    }
    if !audiences.iter().any(|aud| audience_contains(payload, aud)) {
        return false;
    }
    let now = current_seconds();
    for name in ["iat", "exp", "nbf"] {
        if let Some(value) = payload.get(name) {
            let Some(number) = value.as_f64() else {
                return false;
            };
            if (name == "exp" && number <= now) || (name == "nbf" && number > now) {
                return false;
            }
        }
    }
    true
}
#[expect(
    clippy::cast_precision_loss,
    reason = "JavaScript timestamp arithmetic uses numbers"
)]
fn current_seconds() -> f64 {
    chrono::Utc::now().timestamp() as f64
}
fn lifetime_error(payload: &JsValue, max: f64) -> Option<String> {
    let Some(exp) = payload.get("exp").and_then(JsValue::as_f64) else {
        return Some("client assertion must include exp claim".into());
    };
    let now = current_seconds();
    if exp <= now {
        return Some("client assertion has expired".into());
    }
    let limit = || JsValue::Number(max).coerce_string().unwrap_or_default();
    if exp - now > max {
        return Some(format!(
            "client assertion exp is too far in the future (max {}s)",
            limit()
        ));
    }
    if payload
        .get("iat")
        .and_then(JsValue::as_f64)
        .is_some_and(|iat| now - iat > max)
    {
        return Some(format!(
            "client assertion iat is too far in the past (max {}s)",
            limit()
        ));
    }
    None
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SignatureResult {
    Valid,
    NoMatchingKey,
    Invalid,
}
fn signature_result(
    header: &JsValue,
    jwks: &Value,
    algorithm: &str,
    assertion: &str,
) -> SignatureResult {
    if let Some(crit) = header.get("crit")
        && (!crit
            .as_array()
            .is_some_and(|values| matches!(values,[JsValue::String(value)] if value=="b64"))
            || header.get("b64") != Some(&JsValue::Bool(true)))
    {
        return SignatureResult::Invalid;
    }
    let Some(keys) = jwks.get("keys").and_then(Value::as_array) else {
        return SignatureResult::Invalid;
    };
    let (kty, curve) = match algorithm {
        "EdDSA" => ("OKP", Some("Ed25519")),
        "ES256" => ("EC", Some("P-256")),
        "ES384" => ("EC", Some("P-384")),
        "ES512" => ("EC", Some("P-521")),
        _ => ("RSA", None),
    };
    let matching = keys
        .iter()
        .filter(|key| {
            key.get("kty").and_then(Value::as_str) == Some(kty)
                && key.get("ext").is_none_or(Value::is_boolean)
                && curve.is_none_or(|curve| key.get("crv").and_then(Value::as_str) == Some(curve))
                && key.get("alg").is_none_or(|alg| alg == algorithm)
                && key.get("use").is_none_or(|usage| usage == "sig")
                && key.get("key_ops").is_none_or(|ops| {
                    ops.as_array().is_some_and(|ops| {
                        ops.iter().any(|op| op == "verify")
                            && ops.iter().enumerate().all(|(index, op)| {
                                op.is_string()
                                    && !ops.iter().take(index).any(|previous| previous == op)
                            })
                    })
                })
                && header.get("kid").is_none_or(|kid| {
                    kid.as_str()
                        .is_some_and(|kid| key.get("kid").and_then(Value::as_str) == Some(kid))
                })
        })
        .collect::<Vec<_>>();
    if matching.is_empty() {
        return SignatureResult::NoMatchingKey;
    }
    let [key] = matching.as_slice() else {
        return SignatureResult::Invalid;
    };
    if verify_signature(key, algorithm, assertion) == Some(true) {
        SignatureResult::Valid
    } else {
        SignatureResult::Invalid
    }
}
fn verify_signature(key: &Value, algorithm: &str, assertion: &str) -> Option<bool> {
    let (message, signature) = assertion.rsplit_once('.')?;
    if algorithm == "ES512" {
        use p521::ecdsa::signature::Verifier as _;
        let mut point = vec![4];
        point.extend(URL_SAFE_NO_PAD.decode(key.get("x")?.as_str()?).ok()?);
        point.extend(URL_SAFE_NO_PAD.decode(key.get("y")?.as_str()?).ok()?);
        let key = p521::ecdsa::VerifyingKey::from_sec1_bytes(&point).ok()?;
        let bytes = URL_SAFE_NO_PAD.decode(signature).ok()?;
        let signature = p521::ecdsa::Signature::from_slice(&bytes).ok()?;
        return Some(key.verify(message.as_bytes(), &signature).is_ok());
    }
    let jwk = serde_json::from_value::<jsonwebtoken::jwk::Jwk>(key.clone()).ok()?;
    let key = jsonwebtoken::DecodingKey::from_jwk(&jwk).ok()?;
    jsonwebtoken::crypto::verify(signature, message.as_bytes(), &key, algorithm.parse().ok()?).ok()
}