Skip to main content

coqui_access/
model.rs

1use std::collections::BTreeMap;
2use std::fmt;
3
4use guatiao::{FromValue, Schema, ToValue, Value};
5
6/// What an authenticator takes, as [`Description::takes`] names it.
7pub mod takes {
8    /// A name and a password, once, when a client signs in.
9    pub const PASSWORD: &str = "password";
10    /// A key by itself, which is the account: for what has nobody to type a password.
11    pub const KEY: &str = "key";
12    /// The request as it arrived, every time: a header a proxy set, or the certificate a
13    /// client proved it holds.
14    pub const REQUEST: &str = "request";
15    /// A one-time code from an authenticator app, with the account it belongs to, as a
16    /// second step of a sign-in.
17    pub const OTP: &str = "otp";
18    /// A passkey's signed answer to a challenge the same provider issued
19    /// ([`Challenger`](crate::Challenger)), presented with [`Attempt::challenge`](crate::Attempt::challenge).
20    pub const PASSKEY: &str = "passkey";
21}
22
23/// Why a sign-in policy is asked, as [`SignInContext::purpose`] says.
24pub mod purposes {
25    /// A person is signing in.
26    pub const SIGN_IN: &str = "sign_in";
27    /// A session that exists is checked again; `done` holds the steps it was opened with.
28    pub const RESUME: &str = "resume";
29    /// A person sets up or changes a second step of their own.
30    pub const ENROL: &str = "enrol";
31    /// A sign-in that has passed some steps asks to set up a second step it is waiting for, before any session exists.
32    /// Whoever holds those steps may reach it, so a policy allows it only by a rule that names it.
33    pub const ENROL_FIRST: &str = "enrol_first";
34}
35
36/// What kind of client signs in, as [`SignInContext::client`] says.
37pub mod clients {
38    /// A web page.
39    pub const BROWSER: &str = "browser";
40    /// A desktop or mobile application.
41    pub const APP: &str = "app";
42    /// A program using the interface directly.
43    pub const API: &str = "api";
44}
45
46/// The names a consumer gives in [`SignInContext::attributes`] that a policy reads.
47pub mod attributes {
48    /// A boolean: the consumer established [`SignInContext::client`](crate::SignInContext::client) itself, from the
49    /// endpoint or listener the request arrived on, and not from anything the client says.
50    /// Without it a policy treats the client kind as a claim that can only add steps.
51    pub const CLIENT_VERIFIED: &str = "client_verified";
52}
53
54/// What an authenticator or a directory says it is.
55#[derive(Debug, Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
56#[map(crate = ::guatiao)]
57pub struct Description {
58    /// A name to show; a host falls back to the provider's own name when absent.
59    pub name: Option<String>,
60    /// What an authenticator is shown: one of [`takes`](crate::takes).
61    pub takes: Option<String>,
62}
63
64/// Credentials and request facts presented to an authenticator.
65///
66/// Secret material and request metadata are omitted from `Debug` output.
67#[derive(Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
68#[map(crate = ::guatiao)]
69pub struct Attempt {
70    /// Account name supplied by the user, when the method has one.
71    pub name: Option<String>,
72    /// Password or bearer key supplied for this attempt.
73    pub secret: Option<String>,
74    /// Request header `(name, value)` pairs in the order received. A header sent twice
75    /// appears twice; names are matched case-insensitively.
76    pub headers: Vec<(String, String)>,
77    /// Remote peer address when available.
78    pub peer: Option<String>,
79    /// Whether the request arrived over a protected transport.
80    pub secure: Option<bool>,
81    /// Identity of a client certificate whose key was verified by the transport.
82    pub certificate: Option<String>,
83    /// The client's certificates as DER, leaf first, then the intermediates it sent, when the
84    /// transport proved the leaf's key. A provider that decides trust or reads names from the
85    /// certificate takes them from here.
86    pub certificates: Option<Vec<guatiao::Bytes>>,
87    /// The [`methods`](crate::methods) word the consumer presents this credential as, so a
88    /// provider serving two methods (a one-time code and a recovery code) tells them apart.
89    /// `None` is the provider's own default method.
90    pub method: Option<String>,
91    /// The challenge a [`Challenger`](crate::Challenger) issued for this sign-in, as it answered
92    /// it (`Challenge::challenge`), which the consumer keeps with the pending sign-in and returns
93    /// with the answer. `Debug` shows only that there is one.
94    pub challenge: Option<String>,
95}
96
97impl fmt::Debug for Attempt {
98    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
99        formatter
100            .debug_struct("Attempt")
101            .field("name", &self.name.as_ref().map(|_| "…"))
102            .field("secret", &self.secret.as_ref().map(|_| "…"))
103            .field("headers", &self.headers.len())
104            .field("peer", &self.peer.as_ref().map(|_| "…"))
105            .field("secure", &self.secure)
106            .field("certificate", &self.certificate.as_ref().map(|_| "…"))
107            .field("certificates", &self.certificates.as_ref().map(Vec::len))
108            .field("method", &self.method)
109            .field("challenge", &self.challenge.as_ref().map(|_| "…"))
110            .finish()
111    }
112}
113
114/// What a consumer asks a [`Challenger`](crate::Challenger) for.
115///
116/// `Debug` shows the method only.
117#[derive(Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
118#[map(crate = ::guatiao)]
119pub struct ChallengeRequest {
120    /// The [`methods`](crate::methods) word the challenge is for; `None` is the provider's own.
121    pub method: Option<String>,
122    /// The account an earlier step named, when one did; `None` asks for any of the provider's
123    /// accounts (a usernameless sign-in).
124    pub name: Option<String>,
125    /// The remote peer's address, so a provider can bound the challenges one source holds.
126    pub peer: Option<String>,
127}
128
129impl fmt::Debug for ChallengeRequest {
130    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
131        formatter
132            .debug_struct("ChallengeRequest")
133            .field("method", &self.method)
134            .finish_non_exhaustive()
135    }
136}
137
138/// What a [`Challenger`](crate::Challenger) made for one sign-in: a challenge the signed answer
139/// is bound to, and the text the client needs to answer it.
140///
141/// `Debug` shows the expiry only.
142#[derive(Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
143#[map(crate = ::guatiao)]
144pub struct Challenge {
145    /// The key the consumer keeps with the pending sign-in and returns in
146    /// [`Attempt::challenge`] (base64url for a passkey).
147    pub challenge: String,
148    /// The text the client needs, in the method's own wire format: for a passkey the JSON for
149    /// `navigator.credentials.get`. The consumer passes it on unread.
150    pub options: String,
151    /// When it stops being taken, in seconds since the Unix epoch.
152    pub expires_unix: i64,
153}
154
155impl fmt::Debug for Challenge {
156    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
157        formatter
158            .debug_struct("Challenge")
159            .field("expires_unix", &self.expires_unix)
160            .finish_non_exhaustive()
161    }
162}
163
164/// One credential of an account that holds several (a passkey), without anything that proves
165/// it.
166///
167/// `Debug` hides the id and the label.
168#[derive(Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
169#[map(crate = ::guatiao)]
170pub struct CredentialInfo {
171    /// The credential's id, as the provider names it for `remove:<id>` and `label:<id>`.
172    pub id: String,
173    /// What the person calls it.
174    pub label: Option<String>,
175    /// When it was made, in seconds since the Unix epoch.
176    pub made_unix: Option<i64>,
177    /// When it last signed in, in seconds since the Unix epoch.
178    pub used_unix: Option<i64>,
179    /// Whether it is a passkey the platform syncs between devices.
180    pub synced: Option<bool>,
181    /// Whether it is refused for now.
182    pub disabled: Option<bool>,
183}
184
185impl fmt::Debug for CredentialInfo {
186    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
187        formatter
188            .debug_struct("CredentialInfo")
189            .field("synced", &self.synced)
190            .field("disabled", &self.disabled)
191            .finish_non_exhaustive()
192    }
193}
194
195/// The identity an authenticator obtained, in full, for a matcher to tie to a directory
196/// account. A claim is what the credential says, not who the person is: the directory
197/// decides the account and its groups.
198///
199/// The names an authenticator that reads a certificate uses: `subject.dn`, `subject.cn` (and
200/// the other `subject.<attribute>`), `issuer.dn`, `serial.hex`, `serial.reversed` (the same
201/// bytes last first), `san.upn`, `san.email`, `san.dns`, `san.uri`, `san.ip`, `fingerprint`
202/// and `spki` (both `sha256:<hex>`), and the leaf in [`certificate`](Claims::certificate).
203/// A name an authenticator has nothing for is absent. `Debug` shows counts only.
204#[derive(Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
205#[map(crate = ::guatiao)]
206pub struct Claims {
207    /// Each claim and its values, in the order the credential gave them.
208    #[map(default, skip_serializing_if = BTreeMap::is_empty)]
209    pub values: BTreeMap<String, Vec<String>>,
210    /// The credential itself, when it has a form of its own: the leaf certificate as DER.
211    pub certificate: Option<guatiao::Bytes>,
212}
213
214impl Claims {
215    /// The values of `name`; empty when the credential did not give it.
216    pub fn get(&self, name: &str) -> &[String] {
217        self.values.get(name).map_or(&[], Vec::as_slice)
218    }
219}
220
221impl fmt::Debug for Claims {
222    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
223        formatter
224            .debug_struct("Claims")
225            .field("values", &self.values.len())
226            .field("certificate", &self.certificate.as_ref().map(|_| "…"))
227            .finish()
228    }
229}
230
231/// An identity lookup key returned after an authenticator accepts credentials.
232#[derive(Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
233#[map(crate = ::guatiao)]
234pub struct Lookup {
235    /// Directory attribute to match, such as `id`, `name` or `email`; `claims` when the
236    /// authenticator names no account itself and the consumer's matcher decides from
237    /// [`claims`](Lookup::claims).
238    pub by: String,
239    /// Value to resolve in a configured directory; a label for a log when `by` is `claims`.
240    pub value: String,
241    /// What the credential said, in full, when the authenticator has more than a name.
242    pub claims: Option<Claims>,
243}
244
245impl fmt::Debug for Lookup {
246    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
247        formatter
248            .debug_struct("Lookup")
249            .field("by", &self.by)
250            .field("value", &"…")
251            .field("claims", &self.claims)
252            .finish()
253    }
254}
255
256/// Result of checking one credential attempt.
257#[derive(Debug, Clone, PartialEq, Eq, ToValue, FromValue, Schema)]
258#[map(crate = ::guatiao, tag = "kind", rename_all = "snake_case")]
259pub enum Verdict {
260    /// This authenticator does not handle the presented method or identity.
261    Unknown,
262    /// This authenticator recognized the identity but rejected the credentials.
263    Invalid,
264    /// The credentials are valid; resolve this reference through a directory.
265    Valid(Lookup),
266}
267
268/// A person record returned only by an authoritative directory.
269#[derive(Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
270#[map(crate = ::guatiao)]
271pub struct Person {
272    /// Stable directory identity.
273    pub id: String,
274    /// Canonical account name.
275    pub name: String,
276    /// Human-readable name, when the directory has one.
277    pub display_name: Option<String>,
278    /// Email address, when the directory has one.
279    pub email: Option<String>,
280    /// Directory groups used by authorization policy.
281    pub groups: Vec<String>,
282    /// Additional directory-owned attributes.
283    pub attributes: BTreeMap<String, Value>,
284}
285
286impl fmt::Debug for Person {
287    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
288        formatter
289            .debug_struct("Person")
290            .field("id", &"…")
291            .field("name", &"…")
292            .field("display_name", &self.display_name.as_ref().map(|_| "…"))
293            .field("email", &self.email.as_ref().map(|_| "…"))
294            .field("groups", &self.groups.len())
295            .field("attributes", &self.attributes.len())
296            .finish()
297    }
298}
299
300/// A resource-scoped authorization request.
301#[derive(Debug, Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
302#[map(crate = ::guatiao)]
303pub struct AuthorizationRequest {
304    /// Person returned by the authoritative directory.
305    pub person: Person,
306    /// Requested operation, such as `document.read`.
307    pub action: String,
308    /// Resource identifier in the host's own scheme, such as `site:north`, or `*` for the
309    /// whole service.
310    pub resource: String,
311    /// The resources `resource` sits under in the host's own hierarchy, nearest first, such
312    /// as `["site:europe", "site:world"]` for `site:north`; empty when it has none. An
313    /// authorizer may let a grant on one of them reach `resource`.
314    #[map(default, skip_serializing_if = Vec::is_empty)]
315    pub ancestors: Vec<String>,
316}
317
318/// Authorization result and provider-defined limits for the granted action.
319#[derive(Debug, Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
320#[map(crate = ::guatiao)]
321pub struct AuthorizationDecision {
322    /// Whether policy permits the requested action.
323    pub allowed: bool,
324    /// Limits such as lease duration or maximum concurrent sessions.
325    pub limits: BTreeMap<String, Value>,
326}
327
328/// An account as a provider that keeps its own lists it; never with what proves it.
329#[derive(Debug, Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
330#[map(crate = ::guatiao)]
331pub struct AccountInfo {
332    /// Stable identity, the [`Person::id`] a directory returns for it.
333    pub id: String,
334    /// Canonical account name.
335    pub name: String,
336    /// Groups the account is in.
337    pub groups: Vec<String>,
338    /// Whether it is refused for now.
339    pub disabled: Option<bool>,
340    /// When it was made, in seconds since the Unix epoch, where the provider keeps it.
341    pub made_unix: Option<i64>,
342    /// When it stops being taken, in seconds since the Unix epoch, where the provider
343    /// keeps one.
344    pub expires_unix: Option<i64>,
345    /// Whether an administrator reset the account (its factor was taken away and only an
346    /// administrator sets it up again), where the provider keeps that. Absent when the
347    /// provider keeps no such mark.
348    pub reset: Option<bool>,
349    /// When an administrator last cleared the account's failure counts, in seconds since the
350    /// Unix epoch, where the provider keeps it.
351    pub unlocked_unix: Option<i64>,
352    /// The credentials of an account that holds several (passkeys); `None` for a provider whose
353    /// accounts hold one.
354    pub credentials: Option<Vec<CredentialInfo>>,
355}
356
357/// An account to make, or what to change of one there is. A field not said is left as it
358/// is.
359#[derive(Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
360#[map(crate = ::guatiao)]
361pub struct AccountPut {
362    /// The account's canonical name; it selects the account to change.
363    pub name: String,
364    /// What proves the account from now on: a password, or a peer certificate's
365    /// fingerprint. A provider that makes secrets itself takes none and answers with the
366    /// one it made.
367    pub secret: Option<String>,
368    /// Groups, replacing the ones there are.
369    pub groups: Option<Vec<String>>,
370    /// Whether the account is refused.
371    pub disabled: Option<bool>,
372    /// When it stops being taken, in seconds since the Unix epoch.
373    pub expires_unix: Option<i64>,
374    /// The label an enrolment shows the person (an authenticator app's account line); the
375    /// account's name when absent. Providers that keep no such label ignore it.
376    pub display_name: Option<String>,
377    /// The caller has checked the account's current secret in this request (a code from it, or
378    /// a sign-in that just used it). A provider that lets a put replace a secret the person
379    /// holds refuses the replacement without it; one that does not ignores it. Absent is false.
380    #[map(default, skip_serializing_if = is_false)]
381    pub proved_current: bool,
382    /// An administrator's reset: the provider takes the account's factor away and keeps a mark
383    /// ([`AccountInfo::reset`]) until a new one is confirmed. A provider that keeps no such
384    /// mark refuses it as unsupported. Absent is false.
385    #[map(default, skip_serializing_if = is_false)]
386    pub reset: bool,
387    /// An administrator's unlock: the provider clears the account's failure count and any
388    /// delay and notes when ([`AccountInfo::unlocked_unix`]). A provider that counts no
389    /// failures refuses it as unsupported. Absent is false.
390    #[map(default, skip_serializing_if = is_false)]
391    pub unlock: bool,
392}
393
394fn is_false(value: &bool) -> bool {
395    !*value
396}
397
398impl fmt::Debug for AccountPut {
399    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
400        formatter
401            .debug_struct("AccountPut")
402            .field("name", &self.name)
403            .field("secret", &self.secret.as_ref().map(|_| "…"))
404            .field("groups", &self.groups)
405            .field("disabled", &self.disabled)
406            .field("expires_unix", &self.expires_unix)
407            .field("display_name", &self.display_name.as_ref().map(|_| "…"))
408            .field("proved_current", &self.proved_current)
409            .field("reset", &self.reset)
410            .field("unlock", &self.unlock)
411            .finish()
412    }
413}
414
415/// What came of putting an account.
416#[derive(Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
417#[map(crate = ::guatiao)]
418pub struct PutOutcome {
419    /// The secret the provider made for the account, said this once and kept nowhere as
420    /// itself.
421    pub secret: Option<String>,
422    /// One-time recovery codes the provider made for the account, said this once and kept
423    /// nowhere as themselves.
424    pub codes: Option<Vec<String>>,
425}
426
427impl fmt::Debug for PutOutcome {
428    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
429        formatter
430            .debug_struct("PutOutcome")
431            .field("secret", &self.secret.as_ref().map(|_| "…"))
432            .field("codes", &self.codes.as_ref().map(Vec::len))
433            .finish()
434    }
435}
436
437/// Something an authenticator was shown and did not know, kept so that whoever runs the
438/// service can accept it as an account.
439#[derive(Debug, Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
440#[map(crate = ::guatiao)]
441pub struct Waiting {
442    /// What it showed, as it is given to [`AccountPut::secret`] to accept it: a
443    /// certificate fingerprint.
444    pub shown: String,
445    /// The address it came from.
446    pub peer: Option<String>,
447    /// When it last did, in seconds since the Unix epoch.
448    pub seen_unix: Option<i64>,
449}
450
451/// One step of a sign-in that already succeeded.
452///
453/// `Debug` shows the method and provider, never who the step named.
454#[derive(Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
455#[map(crate = ::guatiao)]
456pub struct Factor {
457    /// The [`methods`](crate::methods) word it was presented as.
458    pub method: String,
459    /// The provider that accepted it, by the id the consumer asks it under. A rule that
460    /// names `providers` counts only a factor a listed provider accepted.
461    pub provider: Option<String>,
462    /// The [`Person::id`] the step named. A policy refuses a sign-in whose steps name
463    /// different people; a step that names none (`None`) is not held against it.
464    pub person: Option<String>,
465}
466
467impl fmt::Debug for Factor {
468    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
469        formatter
470            .debug_struct("Factor")
471            .field("method", &self.method)
472            .field("provider", &self.provider)
473            .field("person", &self.person.as_ref().map(|_| "…"))
474            .finish()
475    }
476}
477
478/// What a consumer knows when it asks which methods a sign-in may use, and what is still
479/// needed.
480///
481/// `Debug` shows words and counts, never the address or the person.
482#[derive(Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
483#[map(crate = ::guatiao)]
484pub struct SignInContext {
485    /// Why it is asked: one of [`purposes`](crate::purposes).
486    pub purpose: String,
487    /// The steps already passed; empty when the sign-in has not begun.
488    pub done: Vec<Factor>,
489    /// The client's IP address as the consumer determined it, text without a port; `None`
490    /// when it could not be determined, and never a placeholder such as `0.0.0.0`.
491    pub address: Option<String>,
492    /// What kind of client: one of [`clients`](crate::clients), or the consumer's own word.
493    pub client: Option<String>,
494    /// The consumer's own word for the service signed in to, such as `portal`.
495    pub service: Option<String>,
496    /// When it is asked, in seconds since the Unix epoch.
497    pub time_unix: Option<i64>,
498    /// Who the passed steps named, once one did. `None` before that.
499    pub person: Option<Person>,
500    /// Anything else the consumer says about the sign-in; a policy reads what it knows.
501    #[map(default, skip_serializing_if = BTreeMap::is_empty)]
502    pub attributes: BTreeMap<String, Value>,
503}
504
505impl SignInContext {
506    /// Says the [`client`](SignInContext::client) is one the consumer established itself (see
507    /// [`attributes::CLIENT_VERIFIED`]); call it only when that is so.
508    #[must_use]
509    pub fn with_verified_client(mut self) -> Self {
510        self.attributes
511            .insert(attributes::CLIENT_VERIFIED.to_owned(), Value::from(true));
512        self
513    }
514
515    /// Whether the consumer said the client is verified; a missing or non-boolean attribute is
516    /// not.
517    #[must_use]
518    pub fn client_is_verified(&self) -> bool {
519        self.attributes
520            .get(attributes::CLIENT_VERIFIED)
521            .is_some_and(|value| bool::try_from(value).unwrap_or(false))
522    }
523}
524
525impl fmt::Debug for SignInContext {
526    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
527        formatter
528            .debug_struct("SignInContext")
529            .field("purpose", &self.purpose)
530            .field("done", &self.done.len())
531            .field("address", &self.address.as_ref().map(|_| "…"))
532            .field("client", &self.client)
533            .field("service", &self.service)
534            .field("time_unix", &self.time_unix.map(|_| "…"))
535            .field("person", &self.person.as_ref().map(|_| "…"))
536            .field("attributes", &self.attributes.len())
537            .finish()
538    }
539}
540
541/// A method a sign-in may use next.
542#[derive(Debug, Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
543#[map(crate = ::guatiao)]
544pub struct Offer {
545    /// The [`methods`](crate::methods) word.
546    pub method: String,
547    /// The providers to ask, in order; empty is any provider that takes the method.
548    #[map(default, skip_serializing_if = Vec::is_empty)]
549    pub providers: Vec<String>,
550}
551
552/// What a sign-in may do next.
553#[derive(Debug, Clone, Default, PartialEq, Eq, ToValue, FromValue, Schema)]
554#[map(crate = ::guatiao)]
555pub struct SignInDecision {
556    /// Whether the steps passed are enough to open the session.
557    pub complete: bool,
558    /// The methods that may be presented next, empty when none may: with
559    /// [`complete`](SignInDecision::complete) false that is a refusal.
560    pub methods: Vec<Offer>,
561    /// The rule that decided, by name or position, for a log.
562    pub rule: Option<String>,
563    /// Limits for the session, such as a lifetime; provider-defined.
564    #[map(default, skip_serializing_if = BTreeMap::is_empty)]
565    pub limits: BTreeMap<String, Value>,
566}