Skip to main content

kanidmd_lib/valueset/
session.rs

1use crate::{
2    be::dbvalue::{
3        DbCidV1, DbValueAccessScopeV1, DbValueApiToken, DbValueApiTokenScopeV1, DbValueAuthTypeV1,
4        DbValueIdentityId, DbValueOauth2Session, DbValueSession, DbValueSessionExtMetadataV1,
5        DbValueSessionStateV1,
6    },
7    prelude::*,
8    repl::cid::Cid,
9    schema::SchemaAttribute,
10    value::{
11        ApiToken, ApiTokenScope, AuthType, Oauth2Session, Session, SessionExtMetadata,
12        SessionScope, SessionState,
13    },
14    valueset::{uuid_to_proto_string, DbValueSetV2, ScimResolveStatus, ValueSet},
15};
16use kanidm_proto::scim_v1::server::{ScimApiToken, ScimAuthSession, ScimOAuth2Session};
17use std::collections::{btree_map::Entry as BTreeEntry, BTreeMap};
18use time::OffsetDateTime;
19
20#[derive(Debug, Clone)]
21pub struct ValueSetSession {
22    map: BTreeMap<Uuid, Session>,
23}
24
25impl ValueSetSession {
26    pub fn new(u: Uuid, m: Session) -> Box<Self> {
27        let mut map = BTreeMap::new();
28        map.insert(u, m);
29        Box::new(ValueSetSession { map })
30    }
31
32    pub fn push(&mut self, u: Uuid, m: Session) -> bool {
33        self.map.insert(u, m).is_none()
34    }
35
36    fn to_vec_dbvs(&self) -> Vec<DbValueSession> {
37        self.map
38            .iter()
39            .map(|(u, m)| DbValueSession::V4 {
40                refer: *u,
41                label: m.label.clone(),
42
43                state: match &m.state {
44                    SessionState::ExpiresAt(odt) => {
45                        debug_assert_eq!(odt.offset(), time::UtcOffset::UTC);
46                        #[allow(clippy::expect_used)]
47                        odt.format(&Rfc3339)
48                            .map(DbValueSessionStateV1::ExpiresAt)
49                            .expect("Failed to format timestamp into RFC3339!")
50                    }
51                    SessionState::NeverExpires => DbValueSessionStateV1::Never,
52                    SessionState::RevokedAt(c) => DbValueSessionStateV1::RevokedAt(DbCidV1 {
53                        server_id: c.s_uuid,
54                        timestamp: c.ts,
55                    }),
56                },
57
58                issued_at: {
59                    debug_assert_eq!(m.issued_at.offset(), time::UtcOffset::UTC);
60                    #[allow(clippy::expect_used)]
61                    m.issued_at
62                        .format(&Rfc3339)
63                        .expect("Failed to format timestamp into RFC3339!")
64                },
65                issued_by: match m.issued_by {
66                    IdentityId::Internal(u) => DbValueIdentityId::V2Internal(u),
67                    IdentityId::User(u) => DbValueIdentityId::V1Uuid(u),
68                    IdentityId::Synch(u) => DbValueIdentityId::V1Sync(u),
69                },
70                cred_id: m.cred_id,
71                scope: match m.scope {
72                    SessionScope::ReadOnly => DbValueAccessScopeV1::ReadOnly,
73                    SessionScope::ReadWrite => DbValueAccessScopeV1::ReadWrite,
74                    SessionScope::PrivilegeCapable => DbValueAccessScopeV1::PrivilegeCapable,
75                    SessionScope::Synchronise => DbValueAccessScopeV1::Synchronise,
76                },
77                type_: match m.type_ {
78                    AuthType::Anonymous => DbValueAuthTypeV1::Anonymous,
79                    AuthType::Password => DbValueAuthTypeV1::Password,
80                    AuthType::GeneratedPassword => DbValueAuthTypeV1::GeneratedPassword,
81                    AuthType::PasswordTotp => DbValueAuthTypeV1::PasswordTotp,
82                    AuthType::PasswordBackupCode => DbValueAuthTypeV1::PasswordBackupCode,
83                    AuthType::PasswordSecurityKey => DbValueAuthTypeV1::PasswordSecurityKey,
84                    AuthType::Passkey => DbValueAuthTypeV1::Passkey,
85                    AuthType::AttestedPasskey => DbValueAuthTypeV1::AttestedPasskey,
86                    AuthType::OAuth2Trust => DbValueAuthTypeV1::OAuth2Trust,
87                },
88                ext_metadata: match &m.ext_metadata {
89                    SessionExtMetadata::None => DbValueSessionExtMetadataV1::None,
90                    SessionExtMetadata::OAuth2 {
91                        access_expires_at,
92                        access_token,
93                        refresh_token,
94                    } => DbValueSessionExtMetadataV1::OAuth2 {
95                        access_expires_at: *access_expires_at,
96                        access_token: access_token.clone(),
97                        refresh_token: refresh_token.clone(),
98                    },
99                },
100            })
101            .collect()
102    }
103
104    fn from_dbv_iter<'a>(
105        iter: impl Iterator<Item = &'a DbValueSession>,
106    ) -> Result<ValueSet, OperationError> {
107        let map = iter
108            .filter_map(|dbv| {
109                match dbv {
110                    // We need to ignore all older session records as they lack the AuthType
111                    // record which prevents re-auth working.
112                    DbValueSession::V1 { .. }
113                    | DbValueSession::V2 { .. }
114                    | DbValueSession::V3 { .. } => None,
115                    DbValueSession::V4 {
116                        refer,
117                        label,
118                        state,
119                        issued_at,
120                        issued_by,
121                        cred_id,
122                        scope,
123                        type_,
124                        ext_metadata,
125                    } => {
126                        // Convert things.
127                        let issued_at = OffsetDateTime::parse(issued_at, &Rfc3339)
128                            .map(|odt| odt.to_offset(time::UtcOffset::UTC))
129                            .map_err(|e| {
130                                admin_error!(
131                                    ?e,
132                                    "Invalidating session {} due to invalid issued_at timestamp",
133                                    refer
134                                )
135                            })
136                            .ok()?;
137
138                        let state = match state {
139                            DbValueSessionStateV1::ExpiresAt(e_inner) => {
140                                OffsetDateTime::parse(e_inner, &Rfc3339)
141                                    .map(|odt| odt.to_offset(time::UtcOffset::UTC))
142                                    .map(SessionState::ExpiresAt)
143                                    .map_err(|e| {
144                                        admin_error!(
145                                        ?e,
146                                        "Invalidating session {} due to invalid expiry timestamp",
147                                        refer
148                                    )
149                                    })
150                                    .ok()?
151                            }
152                            DbValueSessionStateV1::Never => SessionState::NeverExpires,
153                            DbValueSessionStateV1::RevokedAt(dc) => SessionState::RevokedAt(Cid {
154                                s_uuid: dc.server_id,
155                                ts: dc.timestamp,
156                            }),
157                        };
158
159                        let issued_by = match issued_by {
160                            DbValueIdentityId::V1Internal => IdentityId::Internal(UUID_SYSTEM),
161                            DbValueIdentityId::V2Internal(u) => IdentityId::Internal(*u),
162                            DbValueIdentityId::V1Uuid(u) => IdentityId::User(*u),
163                            DbValueIdentityId::V1Sync(u) => IdentityId::Synch(*u),
164                        };
165
166                        let scope = match scope {
167                            DbValueAccessScopeV1::IdentityOnly | DbValueAccessScopeV1::ReadOnly => {
168                                SessionScope::ReadOnly
169                            }
170                            DbValueAccessScopeV1::ReadWrite => SessionScope::ReadWrite,
171                            DbValueAccessScopeV1::PrivilegeCapable => {
172                                SessionScope::PrivilegeCapable
173                            }
174                            DbValueAccessScopeV1::Synchronise => SessionScope::Synchronise,
175                        };
176
177                        let type_ = match type_ {
178                            DbValueAuthTypeV1::Anonymous => AuthType::Anonymous,
179                            DbValueAuthTypeV1::Password => AuthType::Password,
180                            DbValueAuthTypeV1::GeneratedPassword => AuthType::GeneratedPassword,
181                            DbValueAuthTypeV1::PasswordTotp => AuthType::PasswordTotp,
182                            DbValueAuthTypeV1::PasswordBackupCode => AuthType::PasswordBackupCode,
183                            DbValueAuthTypeV1::PasswordSecurityKey => AuthType::PasswordSecurityKey,
184                            DbValueAuthTypeV1::Passkey => AuthType::Passkey,
185                            DbValueAuthTypeV1::AttestedPasskey => AuthType::AttestedPasskey,
186                            DbValueAuthTypeV1::OAuth2Trust => AuthType::OAuth2Trust,
187                        };
188
189                        let ext_metadata = match ext_metadata {
190                            DbValueSessionExtMetadataV1::None => SessionExtMetadata::None,
191                            DbValueSessionExtMetadataV1::OAuth2 {
192                                access_expires_at,
193                                access_token,
194                                refresh_token,
195                            } => SessionExtMetadata::OAuth2 {
196                                access_expires_at: *access_expires_at,
197                                access_token: access_token.clone(),
198                                refresh_token: refresh_token.clone(),
199                            },
200                        };
201
202                        Some((
203                            *refer,
204                            Session {
205                                label: label.clone(),
206                                state,
207                                issued_at,
208                                issued_by,
209                                cred_id: *cred_id,
210                                scope,
211                                type_,
212                                ext_metadata,
213                            },
214                        ))
215                    }
216                }
217            })
218            .collect();
219        Ok(Box::new(ValueSetSession { map }))
220    }
221
222    pub fn from_dbvs2(data: &[DbValueSession]) -> Result<ValueSet, OperationError> {
223        Self::from_dbv_iter(data.iter())
224    }
225
226    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
227    // types, and tuples are always foreign.
228    #[allow(clippy::should_implement_trait)]
229    pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
230    where
231        T: IntoIterator<Item = (Uuid, Session)>,
232    {
233        let map = iter.into_iter().collect();
234        Some(Box::new(ValueSetSession { map }))
235    }
236}
237
238impl ValueSetT for ValueSetSession {
239    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
240        match value {
241            Value::Session(u, m) => {
242                if let BTreeEntry::Vacant(e) = self.map.entry(u) {
243                    e.insert(m);
244                    Ok(true)
245                } else {
246                    Ok(false)
247                }
248            }
249            _ => Err(OperationError::InvalidValueState),
250        }
251    }
252
253    fn clear(&mut self) {
254        self.map.clear();
255    }
256
257    fn remove(&mut self, pv: &PartialValue, cid: &Cid) -> bool {
258        if let PartialValue::Refer(u) = pv {
259            if let Some(session) = self.map.get_mut(u) {
260                if !matches!(session.state, SessionState::RevokedAt(_)) {
261                    session.state = SessionState::RevokedAt(cid.clone());
262                }
263            }
264        }
265        self.map.is_empty()
266    }
267
268    fn purge(&mut self, cid: &Cid) -> bool {
269        for session in self.map.values_mut() {
270            // Send them all to the shadow realm
271            if !matches!(session.state, SessionState::RevokedAt(_)) {
272                session.state = SessionState::RevokedAt(cid.clone())
273            }
274        }
275        // Can't be purged since we need the cid's of revoked to persist.
276        false
277    }
278
279    fn trim(&mut self, trim_cid: &Cid) {
280        // There might be a neater way to do this with less iterations. The problem
281        // is we can't just check on what was in b/older, because then we miss
282        // trimmable content from the local map. So once the merge is complete we
283        // do a pass for trim.
284        self.map.retain(|_, session| {
285            match &session.state {
286                SessionState::RevokedAt(cid) if cid < trim_cid => {
287                    // This value is past the replication trim window and can now safely
288                    // be removed
289                    false
290                }
291                // Retain all else
292                _ => true,
293            }
294        });
295
296        // Now, assert that there are fewer or equal sessions to the limit.
297        if self.map.len() > SESSION_MAXIMUM {
298            // At this point we will force a number of sessions to be removed. This
299            // is replication safe since other replicas will also be performing
300            // the same operation on merge, since we trim by session issuance order.
301
302            // This is a "slow path". This is because we optimise session storage
303            // based on fast session lookup, so now we need to actually create an
304            // index based on time. We need to also clone here since we need to mutate
305            // self.map which would violate mut/imut.
306
307            warn!(
308                "entry has exceeded session_maximum limit ({:?}), force trimming will occur",
309                SESSION_MAXIMUM
310            );
311
312            let time_idx: BTreeMap<OffsetDateTime, Uuid> = self
313                .map
314                .iter()
315                .map(|(session_id, session)| (session.issued_at, *session_id))
316                .collect();
317
318            let to_take = self.map.len() - SESSION_MAXIMUM;
319
320            time_idx.values().take(to_take).for_each(|session_id| {
321                warn!(?session_id, "force trimmed");
322                self.map.remove(session_id);
323            });
324        }
325        // And we're done.
326    }
327
328    fn contains(&self, pv: &PartialValue) -> bool {
329        match pv {
330            PartialValue::Refer(u) => self.map.contains_key(u),
331            _ => false,
332        }
333    }
334
335    fn substring(&self, _pv: &PartialValue) -> bool {
336        false
337    }
338
339    fn startswith(&self, _pv: &PartialValue) -> bool {
340        false
341    }
342
343    fn endswith(&self, _pv: &PartialValue) -> bool {
344        false
345    }
346
347    fn lessthan(&self, _pv: &PartialValue) -> bool {
348        false
349    }
350
351    fn len(&self) -> usize {
352        self.map.len()
353    }
354
355    fn generate_idx_eq_keys(&self) -> Vec<String> {
356        self.map
357            .keys()
358            .map(|u| u.as_hyphenated().to_string())
359            .collect()
360    }
361
362    fn syntax(&self) -> SyntaxType {
363        SyntaxType::Session
364    }
365
366    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
367        true
368    }
369
370    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
371        Box::new(
372            self.map
373                .iter()
374                .map(|(u, m)| format!("{}: {:?}", uuid_to_proto_string(*u), m)),
375        )
376    }
377
378    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
379        Some(ScimResolveStatus::Resolved(ScimValueKanidm::from(
380            self.map
381                .iter()
382                .map(|(session_id, session)| {
383                    let (expires, revoked) = match &session.state {
384                        SessionState::ExpiresAt(odt) => (Some(*odt), None),
385                        SessionState::NeverExpires => (None, None),
386                        SessionState::RevokedAt(cid) => {
387                            let odt: OffsetDateTime = cid.into();
388                            (None, Some(odt))
389                        }
390                    };
391
392                    ScimAuthSession {
393                        id: *session_id,
394                        expires,
395                        revoked,
396
397                        issued_at: session.issued_at,
398                        issued_by: Uuid::from(&session.issued_by),
399                        credential_id: session.cred_id,
400                        auth_type: session.type_.to_string(),
401                        session_scope: session.scope.to_string(),
402                    }
403                })
404                .collect::<Vec<_>>(),
405        )))
406    }
407
408    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
409        DbValueSetV2::Session(self.to_vec_dbvs())
410    }
411
412    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
413        Box::new(self.map.keys().cloned().map(PartialValue::Refer))
414    }
415
416    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
417        Box::new(self.map.iter().map(|(u, m)| Value::Session(*u, m.clone())))
418    }
419
420    fn equal(&self, other: &ValueSet) -> bool {
421        if let Some(other) = other.as_session_map() {
422            &self.map == other
423        } else {
424            debug_assert!(false);
425            false
426        }
427    }
428
429    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
430        if let Some(b) = other.as_session_map() {
431            // We can't just do merge maps here, we have to be aware of the
432            // session.state value and what it currently is set to.
433            for (k_other, v_other) in b.iter() {
434                if let Some(v_self) = self.map.get_mut(k_other) {
435                    // We only update if greater. This is where RevokedAt
436                    // always proceeds other states, and lower revoked
437                    // cids will always take effect.
438                    if v_other.state > v_self.state {
439                        *v_self = v_other.clone();
440                    }
441                } else {
442                    // Not present, just insert.
443                    self.map.insert(*k_other, v_other.clone());
444                }
445            }
446            Ok(())
447        } else {
448            debug_assert!(false);
449            Err(OperationError::InvalidValueState)
450        }
451    }
452
453    fn as_session_map(&self) -> Option<&BTreeMap<Uuid, Session>> {
454        Some(&self.map)
455    }
456
457    fn as_ref_uuid_iter(&self) -> Option<Box<dyn Iterator<Item = Uuid> + '_>> {
458        // This is what ties us as a type that can be refint checked.
459        Some(Box::new(self.map.keys().copied()))
460    }
461
462    fn repl_merge_valueset(&self, older: &ValueSet, trim_cid: &Cid) -> Option<ValueSet> {
463        // If the older value has a different type - return nothing, we
464        // just take the newer value.
465        let b = older.as_session_map()?;
466        // We can't just do merge maps here, we have to be aware of the
467        // session.state value and what it currently is set to.
468        let mut map = self.map.clone();
469        for (k_other, v_other) in b.iter() {
470            if let Some(v_self) = map.get_mut(k_other) {
471                // We only update if lower. This is where RevokedAt
472                // always proceeds other states, and lower revoked
473                // cids will always take effect.
474                if v_other.state > v_self.state {
475                    *v_self = v_other.clone();
476                }
477            } else {
478                // Not present, just insert.
479                map.insert(*k_other, v_other.clone());
480            }
481        }
482
483        let mut vs = Box::new(ValueSetSession { map });
484
485        vs.trim(trim_cid);
486
487        Some(vs)
488    }
489}
490
491// == oauth2 session ==
492
493#[derive(Debug, Clone)]
494pub struct ValueSetOauth2Session {
495    map: BTreeMap<Uuid, Oauth2Session>,
496    // this is a "filter" to tell us if as rs_id is used anywhere
497    // in this set. The reason is so that we don't do O(n) searches
498    // on a refer if it's not in this set. The alternate approach is
499    // an index on these maps, but its more work to maintain for a rare
500    // situation where we actually want to query rs_uuid -> sessions.
501    rs_filter: u128,
502}
503
504impl ValueSetOauth2Session {
505    pub fn new(u: Uuid, m: Oauth2Session) -> Box<Self> {
506        let mut map = BTreeMap::new();
507        let rs_filter = m.rs_uuid.as_u128();
508        map.insert(u, m);
509        Box::new(ValueSetOauth2Session { map, rs_filter })
510    }
511
512    pub fn push(&mut self, u: Uuid, m: Oauth2Session) -> bool {
513        self.rs_filter |= m.rs_uuid.as_u128();
514        self.map.insert(u, m).is_none()
515    }
516
517    pub fn from_dbvs2(data: Vec<DbValueOauth2Session>) -> Result<ValueSet, OperationError> {
518        let mut rs_filter = u128::MIN;
519        let map = data
520            .into_iter()
521            .filter_map(|dbv| {
522                match dbv {
523                    DbValueOauth2Session::V1 {
524                        refer,
525                        parent,
526                        expiry,
527                        issued_at,
528                        rs_uuid,
529                    } => {
530                        // Convert things.
531                        let issued_at = OffsetDateTime::parse(&issued_at, &Rfc3339)
532                            .map(|odt| odt.to_offset(time::UtcOffset::UTC))
533                            .map_err(|e| {
534                                admin_error!(
535                                    ?e,
536                                    "Invalidating session {} due to invalid issued_at timestamp",
537                                    refer
538                                )
539                            })
540                            .ok()?;
541
542                        // This is a bit annoying. In the case we can't parse the optional
543                        // expiry, we need to NOT return the session so that it's immediately
544                        // invalidated. To do this we have to invert some of the options involved
545                        // here.
546                        let expiry = expiry
547                            .map(|e_inner| {
548                                OffsetDateTime::parse(&e_inner, &Rfc3339)
549                                    .map(|odt| odt.to_offset(time::UtcOffset::UTC))
550                                // We now have an
551                                // Option<Result<ODT, _>>
552                            })
553                            .transpose()
554                            // Result<Option<ODT>, _>
555                            .map_err(|e| {
556                                admin_error!(
557                                    ?e,
558                                    "Invalidating session {} due to invalid expiry timestamp",
559                                    refer
560                                )
561                            })
562                            // Option<Option<ODT>>
563                            .ok()?;
564
565                        let state = expiry
566                            .map(SessionState::ExpiresAt)
567                            .unwrap_or(SessionState::NeverExpires);
568
569                        let parent = Some(parent);
570
571                        // Insert to the rs_filter.
572                        rs_filter |= rs_uuid.as_u128();
573                        Some((
574                            refer,
575                            Oauth2Session {
576                                parent,
577                                state,
578                                issued_at,
579                                rs_uuid,
580                            },
581                        ))
582                    }
583                    DbValueOauth2Session::V2 {
584                        refer,
585                        parent,
586                        state,
587                        issued_at,
588                        rs_uuid,
589                    } => {
590                        // Convert things.
591                        let issued_at = OffsetDateTime::parse(&issued_at, &Rfc3339)
592                            .map(|odt| odt.to_offset(time::UtcOffset::UTC))
593                            .map_err(|e| {
594                                admin_error!(
595                                    ?e,
596                                    "Invalidating session {} due to invalid issued_at timestamp",
597                                    refer
598                                )
599                            })
600                            .ok()?;
601
602                        let state = match state {
603                            DbValueSessionStateV1::ExpiresAt(e_inner) => {
604                                OffsetDateTime::parse(&e_inner, &Rfc3339)
605                                    .map(|odt| odt.to_offset(time::UtcOffset::UTC))
606                                    .map(SessionState::ExpiresAt)
607                                    .map_err(|e| {
608                                        admin_error!(
609                                    ?e,
610                                    "Invalidating session {} due to invalid expiry timestamp",
611                                    refer
612                                )
613                                    })
614                                    .ok()?
615                            }
616                            DbValueSessionStateV1::Never => SessionState::NeverExpires,
617                            DbValueSessionStateV1::RevokedAt(dc) => SessionState::RevokedAt(Cid {
618                                s_uuid: dc.server_id,
619                                ts: dc.timestamp,
620                            }),
621                        };
622
623                        rs_filter |= rs_uuid.as_u128();
624
625                        let parent = Some(parent);
626
627                        Some((
628                            refer,
629                            Oauth2Session {
630                                parent,
631                                state,
632                                issued_at,
633                                rs_uuid,
634                            },
635                        ))
636                    } // End V2
637                    DbValueOauth2Session::V3 {
638                        refer,
639                        parent,
640                        state,
641                        issued_at,
642                        rs_uuid,
643                    } => {
644                        // Convert things.
645                        let issued_at = OffsetDateTime::parse(&issued_at, &Rfc3339)
646                            .map(|odt| odt.to_offset(time::UtcOffset::UTC))
647                            .map_err(|e| {
648                                admin_error!(
649                                    ?e,
650                                    "Invalidating session {} due to invalid issued_at timestamp",
651                                    refer
652                                )
653                            })
654                            .ok()?;
655
656                        let state = match state {
657                            DbValueSessionStateV1::ExpiresAt(e_inner) => {
658                                OffsetDateTime::parse(&e_inner, &Rfc3339)
659                                    .map(|odt| odt.to_offset(time::UtcOffset::UTC))
660                                    .map(SessionState::ExpiresAt)
661                                    .map_err(|e| {
662                                        admin_error!(
663                                    ?e,
664                                    "Invalidating session {} due to invalid expiry timestamp",
665                                    refer
666                                )
667                                    })
668                                    .ok()?
669                            }
670                            DbValueSessionStateV1::Never => SessionState::NeverExpires,
671                            DbValueSessionStateV1::RevokedAt(dc) => SessionState::RevokedAt(Cid {
672                                s_uuid: dc.server_id,
673                                ts: dc.timestamp,
674                            }),
675                        };
676
677                        rs_filter |= rs_uuid.as_u128();
678
679                        Some((
680                            refer,
681                            Oauth2Session {
682                                parent,
683                                state,
684                                issued_at,
685                                rs_uuid,
686                            },
687                        ))
688                    } // End V3
689                }
690            })
691            .collect();
692        Ok(Box::new(ValueSetOauth2Session { map, rs_filter }))
693    }
694
695    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
696    // types, and tuples are always foreign.
697    #[allow(clippy::should_implement_trait)]
698    pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
699    where
700        T: IntoIterator<Item = (Uuid, Oauth2Session)>,
701    {
702        let mut rs_filter = u128::MIN;
703        let map = iter
704            .into_iter()
705            .map(|(u, m)| {
706                rs_filter |= m.rs_uuid.as_u128();
707                (u, m)
708            })
709            .collect();
710        Some(Box::new(ValueSetOauth2Session { map, rs_filter }))
711    }
712}
713
714impl ValueSetT for ValueSetOauth2Session {
715    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
716        match value {
717            Value::Oauth2Session(u, m) => {
718                // Unlike other types, this allows overwriting as oauth2 sessions
719                // can be *extended* in time length.
720                match self.map.entry(u) {
721                    BTreeEntry::Vacant(e) => {
722                        self.rs_filter |= m.rs_uuid.as_u128();
723                        e.insert(m);
724                        Ok(true)
725                    }
726                    BTreeEntry::Occupied(mut e) => {
727                        let e_v = e.get_mut();
728                        if m.state > e_v.state {
729                            // Replace if the state has higher priority.
730                            *e_v = m;
731                            Ok(true)
732                        } else {
733                            // Else take no action.
734                            Ok(false)
735                        }
736                    }
737                }
738            }
739            _ => Err(OperationError::InvalidValueState),
740        }
741    }
742
743    fn clear(&mut self) {
744        self.rs_filter = u128::MIN;
745        self.map.clear();
746    }
747
748    fn remove(&mut self, pv: &PartialValue, cid: &Cid) -> bool {
749        if let PartialValue::Refer(u) = pv {
750            if let Some(session) = self.map.get_mut(u) {
751                if !matches!(session.state, SessionState::RevokedAt(_)) {
752                    session.state = SessionState::RevokedAt(cid.clone());
753                }
754            } else {
755                // What if it's an rs_uuid?
756                let u_int = u.as_u128();
757                if self.rs_filter & u_int == u_int {
758                    // It's there, so we need to do a more costly revoke over the values
759                    // that are present.
760                    let mut removed = false;
761                    self.map.values_mut().for_each(|session| {
762                        if session.rs_uuid == *u {
763                            session.state = SessionState::RevokedAt(cid.clone());
764                            removed = true;
765                        }
766                    });
767                }
768            }
769        };
770        self.map.is_empty()
771    }
772
773    fn purge(&mut self, cid: &Cid) -> bool {
774        for session in self.map.values_mut() {
775            // Send them all to the shadow realm
776            if !matches!(session.state, SessionState::RevokedAt(_)) {
777                session.state = SessionState::RevokedAt(cid.clone())
778            }
779        }
780        // Can't be purged since we need the cid's of revoked to persist.
781        false
782    }
783
784    fn trim(&mut self, trim_cid: &Cid) {
785        // There might be a neater way to do this with less iterations. The problem
786        // is we can't just check on what was in b/older, because then we miss
787        // trimmable content from the local map. So once the merge is complete we
788        // do a pass for trim.
789        self.map.retain(|_, session| {
790            match &session.state {
791                SessionState::RevokedAt(cid) if cid < trim_cid => {
792                    // This value is past the replication trim window and can now safely
793                    // be removed
794                    false
795                }
796                // Retain all else
797                _ => true,
798            }
799        })
800    }
801
802    fn contains(&self, pv: &PartialValue) -> bool {
803        match pv {
804            PartialValue::Refer(u) => {
805                self.map.contains_key(u) || {
806                    let u_int = u.as_u128();
807                    if self.rs_filter & u_int == u_int {
808                        self.map.values().any(|session| {
809                            session.rs_uuid == *u
810                                && !matches!(session.state, SessionState::RevokedAt(_))
811                        })
812                    } else {
813                        false
814                    }
815                }
816            }
817            _ => false,
818        }
819    }
820
821    fn substring(&self, _pv: &PartialValue) -> bool {
822        false
823    }
824
825    fn startswith(&self, _pv: &PartialValue) -> bool {
826        false
827    }
828
829    fn endswith(&self, _pv: &PartialValue) -> bool {
830        false
831    }
832
833    fn lessthan(&self, _pv: &PartialValue) -> bool {
834        false
835    }
836
837    fn len(&self) -> usize {
838        self.map.len()
839    }
840
841    fn generate_idx_eq_keys(&self) -> Vec<String> {
842        // Allocate twice as much for worst-case when every session is
843        // a unique rs-uuid to prevent re-allocs.
844        let mut idx_keys = Vec::with_capacity(self.map.len() * 2);
845        for (k, v) in self.map.iter() {
846            idx_keys.push(k.as_hyphenated().to_string());
847            idx_keys.push(v.rs_uuid.as_hyphenated().to_string());
848        }
849        idx_keys.sort_unstable();
850        idx_keys.dedup();
851        idx_keys
852    }
853
854    fn syntax(&self) -> SyntaxType {
855        SyntaxType::Oauth2Session
856    }
857
858    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
859        true
860    }
861
862    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
863        Box::new(
864            self.map
865                .iter()
866                .map(|(u, m)| format!("{}: {:?}", uuid_to_proto_string(*u), m)),
867        )
868    }
869
870    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
871        Some(ScimResolveStatus::Resolved(ScimValueKanidm::from(
872            self.map
873                .iter()
874                .map(|(session_id, session)| {
875                    let (expires, revoked) = match &session.state {
876                        SessionState::ExpiresAt(odt) => (Some(*odt), None),
877                        SessionState::NeverExpires => (None, None),
878                        SessionState::RevokedAt(cid) => {
879                            let odt: OffsetDateTime = cid.into();
880                            (None, Some(odt))
881                        }
882                    };
883
884                    ScimOAuth2Session {
885                        id: *session_id,
886                        parent_id: session.parent,
887                        client_id: session.rs_uuid,
888                        issued_at: session.issued_at,
889                        expires,
890                        revoked,
891                    }
892                })
893                .collect::<Vec<_>>(),
894        )))
895    }
896
897    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
898        DbValueSetV2::Oauth2Session(
899            self.map
900                .iter()
901                .map(|(u, m)| DbValueOauth2Session::V3 {
902                    refer: *u,
903                    parent: m.parent,
904                    state: match &m.state {
905                        SessionState::ExpiresAt(odt) => {
906                            debug_assert_eq!(odt.offset(), time::UtcOffset::UTC);
907                            #[allow(clippy::expect_used)]
908                            odt.format(&Rfc3339)
909                                .map(DbValueSessionStateV1::ExpiresAt)
910                                .expect("Failed to format timestamp into RFC3339!")
911                        }
912                        SessionState::NeverExpires => DbValueSessionStateV1::Never,
913                        SessionState::RevokedAt(c) => DbValueSessionStateV1::RevokedAt(DbCidV1 {
914                            server_id: c.s_uuid,
915                            timestamp: c.ts,
916                        }),
917                    },
918                    issued_at: {
919                        debug_assert_eq!(m.issued_at.offset(), time::UtcOffset::UTC);
920                        #[allow(clippy::expect_used)]
921                        m.issued_at
922                            .format(&Rfc3339)
923                            .expect("Failed to format timestamp as RFC3339")
924                    },
925                    rs_uuid: m.rs_uuid,
926                })
927                .collect(),
928        )
929    }
930
931    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
932        Box::new(self.map.keys().cloned().map(PartialValue::Refer))
933    }
934
935    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
936        Box::new(
937            self.map
938                .iter()
939                .map(|(u, m)| Value::Oauth2Session(*u, m.clone())),
940        )
941    }
942
943    fn equal(&self, other: &ValueSet) -> bool {
944        if let Some(other) = other.as_oauth2session_map() {
945            &self.map == other
946        } else {
947            debug_assert!(false);
948            false
949        }
950    }
951
952    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
953        if let Some(b) = other.as_oauth2session_map() {
954            // We can't just do merge maps here, we have to be aware of the
955            // session.state value and what it currently is set to. We also
956            // need to make sure the rs_filter is updated too!
957            for (k_other, v_other) in b.iter() {
958                if let Some(v_self) = self.map.get_mut(k_other) {
959                    // We only update if lower. This is where RevokedAt
960                    // always proceeds other states, and lower revoked
961                    // cids will always take effect.
962                    if v_other.state > v_self.state {
963                        *v_self = v_other.clone();
964                    }
965                } else {
966                    // Update the rs_filter!
967                    self.rs_filter |= v_other.rs_uuid.as_u128();
968                    // Not present, just insert.
969                    self.map.insert(*k_other, v_other.clone());
970                }
971            }
972            Ok(())
973        } else {
974            debug_assert!(false);
975            Err(OperationError::InvalidValueState)
976        }
977    }
978
979    fn as_oauth2session_map(&self) -> Option<&BTreeMap<Uuid, Oauth2Session>> {
980        Some(&self.map)
981    }
982
983    fn as_ref_uuid_iter(&self) -> Option<Box<dyn Iterator<Item = Uuid> + '_>> {
984        // This is what ties us as a type that can be refint checked. We need to
985        // bind to our resource servers, not our ids!
986        Some(Box::new(self.map.values().map(|m| &m.rs_uuid).copied()))
987    }
988
989    fn repl_merge_valueset(&self, older: &ValueSet, trim_cid: &Cid) -> Option<ValueSet> {
990        if let Some(b) = older.as_oauth2session_map() {
991            // We can't just do merge maps here, we have to be aware of the
992            // session.state value and what it currently is set to.
993            let mut map = self.map.clone();
994            let mut rs_filter = self.rs_filter;
995            for (k_other, v_other) in b.iter() {
996                if let Some(v_self) = map.get_mut(k_other) {
997                    // We only update if greater. This is where RevokedAt
998                    // always proceeds other states, and lower revoked
999                    // cids will always take effect.
1000                    if v_other.state > v_self.state {
1001                        *v_self = v_other.clone();
1002                    }
1003                } else {
1004                    // Not present, just insert.
1005                    rs_filter |= v_other.rs_uuid.as_u128();
1006                    map.insert(*k_other, v_other.clone());
1007                }
1008            }
1009
1010            let mut vs = Box::new(ValueSetOauth2Session { map, rs_filter });
1011
1012            vs.trim(trim_cid);
1013
1014            Some(vs)
1015        } else {
1016            // The older value has a different type - return nothing, we
1017            // just take the newer value.
1018            None
1019        }
1020    }
1021}
1022
1023#[derive(Debug, Clone)]
1024pub struct ValueSetApiTokenSet {
1025    map: BTreeMap<Uuid, ApiToken>,
1026}
1027
1028impl ValueSetApiTokenSet {
1029    pub fn new(u: Uuid, m: ApiToken) -> Box<Self> {
1030        let mut map = BTreeMap::new();
1031        map.insert(u, m);
1032        Box::new(Self { map })
1033    }
1034
1035    pub fn push(&mut self, u: Uuid, m: ApiToken) -> bool {
1036        self.map.insert(u, m).is_none()
1037    }
1038
1039    pub fn from_dbvs2(data: Vec<DbValueApiToken>) -> Result<ValueSet, OperationError> {
1040        let map = data
1041            .into_iter()
1042            .filter_map(|dbv| {
1043                match dbv {
1044                    DbValueApiToken::V1 {
1045                        refer,
1046                        label,
1047                        expiry,
1048                        issued_at,
1049                        issued_by,
1050                        scope,
1051                    } => {
1052                        // Convert things.
1053                        let issued_at = OffsetDateTime::parse(&issued_at, &Rfc3339)
1054                            .map(|odt| odt.to_offset(time::UtcOffset::UTC))
1055                            .map_err(|e| {
1056                                admin_error!(
1057                                    ?e,
1058                                    "Invalidating api token {} due to invalid issued_at timestamp",
1059                                    refer
1060                                )
1061                            })
1062                            .ok()?;
1063
1064                        // This is a bit annoying. In the case we can't parse the optional
1065                        // expiry, we need to NOT return the session so that it's immediately
1066                        // invalidated. To do this we have to invert some of the options involved
1067                        // here.
1068                        let expiry = expiry
1069                            .map(|e_inner| {
1070                                OffsetDateTime::parse(&e_inner, &Rfc3339)
1071                                    .map(|odt| odt.to_offset(time::UtcOffset::UTC))
1072                                // We now have an
1073                                // Option<Result<ODT, _>>
1074                            })
1075                            .transpose()
1076                            // Result<Option<ODT>, _>
1077                            .map_err(|e| {
1078                                admin_error!(
1079                                    ?e,
1080                                    "Invalidating api token {} due to invalid expiry timestamp",
1081                                    refer
1082                                )
1083                            })
1084                            // Option<Option<ODT>>
1085                            .ok()?;
1086
1087                        let issued_by = match issued_by {
1088                            DbValueIdentityId::V1Internal => IdentityId::Internal(UUID_SYSTEM),
1089                            DbValueIdentityId::V2Internal(u) => IdentityId::Internal(u),
1090                            DbValueIdentityId::V1Uuid(u) => IdentityId::User(u),
1091                            DbValueIdentityId::V1Sync(u) => IdentityId::Synch(u),
1092                        };
1093
1094                        let scope = match scope {
1095                            DbValueApiTokenScopeV1::ReadOnly => ApiTokenScope::ReadOnly,
1096                            DbValueApiTokenScopeV1::ReadWrite => ApiTokenScope::ReadWrite,
1097                            DbValueApiTokenScopeV1::Synchronise => ApiTokenScope::Synchronise,
1098                        };
1099
1100                        Some((
1101                            refer,
1102                            ApiToken {
1103                                label,
1104                                expiry,
1105                                issued_at,
1106                                issued_by,
1107                                scope,
1108                            },
1109                        ))
1110                    }
1111                }
1112            })
1113            .collect();
1114        Ok(Box::new(Self { map }))
1115    }
1116
1117    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
1118    // types, and tuples are always foreign.
1119    #[allow(clippy::should_implement_trait)]
1120    pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
1121    where
1122        T: IntoIterator<Item = (Uuid, ApiToken)>,
1123    {
1124        let map = iter.into_iter().collect();
1125        Some(Box::new(Self { map }))
1126    }
1127}
1128
1129impl ValueSetT for ValueSetApiTokenSet {
1130    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
1131        match value {
1132            Value::ApiToken(u, m) => {
1133                if let BTreeEntry::Vacant(e) = self.map.entry(u) {
1134                    e.insert(m);
1135                    Ok(true)
1136                } else {
1137                    Ok(false)
1138                }
1139            }
1140            _ => Err(OperationError::InvalidValueState),
1141        }
1142    }
1143
1144    fn clear(&mut self) {
1145        self.map.clear();
1146    }
1147
1148    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
1149        if let PartialValue::Refer(u) = pv {
1150            self.map.remove(u);
1151        };
1152        self.map.is_empty()
1153    }
1154
1155    fn purge(&mut self, _cid: &Cid) -> bool {
1156        // Could consider making this a TS capable entry.
1157        true
1158    }
1159
1160    fn contains(&self, pv: &PartialValue) -> bool {
1161        match pv {
1162            PartialValue::Refer(u) => self.map.contains_key(u),
1163            _ => false,
1164        }
1165    }
1166
1167    fn substring(&self, _pv: &PartialValue) -> bool {
1168        false
1169    }
1170
1171    fn startswith(&self, _pv: &PartialValue) -> bool {
1172        false
1173    }
1174
1175    fn endswith(&self, _pv: &PartialValue) -> bool {
1176        false
1177    }
1178
1179    fn lessthan(&self, _pv: &PartialValue) -> bool {
1180        false
1181    }
1182
1183    fn len(&self) -> usize {
1184        self.map.len()
1185    }
1186
1187    fn generate_idx_eq_keys(&self) -> Vec<String> {
1188        self.map
1189            .keys()
1190            .map(|u| u.as_hyphenated().to_string())
1191            .collect()
1192    }
1193
1194    fn syntax(&self) -> SyntaxType {
1195        SyntaxType::ApiToken
1196    }
1197
1198    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
1199        self.map.iter().all(|(_, at)| {
1200            Value::validate_str_escapes(&at.label) && Value::validate_singleline(&at.label)
1201        })
1202    }
1203
1204    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
1205        Box::new(
1206            self.map
1207                .iter()
1208                .map(|(u, m)| format!("{}: {:?}", uuid_to_proto_string(*u), m)),
1209        )
1210    }
1211
1212    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
1213        Some(ScimResolveStatus::Resolved(ScimValueKanidm::from(
1214            self.map
1215                .iter()
1216                .map(|(token_id, token)| ScimApiToken {
1217                    id: *token_id,
1218                    label: token.label.clone(),
1219                    issued_by: Uuid::from(&token.issued_by),
1220                    issued_at: token.issued_at,
1221                    expires: token.expiry,
1222                    scope: token.scope.to_string(),
1223                })
1224                .collect::<Vec<_>>(),
1225        )))
1226    }
1227
1228    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
1229        DbValueSetV2::ApiTokenSet(
1230            self.map
1231                .iter()
1232                .map(|(u, m)| DbValueApiToken::V1 {
1233                    refer: *u,
1234                    label: m.label.clone(),
1235                    expiry: m.expiry.map(|odt| {
1236                        debug_assert_eq!(odt.offset(), time::UtcOffset::UTC);
1237                        #[allow(clippy::expect_used)]
1238                        odt.format(&Rfc3339)
1239                            .expect("Failed to format timestamp into RFC3339")
1240                    }),
1241                    issued_at: {
1242                        debug_assert_eq!(m.issued_at.offset(), time::UtcOffset::UTC);
1243                        #[allow(clippy::expect_used)]
1244                        m.issued_at
1245                            .format(&Rfc3339)
1246                            .expect("Failed to format timestamp into RFC3339")
1247                    },
1248                    issued_by: match m.issued_by {
1249                        IdentityId::Internal(u) => DbValueIdentityId::V2Internal(u),
1250                        IdentityId::User(u) => DbValueIdentityId::V1Uuid(u),
1251                        IdentityId::Synch(u) => DbValueIdentityId::V1Sync(u),
1252                    },
1253                    scope: match m.scope {
1254                        ApiTokenScope::ReadOnly => DbValueApiTokenScopeV1::ReadOnly,
1255                        ApiTokenScope::ReadWrite => DbValueApiTokenScopeV1::ReadWrite,
1256                        ApiTokenScope::Synchronise => DbValueApiTokenScopeV1::Synchronise,
1257                    },
1258                })
1259                .collect(),
1260        )
1261    }
1262
1263    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
1264        Box::new(self.map.keys().cloned().map(PartialValue::Refer))
1265    }
1266
1267    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
1268        Box::new(self.map.iter().map(|(u, m)| Value::ApiToken(*u, m.clone())))
1269    }
1270
1271    fn equal(&self, other: &ValueSet) -> bool {
1272        if let Some(other) = other.as_apitoken_map() {
1273            &self.map == other
1274        } else {
1275            debug_assert!(false);
1276            false
1277        }
1278    }
1279
1280    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
1281        if let Some(b) = other.as_apitoken_map() {
1282            mergemaps!(self.map, b)
1283        } else {
1284            debug_assert!(false);
1285            Err(OperationError::InvalidValueState)
1286        }
1287    }
1288
1289    fn as_apitoken_map(&self) -> Option<&BTreeMap<Uuid, ApiToken>> {
1290        Some(&self.map)
1291    }
1292
1293    fn as_ref_uuid_iter(&self) -> Option<Box<dyn Iterator<Item = Uuid> + '_>> {
1294        // This is what ties us as a type that can be refint checked.
1295        Some(Box::new(self.map.keys().copied()))
1296    }
1297}
1298
1299#[cfg(test)]
1300mod tests {
1301    use super::{ValueSetOauth2Session, ValueSetSession, SESSION_MAXIMUM};
1302    use crate::{
1303        prelude::{IdentityId, SessionScope, Uuid, ValueSet, UUID_SYSTEM},
1304        repl::cid::Cid,
1305        value::{AuthType, Oauth2Session, Session, SessionState},
1306    };
1307    use time::OffsetDateTime;
1308
1309    #[test]
1310    fn test_valueset_session_purge() {
1311        let s_uuid = Uuid::new_v4();
1312        #[deny(clippy::disallowed_methods)]
1313        let mut vs: ValueSet = ValueSetSession::new(
1314            s_uuid,
1315            Session {
1316                label: "hacks".to_string(),
1317                state: SessionState::NeverExpires,
1318                #[allow(clippy::disallowed_methods)]
1319                issued_at: OffsetDateTime::now_utc(),
1320                issued_by: IdentityId::Internal(UUID_SYSTEM),
1321                cred_id: Uuid::new_v4(),
1322                scope: SessionScope::ReadOnly,
1323                type_: AuthType::Passkey,
1324                ext_metadata: Default::default(),
1325            },
1326        );
1327
1328        let zero_cid = Cid::new_zero();
1329
1330        // Simulate session revocation.
1331        let r = vs.purge(&zero_cid);
1332
1333        assert!(!r);
1334        assert_eq!(vs.len(), 1);
1335
1336        let session = vs
1337            .as_session_map()
1338            .and_then(|map| map.get(&s_uuid))
1339            .expect("Unable to locate session");
1340
1341        assert_eq!(session.state, SessionState::RevokedAt(zero_cid));
1342    }
1343
1344    #[test]
1345    fn test_valueset_session_merge_left() {
1346        let s_uuid = Uuid::new_v4();
1347        let zero_cid = Cid::new_zero();
1348
1349        let mut vs_a: ValueSet = ValueSetSession::new(
1350            s_uuid,
1351            Session {
1352                label: "hacks".to_string(),
1353                state: SessionState::NeverExpires,
1354                #[allow(clippy::disallowed_methods)]
1355                issued_at: OffsetDateTime::now_utc(),
1356                issued_by: IdentityId::Internal(UUID_SYSTEM),
1357                cred_id: Uuid::new_v4(),
1358                scope: SessionScope::ReadOnly,
1359                type_: AuthType::Passkey,
1360                ext_metadata: Default::default(),
1361            },
1362        );
1363
1364        let vs_b: ValueSet = ValueSetSession::new(
1365            s_uuid,
1366            Session {
1367                label: "hacks".to_string(),
1368                state: SessionState::RevokedAt(zero_cid.clone()),
1369                #[allow(clippy::disallowed_methods)]
1370                issued_at: OffsetDateTime::now_utc(),
1371                issued_by: IdentityId::Internal(UUID_SYSTEM),
1372                cred_id: Uuid::new_v4(),
1373                scope: SessionScope::ReadOnly,
1374                type_: AuthType::Passkey,
1375                ext_metadata: Default::default(),
1376            },
1377        );
1378
1379        vs_a.merge(&vs_b).expect("failed to merge");
1380
1381        let session = vs_a
1382            .as_session_map()
1383            .and_then(|map| map.get(&s_uuid))
1384            .expect("Unable to locate session");
1385
1386        assert_eq!(session.state, SessionState::RevokedAt(zero_cid));
1387    }
1388
1389    #[test]
1390    fn test_valueset_session_merge_right() {
1391        let s_uuid = Uuid::new_v4();
1392        let zero_cid = Cid::new_zero();
1393
1394        let vs_a: ValueSet = ValueSetSession::new(
1395            s_uuid,
1396            Session {
1397                label: "hacks".to_string(),
1398                state: SessionState::NeverExpires,
1399                #[allow(clippy::disallowed_methods)]
1400                issued_at: OffsetDateTime::now_utc(),
1401                issued_by: IdentityId::Internal(UUID_SYSTEM),
1402                cred_id: Uuid::new_v4(),
1403                scope: SessionScope::ReadOnly,
1404                type_: AuthType::Passkey,
1405                ext_metadata: Default::default(),
1406            },
1407        );
1408
1409        let mut vs_b: ValueSet = ValueSetSession::new(
1410            s_uuid,
1411            Session {
1412                label: "hacks".to_string(),
1413                state: SessionState::RevokedAt(zero_cid.clone()),
1414                #[allow(clippy::disallowed_methods)]
1415                issued_at: OffsetDateTime::now_utc(),
1416                issued_by: IdentityId::Internal(UUID_SYSTEM),
1417                cred_id: Uuid::new_v4(),
1418                scope: SessionScope::ReadOnly,
1419                type_: AuthType::Passkey,
1420                ext_metadata: Default::default(),
1421            },
1422        );
1423
1424        // Note - inverse order!
1425        vs_b.merge(&vs_a).expect("failed to merge");
1426
1427        let session = vs_b
1428            .as_session_map()
1429            .and_then(|map| map.get(&s_uuid))
1430            .expect("Unable to locate session");
1431
1432        assert_eq!(session.state, SessionState::RevokedAt(zero_cid));
1433    }
1434
1435    #[test]
1436    fn test_valueset_session_repl_merge_left() {
1437        let s_uuid = Uuid::new_v4();
1438        let r_uuid = Uuid::new_v4();
1439        let zero_cid = Cid::new_zero();
1440        let one_cid = Cid::new_count(1);
1441
1442        let vs_a: ValueSet = ValueSetSession::new(
1443            s_uuid,
1444            Session {
1445                label: "hacks".to_string(),
1446                state: SessionState::NeverExpires,
1447                #[allow(clippy::disallowed_methods)]
1448                issued_at: OffsetDateTime::now_utc(),
1449                issued_by: IdentityId::Internal(UUID_SYSTEM),
1450                cred_id: Uuid::new_v4(),
1451                scope: SessionScope::ReadOnly,
1452                type_: AuthType::Passkey,
1453                ext_metadata: Default::default(),
1454            },
1455        );
1456
1457        let vs_b: ValueSet = ValueSetSession::from_iter([
1458            (
1459                s_uuid,
1460                Session {
1461                    label: "hacks".to_string(),
1462                    state: SessionState::RevokedAt(one_cid.clone()),
1463                    #[allow(clippy::disallowed_methods)]
1464                    issued_at: OffsetDateTime::now_utc(),
1465                    issued_by: IdentityId::Internal(UUID_SYSTEM),
1466                    cred_id: Uuid::new_v4(),
1467                    scope: SessionScope::ReadOnly,
1468                    type_: AuthType::Passkey,
1469                    ext_metadata: Default::default(),
1470                },
1471            ),
1472            (
1473                r_uuid,
1474                Session {
1475                    label: "hacks".to_string(),
1476                    state: SessionState::RevokedAt(zero_cid.clone()),
1477                    #[allow(clippy::disallowed_methods)]
1478                    issued_at: OffsetDateTime::now_utc(),
1479                    issued_by: IdentityId::Internal(UUID_SYSTEM),
1480                    cred_id: Uuid::new_v4(),
1481                    scope: SessionScope::ReadOnly,
1482                    type_: AuthType::Passkey,
1483                    ext_metadata: Default::default(),
1484                },
1485            ),
1486        ])
1487        .expect("Unable to build valueset session");
1488
1489        let r_vs = vs_a
1490            .repl_merge_valueset(&vs_b, &one_cid)
1491            .expect("failed to merge");
1492
1493        let sessions = r_vs.as_session_map().expect("Unable to locate sessions");
1494
1495        let session = sessions.get(&s_uuid).expect("Unable to locate session");
1496
1497        assert_eq!(session.state, SessionState::RevokedAt(one_cid));
1498
1499        assert!(!sessions.contains_key(&r_uuid));
1500    }
1501
1502    #[test]
1503    fn test_valueset_session_repl_merge_right() {
1504        let s_uuid = Uuid::new_v4();
1505        let r_uuid = Uuid::new_v4();
1506        let zero_cid = Cid::new_zero();
1507        let one_cid = Cid::new_count(1);
1508
1509        let vs_a: ValueSet = ValueSetSession::new(
1510            s_uuid,
1511            Session {
1512                label: "hacks".to_string(),
1513                state: SessionState::NeverExpires,
1514                #[allow(clippy::disallowed_methods)]
1515                issued_at: OffsetDateTime::now_utc(),
1516                issued_by: IdentityId::Internal(UUID_SYSTEM),
1517                cred_id: Uuid::new_v4(),
1518                scope: SessionScope::ReadOnly,
1519                type_: AuthType::Passkey,
1520                ext_metadata: Default::default(),
1521            },
1522        );
1523
1524        let vs_b: ValueSet = ValueSetSession::from_iter([
1525            (
1526                s_uuid,
1527                Session {
1528                    label: "hacks".to_string(),
1529                    state: SessionState::RevokedAt(one_cid.clone()),
1530                    #[allow(clippy::disallowed_methods)]
1531                    issued_at: OffsetDateTime::now_utc(),
1532                    issued_by: IdentityId::Internal(UUID_SYSTEM),
1533                    cred_id: Uuid::new_v4(),
1534                    scope: SessionScope::ReadOnly,
1535                    type_: AuthType::Passkey,
1536                    ext_metadata: Default::default(),
1537                },
1538            ),
1539            (
1540                r_uuid,
1541                Session {
1542                    label: "hacks".to_string(),
1543                    state: SessionState::RevokedAt(zero_cid.clone()),
1544                    #[allow(clippy::disallowed_methods)]
1545                    issued_at: OffsetDateTime::now_utc(),
1546                    issued_by: IdentityId::Internal(UUID_SYSTEM),
1547                    cred_id: Uuid::new_v4(),
1548                    scope: SessionScope::ReadOnly,
1549                    type_: AuthType::Passkey,
1550                    ext_metadata: Default::default(),
1551                },
1552            ),
1553        ])
1554        .expect("Unable to build valueset session");
1555
1556        // Note - inverse order!
1557        let r_vs = vs_b
1558            .repl_merge_valueset(&vs_a, &one_cid)
1559            .expect("failed to merge");
1560
1561        let sessions = r_vs.as_session_map().expect("Unable to locate sessions");
1562
1563        let session = sessions.get(&s_uuid).expect("Unable to locate session");
1564
1565        assert_eq!(session.state, SessionState::RevokedAt(one_cid));
1566
1567        assert!(!sessions.contains_key(&r_uuid));
1568    }
1569
1570    #[test]
1571    fn test_valueset_session_repl_trim() {
1572        let zero_uuid = Uuid::new_v4();
1573        let zero_cid = Cid::new_zero();
1574        let one_uuid = Uuid::new_v4();
1575        let one_cid = Cid::new_count(1);
1576        let two_uuid = Uuid::new_v4();
1577        let two_cid = Cid::new_count(2);
1578
1579        let mut vs_a: ValueSet = ValueSetSession::from_iter([
1580            (
1581                zero_uuid,
1582                Session {
1583                    state: SessionState::RevokedAt(zero_cid),
1584                    label: "hacks".to_string(),
1585                    #[allow(clippy::disallowed_methods)]
1586                    issued_at: OffsetDateTime::now_utc(),
1587                    issued_by: IdentityId::Internal(UUID_SYSTEM),
1588                    cred_id: Uuid::new_v4(),
1589                    scope: SessionScope::ReadOnly,
1590                    type_: AuthType::Passkey,
1591                    ext_metadata: Default::default(),
1592                },
1593            ),
1594            (
1595                one_uuid,
1596                Session {
1597                    state: SessionState::RevokedAt(one_cid),
1598                    label: "hacks".to_string(),
1599                    #[allow(clippy::disallowed_methods)]
1600                    issued_at: OffsetDateTime::now_utc(),
1601                    issued_by: IdentityId::Internal(UUID_SYSTEM),
1602                    cred_id: Uuid::new_v4(),
1603                    scope: SessionScope::ReadOnly,
1604                    type_: AuthType::Passkey,
1605                    ext_metadata: Default::default(),
1606                },
1607            ),
1608            (
1609                two_uuid,
1610                Session {
1611                    state: SessionState::RevokedAt(two_cid.clone()),
1612                    label: "hacks".to_string(),
1613                    #[allow(clippy::disallowed_methods)]
1614                    issued_at: OffsetDateTime::now_utc(),
1615                    issued_by: IdentityId::Internal(UUID_SYSTEM),
1616                    cred_id: Uuid::new_v4(),
1617                    scope: SessionScope::ReadOnly,
1618                    type_: AuthType::Passkey,
1619                    ext_metadata: Default::default(),
1620                },
1621            ),
1622        ])
1623        .unwrap();
1624
1625        vs_a.trim(&two_cid);
1626
1627        let sessions = vs_a.as_session_map().expect("Unable to locate session");
1628
1629        assert!(!sessions.contains_key(&zero_uuid));
1630        assert!(!sessions.contains_key(&one_uuid));
1631        assert!(sessions.contains_key(&two_uuid));
1632    }
1633
1634    #[test]
1635    fn test_valueset_session_limit_trim() {
1636        // Create a session that will be trimmed.
1637        let zero_uuid = Uuid::new_v4();
1638        let zero_cid = Cid::new_zero();
1639        let issued_at = OffsetDateTime::UNIX_EPOCH;
1640
1641        let session_iter = std::iter::once((
1642            zero_uuid,
1643            Session {
1644                state: SessionState::NeverExpires,
1645                label: "hacks".to_string(),
1646                issued_at,
1647                issued_by: IdentityId::Internal(UUID_SYSTEM),
1648                cred_id: Uuid::new_v4(),
1649                scope: SessionScope::ReadOnly,
1650                type_: AuthType::Passkey,
1651                ext_metadata: Default::default(),
1652            },
1653        ))
1654        .chain((0..SESSION_MAXIMUM).map(|_| {
1655            (
1656                Uuid::new_v4(),
1657                Session {
1658                    state: SessionState::NeverExpires,
1659                    label: "hacks".to_string(),
1660                    #[allow(clippy::disallowed_methods)]
1661                    issued_at: OffsetDateTime::now_utc(),
1662                    issued_by: IdentityId::Internal(UUID_SYSTEM),
1663                    cred_id: Uuid::new_v4(),
1664                    scope: SessionScope::ReadOnly,
1665                    type_: AuthType::Passkey,
1666                    ext_metadata: Default::default(),
1667                },
1668            )
1669        }));
1670
1671        let mut vs_a: ValueSet = ValueSetSession::from_iter(session_iter).unwrap();
1672
1673        assert!(vs_a.len() > SESSION_MAXIMUM);
1674
1675        vs_a.trim(&zero_cid);
1676
1677        assert_eq!(vs_a.len(), SESSION_MAXIMUM);
1678
1679        let sessions = vs_a.as_session_map().expect("Unable to access sessions");
1680
1681        assert!(!sessions.contains_key(&zero_uuid));
1682    }
1683
1684    #[test]
1685    fn test_valueset_oauth2_session_purge() {
1686        let s_uuid = Uuid::new_v4();
1687        let mut vs: ValueSet = ValueSetOauth2Session::new(
1688            s_uuid,
1689            Oauth2Session {
1690                state: SessionState::NeverExpires,
1691                #[allow(clippy::disallowed_methods)]
1692                issued_at: OffsetDateTime::now_utc(),
1693                parent: Some(Uuid::new_v4()),
1694                rs_uuid: Uuid::new_v4(),
1695            },
1696        );
1697
1698        let zero_cid = Cid::new_zero();
1699
1700        // Simulate session revocation.
1701        let r = vs.purge(&zero_cid);
1702
1703        assert!(!r);
1704        assert_eq!(vs.len(), 1);
1705
1706        let session = vs
1707            .as_oauth2session_map()
1708            .and_then(|map| map.get(&s_uuid))
1709            .expect("Unable to locate session");
1710
1711        assert_eq!(session.state, SessionState::RevokedAt(zero_cid));
1712    }
1713
1714    #[test]
1715    fn test_valueset_oauth2_session_merge_left() {
1716        let s_uuid = Uuid::new_v4();
1717        let zero_cid = Cid::new_zero();
1718
1719        let mut vs_a: ValueSet = ValueSetOauth2Session::new(
1720            s_uuid,
1721            Oauth2Session {
1722                state: SessionState::NeverExpires,
1723                #[allow(clippy::disallowed_methods)]
1724                issued_at: OffsetDateTime::now_utc(),
1725                parent: Some(Uuid::new_v4()),
1726                rs_uuid: Uuid::new_v4(),
1727            },
1728        );
1729
1730        let vs_b: ValueSet = ValueSetOauth2Session::new(
1731            s_uuid,
1732            Oauth2Session {
1733                state: SessionState::RevokedAt(zero_cid.clone()),
1734                #[allow(clippy::disallowed_methods)]
1735                issued_at: OffsetDateTime::now_utc(),
1736                parent: Some(Uuid::new_v4()),
1737                rs_uuid: Uuid::new_v4(),
1738            },
1739        );
1740
1741        vs_a.merge(&vs_b).expect("failed to merge");
1742
1743        let session = vs_a
1744            .as_oauth2session_map()
1745            .and_then(|map| map.get(&s_uuid))
1746            .expect("Unable to locate session");
1747
1748        assert_eq!(session.state, SessionState::RevokedAt(zero_cid));
1749    }
1750
1751    #[test]
1752    fn test_valueset_oauth2_session_merge_right() {
1753        let s_uuid = Uuid::new_v4();
1754        let zero_cid = Cid::new_zero();
1755
1756        let vs_a: ValueSet = ValueSetOauth2Session::new(
1757            s_uuid,
1758            Oauth2Session {
1759                state: SessionState::NeverExpires,
1760                #[allow(clippy::disallowed_methods)]
1761                issued_at: OffsetDateTime::now_utc(),
1762                parent: Some(Uuid::new_v4()),
1763                rs_uuid: Uuid::new_v4(),
1764            },
1765        );
1766
1767        let mut vs_b: ValueSet = ValueSetOauth2Session::new(
1768            s_uuid,
1769            Oauth2Session {
1770                state: SessionState::RevokedAt(zero_cid.clone()),
1771                #[allow(clippy::disallowed_methods)]
1772                issued_at: OffsetDateTime::now_utc(),
1773                parent: Some(Uuid::new_v4()),
1774                rs_uuid: Uuid::new_v4(),
1775            },
1776        );
1777
1778        // Note inverse order
1779        vs_b.merge(&vs_a).expect("failed to merge");
1780
1781        let session = vs_b
1782            .as_oauth2session_map()
1783            .and_then(|map| map.get(&s_uuid))
1784            .expect("Unable to locate session");
1785
1786        assert_eq!(session.state, SessionState::RevokedAt(zero_cid));
1787    }
1788
1789    #[test]
1790    fn test_valueset_oauth2_session_repl_merge_left() {
1791        let s_uuid = Uuid::new_v4();
1792        let r_uuid = Uuid::new_v4();
1793        let zero_cid = Cid::new_zero();
1794        let one_cid = Cid::new_count(1);
1795
1796        let vs_a: ValueSet = ValueSetOauth2Session::new(
1797            s_uuid,
1798            Oauth2Session {
1799                state: SessionState::NeverExpires,
1800                #[allow(clippy::disallowed_methods)]
1801                issued_at: OffsetDateTime::now_utc(),
1802                parent: Some(Uuid::new_v4()),
1803                rs_uuid: Uuid::new_v4(),
1804            },
1805        );
1806
1807        let vs_b: ValueSet = ValueSetOauth2Session::from_iter([
1808            (
1809                s_uuid,
1810                Oauth2Session {
1811                    state: SessionState::RevokedAt(one_cid.clone()),
1812                    #[allow(clippy::disallowed_methods)]
1813                    issued_at: OffsetDateTime::now_utc(),
1814                    parent: Some(Uuid::new_v4()),
1815                    rs_uuid: Uuid::new_v4(),
1816                },
1817            ),
1818            (
1819                r_uuid,
1820                Oauth2Session {
1821                    state: SessionState::RevokedAt(zero_cid.clone()),
1822                    #[allow(clippy::disallowed_methods)]
1823                    issued_at: OffsetDateTime::now_utc(),
1824                    parent: Some(Uuid::new_v4()),
1825                    rs_uuid: Uuid::new_v4(),
1826                },
1827            ),
1828        ])
1829        .expect("Unable to build valueset oauth2 session");
1830
1831        let r_vs = vs_a
1832            .repl_merge_valueset(&vs_b, &one_cid)
1833            .expect("failed to merge");
1834
1835        let sessions = r_vs
1836            .as_oauth2session_map()
1837            .expect("Unable to locate sessions");
1838
1839        let session = sessions.get(&s_uuid).expect("Unable to locate session");
1840
1841        assert_eq!(session.state, SessionState::RevokedAt(one_cid));
1842
1843        assert!(!sessions.contains_key(&r_uuid));
1844    }
1845
1846    #[test]
1847    fn test_valueset_oauth2_session_repl_merge_right() {
1848        let s_uuid = Uuid::new_v4();
1849        let r_uuid = Uuid::new_v4();
1850        let zero_cid = Cid::new_zero();
1851        let one_cid = Cid::new_count(1);
1852
1853        let vs_a: ValueSet = ValueSetOauth2Session::new(
1854            s_uuid,
1855            Oauth2Session {
1856                state: SessionState::NeverExpires,
1857                #[allow(clippy::disallowed_methods)]
1858                issued_at: OffsetDateTime::now_utc(),
1859                parent: Some(Uuid::new_v4()),
1860                rs_uuid: Uuid::new_v4(),
1861            },
1862        );
1863
1864        let vs_b: ValueSet = ValueSetOauth2Session::from_iter([
1865            (
1866                s_uuid,
1867                Oauth2Session {
1868                    state: SessionState::RevokedAt(one_cid.clone()),
1869                    #[allow(clippy::disallowed_methods)]
1870                    issued_at: OffsetDateTime::now_utc(),
1871                    parent: Some(Uuid::new_v4()),
1872                    rs_uuid: Uuid::new_v4(),
1873                },
1874            ),
1875            (
1876                r_uuid,
1877                Oauth2Session {
1878                    state: SessionState::RevokedAt(zero_cid.clone()),
1879                    #[allow(clippy::disallowed_methods)]
1880                    issued_at: OffsetDateTime::now_utc(),
1881                    parent: Some(Uuid::new_v4()),
1882                    rs_uuid: Uuid::new_v4(),
1883                },
1884            ),
1885        ])
1886        .expect("Unable to build valueset oauth2 session");
1887
1888        // Note inverse order
1889        let r_vs = vs_b
1890            .repl_merge_valueset(&vs_a, &one_cid)
1891            .expect("failed to merge");
1892
1893        let sessions = r_vs
1894            .as_oauth2session_map()
1895            .expect("Unable to locate sessions");
1896
1897        let session = sessions.get(&s_uuid).expect("Unable to locate session");
1898
1899        assert_eq!(session.state, SessionState::RevokedAt(one_cid));
1900
1901        assert!(!sessions.contains_key(&r_uuid));
1902    }
1903
1904    #[test]
1905    fn test_valueset_oauth2_session_repl_trim() {
1906        let zero_uuid = Uuid::new_v4();
1907        let zero_cid = Cid::new_zero();
1908        let one_uuid = Uuid::new_v4();
1909        let one_cid = Cid::new_count(1);
1910        let two_uuid = Uuid::new_v4();
1911        let two_cid = Cid::new_count(2);
1912
1913        let mut vs_a: ValueSet = ValueSetOauth2Session::from_iter([
1914            (
1915                zero_uuid,
1916                Oauth2Session {
1917                    state: SessionState::RevokedAt(zero_cid),
1918                    #[allow(clippy::disallowed_methods)]
1919                    issued_at: OffsetDateTime::now_utc(),
1920                    parent: Some(Uuid::new_v4()),
1921                    rs_uuid: Uuid::new_v4(),
1922                },
1923            ),
1924            (
1925                one_uuid,
1926                #[allow(clippy::disallowed_methods)]
1927                Oauth2Session {
1928                    state: SessionState::RevokedAt(one_cid),
1929                    issued_at: OffsetDateTime::now_utc(),
1930                    parent: Some(Uuid::new_v4()),
1931                    rs_uuid: Uuid::new_v4(),
1932                },
1933            ),
1934            (
1935                two_uuid,
1936                Oauth2Session {
1937                    state: SessionState::RevokedAt(two_cid.clone()),
1938                    #[allow(clippy::disallowed_methods)]
1939                    issued_at: OffsetDateTime::now_utc(),
1940                    parent: Some(Uuid::new_v4()),
1941                    rs_uuid: Uuid::new_v4(),
1942                },
1943            ),
1944        ])
1945        .unwrap();
1946
1947        vs_a.trim(&two_cid);
1948
1949        let sessions = vs_a
1950            .as_oauth2session_map()
1951            .expect("Unable to locate session");
1952
1953        assert!(!sessions.contains_key(&zero_uuid));
1954        assert!(!sessions.contains_key(&one_uuid));
1955        assert!(sessions.contains_key(&two_uuid));
1956    }
1957
1958    #[test]
1959    fn test_scim_session() {
1960        let s_uuid = uuid::uuid!("3a163ca0-4762-4620-a188-06b750c84c86");
1961
1962        let vs: ValueSet = ValueSetSession::new(
1963            s_uuid,
1964            Session {
1965                label: "hacks".to_string(),
1966                state: SessionState::NeverExpires,
1967                issued_at: OffsetDateTime::UNIX_EPOCH,
1968                issued_by: IdentityId::Internal(UUID_SYSTEM),
1969                cred_id: s_uuid,
1970                scope: SessionScope::ReadOnly,
1971                type_: AuthType::Passkey,
1972                ext_metadata: Default::default(),
1973            },
1974        );
1975
1976        let data = r#"
1977[
1978  {
1979    "authType": "passkey",
1980    "credentialId": "3a163ca0-4762-4620-a188-06b750c84c86",
1981    "issuedAt": "1970-01-01T00:00:00Z",
1982    "issuedBy": "00000000-0000-0000-0000-ffffff000000",
1983    "id": "3a163ca0-4762-4620-a188-06b750c84c86",
1984    "sessionScope": "read_only"
1985  }
1986]
1987        "#;
1988        crate::valueset::scim_json_reflexive(&vs, data);
1989    }
1990
1991    #[test]
1992    fn test_scim_oauth2_session() {
1993        let s_uuid = uuid::uuid!("3a163ca0-4762-4620-a188-06b750c84c86");
1994
1995        let vs: ValueSet = ValueSetOauth2Session::new(
1996            s_uuid,
1997            Oauth2Session {
1998                state: SessionState::NeverExpires,
1999                issued_at: OffsetDateTime::UNIX_EPOCH,
2000                parent: Some(s_uuid),
2001                rs_uuid: s_uuid,
2002            },
2003        );
2004
2005        let data = r#"
2006[
2007  {
2008    "clientId": "3a163ca0-4762-4620-a188-06b750c84c86",
2009    "issuedAt": "1970-01-01T00:00:00Z",
2010    "parentId": "3a163ca0-4762-4620-a188-06b750c84c86",
2011    "id": "3a163ca0-4762-4620-a188-06b750c84c86"
2012  }
2013]
2014        "#;
2015
2016        crate::valueset::scim_json_reflexive(&vs, data);
2017    }
2018}