alibi-core 0.8.0

Shared authentication contracts and backend-independent services 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
//! Durable OAuth provider clients, grants, and resource policy.
use crate::{AuthError, AuthResult};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde_json::Value;
#[derive(Clone, Debug)]
pub struct OAuthClient {
    pub id: String,
    pub client_id: String,
    pub user_id: Option<String>,
    pub client_secret: Option<String>,
    pub metadata: Value,
    pub created_at: Option<DateTime<Utc>>,
    pub updated_at: Option<DateTime<Utc>>,
}
#[derive(Clone, Debug)]
pub struct CreateOAuthClient {
    pub client_id: String,
    pub user_id: Option<String>,
    pub client_secret: Option<String>,
    pub metadata: Value,
    pub created_at: DateTime<Utc>,
}
/// Durable token kind; refresh and opaque access tokens have distinct lifecycles.
#[derive(Clone, Copy, Debug)]
pub enum OAuthTokenKind {
    Access,
    Refresh,
}
#[derive(Clone, Debug)]
pub struct OAuthToken {
    pub id: String,
    pub token: String,
    pub client_id: String,
    pub user_id: Option<String>,
    pub session_id: Option<String>,
    pub authorization_code_id: Option<String>,
    pub metadata: Value,
    pub created_at: DateTime<Utc>,
    pub expires_at: DateTime<Utc>,
}
#[derive(Clone, Debug)]
pub struct CreateOAuthToken {
    pub token: String,
    pub client_id: String,
    pub user_id: Option<String>,
    pub session_id: Option<String>,
    pub authorization_code_id: Option<String>,
    pub metadata: Value,
    pub created_at: DateTime<Utc>,
    pub expires_at: DateTime<Utc>,
}
#[async_trait]
pub trait OAuthClientStore: Send + Sync {
    /// Claim default refresh rotation with both revocation and rotation timestamps.
    async fn store_oauth_refresh_replay(&self, id: &str, ciphertext: &str) -> AuthResult<()> {
        let _ = (id, ciphertext);
        Err(AuthError::config(
            "OAuth token persistence is not supported by this store",
        ))
    }
    async fn claim_oauth_refresh_rotation(
        &self,
        _token: &str,
        _at: DateTime<Utc>,
        _replay_expires: Option<DateTime<Utc>>,
    ) -> AuthResult<bool> {
        Err(AuthError::config(
            "OAuth token persistence is not supported by this store",
        ))
    }

    async fn list_oauth_tokens_for_session(
        &self,
        _kind: OAuthTokenKind,
        _session_id: &str,
    ) -> AuthResult<Vec<OAuthToken>> {
        Err(AuthError::config(
            "OAuth token persistence is not supported by this store",
        ))
    }
    async fn mark_oauth_token_revoked(
        &self,
        _kind: OAuthTokenKind,
        _id: &str,
        _at: DateTime<Utc>,
    ) -> AuthResult<()> {
        Err(AuthError::config(
            "OAuth token persistence is not supported by this store",
        ))
    }

    async fn delete_oauth_token(&self, _kind: OAuthTokenKind, _token: &str) -> AuthResult<()> {
        Err(AuthError::config(
            "OAuth token persistence is not supported by this store",
        ))
    }
    /// Atomically claim an unrevoked refresh token; concurrent claimants lose.
    async fn revoke_oauth_refresh_token(
        &self,
        _token: &str,
        _revoked_at: DateTime<Utc>,
    ) -> AuthResult<bool> {
        Err(AuthError::config(
            "OAuth token persistence is not supported by this store",
        ))
    }
    async fn delete_oauth_access_tokens_for_refresh(&self, _refresh_id: &str) -> AuthResult<()> {
        Err(AuthError::config(
            "OAuth token persistence is not supported by this store",
        ))
    }
    async fn delete_oauth_refresh_family(
        &self,
        _client_id: &str,
        _user_id: &str,
    ) -> AuthResult<()> {
        Err(AuthError::config(
            "OAuth token persistence is not supported by this store",
        ))
    }
    async fn create_oauth_token(
        &self,
        _kind: OAuthTokenKind,
        _data: CreateOAuthToken,
    ) -> AuthResult<OAuthToken> {
        Err(AuthError::config(
            "OAuth token persistence is not supported by this store",
        ))
    }
    async fn get_oauth_token(
        &self,
        _kind: OAuthTokenKind,
        _token: &str,
    ) -> AuthResult<Option<OAuthToken>> {
        Err(AuthError::config(
            "OAuth token persistence is not supported by this store",
        ))
    }
    async fn delete_oauth_tokens_for_code(&self, _code: &str) -> AuthResult<()> {
        Err(AuthError::config(
            "OAuth token persistence is not supported by this store",
        ))
    }

