alibi-plugins 0.10.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
//! Trusted server access-token validation without protocol client authentication.
use super::OAuthProviderPlugin;
use alibi_core::endpoint::EndpointError;
use alibi_core::store::OAuthTokenKind;
use alibi_core::{AuthContext, AuthError, AuthResult, AuthSchema, AuthSession};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use serde_json::{Value, json};

#[derive(Debug)]
pub(super) struct AccessTokenValidation {
    pub payload: Value,
    pub requested_user_info_claims: Vec<String>,
}
impl From<Value> for AccessTokenValidation {
    fn from(payload: Value) -> Self {
        Self {
            payload,
            requested_user_info_claims: Vec::new(),
        }
    }
}
impl OAuthProviderPlugin {
    /// Validate access authority and return its RFC 7662 payload.
    /// Unknown tokens are errors; recognized but inactive authority returns `active: false`.
    pub async fn validate_access_token<S: AuthSchema>(
        &self,
        ctx: &AuthContext<S>,
        token: &str,
        client_id: Option<&str>,
    ) -> Result<Value, EndpointError> {
        Ok(self
            .resolve_access_token_validation(ctx, token, client_id)
            .await?
            .payload)
    }
    async fn resolve_access_token_validation<S: AuthSchema>(
        &self,
        ctx: &AuthContext<S>,
        token: &str,
        client_id: Option<&str>,
    ) -> Result<AccessTokenValidation, EndpointError> {
        let decoded = self.decode_token_prefix(token, OAuthTokenKind::Access);
        // A prefix may introduce JWT separators. With prefix presentation in
        // use, non-JWS headers must still reach opaque prefix/row validation,
        // as they do after the reference's caught JWS-format error.
        let prefixed_opaque = self
            .config
            .opaque_access_token_prefix
            .as_deref()
            .is_some_and(|prefix| !prefix.is_empty())
            && token
                .split('.')
                .next()
                .and_then(|header| URL_SAFE_NO_PAD.decode(header).ok())
                .and_then(|header| serde_json::from_slice::<Value>(&header).ok())
                .is_none_or(|header| !header.is_object());
        if !self.config.disable_jwt_plugin
            && !prefixed_opaque
            && let Some(jwt) = ctx.extensions.get::<crate::jwt::JwtPlugin>()
            && let Some(mut claims) = jwt
                .verify_signed_payload_with_optional_kid(token, None, ctx)
                .await?
        {
            let now = serde_json::Number::from(chrono::Utc::now().timestamp())
                .as_f64()
                .ok_or_else(|| AuthError::internal("Invalid token validation time"))?;
            let issuer = issuer(ctx, self.config.disable_jwt_plugin);
            if claims.get("iss").and_then(Value::as_str) != Some(issuer.as_str()) {
                return Err(AuthError::internal("unexpected \"iss\" claim value").into());
            }
            for field in ["exp", "nbf", "iat"] {
                if claims.get(field).is_some_and(|value| !value.is_number()) {
                    return Ok(json!({"active":false}).into());
                }
            }
            if claims
                .get("nbf")
                .and_then(Value::as_f64)
                .is_some_and(|nbf| nbf > now)
            {
                return Err(AuthError::internal("unexpected \"nbf\" claim value").into());
            }
            if claims
                .get("exp")
                .and_then(Value::as_f64)
                .is_some_and(|exp| exp <= now)
            {
                return Ok(json!({"active":false}).into());
            }
            let Some(resources) = audience_values(claims.get("aud")) else {
                return Ok(json!({"active":false}).into());
            };
            if !audiences_allowed(self, ctx, &resources).await? {
                return Ok(json!({"active":false}).into());
            }
            let Some(issuing_id) = claims
                .get("azp")
                .and_then(Value::as_str)
                .filter(|id| !id.is_empty())
                .map(str::to_owned)
            else {
                return Ok(json!({"active":false}).into());
            };
            let Some(client) = self.get_client(ctx, &issuing_id).await? else {
                return Ok(json!({"active":false}).into());
            };
            if client.metadata.get("disabled") == Some(&Value::Bool(true))
                || !authorized(ctx, client_id, &issuing_id, &resources).await?
            {
                return Ok(json!({"active":false}).into());
            }
            if let Some(sid) = claims.get("sid").and_then(Value::as_str)
                && ctx
                    .database
                    .get_session_by_id(sid)
                    .await?
                    .is_none_or(|session| session.expires_at() < chrono::Utc::now())
            {
                return Ok(json!({"active":false}).into());
            }
            _ = claims.insert("client_id".into(), json!(issuing_id));
            _ = claims.insert("active".into(), json!(true));
            _ = claims.insert(
                "token_type".into(),
                json!(if claims
                    .get("cnf")
                    .and_then(|cnf| cnf.get("jkt"))
                    .and_then(Value::as_str)
                    .is_some_and(|jkt| !jkt.is_empty())
                {
                    "DPoP"
                } else {
                    "Bearer"
                }),
            );
            return Ok(Value::Object(claims).into());
        }
        if !self.config.disable_jwt_plugin && compact_jwt(token) && !prefixed_opaque {
            return Err(AuthError::internal("JWT verification failed").into());
        }
        let Some(token) = decoded else {
            return Err(invalid_access_token());
        };
        let hash = self.hash_token(token, "access_token").await?;
        let Some(row) = ctx
            .database
            .get_oauth_token(OAuthTokenKind::Access, &hash)
            .await?
        else {
            return Err(invalid_access_token());
        };
        let Some((row, client)) = super::userinfo::live_access_row(row, ctx, self).await? else {
            return Ok(json!({"active":false}).into());
        };
        let resources = row
            .metadata
            .get("resources")
            .and_then(Value::as_array)
            .map(|values| {
                values
                    .iter()
                    .filter_map(Value::as_str)
                    .map(str::to_owned)
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();
        if !audiences_allowed(self, ctx, &resources).await?
            || !authorized(ctx, client_id, &row.client_id, &resources).await?
        {
            return Ok(json!({"active":false}).into());
        }
        let scopes = row
            .metadata
            .get("scopes")
            .and_then(Value::as_array)
            .map(|values| {
                values
                    .iter()
                    .filter_map(Value::as_str)
                    .map(str::to_owned)
                    .collect::<Vec<_>>()
            });
        let mut params =
            super::OAuthTokenIssueParams::new(client, scopes.clone().unwrap_or_default());
        if let Some(user_id) = row.user_id.as_deref()
            && let Some(user) = ctx.database.get_user_by_id(user_id).await?
        {
            params.user = Some(ctx.trusted_user_view(&user));
        }
        params.reference_id = row
            .metadata
            .get("referenceId")
            .and_then(Value::as_str)
            .map(str::to_owned);
        params.resources = row
            .metadata
            .get("resources")
            .and_then(Value::as_array)
            .map(|_| resources.clone());
        // Validation has no issuance grant, session context or per-request
        // claims. Re-read both application and resource claims only after all
        // authority/liveness gates; do not re-apply new-issuance admission.
        let mut resource_claims = serde_json::Map::new();
        for resource in &resources {
            if let Some(resource) = ctx.database.get_oauth_resource(resource).await?
                && let Some(claims) = resource
                    .metadata
                    .get("customClaims")
                    .and_then(Value::as_object)
            {
                resource_claims.extend(claims.clone());
            }
        }
        let claims = self
            .resolve_access_token_claims(alibi_core::CallbackContext::new(ctx, None), &params, None)
            .await?;
        let payload = json!({"active":true,"iss":issuer(ctx,self.config.disable_jwt_plugin),"client_id":row.client_id,"azp":row.client_id,"exp":row.expires_at.timestamp(),"iat":row.created_at.timestamp()});
        let core = payload
            .as_object()
            .cloned()
            .ok_or_else(|| AuthError::internal("Invalid access-token payload"))?;
        let mut payload = super::extension_claims::compose_access_claims(claims, resource_claims);
        payload.extend(core);
        payload.extend(confirmation_claims(row.metadata.get("confirmation")));
        if let Some(scope) = scopes {
            _ = payload.insert("scope".into(), json!(scope.join(" ")));
        }
        if let Some(user) = params.user.as_ref() {
            _ = payload.insert("sub".into(), json!(user.id));
        }
        if let Some(sid) = row.session_id {
            _ = payload.insert("sid".into(), json!(sid));
        }
        if !resources.is_empty() {
            let mut audiences = resources;
            let userinfo = format!("{}/oauth2/userinfo", base_url(ctx));
            if scopes_contain(&row.metadata, "openid") && !audiences.contains(&userinfo) {
                audiences.push(userinfo);
            }
            _ = payload.insert(
                "aud".into(),
                match audiences.as_slice() {
                    [one] => json!(one),
                    _ => json!(audiences),
                },
            );
        }
        let requested_user_info_claims = row
            .metadata
            .get("requestedUserInfoClaims")
            .and_then(Value::as_array)
            .map(|values| {
                values
                    .iter()
                    .filter_map(Value::as_str)
                    .map(str::to_owned)
                    .collect()
            })
            .unwrap_or_default();
        Ok(AccessTokenValidation {
            payload: Value::Object(payload),
            requested_user_info_claims,
        })
    }
    /// Require recognized and active authority, preserving the reference Bearer challenge.
    pub async fn require_active_access_token<S: AuthSchema>(
        &self,
        ctx: &AuthContext<S>,
        token: &str,
        client_id: Option<&str>,
    ) -> Result<Value, EndpointError> {
        Ok(self
            .require_active_access_token_with_claims(ctx, token, client_id)
            .await?
            .payload)
    }
    pub(super) async fn require_active_access_token_with_claims<S: AuthSchema>(
        &self,
        ctx: &AuthContext<S>,
        token: &str,
        client_id: Option<&str>,
    ) -> Result<AccessTokenValidation, EndpointError> {
        let validation = self
            .resolve_access_token_validation(ctx, token, client_id)
            .await?;
        if validation.payload.get("active") == Some(&Value::Bool(true)) {
            Ok(validation)
        } else {
            Err(invalid_access_token())
        }
    }
}
// Opaque access and refresh projections share the same sender-constraint
// policy. Preserve truthy untrusted confirmation shapes without treating
// mTLS, arrays, or empty jkt values as DPoP.
pub(super) fn confirmation_claims(confirmation: Option<&Value>) -> serde_json::Map<String, Value> {
    let token_type = if confirmation
        .and_then(crate::oauth2::get_confirmation_jkt)
        .is_some()
    {
        "DPoP"
    } else {
        "Bearer"
    };
    let mut claims = serde_json::Map::from_iter([("token_type".into(), json!(token_type))]);
    if let Some(confirmation) = confirmation
        .filter(|value| alibi_core::utils::json::JsValue::from((**value).clone()).is_truthy())
    {
        _ = claims.insert("cnf".into(), confirmation.clone());
    }
    claims
}
fn base_url<S: AuthSchema>(ctx: &AuthContext<S>) -> String {
    format!(
        "{}{}",
        ctx.config.base_url.trim_end_matches('/'),
        ctx.config.base_path
    )
}
fn issuer<S: AuthSchema>(ctx: &AuthContext<S>, disabled: bool) -> String {
    if !disabled
        && let Some(value) = ctx
            .extensions
            .get::<crate::jwt::JwtDiscoveryOptions>()
            .and_then(|jwt| jwt.issuer.clone())
    {
        return value;
    }
    base_url(ctx)
}
fn audience_values(value: Option<&Value>) -> Option<Vec<String>> {
    match value {
        None => Some(Vec::new()),
        Some(Value::String(value)) => Some(vec![value.clone()]),
        Some(Value::Array(values)) => values
            .iter()
            .map(|value| value.as_str().map(str::to_owned))
            .collect(),
        _ => None,
    }
}
async fn audiences_allowed<S: AuthSchema>(
    provider: &OAuthProviderPlugin,
    ctx: &AuthContext<S>,
    audiences: &[String],
) -> AuthResult<bool> {
    if audiences.len() > 64 {
        return Ok(false);
    }
    let userinfo = format!("{}/oauth2/userinfo", base_url(ctx));
    for audience in audiences {
        if audience != &userinfo && provider.get_resource(ctx, audience).await?.is_none() {
            return Ok(false);
        }
    }
    Ok(true)
}
async fn authorized<S: AuthSchema>(
    ctx: &AuthContext<S>,
    caller: Option<&str>,
    issuer: &str,
    resources: &[String],
) -> AuthResult<bool> {
    if caller.is_none_or(|caller| caller.is_empty() || caller == issuer) {
        return Ok(true);
    }
    let links = ctx
        .database
        .list_oauth_client_resources(caller.unwrap_or_default())
        .await?;
    Ok(links
        .iter()
        .any(|link| resources.contains(&link.resource_id)))
}
fn scopes_contain(metadata: &Value, scope: &str) -> bool {
    metadata
        .get("scopes")
        .and_then(Value::as_array)
        .is_some_and(|values| values.iter().any(|value| value == scope))
}
fn invalid_access_token() -> EndpointError {
    let mut headers = alibi_core::Headers::new();
    _ = headers.insert(
        "WWW-Authenticate",
        "Bearer error=\"invalid_token\", error_description=\"Invalid access token\"",
    );
    EndpointError {
        error: AuthError::Api {
            status: 401,
            code: None,
            message: String::new(),
        },
        headers: Some(headers),
        body: Some(Box::new(alibi_core::utils::json::JsValue::from(
            json!({"error":"invalid_token","error_description":"Invalid access token"}),
        ))),
        body_absent: false,
    }
}

fn compact_jwt(token: &str) -> bool {
    use base64::Engine as _;
    let parts = token.split('.').collect::<Vec<_>>();
    let [header, payload, signature] = parts.as_slice() else {
        return false;
    };
    let decode = |text: &str| {
        base64::engine::general_purpose::URL_SAFE_NO_PAD
            .decode(text)
            .ok()
            .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
    };
    decode(header).is_some_and(|value| value.get("alg").is_some_and(Value::is_string))
        && decode(payload).is_some_and(|value| value.is_object())
        && !signature.is_empty()
}