alibi-core 0.10.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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! Durable, atomic framework-managed provisioning credentials.
use crate::{AuthError, AuthResult};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScimManagedConnection {
    pub id: String,
    pub creation_request_id: String,
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub status: String,
    pub revision: i64,
    pub created_at: DateTime<Utc>,
    pub created_by: String,
    pub decommission_started_at: Option<DateTime<Utc>>,
    pub decommission_started_by: Option<String>,
    pub decommissioned_at: Option<DateTime<Utc>>,
    pub decommissioned_by: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScimManagedCredential {
    pub id: String,
    pub connection_record_id: String,
    pub credential_id: String,
    pub token_digest: String,
    pub hash_version: String,
    pub active_slot_key: String,
    pub status: String,
    pub serialized_scopes: String,
    pub expires_at: DateTime<Utc>,
    pub created_at: DateTime<Utc>,
    pub created_by: String,
    pub last_used_at: Option<DateTime<Utc>>,
    pub revoked_at: Option<DateTime<Utc>>,
    pub revoked_by: Option<String>,
    pub decommissioned_at: Option<DateTime<Utc>>,
}
pub struct CreateScimManagedConnection {
    pub creation_request_id: String,
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub actor_id: String,
    pub credential_id: String,
    pub token_digest: String,
    pub serialized_scopes: String,
    pub expires_at: DateTime<Utc>,
    pub created_at: DateTime<Utc>,
}
#[derive(Clone)]
pub struct RotateScimManagedCredential {
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub actor_id: String,
    pub credential_id: String,
    pub token_digest: String,
    pub serialized_scopes: String,
    pub expires_at: DateTime<Utc>,
    pub created_at: DateTime<Utc>,
    pub max_active_credentials: usize,
}
#[derive(Clone)]
pub struct RevokeScimManagedCredential {
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub credential_id: String,
    pub actor_id: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScimManagedConnectionEvent {
    pub sequence: i64,
    #[serde(rename = "type")]
    pub kind: String,
    pub actor_id: String,
    pub credential_id: Option<String>,
    pub created_at: DateTime<Utc>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScimConnectionBinding {
    pub id: String,
    pub connection_id: String,
    pub connection_key: String,
    pub provisioning_domain_id: String,
    pub created_at: DateTime<Utc>,
    pub decommission_status: String,
    pub decommission_cursor_user_id: Option<String>,
    pub decommission_reconciled_user_count: i64,
    pub decommission_batch_count: i64,
    pub decommission_revision: i64,
    pub decommissioned_at: Option<DateTime<Utc>>,
    pub decommission_completed_at: Option<DateTime<Utc>>,
    pub decommission_lease_id: Option<String>,
    pub decommission_lease_expires_at: Option<DateTime<Utc>>,
}
#[derive(Clone)]
pub struct DecommissionScimManagedConnection {
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub actor_id: String,
}
pub struct ScimManagedConnectionState {
    pub connection: ScimManagedConnection,
    pub credentials: Vec<ScimManagedCredential>,
}
pub struct ScimManagedCreation {
    pub connection: ScimManagedConnection,
    pub credential: ScimManagedCredential,
}
/// Canonical connection-owned User fields required for protocol serialization.
#[derive(Clone)]
pub struct ScimUserRecord {
    pub id: String,
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub user_name: String,
    pub primary_email: String,
    pub display_name: String,
    pub active: bool,
    pub external_id: Option<String>,
    pub formatted_name: String,
    pub given_name: Option<String>,
    pub family_name: Option<String>,
    pub serialized_emails: String,
    pub serialized_attributes: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}
/// Normalized canonical User creation, committed with its identity subject.
#[derive(Clone)]
pub struct ScimUserAttributes {
    pub user_name: String,
    pub user_name_key: String,
    pub primary_email: String,
    pub work_email_value_index: String,
    pub email_value_index: String,
    pub display_name: String,
    pub formatted_name: String,
    pub given_name: Option<String>,
    pub family_name: Option<String>,
    pub serialized_emails: String,
    pub serialized_attributes: Option<String>,
    pub external_id: Option<String>,
    pub external_id_key: Option<String>,
    pub active: bool,
}
pub struct ReplaceScimUser {
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub attributes: ScimUserAttributes,
    pub updated_at: DateTime<Utc>,
}
pub struct ScimUserMutationContext {
    pub user_id: String,
    pub source: ScimUserRecord,
    pub manage_profile: bool,
}
pub struct CreateScimUser {
    pub attributes: ScimUserAttributes,
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub user_id: String,
    pub connection_user_key: String,
    pub order_key: String,
    pub created_at: DateTime<Utc>,
    pub manage_profile: bool,
    pub tombstone_id: Option<String>,
}
#[derive(Clone)]
pub struct ScimIdentityTombstone {
    pub id: String,
    pub provisioning_domain_id: String,
    pub user_id: String,
    pub profile: String,
}
/// Prepared durable Group creation inside a provisioning transaction.
pub struct CreateScimGroup {
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub display_name: String,
    pub display_name_key: String,
    pub external_id: Option<String>,
    pub external_id_key: Option<String>,
    pub order_key: String,
    pub member_ids: Vec<String>,
    pub created_at: DateTime<Utc>,
}
/// Complete replacement of the mutable fields of a canonical Group.
#[derive(Clone)]
pub struct ReplaceScimGroup {
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub display_name: String,
    pub display_name_key: String,
    pub external_id: Option<String>,
    pub external_id_key: Option<String>,
    pub member_ids: Vec<String>,
}
/// Canonical connection-owned group metadata.
pub struct ScimGroupRecord {
    pub id: String,
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub display_name: String,
    pub external_id: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}
pub struct ScimGroupMemberRecord {
    pub id: String,
    pub display_name: String,
}
pub struct ScimUserPage {
    pub total_results: i64,
    pub users: Vec<ScimUserRecord>,
}
pub struct ScimGroupPage {
    pub total_results: i64,
    pub groups: Vec<ScimGroupRecord>,
}
pub struct ScimGroupMemberships {
    pub persisted_count: usize,
    pub members: Vec<ScimGroupMemberRecord>,
}
#[async_trait]
pub trait ScimManagedStore: Send + Sync {
    async fn find_scim_identity_tombstone(
        &self,
        _connection: &str,
        _key: &str,
    ) -> AuthResult<Option<ScimIdentityTombstone>> {
        Err(AuthError::not_implemented(
            "SCIM identity tombstones are unsupported",
        ))
    }

    async fn scim_user_domain_stable(&self, _connection: &str, _domain: &str) -> AuthResult<bool> {
        Err(AuthError::config(
            "SCIM resource persistence is not supported by this store",
        ))
    }
    async fn list_scim_users(
        &self,
        _connection: &str,
        _filters: &[(String, String)],
        _offset: i64,
        _count: i64,
    ) -> AuthResult<ScimUserPage> {
        Err(AuthError::config(
            "SCIM resource persistence is not supported by this store",
        ))
    }

    async fn scim_group_domain_stable(&self, _connection: &str, _domain: &str) -> AuthResult<bool> {
        Err(AuthError::config(
            "SCIM resource persistence is not supported by this store",
        ))
    }
    async fn list_scim_groups(
        &self,
        _connection: &str,
        _filters: &[(String, String)],
        _offset: i64,
        _count: i64,
    ) -> AuthResult<ScimGroupPage> {
        Err(AuthError::config(
            "SCIM resource persistence is not supported by this store",
        ))
    }

    async fn get_scim_user(
        &self,
        _id: &str,
        _connection: &str,
    ) -> AuthResult<Option<ScimUserRecord>> {
        Err(AuthError::config(
            "SCIM resource persistence is not supported by this store",
        ))
    }

    async fn find_scim_managed_credential(
        &self,
        _credential_id: &str,
    ) -> AuthResult<Option<ScimManagedCredential>> {
        Err(AuthError::config(
            "Managed SCIM persistence is not supported by this store",
        ))
    }
    async fn find_scim_active_managed_connection(
        &self,
        _id: &str,
    ) -> AuthResult<Option<ScimManagedConnection>> {
        Err(AuthError::config(
            "Managed SCIM persistence is not supported by this store",
        ))
    }
    async fn record_scim_credential_use(
        &self,
        _id: &str,
        _previous: Option<DateTime<Utc>>,
        _at: DateTime<Utc>,
    ) -> AuthResult<()> {
        Err(AuthError::config(
            "Managed SCIM persistence is not supported by this store",
        ))
    }

    async fn active_scim_connection_binding(
        &self,
        _id: &str,
        _domain: &str,
        _key: &str,
    ) -> AuthResult<ScimConnectionBinding> {
        Err(AuthError::config(
            "SCIM binding persistence is not supported by this store",
        ))
    }
    async fn get_scim_group(
        &self,
        _id: &str,
        _connection: &str,
    ) -> AuthResult<Option<ScimGroupRecord>> {
        Err(AuthError::config(
            "SCIM resource persistence is not supported by this store",
        ))
    }
    async fn scim_group_members(
        &self,
        _id: &str,
        _connection: &str,
    ) -> AuthResult<ScimGroupMemberships> {
        Err(AuthError::config(
            "SCIM resource persistence is not supported by this store",
        ))
    }

    async fn acquire_scim_decommission_lease(
        &self,
        _binding: ScimConnectionBinding,
    ) -> AuthResult<Option<ScimConnectionBinding>> {
        Err(AuthError::config(
            "SCIM binding persistence is not supported by this store",
        ))
    }
    async fn release_scim_decommission_lease(&self, _id: &str, _lease: &str) -> AuthResult<()> {
        Err(AuthError::config(
            "SCIM binding persistence is not supported by this store",
        ))
    }

    async fn scim_projection_candidates(
        &self,
        _domain: &str,
        _cursor: Option<&str>,
    ) -> AuthResult<Vec<ScimProjectionCandidate>> {
        Err(AuthError::config(
            "SCIM projection persistence is not supported by this store",
        ))
    }

    async fn decommission_scim_managed_connection(
        &self,
        _data: DecommissionScimManagedConnection,
        _complete: bool,
    ) -> AuthResult<Option<ScimManagedConnection>> {
        Err(AuthError::config(
            "Managed SCIM persistence is not supported by this store",
        ))
    }

    async fn terminal_scim_connection_binding(
        &self,
        _id: &str,
        _domain: Option<&str>,
        _key: &str,
    ) -> AuthResult<ScimConnectionBinding> {
        Err(AuthError::config(
            "SCIM binding persistence is not supported by this store",
        ))
    }

    async fn list_scim_managed_connection_events(
        &self,
        _id: &str,
        _domain: &str,
    ) -> AuthResult<Option<Vec<ScimManagedConnectionEvent>>> {
        Err(AuthError::config(
            "Managed SCIM persistence is not supported by this store",
        ))
    }

    async fn revoke_scim_managed_credential(
        &self,
        _data: RevokeScimManagedCredential,
    ) -> AuthResult<Option<ScimManagedConnection>> {
        Err(AuthError::config(
            "Managed SCIM persistence is not supported by this store",
        ))
    }

    async fn rotate_scim_managed_credential(
        &self,
        _data: RotateScimManagedCredential,
    ) -> AuthResult<Option<ScimManagedCreation>> {
        Err(AuthError::config(
            "Managed SCIM persistence is not supported by this store",
        ))
    }

    async fn get_scim_managed_connection(
        &self,
        _id: &str,
        _domain: &str,
    ) -> AuthResult<Option<ScimManagedConnectionState>> {
        Err(AuthError::config(
            "Managed SCIM persistence is not supported by this store",
        ))
    }

    async fn list_scim_managed_connections(
        &self,
        _domain: &str,
    ) -> AuthResult<Vec<ScimManagedConnection>> {
        Err(AuthError::config(
            "Managed SCIM persistence is not supported by this store",
        ))
    }

    /// Insert one connection, its credential, and both ordered events in one transaction.
    /// # Errors
    /// Returns a conflict when the creation request was already consumed.
    async fn create_scim_managed_connection(
        &self,
        _data: CreateScimManagedConnection,
    ) -> AuthResult<ScimManagedCreation> {
        Err(AuthError::config(
            "Managed SCIM persistence is not supported by this store",
        ))
    }
}
pub fn scim_creation_conflict() -> AuthError {
    AuthError::Api {
        status: 409,
        code: Some("SCIM_MANAGED_CREATION_REQUEST_ID_CONFLICT".into()),
        message: "Managed SCIM connection creation request ID already exists".into(),
    }
}

pub fn scim_managed_conflict(message: &str) -> AuthError {
    AuthError::Api {
        status: 409,
        code: None,
        message: message.into(),
    }
}

pub fn validate_scim_binding_domain(
    binding: &ScimConnectionBinding,
    domain: Option<&str>,
) -> AuthResult<()> {
    if let Some(domain) = domain
        && domain != binding.provisioning_domain_id
    {
        return Err(AuthError::internal(format!(
            "SCIM connection \"{}\" is already bound to provisioning domain \"{}\".",
            binding.connection_id, binding.provisioning_domain_id
        )));
    }
    Ok(())
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScimIdentitySource {
    pub id: String,
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub active: bool,
}
/// Order callback sources like the reference's `String.localeCompare`.
///
/// # Errors
/// Returns an error if the compiled collation data cannot be loaded.
pub fn sort_scim_sources(sources: &mut [ScimIdentitySource]) -> AuthResult<()> {
    let collator = icu_collator::Collator::try_new(
        icu_collator::CollatorPreferences::default(),
        icu_collator::options::CollatorOptions::default(),
    )
    .map_err(|error| AuthError::internal(error.to_string()))?;
    sources.sort_by(|left, right| collator.compare(&left.id, &right.id));
    Ok(())
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScimProjectedUserState {
    pub provisioning_domain_id: String,
    pub user_id: String,
    pub active: bool,
    pub sources: Vec<ScimIdentitySource>,
    pub grants: Vec<serde_json::Value>,
}

#[derive(Clone, Debug)]
pub struct ScimProjectionCandidate {
    pub id: String,
    pub user_id: String,
}
pub struct ScimProjectionPreparedUser {
    pub state: ScimProjectedUserState,
    pub removed_grant_ids: Vec<String>,
    pub existing_grants: Vec<(String, String)>,
    pub role_sources: Vec<ScimRoleMappingInput>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum ScimAuthorizationSource {
    Group {
        id: String,
        #[serde(rename = "externalId", skip_serializing_if = "Option::is_none")]
        external_id: Option<String>,
        #[serde(rename = "displayName")]
        display_name: String,
    },
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScimRoleMappingInput {
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub scim_user_id: String,
    pub user_id: String,
    pub source: ScimAuthorizationSource,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScimRoleExistenceInput {
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub role: String,
}

#[derive(Clone)]
pub struct CreateScimProjectionGrant {
    pub connection_id: String,
    pub provisioning_domain_id: String,
    pub scim_user_id: String,
    pub user_id: String,
    pub source_id: String,
    pub source_value: String,
    pub role: String,
    pub grant_key: String,
    pub created_at: DateTime<Utc>,
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScimIdentityState {
    pub user_id: String,
    pub active: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_source_id: Option<String>,
    pub sources: Vec<ScimIdentitySource>,
}

/// Stable tuple key for one connection-owned Group membership.
/// # Errors
/// Returns an error if the key tuple cannot be serialized.
pub fn scim_group_membership_key(connection: &str, group: &str, user: &str) -> AuthResult<String> {
    use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
    use sha2::{Digest, Sha256};
    Ok(URL_SAFE_NO_PAD.encode(Sha256::digest(serde_json::to_vec(&[
        "scim-group-member",
        connection,
        group,
        user,
    ])?)))
}