    async fn delete_oauth_client_resource(
        &self,
        _client_id: &str,
        _resource_id: &str,
    ) -> AuthResult<()> {
        Err(AuthError::config(
            "OAuth resource linkage is not supported by this store",
        ))
    }
    async fn create_oauth_client_resource(
        &self,
        _data: CreateOAuthClientResource,
    ) -> AuthResult<OAuthClientResource> {
        Err(AuthError::config(
            "OAuth resource linkage is not supported by this store",
        ))
    }
    async fn delete_oauth_resource(&self, _identifier: &str) -> AuthResult<()> {
        Err(AuthError::config(
            "OAuth resource persistence is not supported by this store",
        ))
    }
    async fn update_oauth_resource(
        &self,
        _identifier: &str,
        _metadata: Value,
        _updated_at: DateTime<Utc>,
    ) -> AuthResult<Option<OAuthResource>> {
        Err(AuthError::config(
            "OAuth resource persistence is not supported by this store",
        ))
    }
    async fn list_oauth_resources(&self) -> AuthResult<Vec<OAuthResource>> {
        Err(AuthError::config(
            "OAuth resource persistence is not supported by this store",
        ))
    }
    async fn list_oauth_client_resources(
        &self,
        _client_id: &str,
    ) -> AuthResult<Vec<OAuthClientResource>> {
        Err(AuthError::config(
            "OAuth resource linkage is not supported by this store",
        ))
    }
    async fn create_oauth_resource(&self, _data: CreateOAuthResource) -> AuthResult<OAuthResource> {
        Err(AuthError::config(
            "OAuth resource persistence is not supported by this store",
        ))
    }
    async fn get_oauth_resource(&self, _identifier: &str) -> AuthResult<Option<OAuthResource>> {
        Err(AuthError::config(
            "OAuth resource persistence is not supported by this store",
        ))
    }
    async fn delete_oauth_consent(&self, _id: &str) -> AuthResult<()> {
        Err(AuthError::config(
            "OAuth consent persistence is not supported by this store",
        ))
    }
    async fn get_oauth_consent(&self, _id: &str) -> AuthResult<Option<OAuthConsent>> {
        Err(AuthError::config(
            "OAuth consent persistence is not supported by this store",
        ))
    }
    async fn create_oauth_consent(&self, _data: CreateOAuthConsent) -> AuthResult<OAuthConsent> {
        Err(AuthError::config(
            "OAuth consent persistence is not supported by this store",
        ))
    }
    async fn list_oauth_consents_by_user(&self, _user_id: &str) -> AuthResult<Vec<OAuthConsent>> {
        Err(AuthError::config(
            "OAuth consent persistence is not supported by this store",
        ))
    }
    async fn update_oauth_consent_metadata(
        &self,
        _id: &str,
        _metadata: Value,
        _updated_at: DateTime<Utc>,
    ) -> AuthResult<Option<OAuthConsent>> {
        Err(AuthError::config(
            "OAuth consent persistence is not supported by this store",
        ))
    }
    async fn create_oauth_client(&self, _data: CreateOAuthClient) -> AuthResult<OAuthClient> {
        Err(AuthError::config(
            "OAuth client persistence is not supported by this store",
        ))
    }
    async fn get_oauth_client(&self, _client_id: &str) -> AuthResult<Option<OAuthClient>> {
        Err(AuthError::config(
            "OAuth client persistence is not supported by this store",
        ))
    }
    async fn list_oauth_clients_by_user(&self, _user_id: &str) -> AuthResult<Vec<OAuthClient>> {
        Err(AuthError::config(
            "OAuth client persistence is not supported by this store",
        ))
    }
    async fn delete_oauth_client(&self, _client_id: &str) -> AuthResult<()> {
        Err(AuthError::config(
            "OAuth client persistence is not supported by this store",
        ))
    }
    async fn update_oauth_client_secret(
        &self,
        _client_id: &str,
        _secret: String,
        _updated_at: DateTime<Utc>,
    ) -> AuthResult<Option<OAuthClient>> {
        Err(AuthError::config(
            "OAuth client persistence is not supported by this store",
        ))
    }
    async fn update_oauth_client_metadata(
        &self,
        _client_id: &str,
        _metadata: Value,
        _updated_at: DateTime<Utc>,
    ) -> AuthResult<Option<OAuthClient>> {
        Err(AuthError::config(
            "OAuth client persistence is not supported by this store",
        ))
    }
}

