1use crate::{
7 be::{dbentry::DbIdentSpn, dbvalue::DbValueOauthClaimMapJoinV1},
8 credential::{apppwd::ApplicationPassword, totp::Totp, Credential},
9 prelude::*,
10 repl::cid::Cid,
11 server::{identity::IdentityId, keys::KeyId},
12 valueset::{image::ImageValueThings, uuid_to_proto_string},
13};
14use compact_jwt::{crypto::JwsRs256Signer, JwsEs256Signer};
15use crypto_glue::{
16 s256::Sha256Output,
17 traits::{DecodePem, Zeroizing},
18 x509::Certificate,
19};
20use hashbrown::HashSet;
21use kanidm_proto::{
22 internal::{ApiTokenPurpose, Filter as ProtoFilter, ImageValue, UiHint},
23 scim_v1::ScimOauth2ClaimMapJoinChar,
24 v1::UatPurposeStatus,
25};
26use num_enum::TryFromPrimitive;
27use regex::Regex;
28use serde::{Deserialize, Serialize};
29use sshkey_attest::proto::PublicKey as SshPublicKey;
30use std::{
31 cmp::Ordering, collections::BTreeSet, convert::TryFrom, fmt, fmt::Formatter, hash::Hash,
32 str::FromStr, time::Duration,
33};
34use time::OffsetDateTime;
35use url::Url;
36use uuid::Uuid;
37use webauthn_rs::prelude::{
38 AttestationCaList, AttestedPasskey as AttestedPasskeyV4, Passkey as PasskeyV4,
39};
40
41#[cfg(test)]
42use base64::{engine::general_purpose, Engine as _};
43
44pub static SPN_RE: LazyLock<Regex> = LazyLock::new(|| {
45 #[allow(clippy::expect_used)]
46 Regex::new("(?P<name>[^@]+)@(?P<realm>[^@]+)").expect("Invalid SPN regex found")
47});
48
49pub static DISALLOWED_NAMES: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
50 let mut m = HashSet::with_capacity(2);
53 m.insert("root");
54 m.insert("dn=token");
55 m
56});
57
58pub static INAME_RE: LazyLock<Regex> = LazyLock::new(|| {
60 #[allow(clippy::expect_used)]
61 Regex::new("^[a-z][a-z0-9-_\\.]{0,63}$").expect("Invalid Iname regex found")
62});
63
64pub static LABEL_RE: LazyLock<Regex> = LazyLock::new(|| {
66 #[allow(clippy::expect_used)]
67 Regex::new("^[a-zA-Z0-9][ a-zA-Z0-9-_\\.@]{0,63}$").expect("Invalid Iname regex found")
68});
69
70pub static HEXSTR_RE: LazyLock<Regex> = LazyLock::new(|| {
72 #[allow(clippy::expect_used)]
73 Regex::new("^[a-f0-9]+$").expect("Invalid hexstring regex found")
74});
75
76pub static EXTRACT_VAL_DN: LazyLock<Regex> = LazyLock::new(|| {
77 #[allow(clippy::expect_used)]
78 Regex::new("^(([^=,]+)=)?(?P<val>[^=,]+)").expect("extract val from dn regex")
79});
80
81pub static NSUNIQUEID_RE: LazyLock<Regex> = LazyLock::new(|| {
82 #[allow(clippy::expect_used)]
83 Regex::new("^[0-9a-fA-F]{8}-[0-9a-fA-F]{8}-[0-9a-fA-F]{8}-[0-9a-fA-F]{8}$")
84 .expect("Invalid Nsunique regex found")
85});
86
87pub static OAUTHSCOPE_RE: LazyLock<Regex> = LazyLock::new(|| {
89 #[allow(clippy::expect_used)]
90 Regex::new("^[0-9a-zA-Z_]+(([:\\-.]|(://))[0-9a-zA-Z_]+)*$")
91 .expect("Invalid oauthscope regex found")
92});
93
94pub static OAUTH_CLAIMNAME_RE: LazyLock<Regex> = LazyLock::new(|| {
97 #[allow(clippy::expect_used)]
98 Regex::new("^[0-9a-zA-Z_]+([:\\-][0-9a-zA-Z_]+)*$").expect("Invalid oauth claim regex found")
99});
100
101pub static SINGLELINE_RE: LazyLock<Regex> = LazyLock::new(|| {
102 #[allow(clippy::expect_used)]
103 Regex::new("[\n\r\t]").expect("Invalid singleline regex found")
104});
105
106pub static VALIDATE_EMAIL_RE: LazyLock<Regex> = LazyLock::new(|| {
109 #[allow(clippy::expect_used)]
110 Regex::new(r"^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
111 .expect("Invalid singleline regex found")
112});
113
114pub static UNICODE_CONTROL_RE: LazyLock<Regex> = LazyLock::new(|| {
115 #[allow(clippy::expect_used)]
116 Regex::new(r"[[:cntrl:]]").expect("Invalid unicode control regex found")
117});
118
119#[derive(Debug, Clone, PartialOrd, Ord, Eq, PartialEq, Hash)]
120pub struct Address {
122 pub formatted: String,
123 pub street_address: String,
124 pub locality: String,
125 pub region: String,
126 pub postal_code: String,
127 pub country: String,
129}
130#[derive(Debug, Copy, Clone, PartialEq, Eq)]
131pub struct CredUpdateSessionPerms {
132 pub ext_cred_portal_can_view: bool,
133 pub primary_can_edit: bool,
134 pub passkeys_can_edit: bool,
135 pub attested_passkeys_can_edit: bool,
136 pub unixcred_can_edit: bool,
137 pub sshpubkey_can_edit: bool,
138}
139
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub enum IntentTokenState {
142 Valid {
143 max_ttl: Duration,
144 perms: CredUpdateSessionPerms,
145 },
146 InProgress {
147 max_ttl: Duration,
148 perms: CredUpdateSessionPerms,
149 session_id: Uuid,
150 session_ttl: Duration,
151 },
152 Consumed {
153 max_ttl: Duration,
154 },
155}
156
157#[allow(non_camel_case_types)]
158#[derive(
159 Debug,
160 Clone,
161 Copy,
162 PartialEq,
163 Eq,
164 PartialOrd,
165 Ord,
166 Deserialize,
167 Serialize,
168 Hash,
169 TryFromPrimitive,
170)]
171#[repr(u16)]
172pub enum IndexType {
173 Equality,
174 Presence,
175 SubString,
176 Ordering,
177}
178
179impl TryFrom<&str> for IndexType {
180 type Error = ();
181
182 fn try_from(value: &str) -> Result<Self, Self::Error> {
183 let n_value = value.to_uppercase();
184 match n_value.as_str() {
185 "EQUALITY" => Ok(IndexType::Equality),
186 "PRESENCE" => Ok(IndexType::Presence),
187 "SUBSTRING" => Ok(IndexType::SubString),
188 "ORDERING" => Ok(IndexType::Ordering),
189 _ => Err(()),
192 }
193 }
194}
195
196impl IndexType {
197 pub fn as_idx_str(&self) -> &str {
198 match self {
199 IndexType::Equality => "eq",
200 IndexType::Presence => "pres",
201 IndexType::SubString => "sub",
202 IndexType::Ordering => "ord",
203 }
204 }
205}
206
207impl fmt::Display for IndexType {
208 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
209 write!(
210 f,
211 "{}",
212 match self {
213 IndexType::Equality => "EQUALITY",
214 IndexType::Presence => "PRESENCE",
215 IndexType::SubString => "SUBSTRING",
216 IndexType::Ordering => "ORDERING",
217 }
218 )
219 }
220}
221
222#[allow(non_camel_case_types)]
223#[allow(clippy::derived_hash_with_manual_eq)]
224#[derive(
225 Hash,
226 Debug,
227 Clone,
228 Copy,
229 PartialEq,
230 Eq,
231 PartialOrd,
232 Ord,
233 Deserialize,
234 Serialize,
235 TryFromPrimitive,
236 Default,
237)]
238#[repr(u16)]
239pub enum SyntaxType {
240 #[default]
241 Utf8String = 0,
242 Utf8StringInsensitive = 1,
243 Uuid = 2,
244 Boolean = 3,
245 SyntaxId = 4,
246 IndexId = 5,
247 ReferenceUuid = 6,
248 JsonFilter = 7,
249 Credential = 8,
250 SecretUtf8String = 9,
251 SshKey = 10,
252 SecurityPrincipalName = 11,
253 Uint32 = 12,
254 Cid = 13,
255 Utf8StringIname = 14,
256 NsUniqueId = 15,
257 DateTime = 16,
258 EmailAddress = 17,
259 Url = 18,
260 OauthScope = 19,
261 OauthScopeMap = 20,
262 PrivateBinary = 21,
263 IntentToken = 22,
264 Passkey = 23,
265 AttestedPasskey = 24,
266 Session = 25,
267 JwsKeyEs256 = 26,
268 JwsKeyRs256 = 27,
269 Oauth2Session = 28,
270 UiHint = 29,
271 TotpSecret = 30,
272 ApiToken = 31,
273 AuditLogString = 32,
274 EcKeyPrivate = 33,
275 Image = 34,
276 CredentialType = 35,
277 WebauthnAttestationCaList = 36,
278 OauthClaimMap = 37,
279 KeyInternal = 38,
280 HexString = 39,
281 Certificate = 40,
282 ApplicationPassword = 41,
283 Json = 42,
284 Message = 43,
285 Sha256 = 44,
286 Int64 = 45,
287 Uint64 = 46,
288
289 UuidN = 47,
290 Utf8StringInsensitiveN = 48,
291 ReferenceUuidN = 49,
292 Utf8StringInameN = 50,
293 UrlN = 51,
294}
295
296impl TryFrom<&str> for SyntaxType {
297 type Error = ();
298
299 fn try_from(value: &str) -> Result<SyntaxType, Self::Error> {
300 let n_value = value.to_uppercase();
301 match n_value.as_str() {
302 "UTF8STRING" => Ok(SyntaxType::Utf8String),
303 "UTF8STRING_INSENSITIVE" => Ok(SyntaxType::Utf8StringInsensitive),
304 "UTF8STRING_INAME" => Ok(SyntaxType::Utf8StringIname),
305 "UUID" => Ok(SyntaxType::Uuid),
306 "UUID_MULTI" => Ok(SyntaxType::UuidN),
307 "BOOLEAN" => Ok(SyntaxType::Boolean),
308 "SYNTAX_ID" => Ok(SyntaxType::SyntaxId),
309 "INDEX_ID" => Ok(SyntaxType::IndexId),
310 "REFERENCE_UUID" => Ok(SyntaxType::ReferenceUuid),
311 "JSON_FILTER" => Ok(SyntaxType::JsonFilter),
312 "CREDENTIAL" => Ok(SyntaxType::Credential),
313 "RADIUS_UTF8STRING" | "SECRET_UTF8STRING" => Ok(SyntaxType::SecretUtf8String),
315 "SSHKEY" => Ok(SyntaxType::SshKey),
316 "SECURITY_PRINCIPAL_NAME" => Ok(SyntaxType::SecurityPrincipalName),
317 "UINT32" => Ok(SyntaxType::Uint32),
318 "CID" => Ok(SyntaxType::Cid),
319 "NSUNIQUEID" => Ok(SyntaxType::NsUniqueId),
320 "DATETIME" => Ok(SyntaxType::DateTime),
321 "EMAIL_ADDRESS" => Ok(SyntaxType::EmailAddress),
322 "URL" => Ok(SyntaxType::Url),
323 "OAUTH_SCOPE" => Ok(SyntaxType::OauthScope),
324 "OAUTH_SCOPE_MAP" => Ok(SyntaxType::OauthScopeMap),
325 "PRIVATE_BINARY" => Ok(SyntaxType::PrivateBinary),
326 "INTENT_TOKEN" => Ok(SyntaxType::IntentToken),
327 "PASSKEY" => Ok(SyntaxType::Passkey),
328 "ATTESTED_PASSKEY" => Ok(SyntaxType::AttestedPasskey),
329 "SESSION" => Ok(SyntaxType::Session),
330 "JWS_KEY_ES256" => Ok(SyntaxType::JwsKeyEs256),
331 "JWS_KEY_RS256" => Ok(SyntaxType::JwsKeyRs256),
332 "OAUTH2SESSION" => Ok(SyntaxType::Oauth2Session),
333 "UIHINT" => Ok(SyntaxType::UiHint),
334 "TOTPSECRET" => Ok(SyntaxType::TotpSecret),
335 "APITOKEN" => Ok(SyntaxType::ApiToken),
336 "AUDIT_LOG_STRING" => Ok(SyntaxType::AuditLogString),
337 "EC_KEY_PRIVATE" => Ok(SyntaxType::EcKeyPrivate),
338 "CREDENTIAL_TYPE" => Ok(SyntaxType::CredentialType),
339 "WEBAUTHN_ATTESTATION_CA_LIST" => Ok(SyntaxType::WebauthnAttestationCaList),
340 "OAUTH_CLAIM_MAP" => Ok(SyntaxType::OauthClaimMap),
341 "KEY_INTERNAL" => Ok(SyntaxType::KeyInternal),
342 "HEX_STRING" => Ok(SyntaxType::HexString),
343 "CERTIFICATE" => Ok(SyntaxType::Certificate),
344 "APPLICATION_PASSWORD" => Ok(SyntaxType::ApplicationPassword),
345 "JSON" => Ok(SyntaxType::Json),
346 "MESSAGE" => Ok(SyntaxType::Message),
347 "SHA256" => Ok(SyntaxType::Sha256),
348 "INT64" => Ok(SyntaxType::Int64),
349 "UINT64" => Ok(SyntaxType::Uint64),
350
351 "UTF8STRING_INSENSITIVE_MULTI" => Ok(SyntaxType::Utf8StringInsensitiveN),
352 "REFERENCE_UUID_MULTI" => Ok(SyntaxType::ReferenceUuidN),
353 "UTF8STRING_INAME_MULTI" => Ok(SyntaxType::Utf8StringInameN),
354 "URL_MULTI" => Ok(SyntaxType::UrlN),
355
356 _ => Err(()),
357 }
358 }
359}
360
361impl fmt::Display for SyntaxType {
362 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
363 f.write_str(match self {
364 SyntaxType::Utf8String => "UTF8STRING",
365 SyntaxType::Utf8StringInsensitive => "UTF8STRING_INSENSITIVE",
366 SyntaxType::Utf8StringIname => "UTF8STRING_INAME",
367 SyntaxType::Uuid => "UUID",
368 SyntaxType::UuidN => "UUID_MULTI",
369 SyntaxType::Boolean => "BOOLEAN",
370 SyntaxType::SyntaxId => "SYNTAX_ID",
371 SyntaxType::IndexId => "INDEX_ID",
372 SyntaxType::ReferenceUuid => "REFERENCE_UUID",
373 SyntaxType::JsonFilter => "JSON_FILTER",
374 SyntaxType::Credential => "CREDENTIAL",
375 SyntaxType::SecretUtf8String => "SECRET_UTF8STRING",
376 SyntaxType::SshKey => "SSHKEY",
377 SyntaxType::SecurityPrincipalName => "SECURITY_PRINCIPAL_NAME",
378 SyntaxType::Uint32 => "UINT32",
379 SyntaxType::Cid => "CID",
380 SyntaxType::NsUniqueId => "NSUNIQUEID",
381 SyntaxType::DateTime => "DATETIME",
382 SyntaxType::EmailAddress => "EMAIL_ADDRESS",
383 SyntaxType::Url => "URL",
384 SyntaxType::OauthScope => "OAUTH_SCOPE",
385 SyntaxType::OauthScopeMap => "OAUTH_SCOPE_MAP",
386 SyntaxType::PrivateBinary => "PRIVATE_BINARY",
387 SyntaxType::IntentToken => "INTENT_TOKEN",
388 SyntaxType::Passkey => "PASSKEY",
389 SyntaxType::AttestedPasskey => "ATTESTED_PASSKEY",
390 SyntaxType::Session => "SESSION",
391 SyntaxType::JwsKeyEs256 => "JWS_KEY_ES256",
392 SyntaxType::JwsKeyRs256 => "JWS_KEY_RS256",
393 SyntaxType::Oauth2Session => "OAUTH2SESSION",
394 SyntaxType::UiHint => "UIHINT",
395 SyntaxType::TotpSecret => "TOTPSECRET",
396 SyntaxType::ApiToken => "APITOKEN",
397 SyntaxType::AuditLogString => "AUDIT_LOG_STRING",
398 SyntaxType::EcKeyPrivate => "EC_KEY_PRIVATE",
399 SyntaxType::Image => "IMAGE",
400 SyntaxType::CredentialType => "CREDENTIAL_TYPE",
401 SyntaxType::WebauthnAttestationCaList => "WEBAUTHN_ATTESTATION_CA_LIST",
402 SyntaxType::OauthClaimMap => "OAUTH_CLAIM_MAP",
403 SyntaxType::KeyInternal => "KEY_INTERNAL",
404 SyntaxType::HexString => "HEX_STRING",
405 SyntaxType::Certificate => "CERTIFICATE",
406 SyntaxType::ApplicationPassword => "APPLICATION_PASSWORD",
407 SyntaxType::Json => "JSON",
408 SyntaxType::Message => "MESSAGE",
409 SyntaxType::Sha256 => "SHA256",
410 SyntaxType::Int64 => "INT64",
411 SyntaxType::Uint64 => "UINT64",
412
413 SyntaxType::Utf8StringInsensitiveN => "UTF8STRING_INSENSITIVE_MULTI",
414 SyntaxType::ReferenceUuidN => "REFERENCE_UUID_MULTI",
415 SyntaxType::Utf8StringInameN => "UTF8STRING_INAME_MULTI",
416 SyntaxType::UrlN => "URL_MULTI",
417 })
418 }
419}
420
421impl SyntaxType {
422 pub fn index_types(&self) -> &[IndexType] {
423 match self {
424 SyntaxType::Utf8String => &[IndexType::Equality, IndexType::Presence],
425 SyntaxType::Utf8StringInsensitiveN | SyntaxType::Utf8StringInsensitive => {
428 &[IndexType::Equality, IndexType::Presence]
429 }
430 SyntaxType::Utf8StringInameN | SyntaxType::Utf8StringIname => &[
431 IndexType::Equality,
432 IndexType::Presence,
433 IndexType::SubString,
434 ],
435 SyntaxType::Uuid | SyntaxType::UuidN => &[IndexType::Equality, IndexType::Presence],
436 SyntaxType::Boolean => &[IndexType::Equality],
437 SyntaxType::ReferenceUuidN | SyntaxType::ReferenceUuid => {
438 &[IndexType::Equality, IndexType::Presence]
439 }
440 SyntaxType::Credential => &[IndexType::Equality],
441 SyntaxType::SshKey => &[IndexType::Equality, IndexType::Presence],
442 SyntaxType::SecurityPrincipalName => &[
443 IndexType::Equality,
444 IndexType::Presence,
445 IndexType::SubString,
446 ],
447 SyntaxType::Uint32 | SyntaxType::Int64 | SyntaxType::Uint64 => &[
448 IndexType::Equality,
449 IndexType::Presence,
450 IndexType::Ordering,
451 ],
452 SyntaxType::Cid => &[
453 IndexType::Equality,
454 IndexType::Presence,
455 IndexType::Ordering,
456 ],
457 SyntaxType::NsUniqueId => &[IndexType::Equality, IndexType::Presence],
458 SyntaxType::DateTime => &[
459 IndexType::Equality,
460 IndexType::Presence,
461 IndexType::Ordering,
462 ],
463 SyntaxType::EmailAddress => &[IndexType::Equality, IndexType::SubString],
464 SyntaxType::OauthScopeMap => &[IndexType::Equality],
465 SyntaxType::IntentToken => &[IndexType::Equality],
466 SyntaxType::Passkey => &[IndexType::Equality],
467 SyntaxType::AttestedPasskey => &[IndexType::Equality],
468 SyntaxType::Session => &[IndexType::Equality],
469 SyntaxType::Oauth2Session => &[IndexType::Equality],
470 SyntaxType::ApiToken => &[IndexType::Equality],
471 SyntaxType::OauthClaimMap => &[IndexType::Equality],
472 SyntaxType::ApplicationPassword => &[IndexType::Equality],
473 SyntaxType::Sha256 => &[IndexType::Equality],
474 SyntaxType::SecretUtf8String => &[],
475 SyntaxType::UrlN => &[],
476 SyntaxType::Url => &[],
477 SyntaxType::OauthScope => &[],
478 SyntaxType::PrivateBinary => &[],
479 SyntaxType::JwsKeyEs256 => &[],
480 SyntaxType::JwsKeyRs256 => &[],
481 SyntaxType::UiHint => &[],
482 SyntaxType::TotpSecret => &[],
483 SyntaxType::AuditLogString => &[],
484 SyntaxType::EcKeyPrivate => &[],
485 SyntaxType::Image => &[],
486 SyntaxType::CredentialType => &[],
487 SyntaxType::WebauthnAttestationCaList => &[],
488 SyntaxType::KeyInternal => &[],
489 SyntaxType::HexString => &[],
490 SyntaxType::Certificate => &[],
491 SyntaxType::SyntaxId => &[],
492 SyntaxType::IndexId => &[],
493 SyntaxType::JsonFilter => &[],
494 SyntaxType::Json => &[],
495 SyntaxType::Message => &[],
496 }
497 }
498}
499
500#[derive(
501 Hash,
502 Debug,
503 Clone,
504 Copy,
505 PartialEq,
506 Eq,
507 PartialOrd,
508 Ord,
509 Deserialize,
510 Serialize,
511 TryFromPrimitive,
512 Default,
513)]
514#[repr(u16)]
515pub enum CredentialType {
516 Any = 0,
517 External = 5,
520 #[default]
521 Mfa = 10,
522 Passkey = 20,
523 AttestedPasskey = 30,
524 AttestedResidentkey = 40,
525 Invalid = u16::MAX,
526}
527
528impl TryFrom<&str> for CredentialType {
529 type Error = ();
530
531 fn try_from(value: &str) -> Result<CredentialType, Self::Error> {
532 match value {
533 "any" => Ok(CredentialType::Any),
534 "external" => Ok(CredentialType::External),
535 "mfa" => Ok(CredentialType::Mfa),
536 "passkey" => Ok(CredentialType::Passkey),
537 "attested_passkey" => Ok(CredentialType::AttestedPasskey),
538 "attested_residentkey" => Ok(CredentialType::AttestedResidentkey),
539 "invalid" => Ok(CredentialType::Invalid),
540 _ => Err(()),
541 }
542 }
543}
544
545impl fmt::Display for CredentialType {
546 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
547 f.write_str(match self {
548 CredentialType::Any => "any",
549 CredentialType::External => "external",
550 CredentialType::Mfa => "mfa",
551 CredentialType::Passkey => "passkey",
552 CredentialType::AttestedPasskey => "attested_passkey",
553 CredentialType::AttestedResidentkey => "attested_residentkey",
554 CredentialType::Invalid => "invalid",
555 })
556 }
557}
558
559impl From<CredentialType> for Value {
560 fn from(ct: CredentialType) -> Value {
561 Value::CredentialType(ct)
562 }
563}
564
565impl From<CredentialType> for PartialValue {
566 fn from(ct: CredentialType) -> PartialValue {
567 PartialValue::CredentialType(ct)
568 }
569}
570
571impl From<Attribute> for PartialValue {
572 fn from(attr: Attribute) -> PartialValue {
573 let s: &str = attr.as_str();
574 PartialValue::new_iutf8(s)
575 }
576}
577
578#[derive(Hash, Debug, Clone, Eq, Ord, PartialOrd, PartialEq, Deserialize, Serialize)]
585pub enum PartialValue {
586 Utf8(String),
587 Iutf8(String),
588 Iname(String),
589 Uuid(Uuid),
590 Bool(bool),
591 Syntax(SyntaxType),
592 Index(IndexType),
593 Refer(Uuid),
594 JsonFilt(ProtoFilter),
597 Cred(String),
599 SshKey(String),
600 SecretValue,
601 Spn(String, String),
602 Uint32(u32),
603 Cid(Cid),
604 Nsuniqueid(String),
605 DateTime(OffsetDateTime),
606 EmailAddress(String),
607 PhoneNumber(String),
608 Address(String),
609 Url(Url),
611 OauthScope(String),
612 PrivateBinary,
613 PublicBinary(String),
614 IntentToken(String),
615 UiHint(UiHint),
616 Passkey(Uuid),
617 AttestedPasskey(Uuid),
618 Image(String),
620 CredentialType(CredentialType),
621
622 OauthClaim(String, Uuid),
623 OauthClaimValue(String, Uuid, String),
624
625 HexString(String),
626 Json,
627 Sha256(Sha256Output),
628 Int64(i64),
629 Uint64(u64),
630}
631
632impl From<SyntaxType> for PartialValue {
633 fn from(s: SyntaxType) -> Self {
634 PartialValue::Syntax(s)
635 }
636}
637
638impl From<IndexType> for PartialValue {
639 fn from(i: IndexType) -> Self {
640 PartialValue::Index(i)
641 }
642}
643
644impl From<bool> for PartialValue {
645 fn from(b: bool) -> Self {
646 PartialValue::Bool(b)
647 }
648}
649
650impl From<&bool> for PartialValue {
651 fn from(b: &bool) -> Self {
652 PartialValue::Bool(*b)
653 }
654}
655
656impl From<ProtoFilter> for PartialValue {
657 fn from(i: ProtoFilter) -> Self {
658 PartialValue::JsonFilt(i)
659 }
660}
661
662impl From<u32> for PartialValue {
663 fn from(i: u32) -> Self {
664 PartialValue::Uint32(i)
665 }
666}
667
668impl From<OffsetDateTime> for PartialValue {
669 fn from(i: OffsetDateTime) -> Self {
670 PartialValue::DateTime(i)
671 }
672}
673
674impl From<Url> for PartialValue {
675 fn from(i: Url) -> Self {
676 PartialValue::Url(i)
677 }
678}
679
680impl From<Sha256Output> for PartialValue {
681 fn from(i: Sha256Output) -> Self {
682 PartialValue::Sha256(i)
683 }
684}
685
686impl PartialValue {
687 pub fn new_utf8(s: String) -> Self {
688 PartialValue::Utf8(s)
689 }
690
691 pub fn new_utf8s(s: &str) -> Self {
692 PartialValue::Utf8(s.to_string())
693 }
694
695 pub fn is_utf8(&self) -> bool {
696 matches!(self, PartialValue::Utf8(_))
697 }
698
699 pub fn new_iutf8(s: &str) -> Self {
700 PartialValue::Iutf8(s.to_lowercase())
701 }
702
703 pub fn new_iname(s: &str) -> Self {
704 PartialValue::Iname(s.to_lowercase())
705 }
706
707 pub fn is_iutf8(&self) -> bool {
708 matches!(self, PartialValue::Iutf8(_))
709 }
710
711 pub fn is_iname(&self) -> bool {
712 matches!(self, PartialValue::Iname(_))
713 }
714
715 pub const fn new_bool(b: bool) -> Self {
716 PartialValue::Bool(b)
717 }
718
719 pub fn new_bools(s: &str) -> Option<Self> {
720 bool::from_str(s).map(PartialValue::Bool).ok()
721 }
722
723 pub fn is_bool(&self) -> bool {
724 matches!(self, PartialValue::Bool(_))
725 }
726
727 pub fn new_uuid_s(us: &str) -> Option<Self> {
728 Uuid::parse_str(us).map(PartialValue::Uuid).ok()
729 }
730
731 pub fn is_uuid(&self) -> bool {
732 matches!(self, PartialValue::Uuid(_))
733 }
734
735 pub fn new_refer_s(us: &str) -> Option<Self> {
736 match Uuid::parse_str(us) {
737 Ok(u) => Some(PartialValue::Refer(u)),
738 Err(_) => None,
739 }
740 }
741
742 pub fn is_refer(&self) -> bool {
743 matches!(self, PartialValue::Refer(_))
744 }
745
746 pub fn new_indexes(s: &str) -> Option<Self> {
747 IndexType::try_from(s).map(PartialValue::Index).ok()
748 }
749
750 pub fn is_index(&self) -> bool {
751 matches!(self, PartialValue::Index(_))
752 }
753
754 pub fn new_syntaxs(s: &str) -> Option<Self> {
755 SyntaxType::try_from(s).map(PartialValue::Syntax).ok()
756 }
757
758 pub fn is_syntax(&self) -> bool {
759 matches!(self, PartialValue::Syntax(_))
760 }
761
762 pub fn new_json_filter_s(s: &str) -> Option<Self> {
763 serde_json::from_str(s)
764 .map(PartialValue::JsonFilt)
765 .map_err(|e| {
766 trace!(?e, ?s);
767 })
768 .ok()
769 }
770
771 pub fn is_json_filter(&self) -> bool {
772 matches!(self, PartialValue::JsonFilt(_))
773 }
774
775 pub fn new_credential_tag(s: &str) -> Self {
776 PartialValue::Cred(s.to_lowercase())
777 }
778
779 pub fn is_credential(&self) -> bool {
780 matches!(self, PartialValue::Cred(_))
781 }
782
783 pub fn new_secret_str() -> Self {
784 PartialValue::SecretValue
785 }
786
787 pub fn is_secret_string(&self) -> bool {
788 matches!(self, PartialValue::SecretValue)
789 }
790
791 pub fn new_sshkey_tag(s: String) -> Self {
792 PartialValue::SshKey(s)
793 }
794
795 pub fn new_sshkey_tag_s(s: &str) -> Self {
796 PartialValue::SshKey(s.to_string())
797 }
798
799 pub fn is_sshkey(&self) -> bool {
800 matches!(self, PartialValue::SshKey(_))
801 }
802
803 pub fn new_spn_s(s: &str) -> Option<Self> {
804 SPN_RE.captures(s).and_then(|caps| {
805 let name = match caps.name(Attribute::Name.as_ref()) {
806 Some(v) => v.as_str().to_string(),
807 None => return None,
808 };
809 let realm = match caps.name("realm") {
810 Some(v) => v.as_str().to_string(),
811 None => return None,
812 };
813 Some(PartialValue::Spn(name, realm))
814 })
815 }
816
817 pub fn new_spn_nrs(n: &str, r: &str) -> Self {
818 PartialValue::Spn(n.to_string(), r.to_string())
819 }
820
821 pub fn is_spn(&self) -> bool {
822 matches!(self, PartialValue::Spn(_, _))
823 }
824
825 pub fn new_uint32(u: u32) -> Self {
826 PartialValue::Uint32(u)
827 }
828
829 pub fn new_uint32_str(u: &str) -> Option<Self> {
830 u.parse::<u32>().ok().map(PartialValue::Uint32)
831 }
832
833 pub fn new_int64_str(u: &str) -> Option<Self> {
834 u.parse::<i64>().ok().map(PartialValue::Int64)
835 }
836
837 pub fn new_uint64_str(u: &str) -> Option<Self> {
838 u.parse::<u64>().ok().map(PartialValue::Uint64)
839 }
840
841 pub fn is_uint32(&self) -> bool {
842 matches!(self, PartialValue::Uint32(_))
843 }
844
845 pub fn new_cid(c: Cid) -> Self {
846 PartialValue::Cid(c)
847 }
848
849 pub fn new_cid_s(_c: &str) -> Option<Self> {
850 None
851 }
852
853 pub fn is_cid(&self) -> bool {
854 matches!(self, PartialValue::Cid(_))
855 }
856
857 pub fn new_nsuniqueid_s(s: &str) -> Self {
858 PartialValue::Nsuniqueid(s.to_lowercase())
859 }
860
861 pub fn is_nsuniqueid(&self) -> bool {
862 matches!(self, PartialValue::Nsuniqueid(_))
863 }
864
865 pub fn new_datetime_epoch(ts: Duration) -> Self {
866 PartialValue::DateTime(OffsetDateTime::UNIX_EPOCH + ts)
867 }
868
869 pub fn new_datetime_s(s: &str) -> Option<Self> {
870 OffsetDateTime::parse(s, &Rfc3339)
871 .ok()
872 .map(|odt| odt.to_offset(time::UtcOffset::UTC))
873 .map(PartialValue::DateTime)
874 }
875
876 pub fn is_datetime(&self) -> bool {
877 matches!(self, PartialValue::DateTime(_))
878 }
879
880 pub fn new_email_address_s(s: &str) -> Self {
881 PartialValue::EmailAddress(s.to_string())
882 }
883
884 pub fn is_email_address(&self) -> bool {
885 matches!(self, PartialValue::EmailAddress(_))
886 }
887
888 pub fn new_phonenumber_s(s: &str) -> Self {
889 PartialValue::PhoneNumber(s.to_string())
890 }
891
892 pub fn new_address(s: &str) -> Self {
893 PartialValue::Address(s.to_string())
894 }
895
896 pub fn new_url_s(s: &str) -> Option<Self> {
897 Url::parse(s).ok().map(PartialValue::Url)
898 }
899
900 pub fn is_url(&self) -> bool {
901 matches!(self, PartialValue::Url(_))
902 }
903
904 pub fn new_oauthscope(s: &str) -> Self {
905 PartialValue::OauthScope(s.to_string())
906 }
907
908 pub fn is_oauthscope(&self) -> bool {
909 matches!(self, PartialValue::OauthScope(_))
910 }
911
912 pub fn is_privatebinary(&self) -> bool {
913 matches!(self, PartialValue::PrivateBinary)
914 }
915
916 pub fn new_publicbinary_tag_s(s: &str) -> Self {
917 PartialValue::PublicBinary(s.to_string())
918 }
919
920 pub fn new_intenttoken_s(s: String) -> Option<Self> {
921 Some(PartialValue::IntentToken(s))
922 }
923
924 pub fn new_passkey_s(us: &str) -> Option<Self> {
925 Uuid::parse_str(us).map(PartialValue::Passkey).ok()
926 }
927
928 pub fn new_attested_passkey_s(us: &str) -> Option<Self> {
929 Uuid::parse_str(us).map(PartialValue::AttestedPasskey).ok()
930 }
931
932 pub fn new_hex_string_s(hexstr: &str) -> Option<Self> {
933 let hexstr_lower = hexstr.to_lowercase();
934 if HEXSTR_RE.is_match(&hexstr_lower) {
935 Some(PartialValue::HexString(hexstr_lower))
936 } else {
937 None
938 }
939 }
940
941 pub fn new_image(input: &str) -> Self {
942 PartialValue::Image(input.to_string())
943 }
944
945 pub fn to_str(&self) -> Option<&str> {
946 match self {
947 PartialValue::Utf8(s) => Some(s.as_str()),
948 PartialValue::Iutf8(s) => Some(s.as_str()),
949 PartialValue::Iname(s) => Some(s.as_str()),
950 _ => None,
951 }
952 }
953
954 pub fn to_url(&self) -> Option<&Url> {
955 match self {
956 PartialValue::Url(u) => Some(u),
957 _ => None,
958 }
959 }
960
961 pub fn get_idx_eq_key(&self) -> String {
962 match self {
963 PartialValue::Utf8(s)
964 | PartialValue::Iutf8(s)
965 | PartialValue::Iname(s)
966 | PartialValue::Nsuniqueid(s)
967 | PartialValue::EmailAddress(s) => s.clone(),
968 PartialValue::Passkey(u)
969 | PartialValue::AttestedPasskey(u)
970 | PartialValue::Refer(u)
971 | PartialValue::Uuid(u) => u.as_hyphenated().to_string(),
972 PartialValue::Bool(b) => b.to_string(),
973 PartialValue::Syntax(syn) => syn.to_string(),
974 PartialValue::Index(it) => it.to_string(),
975 PartialValue::JsonFilt(s) =>
976 {
977 #[allow(clippy::expect_used)]
978 serde_json::to_string(s).expect("A json filter value was corrupted during run-time")
979 }
980 PartialValue::Cred(tag)
981 | PartialValue::PublicBinary(tag)
982 | PartialValue::SshKey(tag) => tag.to_string(),
983 PartialValue::SecretValue | PartialValue::PrivateBinary => "_".to_string(),
985 PartialValue::Spn(name, realm) => format!("{name}@{realm}"),
986 PartialValue::Uint32(u) => u.to_string(),
987 PartialValue::Int64(u) => u.to_string(),
988 PartialValue::Uint64(u) => u.to_string(),
989 PartialValue::DateTime(odt) => {
990 debug_assert_eq!(odt.offset(), time::UtcOffset::UTC);
991 #[allow(clippy::expect_used)]
992 odt.format(&Rfc3339)
993 .expect("Failed to format timestamp into RFC3339")
994 }
995 PartialValue::Url(u) => u.to_string(),
996 PartialValue::OauthScope(u) => u.to_string(),
997 PartialValue::Address(a) => a.to_string(),
998 PartialValue::PhoneNumber(a) => a.to_string(),
999 PartialValue::IntentToken(u) => u.clone(),
1000 PartialValue::UiHint(u) => (*u as u16).to_string(),
1001 PartialValue::Image(imagehash) => imagehash.to_owned(),
1002 PartialValue::CredentialType(ct) => ct.to_string(),
1003 PartialValue::Cid(_) => "_".to_string(),
1005 PartialValue::OauthClaim(_, _) => "_".to_string(),
1007 PartialValue::OauthClaimValue(_, _, _) => "_".to_string(),
1008 PartialValue::HexString(hexstr) => hexstr.to_string(),
1009 PartialValue::Json => "_".to_string(),
1010 PartialValue::Sha256(bytes) => hex::encode(bytes),
1011 }
1012 }
1013
1014 pub fn get_idx_sub_key(&self) -> Option<String> {
1015 match self {
1016 PartialValue::Utf8(s)
1017 | PartialValue::Iutf8(s)
1018 | PartialValue::Iname(s)
1019 | PartialValue::EmailAddress(s) => Some(s.to_lowercase()),
1021
1022 PartialValue::Cred(tag)
1023 | PartialValue::PublicBinary(tag)
1024 | PartialValue::SshKey(tag) => Some(tag.to_lowercase()),
1025
1026 _ => None,
1028 }
1029 }
1030}
1031
1032#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1033pub enum ApiTokenScope {
1034 ReadOnly,
1035 ReadWrite,
1036 Synchronise,
1037}
1038
1039impl fmt::Display for ApiTokenScope {
1040 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1041 match self {
1042 ApiTokenScope::ReadOnly => write!(f, "read_only"),
1043 ApiTokenScope::ReadWrite => write!(f, "read_write"),
1044 ApiTokenScope::Synchronise => write!(f, "synchronise"),
1045 }
1046 }
1047}
1048
1049impl TryInto<ApiTokenPurpose> for ApiTokenScope {
1050 type Error = OperationError;
1051
1052 fn try_into(self: ApiTokenScope) -> Result<ApiTokenPurpose, OperationError> {
1053 match self {
1054 ApiTokenScope::ReadOnly => Ok(ApiTokenPurpose::ReadOnly),
1055 ApiTokenScope::ReadWrite => Ok(ApiTokenPurpose::ReadWrite),
1056 ApiTokenScope::Synchronise => Ok(ApiTokenPurpose::Synchronise),
1057 }
1058 }
1059}
1060
1061#[derive(Clone, Debug, PartialEq, Eq)]
1062pub struct ApiToken {
1063 pub label: String,
1064 pub expiry: Option<OffsetDateTime>,
1065 pub issued_at: OffsetDateTime,
1066 pub issued_by: IdentityId,
1067 pub scope: ApiTokenScope,
1068}
1069
1070#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1071pub enum SessionScope {
1072 ReadOnly,
1073 ReadWrite,
1074 PrivilegeCapable,
1075 Synchronise,
1077}
1078
1079impl fmt::Display for SessionScope {
1080 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1081 match self {
1082 SessionScope::ReadOnly => write!(f, "read_only"),
1083 SessionScope::ReadWrite => write!(f, "read_write"),
1084 SessionScope::PrivilegeCapable => write!(f, "privilege_capable"),
1085 SessionScope::Synchronise => write!(f, "synchronise"),
1086 }
1087 }
1088}
1089
1090impl TryInto<UatPurposeStatus> for SessionScope {
1091 type Error = OperationError;
1092
1093 fn try_into(self: SessionScope) -> Result<UatPurposeStatus, OperationError> {
1094 match self {
1095 SessionScope::ReadOnly => Ok(UatPurposeStatus::ReadOnly),
1096 SessionScope::ReadWrite => Ok(UatPurposeStatus::ReadWrite),
1097 SessionScope::PrivilegeCapable => Ok(UatPurposeStatus::PrivilegeCapable),
1098 SessionScope::Synchronise => Err(OperationError::InvalidEntryState),
1099 }
1100 }
1101}
1102
1103#[derive(Clone, Debug, PartialEq, Eq)]
1104pub enum SessionState {
1105 RevokedAt(Cid),
1109 ExpiresAt(OffsetDateTime),
1110 NeverExpires,
1111}
1112
1113impl PartialOrd for SessionState {
1114 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1115 Some(self.cmp(other))
1116 }
1117}
1118
1119impl Ord for SessionState {
1120 fn cmp(&self, other: &Self) -> Ordering {
1121 match (self, other) {
1124 (SessionState::RevokedAt(c_self), SessionState::RevokedAt(c_other)) => {
1126 c_other.cmp(c_self)
1129 }
1130 (SessionState::RevokedAt(_), _) => Ordering::Greater,
1131 (_, SessionState::RevokedAt(_)) => Ordering::Less,
1132 (SessionState::ExpiresAt(e_self), SessionState::ExpiresAt(e_other)) => {
1134 e_self.cmp(e_other)
1137 }
1138 (SessionState::ExpiresAt(_), _) => Ordering::Greater,
1139 (_, SessionState::ExpiresAt(_)) => Ordering::Less,
1140 (SessionState::NeverExpires, SessionState::NeverExpires) => Ordering::Equal,
1142 }
1143 }
1144}
1145
1146#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
1147pub enum AuthType {
1148 Anonymous,
1149 Password,
1150 GeneratedPassword,
1151 PasswordTotp,
1152 PasswordBackupCode,
1153 PasswordSecurityKey,
1154 Passkey,
1155 AttestedPasskey,
1156 OAuth2Trust,
1157}
1158
1159impl fmt::Display for AuthType {
1160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1161 match self {
1162 AuthType::Anonymous => write!(f, "anonymous"),
1163 AuthType::Password => write!(f, "password"),
1164 AuthType::GeneratedPassword => write!(f, "generatedpassword"),
1165 AuthType::PasswordTotp => write!(f, "passwordtotp"),
1166 AuthType::PasswordBackupCode => write!(f, "passwordbackupcode"),
1167 AuthType::PasswordSecurityKey => write!(f, "passwordsecuritykey"),
1168 AuthType::Passkey => write!(f, "passkey"),
1169 AuthType::AttestedPasskey => write!(f, "attested_passkey"),
1170 AuthType::OAuth2Trust => write!(f, "oauth2_trust"),
1171 }
1172 }
1173}
1174
1175#[derive(Clone, PartialEq, Eq, Default)]
1176pub enum SessionExtMetadata {
1177 #[default]
1178 None,
1179 OAuth2 {
1180 access_expires_at: Duration,
1181 access_token: String,
1182 refresh_token: Option<String>,
1183 },
1184}
1185
1186impl fmt::Debug for SessionExtMetadata {
1187 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1188 match self {
1189 Self::None => f.debug_struct("SessionExtMetadata::None").finish(),
1190 Self::OAuth2 {
1191 access_expires_at, ..
1192 } => f
1193 .debug_struct("SessionExtMetadata::OAuth2")
1194 .field("access_expires_at", access_expires_at)
1195 .finish(),
1196 }
1197 }
1198}
1199
1200#[derive(Clone, PartialEq, Eq)]
1201pub struct Session {
1202 pub label: String,
1203 pub state: SessionState,
1205 pub issued_at: OffsetDateTime,
1206 pub issued_by: IdentityId,
1207 pub cred_id: Uuid,
1208 pub scope: SessionScope,
1209 pub type_: AuthType,
1210 pub ext_metadata: SessionExtMetadata,
1211}
1212
1213impl fmt::Debug for Session {
1214 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1215 let issuer = match self.issued_by {
1216 IdentityId::User(u) => format!("User - {}", uuid_to_proto_string(u)),
1217 IdentityId::Synch(u) => format!("Synch - {}", uuid_to_proto_string(u)),
1218 IdentityId::Internal(u) => format!("Internal - {}", uuid_to_proto_string(u)),
1219 };
1220 let expiry = match self.state {
1221 SessionState::ExpiresAt(e) => e.to_string(),
1222 SessionState::NeverExpires => "never".to_string(),
1223 SessionState::RevokedAt(_) => "revoked".to_string(),
1224 };
1225 write!(
1226 f,
1227 "state: {}, issued at: {}, issued by: {}, credential id: {}, scope: {:?}",
1228 expiry, self.issued_at, issuer, self.cred_id, self.scope
1229 )
1230 }
1231}
1232
1233#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
1234pub enum OauthClaimMapJoin {
1235 CommaSeparatedValue,
1236 SpaceSeparatedValue,
1237 #[default]
1238 JsonArray,
1239}
1240
1241impl From<OauthClaimMapJoin> for ScimOauth2ClaimMapJoinChar {
1242 fn from(value: OauthClaimMapJoin) -> Self {
1243 match value {
1244 OauthClaimMapJoin::CommaSeparatedValue => {
1245 ScimOauth2ClaimMapJoinChar::CommaSeparatedValue
1246 }
1247 OauthClaimMapJoin::SpaceSeparatedValue => {
1248 ScimOauth2ClaimMapJoinChar::SpaceSeparatedValue
1249 }
1250 OauthClaimMapJoin::JsonArray => ScimOauth2ClaimMapJoinChar::JsonArray,
1251 }
1252 }
1253}
1254
1255impl From<ScimOauth2ClaimMapJoinChar> for OauthClaimMapJoin {
1256 fn from(value: ScimOauth2ClaimMapJoinChar) -> Self {
1257 match value {
1258 ScimOauth2ClaimMapJoinChar::CommaSeparatedValue => {
1259 OauthClaimMapJoin::CommaSeparatedValue
1260 }
1261 ScimOauth2ClaimMapJoinChar::SpaceSeparatedValue => {
1262 OauthClaimMapJoin::SpaceSeparatedValue
1263 }
1264 ScimOauth2ClaimMapJoinChar::JsonArray => OauthClaimMapJoin::JsonArray,
1265 }
1266 }
1267}
1268
1269impl OauthClaimMapJoin {
1270 pub(crate) fn to_str(self) -> &'static str {
1271 match self {
1272 OauthClaimMapJoin::CommaSeparatedValue => ",",
1273 OauthClaimMapJoin::SpaceSeparatedValue => " ",
1274 OauthClaimMapJoin::JsonArray => ";",
1276 }
1277 }
1278}
1279
1280impl From<DbValueOauthClaimMapJoinV1> for OauthClaimMapJoin {
1281 fn from(value: DbValueOauthClaimMapJoinV1) -> OauthClaimMapJoin {
1282 match value {
1283 DbValueOauthClaimMapJoinV1::CommaSeparatedValue => {
1284 OauthClaimMapJoin::CommaSeparatedValue
1285 }
1286 DbValueOauthClaimMapJoinV1::SpaceSeparatedValue => {
1287 OauthClaimMapJoin::SpaceSeparatedValue
1288 }
1289 DbValueOauthClaimMapJoinV1::JsonArray => OauthClaimMapJoin::JsonArray,
1290 }
1291 }
1292}
1293
1294impl From<OauthClaimMapJoin> for DbValueOauthClaimMapJoinV1 {
1295 fn from(value: OauthClaimMapJoin) -> DbValueOauthClaimMapJoinV1 {
1296 match value {
1297 OauthClaimMapJoin::CommaSeparatedValue => {
1298 DbValueOauthClaimMapJoinV1::CommaSeparatedValue
1299 }
1300 OauthClaimMapJoin::SpaceSeparatedValue => {
1301 DbValueOauthClaimMapJoinV1::SpaceSeparatedValue
1302 }
1303 OauthClaimMapJoin::JsonArray => DbValueOauthClaimMapJoinV1::JsonArray,
1304 }
1305 }
1306}
1307
1308#[derive(Clone, Debug, PartialEq, Eq)]
1309pub struct Oauth2Session {
1310 pub parent: Option<Uuid>,
1311 pub state: SessionState,
1312 pub issued_at: OffsetDateTime,
1313 pub rs_uuid: Uuid,
1314}
1315
1316#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1317pub enum KeyUsage {
1318 JwsEs256,
1319 JwsHs256,
1320 JwsRs256,
1321 JweA128GCM,
1322 JweA256GCM,
1323 HkdfS256,
1324}
1325
1326impl fmt::Display for KeyUsage {
1327 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1328 write!(
1329 f,
1330 "{}",
1331 match self {
1332 KeyUsage::JwsEs256 => "jws_es256",
1333 KeyUsage::JwsHs256 => "jws_hs256",
1334 KeyUsage::JwsRs256 => "jws_rs256",
1335 KeyUsage::JweA128GCM => "jwe_a128gcm",
1336 KeyUsage::JweA256GCM => "jwe_a256gcm",
1337 KeyUsage::HkdfS256 => "hkdf_s256",
1338 }
1339 )
1340 }
1341}
1342
1343#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1344pub enum KeyStatus {
1345 Valid,
1346 Retained,
1347 Revoked,
1348}
1349
1350impl fmt::Display for KeyStatus {
1351 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1352 write!(
1353 f,
1354 "{}",
1355 match self {
1356 KeyStatus::Valid => "valid",
1357 KeyStatus::Retained => "retained",
1358 KeyStatus::Revoked => "revoked",
1359 }
1360 )
1361 }
1362}
1363
1364#[derive(Clone, Debug)]
1371pub enum Value {
1372 Utf8(String),
1373 Iutf8(String),
1375 Iutf8N(String),
1376 Iname(String),
1378 InameN(String),
1379 Uuid(Uuid),
1380 UuidN(Uuid),
1381 Bool(bool),
1382 Syntax(SyntaxType),
1383 Index(IndexType),
1384 Refer(Uuid),
1385 ReferN(Uuid),
1386 JsonFilt(ProtoFilter),
1387 Cred(String, Credential),
1388 SshKey(String, SshPublicKey),
1389 SecretValue(String),
1390 Spn(String, String),
1391 Uint32(u32),
1392 Int64(i64),
1393 Uint64(u64),
1394 Cid(Cid),
1395 Nsuniqueid(String),
1396 DateTime(OffsetDateTime),
1397 EmailAddress(String, bool),
1398 PhoneNumber(String, bool),
1399 Address(Address),
1400 Url(Url),
1401 UrlN(Url),
1402 OauthScope(String),
1403 OauthScopeMap(Uuid, BTreeSet<String>),
1404 PrivateBinary(Vec<u8>),
1405 PublicBinary(String, Vec<u8>),
1406 IntentToken(String, IntentTokenState),
1407 Passkey(Uuid, String, PasskeyV4),
1408 AttestedPasskey(Uuid, String, AttestedPasskeyV4),
1409
1410 Session(Uuid, Session),
1411 ApiToken(Uuid, ApiToken),
1412 Oauth2Session(Uuid, Oauth2Session),
1413
1414 JwsKeyEs256(JwsEs256Signer),
1415 JwsKeyRs256(JwsRs256Signer),
1416 UiHint(UiHint),
1417
1418 TotpSecret(String, Totp),
1419 AuditLogString(Cid, String),
1420
1421 Image(ImageValue),
1422 CredentialType(CredentialType),
1423 WebauthnAttestationCaList(AttestationCaList),
1424
1425 OauthClaimValue(String, Uuid, BTreeSet<String>),
1426 OauthClaimMap(String, OauthClaimMapJoin),
1427
1428 KeyInternal {
1429 id: KeyId,
1430 usage: KeyUsage,
1431 valid_from: u64,
1432 status: KeyStatus,
1433 status_cid: Cid,
1434 der: Zeroizing<Vec<u8>>,
1435 },
1436
1437 HexString(String),
1438
1439 Certificate(Box<Certificate>),
1440 ApplicationPassword(ApplicationPassword),
1441 Json(JsonValue),
1442 Sha256(Sha256Output),
1443}
1444
1445impl PartialEq for Value {
1446 fn eq(&self, other: &Self) -> bool {
1447 match (self, other) {
1448 (Value::Utf8(a), Value::Utf8(b))
1449 | (Value::Iutf8(a), Value::Iutf8(b))
1450 | (Value::Iutf8N(a), Value::Iutf8N(b))
1451 | (Value::Iname(a), Value::Iname(b))
1452 | (Value::InameN(a), Value::InameN(b))
1454 | (Value::InameN(a), Value::Iname(b))
1455 | (Value::Cred(a, _), Value::Cred(b, _))
1457 | (Value::SshKey(a, _), Value::SshKey(b, _))
1458 | (Value::Nsuniqueid(a), Value::Nsuniqueid(b))
1459 | (Value::EmailAddress(a, _), Value::EmailAddress(b, _))
1460 | (Value::PhoneNumber(a, _), Value::PhoneNumber(b, _))
1461 | (Value::OauthScope(a), Value::OauthScope(b))
1462 | (Value::PublicBinary(a, _), Value::PublicBinary(b, _)) => a.eq(b),
1463 (Value::Spn(a, c), Value::Spn(b, d)) => a.eq(b) && c.eq(d),
1465 (Value::Uuid(a), Value::Uuid(b))
1467 | (Value::Refer(a), Value::Refer(b))
1468 | (Value::UuidN(a), Value::UuidN(b))
1469 | (Value::ReferN(a), Value::ReferN(b)) => a.eq(b),
1470 (Value::Bool(a), Value::Bool(b)) => a.eq(b),
1472 (Value::Syntax(a), Value::Syntax(b)) => a.eq(b),
1474 (Value::Index(a), Value::Index(b)) => a.eq(b),
1476 (Value::JsonFilt(a), Value::JsonFilt(b)) => a.eq(b),
1478 (Value::Uint32(a), Value::Uint32(b)) => a.eq(b),
1480 (Value::Int64(a), Value::Int64(b)) => a.eq(b),
1482 (Value::Uint64(a), Value::Uint64(b)) => a.eq(b),
1484 (Value::Cid(a), Value::Cid(b)) => a.eq(b),
1486 (Value::DateTime(a), Value::DateTime(b)) => a.eq(b),
1488 (Value::Url(a), Value::Url(b)) => a.eq(b),
1490 (Value::OauthScopeMap(a, c), Value::OauthScopeMap(b, d)) => a.eq(b) && c.eq(d),
1492
1493 (Value::Image(image1), Value::Image(image2)) => {
1494 image1.hash_imagevalue().eq(&image2.hash_imagevalue())
1495 }
1496 (Value::Address(_), Value::Address(_))
1497 | (Value::PrivateBinary(_), Value::PrivateBinary(_))
1498 | (Value::SecretValue(_), Value::SecretValue(_)) => false,
1499 (Value::Iutf8(_), Value::Iname(_)) | (Value::Iname(_), Value::Iutf8(_)) => false,
1501 (Value::Uuid(_), Value::Iname(_))
1503 | (Value::Iname(_), Value::Spn(_, _))
1504 | (Value::Uuid(_), Value::Spn(_, _)) => false,
1505 (l, r) => {
1506 error!(?l, ?r, "mismatched value types");
1507 debug_assert!(false);
1508 false
1509 }
1510 }
1511 }
1512}
1513
1514impl Eq for Value {}
1515
1516impl From<bool> for Value {
1517 fn from(b: bool) -> Self {
1518 Value::Bool(b)
1519 }
1520}
1521
1522impl From<&bool> for Value {
1523 fn from(b: &bool) -> Self {
1524 Value::Bool(*b)
1525 }
1526}
1527
1528impl From<SyntaxType> for Value {
1529 fn from(s: SyntaxType) -> Self {
1530 Value::Syntax(s)
1531 }
1532}
1533
1534impl From<IndexType> for Value {
1535 fn from(i: IndexType) -> Self {
1536 Value::Index(i)
1537 }
1538}
1539
1540impl From<ProtoFilter> for Value {
1541 fn from(i: ProtoFilter) -> Self {
1542 Value::JsonFilt(i)
1543 }
1544}
1545
1546impl From<OffsetDateTime> for Value {
1547 fn from(i: OffsetDateTime) -> Self {
1548 Value::DateTime(i)
1549 }
1550}
1551
1552impl From<u32> for Value {
1553 fn from(i: u32) -> Self {
1554 Value::Uint32(i)
1555 }
1556}
1557
1558impl From<Url> for Value {
1559 fn from(i: Url) -> Self {
1560 Value::Url(i)
1561 }
1562}
1563
1564#[cfg(test)]
1567impl From<&str> for Value {
1568 fn from(s: &str) -> Self {
1569 match Uuid::parse_str(s) {
1571 Ok(u) => Value::Uuid(u),
1572 Err(_) => Value::Utf8(s.to_string()),
1573 }
1574 }
1575}
1576
1577#[cfg(test)]
1578impl From<&Uuid> for Value {
1579 fn from(u: &Uuid) -> Self {
1580 Value::Uuid(*u)
1581 }
1582}
1583
1584#[cfg(test)]
1585impl From<Uuid> for Value {
1586 fn from(u: Uuid) -> Self {
1587 Value::Uuid(u)
1588 }
1589}
1590
1591impl From<DbIdentSpn> for Value {
1592 fn from(dis: DbIdentSpn) -> Self {
1593 match dis {
1594 DbIdentSpn::Spn(n, r) => Value::Spn(n, r),
1595 DbIdentSpn::Iname(n) => Value::Iname(n),
1596 DbIdentSpn::Uuid(u) => Value::Uuid(u),
1597 }
1598 }
1599}
1600
1601impl Value {
1602 pub fn new_utf8(s: String) -> Self {
1603 Value::Utf8(s)
1604 }
1605
1606 pub fn new_utf8s(s: &str) -> Self {
1607 Value::Utf8(s.to_string())
1608 }
1609
1610 pub fn is_utf8(&self) -> bool {
1611 matches!(self, Value::Utf8(_))
1612 }
1613
1614 pub fn new_iutf8(s: &str) -> Self {
1615 Value::Iutf8(s.to_lowercase())
1616 }
1617
1618 pub fn new_iutf8n(s: &str) -> Self {
1619 Value::Iutf8N(s.to_lowercase())
1620 }
1621
1622 pub fn is_iutf8(&self) -> bool {
1623 matches!(self, Value::Iutf8(_))
1624 }
1625
1626 pub fn new_attr(s: &str) -> Self {
1627 Value::Iutf8(s.to_lowercase())
1628 }
1629
1630 pub fn is_insensitive_utf8(&self) -> bool {
1631 matches!(self, Value::Iutf8(_))
1632 }
1633
1634 pub fn new_iname(s: &str) -> Self {
1635 Value::Iname(s.to_lowercase())
1636 }
1637
1638 pub fn new_inamen(s: &str) -> Self {
1639 Value::InameN(s.to_lowercase())
1640 }
1641
1642 pub fn is_iname(&self) -> bool {
1643 matches!(self, Value::Iname(_))
1644 }
1645
1646 pub fn new_uuid_s(s: &str) -> Option<Self> {
1647 Uuid::parse_str(s).map(Value::Uuid).ok()
1648 }
1649
1650 pub fn is_uuid(&self) -> bool {
1652 matches!(self, Value::Uuid(_))
1653 }
1654
1655 pub fn new_bool(b: bool) -> Self {
1656 Value::Bool(b)
1657 }
1658
1659 pub fn new_bools(s: &str) -> Option<Self> {
1660 bool::from_str(s).map(Value::Bool).ok()
1661 }
1662
1663 pub fn new_audit_log_string(e: (Cid, String)) -> Option<Self> {
1664 Some(Value::AuditLogString(e.0, e.1))
1665 }
1666
1667 #[inline]
1668 pub fn is_bool(&self) -> bool {
1669 matches!(self, Value::Bool(_))
1670 }
1671
1672 pub fn new_syntaxs(s: &str) -> Option<Self> {
1673 SyntaxType::try_from(s).map(Value::Syntax).ok()
1674 }
1675
1676 pub fn new_syntax(s: SyntaxType) -> Self {
1677 Value::Syntax(s)
1678 }
1679
1680 pub fn is_syntax(&self) -> bool {
1681 matches!(self, Value::Syntax(_))
1682 }
1683
1684 pub fn new_indexes(s: &str) -> Option<Self> {
1685 IndexType::try_from(s).map(Value::Index).ok()
1686 }
1687
1688 pub fn new_index(i: IndexType) -> Self {
1689 Value::Index(i)
1690 }
1691
1692 pub fn is_index(&self) -> bool {
1693 matches!(self, Value::Index(_))
1694 }
1695
1696 pub fn new_refer_s(us: &str) -> Option<Self> {
1697 Uuid::parse_str(us).map(Value::Refer).ok()
1698 }
1699
1700 pub fn is_refer(&self) -> bool {
1701 matches!(self, Value::Refer(_))
1702 }
1703
1704 pub fn new_json_filter_s(s: &str) -> Option<Self> {
1705 serde_json::from_str(s).map(Value::JsonFilt).ok()
1706 }
1707
1708 pub fn new_json_filter(f: ProtoFilter) -> Self {
1709 Value::JsonFilt(f)
1710 }
1711
1712 pub fn is_json_filter(&self) -> bool {
1713 matches!(self, Value::JsonFilt(_))
1714 }
1715
1716 pub fn as_json_filter(&self) -> Option<&ProtoFilter> {
1717 match &self {
1718 Value::JsonFilt(f) => Some(f),
1719 _ => None,
1720 }
1721 }
1722
1723 pub fn new_credential(tag: &str, cred: Credential) -> Self {
1724 Value::Cred(tag.to_string(), cred)
1725 }
1726
1727 pub fn is_credential(&self) -> bool {
1728 matches!(&self, Value::Cred(_, _))
1729 }
1730
1731 pub fn to_credential(&self) -> Option<&Credential> {
1732 match &self {
1733 Value::Cred(_, cred) => Some(cred),
1734 _ => None,
1735 }
1736 }
1737
1738 pub fn new_hex_string_s(hexstr: &str) -> Option<Self> {
1739 let hexstr_lower = hexstr.to_lowercase();
1740 if HEXSTR_RE.is_match(&hexstr_lower) {
1741 Some(Value::HexString(hexstr_lower))
1742 } else {
1743 None
1744 }
1745 }
1746
1747 pub fn new_certificate_s(cert_str: &str) -> Option<Self> {
1748 Certificate::from_pem(cert_str)
1749 .map(Box::new)
1750 .map(Value::Certificate)
1751 .ok()
1752 }
1753
1754 pub fn new_image(input: &str) -> Result<Self, OperationError> {
1756 serde_json::from_str::<ImageValue>(input)
1757 .map(Value::Image)
1758 .map_err(|_e| OperationError::InvalidValueState)
1759 }
1760
1761 pub fn new_secret_str(cleartext: &str) -> Self {
1762 Value::SecretValue(cleartext.to_string())
1763 }
1764
1765 pub fn is_secret_string(&self) -> bool {
1766 matches!(&self, Value::SecretValue(_))
1767 }
1768
1769 pub fn get_secret_str(&self) -> Option<&str> {
1770 match &self {
1771 Value::SecretValue(c) => Some(c.as_str()),
1772 _ => None,
1773 }
1774 }
1775
1776 pub fn new_sshkey_str(tag: &str, key: &str) -> Result<Self, OperationError> {
1777 SshPublicKey::from_string(key)
1778 .map(|pk| Value::SshKey(tag.to_string(), pk))
1779 .map_err(|err| {
1780 error!(?err, "value sshkey failed to parse string");
1781 OperationError::VL0001ValueSshPublicKeyString
1782 })
1783 }
1784
1785 pub fn is_sshkey(&self) -> bool {
1786 matches!(&self, Value::SshKey(_, _))
1787 }
1788
1789 pub fn get_sshkey(&self) -> Option<String> {
1790 match &self {
1791 Value::SshKey(_, key) => Some(key.to_string()),
1792 _ => None,
1793 }
1794 }
1795
1796 pub fn new_spn_parse(s: &str) -> Option<Self> {
1797 SPN_RE.captures(s).and_then(|caps| {
1798 let name = match caps.name(Attribute::Name.as_ref()) {
1799 Some(v) => v.as_str().to_string(),
1800 None => return None,
1801 };
1802 let realm = match caps.name("realm") {
1803 Some(v) => v.as_str().to_string(),
1804 None => return None,
1805 };
1806 Some(Value::Spn(name, realm))
1807 })
1808 }
1809
1810 pub fn new_spn_str(n: &str, r: &str) -> Self {
1811 Value::Spn(n.to_string(), r.to_string())
1812 }
1813
1814 pub fn is_spn(&self) -> bool {
1815 matches!(&self, Value::Spn(_, _))
1816 }
1817
1818 pub fn new_uint32(u: u32) -> Self {
1819 Value::Uint32(u)
1820 }
1821
1822 pub fn new_uint32_str(u: &str) -> Option<Self> {
1823 u.parse::<u32>().ok().map(Value::Uint32)
1824 }
1825
1826 pub fn is_uint32(&self) -> bool {
1827 matches!(&self, Value::Uint32(_))
1828 }
1829
1830 pub fn new_int64_str(u: &str) -> Option<Self> {
1831 u.parse::<i64>().ok().map(Value::Int64)
1832 }
1833
1834 pub fn new_uint64_str(u: &str) -> Option<Self> {
1835 u.parse::<u64>().ok().map(Value::Uint64)
1836 }
1837
1838 pub fn new_cid(c: Cid) -> Self {
1839 Value::Cid(c)
1840 }
1841
1842 pub fn is_cid(&self) -> bool {
1843 matches!(&self, Value::Cid(_))
1844 }
1845
1846 pub fn new_nsuniqueid_s(s: &str) -> Option<Self> {
1847 if NSUNIQUEID_RE.is_match(s) {
1848 Some(Value::Nsuniqueid(s.to_lowercase()))
1849 } else {
1850 None
1851 }
1852 }
1853
1854 pub fn is_nsuniqueid(&self) -> bool {
1855 matches!(&self, Value::Nsuniqueid(_))
1856 }
1857
1858 pub fn new_datetime_epoch(ts: Duration) -> Self {
1859 Value::DateTime(OffsetDateTime::UNIX_EPOCH + ts)
1860 }
1861
1862 pub fn new_datetime_s(s: &str) -> Option<Self> {
1863 OffsetDateTime::parse(s, &Rfc3339)
1864 .ok()
1865 .map(|odt| odt.to_offset(time::UtcOffset::UTC))
1866 .map(Value::DateTime)
1867 }
1868
1869 pub fn new_datetime(dt: OffsetDateTime) -> Self {
1870 Value::DateTime(dt)
1871 }
1872
1873 pub fn to_datetime(&self) -> Option<OffsetDateTime> {
1874 match &self {
1875 Value::DateTime(odt) => {
1876 debug_assert_eq!(odt.offset(), time::UtcOffset::UTC);
1877 Some(*odt)
1878 }
1879 _ => None,
1880 }
1881 }
1882
1883 pub fn is_datetime(&self) -> bool {
1884 matches!(&self, Value::DateTime(_))
1885 }
1886
1887 pub fn new_email_address_s(s: &str) -> Option<Self> {
1888 if VALIDATE_EMAIL_RE.is_match(s) {
1889 Some(Value::EmailAddress(s.to_string(), false))
1890 } else {
1891 None
1892 }
1893 }
1894
1895 pub fn new_email_address_primary_s(s: &str) -> Option<Self> {
1896 if VALIDATE_EMAIL_RE.is_match(s) {
1897 Some(Value::EmailAddress(s.to_string(), true))
1898 } else {
1899 None
1900 }
1901 }
1902
1903 pub fn is_email_address(&self) -> bool {
1904 matches!(&self, Value::EmailAddress(_, _))
1905 }
1906
1907 pub fn new_phonenumber_s(s: &str) -> Self {
1908 Value::PhoneNumber(s.to_string(), false)
1909 }
1910
1911 pub fn new_address(a: Address) -> Self {
1912 Value::Address(a)
1913 }
1914
1915 pub fn new_url_s(s: &str) -> Option<Self> {
1916 Url::parse(s).ok().map(Value::Url)
1917 }
1918
1919 pub fn new_urln_s(s: &str) -> Option<Self> {
1920 Url::parse(s).ok().map(Value::UrlN)
1921 }
1922
1923 pub fn new_url(u: Url) -> Self {
1924 Value::Url(u)
1925 }
1926
1927 pub fn is_url(&self) -> bool {
1928 matches!(&self, Value::Url(_))
1929 }
1930
1931 pub fn new_oauthscope(s: &str) -> Option<Self> {
1932 if OAUTHSCOPE_RE.is_match(s) {
1933 Some(Value::OauthScope(s.to_string()))
1934 } else {
1935 None
1936 }
1937 }
1938
1939 pub fn is_oauthscope(&self) -> bool {
1940 matches!(&self, Value::OauthScope(_))
1941 }
1942
1943 pub fn new_oauthscopemap(u: Uuid, m: BTreeSet<String>) -> Option<Self> {
1944 if m.iter().all(|s| OAUTHSCOPE_RE.is_match(s)) {
1945 Some(Value::OauthScopeMap(u, m))
1946 } else {
1947 None
1948 }
1949 }
1950
1951 pub fn new_oauthclaimmap(n: String, u: Uuid, c: BTreeSet<String>) -> Option<Self> {
1952 if OAUTH_CLAIMNAME_RE.is_match(&n) && c.iter().all(|s| OAUTH_CLAIMNAME_RE.is_match(s)) {
1953 Some(Value::OauthClaimValue(n, u, c))
1954 } else {
1955 None
1956 }
1957 }
1958
1959 pub fn is_oauthscopemap(&self) -> bool {
1960 matches!(&self, Value::OauthScopeMap(_, _))
1961 }
1962
1963 #[cfg(test)]
1964 pub fn new_privatebinary_base64(der: &str) -> Self {
1965 let der = general_purpose::STANDARD
1966 .decode(der)
1967 .expect("Failed to decode base64 der value");
1968 Value::PrivateBinary(der)
1969 }
1970
1971 pub fn new_privatebinary(der: &[u8]) -> Self {
1972 Value::PrivateBinary(der.to_owned())
1973 }
1974
1975 pub fn to_privatebinary(&self) -> Option<&Vec<u8>> {
1976 match &self {
1977 Value::PrivateBinary(c) => Some(c),
1978 _ => None,
1979 }
1980 }
1981
1982 pub fn is_privatebinary(&self) -> bool {
1983 matches!(&self, Value::PrivateBinary(_))
1984 }
1985
1986 pub fn new_publicbinary(tag: String, der: Vec<u8>) -> Self {
1987 Value::PublicBinary(tag, der)
1988 }
1989
1990 pub fn new_webauthn_attestation_ca_list(s: &str) -> Option<Self> {
1991 serde_json::from_str(s)
1992 .map(Value::WebauthnAttestationCaList)
1993 .map_err(|err| {
1994 debug!(?err, ?s);
1995 })
1996 .ok()
1997 }
1998
1999 #[allow(clippy::unreachable)]
2000 pub(crate) fn to_db_ident_spn(&self) -> DbIdentSpn {
2001 match &self {
2003 Value::Spn(n, r) => DbIdentSpn::Spn(n.clone(), r.clone()),
2004 Value::Iname(s) | Value::InameN(s) => DbIdentSpn::Iname(s.clone()),
2005 Value::Uuid(u) => DbIdentSpn::Uuid(*u),
2006 v => unreachable!("-> {:?}", v),
2010 }
2011 }
2012
2013 pub fn to_str(&self) -> Option<&str> {
2014 match &self {
2015 Value::Utf8(s) => Some(s.as_str()),
2016 Value::Iutf8(s) => Some(s.as_str()),
2017 Value::Iutf8N(s) => Some(s.as_str()),
2018 Value::Iname(s) => Some(s.as_str()),
2019 _ => None,
2020 }
2021 }
2022
2023 pub fn to_url(&self) -> Option<&Url> {
2024 match &self {
2025 Value::Url(u) => Some(u),
2026 _ => None,
2027 }
2028 }
2029
2030 pub fn as_string(&self) -> Option<&String> {
2031 match &self {
2032 Value::Utf8(s) => Some(s),
2033 Value::Iutf8(s) => Some(s),
2034 Value::Iname(s) => Some(s),
2035 _ => None,
2036 }
2037 }
2038
2039 pub fn to_ref_uuid(&self) -> Option<Uuid> {
2042 match &self {
2043 Value::Refer(u) | Value::ReferN(u) => Some(*u),
2044 Value::OauthScopeMap(u, _) => Some(*u),
2045 Value::Oauth2Session(_, m) => Some(m.rs_uuid),
2047 _ => None,
2048 }
2049 }
2050
2051 pub fn to_uuid(&self) -> Option<&Uuid> {
2052 match &self {
2053 Value::Uuid(u) | Value::UuidN(u) => Some(u),
2054 _ => None,
2055 }
2056 }
2057
2058 pub fn to_indextype(&self) -> Option<&IndexType> {
2059 match &self {
2060 Value::Index(i) => Some(i),
2061 _ => None,
2062 }
2063 }
2064
2065 pub fn to_syntaxtype(&self) -> Option<&SyntaxType> {
2066 match &self {
2067 Value::Syntax(s) => Some(s),
2068 _ => None,
2069 }
2070 }
2071
2072 pub fn to_bool(&self) -> Option<bool> {
2073 match self {
2074 Value::Bool(v) => Some(*v),
2076 _ => None,
2077 }
2078 }
2079
2080 pub fn to_uint32(&self) -> Option<u32> {
2081 match &self {
2082 Value::Uint32(v) => Some(*v),
2083 _ => None,
2084 }
2085 }
2086
2087 pub fn to_utf8(self) -> Option<String> {
2088 match self {
2089 Value::Utf8(s) => Some(s),
2090 _ => None,
2091 }
2092 }
2093
2094 pub fn to_iutf8(self) -> Option<String> {
2095 match self {
2096 Value::Iutf8(s) => Some(s),
2097 _ => None,
2098 }
2099 }
2100
2101 pub fn to_iname(self) -> Option<String> {
2102 match self {
2103 Value::Iname(s) => Some(s),
2104 _ => None,
2105 }
2106 }
2107
2108 pub fn to_jsonfilt(self) -> Option<ProtoFilter> {
2109 match self {
2110 Value::JsonFilt(f) => Some(f),
2111 _ => None,
2112 }
2113 }
2114
2115 pub fn to_cred(self) -> Option<(String, Credential)> {
2116 match self {
2117 Value::Cred(tag, c) => Some((tag, c)),
2118 _ => None,
2119 }
2120 }
2121
2122 pub fn to_spn(self) -> Option<(String, String)> {
2123 match self {
2124 Value::Spn(n, d) => Some((n, d)),
2125 _ => None,
2126 }
2127 }
2128
2129 pub fn to_cid(self) -> Option<Cid> {
2130 match self {
2131 Value::Cid(s) => Some(s),
2132 _ => None,
2133 }
2134 }
2135
2136 pub fn to_nsuniqueid(self) -> Option<String> {
2137 match self {
2138 Value::Nsuniqueid(s) => Some(s),
2139 _ => None,
2140 }
2141 }
2142
2143 pub fn to_emailaddress(self) -> Option<String> {
2144 match self {
2145 Value::EmailAddress(s, _) => Some(s),
2146 _ => None,
2147 }
2148 }
2149
2150 pub fn to_oauthscope(self) -> Option<String> {
2151 match self {
2152 Value::OauthScope(s) => Some(s),
2153 _ => None,
2154 }
2155 }
2156
2157 pub fn to_oauthscopemap(self) -> Option<(Uuid, BTreeSet<String>)> {
2158 match self {
2159 Value::OauthScopeMap(u, m) => Some((u, m)),
2160 _ => None,
2161 }
2162 }
2163
2164 pub fn to_phonenumber(self) -> Option<String> {
2165 match self {
2166 Value::PhoneNumber(p, _b) => Some(p),
2167 _ => None,
2168 }
2169 }
2170
2171 pub fn to_publicbinary(self) -> Option<(String, Vec<u8>)> {
2172 match self {
2173 Value::PublicBinary(t, d) => Some((t, d)),
2174 _ => None,
2175 }
2176 }
2177
2178 pub fn to_address(self) -> Option<Address> {
2179 match self {
2180 Value::Address(a) => Some(a),
2181 _ => None,
2182 }
2183 }
2184
2185 pub fn to_intenttoken(self) -> Option<(String, IntentTokenState)> {
2186 match self {
2187 Value::IntentToken(u, s) => Some((u, s)),
2188 _ => None,
2189 }
2190 }
2191
2192 pub fn to_session(self) -> Option<(Uuid, Session)> {
2193 match self {
2194 Value::Session(u, s) => Some((u, s)),
2195 _ => None,
2196 }
2197 }
2198
2199 pub fn migrate_iutf8_iname(self) -> Option<Self> {
2200 match self {
2201 Value::Iutf8(v) => Some(Value::Iname(v)),
2202 _ => None,
2203 }
2204 }
2205
2206 #[allow(clippy::unreachable)]
2208 pub(crate) fn to_proto_string_clone(&self) -> String {
2209 match &self {
2210 Value::Iname(s) | Value::InameN(s) => s.clone(),
2211 Value::Uuid(u) | Value::UuidN(u) => u.as_hyphenated().to_string(),
2212 Value::SshKey(tag, key) => format!("{tag}: {key}"),
2214 Value::Spn(n, r) => format!("{n}@{r}"),
2215 _ => unreachable!(
2216 "You've specified the wrong type for the attribute, got: {:?}",
2217 self
2218 ),
2219 }
2220 }
2221
2222 pub(crate) fn validate(&self) -> bool {
2223 match &self {
2227 Value::Utf8(s)
2229 | Value::Iutf8(s)
2230 | Value::Iutf8N(s)
2231 | Value::Cred(s, _)
2232 | Value::PublicBinary(s, _)
2233 | Value::IntentToken(s, _)
2234 | Value::Passkey(_, s, _)
2235 | Value::AttestedPasskey(_, s, _)
2236 | Value::TotpSecret(s, _) => {
2237 Value::validate_str_escapes(s) && Value::validate_singleline(s)
2238 }
2239
2240 Value::Spn(a, b) => {
2241 Value::validate_str_escapes(a)
2242 && Value::validate_str_escapes(b)
2243 && Value::validate_singleline(a)
2244 && Value::validate_singleline(b)
2245 }
2246 Value::Image(image) => image.validate_image().is_ok(),
2247 Value::Iname(s) | Value::InameN(s) => {
2248 Value::validate_str_escapes(s)
2249 && Value::validate_iname(s)
2250 && Value::validate_singleline(s)
2251 }
2252
2253 Value::SshKey(s, _key) => {
2254 Value::validate_str_escapes(s)
2255 && Value::validate_singleline(s)
2257 }
2258
2259 Value::ApiToken(_, at) => {
2260 Value::validate_str_escapes(&at.label) && Value::validate_singleline(&at.label)
2261 }
2262 Value::AuditLogString(_, s) => {
2263 Value::validate_str_escapes(s) && Value::validate_singleline(s)
2264 }
2265 Value::ApplicationPassword(ap) => {
2266 Value::validate_str_escapes(&ap.label) && Value::validate_singleline(&ap.label)
2267 }
2268
2269 Value::Nsuniqueid(s) => NSUNIQUEID_RE.is_match(s),
2271 Value::DateTime(odt) => odt.offset() == time::UtcOffset::UTC,
2272 Value::EmailAddress(mail, _) => VALIDATE_EMAIL_RE.is_match(mail.as_str()),
2273 Value::OauthScope(s) => OAUTHSCOPE_RE.is_match(s),
2274 Value::OauthScopeMap(_, m) => m.iter().all(|s| OAUTHSCOPE_RE.is_match(s)),
2275
2276 Value::OauthClaimMap(name, _) => OAUTH_CLAIMNAME_RE.is_match(name),
2277 Value::OauthClaimValue(name, _, value) => {
2278 OAUTH_CLAIMNAME_RE.is_match(name)
2279 && value.iter().all(|s| OAUTH_CLAIMNAME_RE.is_match(s))
2280 }
2281
2282 Value::KeyInternal { id, .. } => {
2283 let s = id.as_str();
2284 Value::validate_str_escapes(s)
2285 && Value::validate_singleline(s)
2286 && Value::validate_hexstr(s)
2287 }
2288 Value::HexString(id) => {
2289 Value::validate_str_escapes(id.as_str())
2290 && Value::validate_singleline(id.as_str())
2291 && Value::validate_hexstr(id.as_str())
2292 }
2293
2294 Value::PhoneNumber(_, _) => true,
2295 Value::Address(_) => true,
2296 Value::Certificate(_) => true,
2297
2298 Value::Uuid(_)
2299 | Value::UuidN(_)
2300 | Value::Bool(_)
2301 | Value::Syntax(_)
2302 | Value::Index(_)
2303 | Value::Refer(_)
2304 | Value::ReferN(_)
2305 | Value::JsonFilt(_)
2306 | Value::SecretValue(_)
2307 | Value::Uint32(_)
2308 | Value::Int64(_)
2309 | Value::Uint64(_)
2310 | Value::Url(_)
2311 | Value::UrlN(_)
2312 | Value::Cid(_)
2313 | Value::PrivateBinary(_)
2314 | Value::JwsKeyEs256(_)
2315 | Value::Session(_, _)
2316 | Value::Oauth2Session(_, _)
2317 | Value::JwsKeyRs256(_)
2318 | Value::UiHint(_)
2319 | Value::CredentialType(_)
2320 | Value::Json(_)
2321 | Value::Sha256(_)
2322 | Value::WebauthnAttestationCaList(_) => true,
2323 }
2324 }
2325
2326 pub(crate) fn validate_iname(s: &str) -> bool {
2327 match Uuid::parse_str(s) {
2328 Ok(_) => {
2330 error!("iname values may not contain uuids");
2331 false
2332 }
2333 Err(_) => {
2335 if !INAME_RE.is_match(s) {
2336 error!("iname values may only contain limited characters - \"{}\" does not pass regex pattern \"{}\"", s, *INAME_RE);
2337 false
2338 } else if DISALLOWED_NAMES.contains(s) {
2339 error!("iname value \"{}\" is in denied list", s);
2340 false
2341 } else {
2342 true
2343 }
2344 }
2345 }
2346 }
2347
2348 pub(crate) fn validate_hexstr(s: &str) -> bool {
2349 if !HEXSTR_RE.is_match(s) {
2350 error!("hexstrings may only contain limited characters. - \"{}\" does not pass regex pattern \"{}\"", s, *HEXSTR_RE);
2351 false
2352 } else {
2353 true
2354 }
2355 }
2356
2357 pub(crate) fn validate_singleline(s: &str) -> bool {
2358 if !SINGLELINE_RE.is_match(s) {
2359 true
2360 } else {
2361 error!(
2362 "value contains invalid whitespace chars forbidden by \"{}\"",
2363 *SINGLELINE_RE
2364 );
2365 trace!(?s, "Invalid whitespace");
2367 false
2368 }
2369 }
2370
2371 pub(crate) fn validate_str_escapes(s: &str) -> bool {
2372 if UNICODE_CONTROL_RE.is_match(s) {
2374 error!("value contains invalid unicode control character",);
2375 trace!(?s, "Invalid Unicode Control");
2377 false
2378 } else {
2379 true
2380 }
2381 }
2382}
2383
2384#[cfg(test)]
2385mod tests {
2386 use crate::value::*;
2387
2388 #[test]
2389 fn test_value_index_tryfrom() {
2390 let r1 = IndexType::try_from("EQualiTY");
2391 assert_eq!(r1, Ok(IndexType::Equality));
2392
2393 let r2 = IndexType::try_from("PResenCE");
2394 assert_eq!(r2, Ok(IndexType::Presence));
2395
2396 let r3 = IndexType::try_from("SUbstrING");
2397 assert_eq!(r3, Ok(IndexType::SubString));
2398
2399 let r4 = IndexType::try_from("thaoeusaneuh");
2400 assert_eq!(r4, Err(()));
2401 }
2402
2403 #[test]
2404 fn test_value_syntax_tryfrom() {
2405 let r1 = SyntaxType::try_from("UTF8strinG");
2406 assert_eq!(r1, Ok(SyntaxType::Utf8String));
2407
2408 let r2 = SyntaxType::try_from("UTF8STRING_INSensitIVE");
2409 assert_eq!(r2, Ok(SyntaxType::Utf8StringInsensitive));
2410
2411 let r3 = SyntaxType::try_from("BOOLEAN");
2412 assert_eq!(r3, Ok(SyntaxType::Boolean));
2413
2414 let r4 = SyntaxType::try_from("SYNTAX_ID");
2415 assert_eq!(r4, Ok(SyntaxType::SyntaxId));
2416
2417 let r5 = SyntaxType::try_from("INDEX_ID");
2418 assert_eq!(r5, Ok(SyntaxType::IndexId));
2419
2420 let r6 = SyntaxType::try_from("zzzzantheou");
2421 assert_eq!(r6, Err(()));
2422 }
2423
2424 #[test]
2425 fn test_value_sshkey_validation_display() {
2426 let ecdsa = concat!("ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBAGyIY7o3B",
2427 "tOzRiJ9vvjj96bRImwmyy5GvFSIUPlK00HitiAWGhiO1jGZKmK7220Oe4rqU3uAwA00a0758UODs+0OQHLMDRtl81l",
2428 "zPrVSdrYEDldxH9+a86dBZhdm0e15+ODDts2LHUknsJCRRldO4o9R9VrohlF7cbyBlnhJQrR4S+Oag== william@a",
2429 "methyst");
2430 let ed25519 = concat!(
2431 "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAeGW1P6Pc2rPq0XqbRaDKBcXZUPRklo0L1EyR30CwoP",
2432 " william@amethyst"
2433 );
2434 let rsa = concat!("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDTcXpclurQpyOHZBM/cDY9EvInSYkYSGe51by/wJP0Njgi",
2435 "GZUJ3HTaPqoGWux0PKd7KJki+onLYt4IwDV1RhV/GtMML2U9v94+pA8RIK4khCxvpUxlM7Kt/svjOzzzqiZfKdV37/",
2436 "OUXmM7bwVGOvm3EerDOwmO/QdzNGfkca12aWLoz97YrleXnCoAzr3IN7j3rwmfJGDyuUtGTdmyS/QWhK9FPr8Ic3eM",
2437 "QK1JSAQqVfGhA8lLbJHmnQ/b/KMl2lzzp7SXej0wPUfvI/IP3NGb8irLzq8+JssAzXGJ+HMql+mNHiSuPaktbFzZ6y",
2438 "ikMR6Rx/psU07nAkxKZDEYpNVv william@amethyst");
2439
2440 let sk1 = Value::new_sshkey_str("tag", ecdsa).expect("Invalid ssh key");
2441 assert!(sk1.validate());
2442 let psk1 = sk1.to_proto_string_clone();
2444 assert_eq!(psk1, format!("tag: {ecdsa}"));
2445
2446 let sk2 = Value::new_sshkey_str("tag", ed25519).expect("Invalid ssh key");
2447 assert!(sk2.validate());
2448 let psk2 = sk2.to_proto_string_clone();
2449 assert_eq!(psk2, format!("tag: {ed25519}"));
2450
2451 let sk3 = Value::new_sshkey_str("tag", rsa).expect("Invalid ssh key");
2452 assert!(sk3.validate());
2453 let psk3 = sk3.to_proto_string_clone();
2454 assert_eq!(psk3, format!("tag: {rsa}"));
2455
2456 let sk4 = Value::new_sshkey_str("tag", "ntaouhtnhtnuehtnuhotnuhtneouhtneouh");
2457 assert!(sk4.is_err());
2458
2459 let sk5 = Value::new_sshkey_str(
2460 "tag",
2461 "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAeGW1P6Pc2rPq0XqbRaDKBcXZUPRklo",
2462 );
2463 assert!(sk5.is_err());
2464 }
2465
2466 #[test]
2502 fn test_value_cid() {
2503 assert!(PartialValue::new_cid_s("_").is_none());
2504 }
2505
2506 #[test]
2507 fn test_value_iname() {
2508 let inv1 = Value::new_iname("1234");
2519 let inv2 = Value::new_iname("bc23f637-4439-4c07-b95d-eaed0d9e4b8b");
2520 let inv3 = Value::new_iname("hello@test.com");
2521 let inv4 = Value::new_iname("_bad");
2522 let inv5 = Value::new_iname("no spaces I'm sorry :(");
2523 let inv6 = Value::new_iname("bad=equals");
2524 let inv7 = Value::new_iname("bad,comma");
2525 let inv8 = Value::new_iname("123_456");
2526 let inv9 = Value::new_iname("🍿");
2527
2528 let val1 = Value::new_iname("William");
2529 let val2 = Value::new_iname("this_is_okay");
2530 let val3 = Value::new_iname("a123_456");
2531
2532 assert!(!inv1.validate());
2533 assert!(!inv2.validate());
2534 assert!(!inv3.validate());
2535 assert!(!inv4.validate());
2536 assert!(!inv5.validate());
2537 assert!(!inv6.validate());
2538 assert!(!inv7.validate());
2539 assert!(!inv8.validate());
2540 assert!(!inv9.validate());
2541
2542 assert!(val1.validate());
2543 assert!(val2.validate());
2544 assert!(val3.validate());
2545 }
2546
2547 #[test]
2548 fn test_value_nsuniqueid() {
2549 let val1 = Value::new_nsuniqueid_s("d765e707-48e111e6-8c9ebed8-f7926cc3");
2554 let val2 = Value::new_nsuniqueid_s("D765E707-48E111E6-8C9EBED8-F7926CC3");
2555 let inv1 = Value::new_nsuniqueid_s("d765e707-48e1-11e6-8c9e-bed8f7926cc3");
2556 let inv2 = Value::new_nsuniqueid_s("xxxx");
2557
2558 assert!(inv1.is_none());
2559 assert!(inv2.is_none());
2560 assert!(val1.unwrap().validate());
2561 assert!(val2.unwrap().validate());
2562 }
2563
2564 #[test]
2565 fn test_value_datetime() {
2566 let val1 = Value::new_datetime_s("2020-09-25T11:22:02+10:00").expect("Must be valid");
2568 assert!(val1.validate());
2569 let val2 = Value::new_datetime_s("2020-09-25T01:22:02+00:00").expect("Must be valid");
2570 assert!(val2.validate());
2571 let val3 = Value::new_datetime_s("2020-09-25 01:22:02+00:00").expect("Must be valid");
2573 assert!(val3.validate());
2574
2575 assert!(Value::new_datetime_s("2020-09-25T01:22:02").is_none());
2576 assert!(Value::new_datetime_s("2020-09-25").is_none());
2577 assert!(Value::new_datetime_s("2020-09-25T01:22:02+10").is_none());
2578
2579 let inv1 = Value::DateTime(
2581 #[allow(clippy::disallowed_methods)]
2582 OffsetDateTime::now_utc()
2583 .to_offset(time::UtcOffset::from_whole_seconds(36000).unwrap()),
2584 );
2585 assert!(!inv1.validate());
2586 #[allow(clippy::disallowed_methods)]
2587 let val3 = Value::DateTime(OffsetDateTime::now_utc());
2588 assert!(val3.validate());
2589 }
2590
2591 #[test]
2592 fn test_value_email_address() {
2593 let val1 = Value::new_email_address_s("william@blackhats.net.au");
2595 let val2 = Value::new_email_address_s("alice@idm.example.com");
2596 let val3 = Value::new_email_address_s("test+mailbox@foo.com");
2597 let inv1 = Value::new_email_address_s("william");
2598 let inv2 = Value::new_email_address_s("test~uuid");
2599
2600 assert!(inv1.is_none());
2601 assert!(inv2.is_none());
2602 assert!(val1.unwrap().validate());
2603 assert!(val2.unwrap().validate());
2604 assert!(val3.unwrap().validate());
2605 }
2606
2607 #[test]
2608 fn test_value_url() {
2609 let val1 = Value::new_url_s("https://localhost:8000/search?q=text#hello");
2611 let val2 = Value::new_url_s("https://github.com/kanidm/kanidm");
2612 let val3 = Value::new_url_s("ldap://foo.com");
2613 let inv1 = Value::new_url_s("127.0.");
2614 let inv2 = Value::new_url_s("🤔");
2615
2616 assert!(inv1.is_none());
2617 assert!(inv2.is_none());
2618 assert!(val1.is_some());
2619 assert!(val2.is_some());
2620 assert!(val3.is_some());
2621 }
2622
2623 #[test]
2624 fn test_singleline() {
2625 assert!(Value::validate_singleline("no new lines"));
2626
2627 assert!(!Value::validate_singleline("contains a \n new line"));
2628 assert!(!Value::validate_singleline("contains a \r return feed"));
2629 assert!(!Value::validate_singleline("contains a \t tab char"));
2630 }
2631
2632 #[test]
2633 fn test_str_escapes() {
2634 assert!(Value::validate_str_escapes("safe str"));
2635 assert!(Value::validate_str_escapes("🙃 emoji are 👍"));
2636
2637 assert!(!Value::validate_str_escapes("naughty \x1b[31mred"));
2638 }
2639
2640 #[test]
2641 fn test_value_key_internal_status_order() {
2642 assert!(KeyStatus::Valid < KeyStatus::Retained);
2643 assert!(KeyStatus::Retained < KeyStatus::Revoked);
2644 }
2645
2646 #[test]
2647 fn test_value_session_state_order() {
2648 assert!(
2649 SessionState::RevokedAt(Cid::new_zero()) > SessionState::RevokedAt(Cid::new_count(1))
2650 );
2651 assert!(
2652 SessionState::RevokedAt(Cid::new_zero())
2653 > SessionState::ExpiresAt(OffsetDateTime::UNIX_EPOCH)
2654 );
2655 assert!(
2656 SessionState::ExpiresAt(OffsetDateTime::UNIX_EPOCH + Duration::from_secs(1))
2657 > SessionState::ExpiresAt(OffsetDateTime::UNIX_EPOCH)
2658 );
2659 assert!(SessionState::ExpiresAt(OffsetDateTime::UNIX_EPOCH) > SessionState::NeverExpires);
2660 }
2661
2662 #[test]
2663 fn test_extract_val_dn_regexn() {
2664 fn do_extract(name: &str) -> &str {
2665 EXTRACT_VAL_DN
2666 .captures(name)
2667 .and_then(|caps| caps.name("val"))
2668 .map(|v| v.as_str())
2669 .unwrap()
2670 }
2671
2672 assert_eq!(do_extract("william"), "william");
2673 assert_eq!(do_extract("cn=william"), "william");
2674 assert_eq!(do_extract("cn=william,o=blackhats"), "william");
2675 assert_eq!(do_extract("cn=william@example.com"), "william@example.com");
2676 }
2677
2678 #[test]
2679 fn test_oauth2_scope_re_valid() {
2680 assert!(OAUTHSCOPE_RE.is_match("abcd"));
2682 assert!(OAUTHSCOPE_RE.is_match("https://abcd"));
2683 assert!(OAUTHSCOPE_RE.is_match("abcd.efgh"));
2684 assert!(OAUTHSCOPE_RE.is_match("abcd.efgh.xfz"));
2685
2686 assert!(!OAUTHSCOPE_RE.is_match(""));
2688 assert!(!OAUTHSCOPE_RE.is_match("."));
2689 assert!(!OAUTHSCOPE_RE.is_match(":"));
2690 assert!(!OAUTHSCOPE_RE.is_match("/"));
2691 assert!(!OAUTHSCOPE_RE.is_match("abcd."));
2692 assert!(!OAUTHSCOPE_RE.is_match("abcd::blah"));
2693 }
2694}