/// RFC client metadata names mapped to the TypeScript persistence schema.
const CLIENT_FIELDS: &[(&str, &str)] = &[
    ("client_discovery_id", "clientDiscoveryId"),
    ("disabled", "disabled"),
    ("skip_consent", "skipConsent"),
    ("enable_end_session", "enableEndSession"),
    ("subject_type", "subjectType"),
    ("client_credentials_scopes", "clientCredentialsScopes"),
    ("contacts", "contacts"),
    ("software_id", "softwareId"),
    ("software_version", "softwareVersion"),
    ("software_statement", "softwareStatement"),
    ("redirect_uris", "redirectUris"),
    ("post_logout_redirect_uris", "postLogoutRedirectUris"),
    ("backchannel_logout_uri", "backchannelLogoutUri"),
    (
        "backchannel_logout_session_required",
        "backchannelLogoutSessionRequired",
    ),
    ("token_endpoint_auth_method", "tokenEndpointAuthMethod"),
    ("application_type", "applicationType"),
    ("jwks", "jwks"),
    ("jwks_uri", "jwksUri"),
    ("grant_types", "grantTypes"),
    ("response_types", "responseTypes"),
    ("require_pkce", "requirePKCE"),
    ("dpop_bound_access_tokens", "dpopBoundAccessTokens"),
    ("reference_id", "referenceId"),
    ("client_name", "name"),
    ("client_uri", "uri"),
    ("logo_uri", "icon"),
    ("tos_uri", "tos"),
    ("policy_uri", "policy"),
    ("scope", "scopes"),
];

/// Separate registration fields from application metadata for physical persistence.
/// # Errors
/// Rejects metadata that is not an object.
pub fn metadata_to_columns(metadata: Value) -> AuthResult<Value> {
    let Value::Object(mut metadata) = metadata else {
        return Err(AuthError::bad_request(
            "OAuth client metadata must be an object",
        ));
    };
    let mut fields = serde_json::Map::new();
    for (rfc, column) in CLIENT_FIELDS {
        if let Some(mut value) = metadata.remove(*rfc) {
            if *rfc == "scope"
                && let Some(scope) = value.as_str()
            {
                value = Value::Array(
                    scope
                        .split_whitespace()
                        .map(|scope| Value::String(scope.into()))
                        .collect(),
                );
            }
            if *rfc == "jwks" && value.is_object() {
                value = Value::String(serde_json::to_string(&value)?);
            }
            _ = fields.insert((*column).into(), value);
        }
    }
    if !fields.contains_key("redirectUris") {
        _ = fields.insert("redirectUris".into(), serde_json::json!([]));
    }
    _ = fields.insert(
        "metadata".into(),
        if metadata.is_empty() {
            Value::Null
        } else {
            Value::Object(metadata)
        },
    );
    Ok(Value::Object(fields))
}

/// Rebuild the registration projection from the TypeScript client columns.
/// # Errors
/// Returns an error when a stored client is malformed.
pub fn metadata_from_columns(fields: &Value) -> AuthResult<Value> {
    let fields = fields
        .as_object()
        .ok_or_else(|| AuthError::internal("Stored OAuth client must be an object"))?;
    let mut metadata = fields
        .get("metadata")
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default();
    for (rfc, column) in CLIENT_FIELDS {
        if let Some(mut value) = fields
            .get(*column)
            .filter(|value| !value.is_null())
            .cloned()
        {
            if *rfc == "scope"
                && let Some(scopes) = value.as_array()
            {
                value = Value::String(
                    scopes
                        .iter()
                        .filter_map(Value::as_str)
                        .collect::<Vec<_>>()
                        .join(" "),
                );
            }
            if *rfc == "jwks"
                && let Some(jwks) = value.as_str()
            {
                value = serde_json::from_str(jwks)?;
            }
            _ = metadata.insert((*rfc).into(), value);
        }
    }
    Ok(Value::Object(metadata))
}

/// Durable consent attached to the client and consenting user.
#[derive(Clone, Debug)]
pub struct OAuthConsent {
    pub id: String,
    pub client_id: String,
    pub user_id: Option<String>,
    pub metadata: Value,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}
#[derive(Clone, Debug)]
pub struct CreateOAuthConsent {
    pub client_id: String,
    pub user_id: Option<String>,
    pub metadata: Value,
    pub created_at: DateTime<Utc>,
}

#[derive(Clone, Debug)]
pub struct OAuthResource {
    pub id: String,
    pub identifier: String,
    pub metadata: Value,
    pub created_at: Option<DateTime<Utc>>,
    pub updated_at: Option<DateTime<Utc>>,
}
#[derive(Clone, Debug)]
pub struct CreateOAuthResource {
    pub identifier: String,
    pub metadata: Value,
    pub created_at: DateTime<Utc>,
}

#[derive(Clone, Debug)]
pub struct OAuthClientResource {
    pub id: String,
    pub client_id: String,
    pub resource_id: String,
    pub metadata: Value,
    pub created_at: Option<DateTime<Utc>>,
}

#[derive(Clone, Debug)]
pub struct CreateOAuthClientResource {
    pub client_id: String,
    pub resource_id: String,
    pub created_at: DateTime<Utc>,
}