Skip to main content

universal_exports/
second_factor.rs

1//! The steps of a sign-in after its first, and the setting up of a second factor.
2//!
3//! A sign-in whose policy decision offers more steps is kept in the Registry as a *pending*
4//! sign-in, by the digest of the value its person holds, so any gateway sharing the Registry
5//! continues it. Every try at its next step is counted twice: against the account in the login
6//! guard and against the pending sign-in's own cap. Enrolling a factor is decided under the
7//! sign-in policy (`enrol`, or `enrol_first` before any session exists), audited before it is
8//! stored, and never audits or logs a code, a recovery code or a provisioning link.
9
10use std::net::SocketAddr;
11use std::sync::Arc;
12
13use ai6::directorates::m::access::{
14    Person, SignInContext, SignInDecision, methods as method_words, purposes,
15};
16use ai6::guatiao::Status;
17use ai6::wire::login::{FactorBegun, FactorCode, FactorConfirmed, FactorState, SignInStep};
18use ai6::{
19    AccountPut, Accounts, Attempt, CONFIG_ACCOUNTS, Lookup, ProviderConfig, RegistryBackend,
20    SignInFactor, Verdict,
21};
22use axum::extract::{ConnectInfo, Path, State};
23use axum::http::header::{CACHE_CONTROL, ORIGIN};
24use axum::http::{HeaderMap, HeaderValue, StatusCode};
25use axum::response::{IntoResponse, Response};
26use axum::{Extension, Json};
27use coqui_access_totp::{Algorithm, Lockout, TotpAccounts, TotpBuilder};
28use serde::{Deserialize, Serialize};
29
30use ai6::directorates::registry::factors::FactorChange;
31
32use crate::access_admin::{AdminError, audit};
33use crate::factor_seal::FactorSealer;
34use crate::{
35    AccessProviders, ApiError, Gateway, LoginRequest, Signer, access_token_digest, bearer,
36    complete_login, new_secret, require_login_origin, require_origin, resolve_user, sign_in,
37    unix_timestamp,
38};
39
40/// The ID the one-time code provider is listed under in `authenticators` and in a policy.
41pub const TOTP: &str = "coqui_access_totp";
42
43/// The header a page names a pending sign-in in when it asks what comes next.
44pub(crate) const PENDING_HEADER: &str = "x-ai6-pending";
45
46const PENDING: &str = "pending";
47
48/// A sign-in that has passed some steps and waits for the next, as the Registry keeps it.
49#[derive(Serialize, Deserialize)]
50#[serde(deny_unknown_fields)]
51struct Pending {
52    /// The ID of the person its steps named.
53    person: String,
54    factors: Vec<SignInFactor>,
55    /// Unix seconds.
56    expires: f64,
57    /// Tries made at its next step.
58    tries: u32,
59    /// Whether a browser began it: only a browser continues it.
60    browser: bool,
61    ttl_seconds: Option<u64>,
62    session_cookie: Option<bool>,
63}
64
65fn read_pending(text: &str, now: f64) -> Option<Pending> {
66    serde_json::from_str::<Pending>(text)
67        .ok()
68        .filter(|pending| pending.expires > now)
69}
70
71/// What a try at a pending sign-in's next step finds.
72enum Tried {
73    /// There is no such sign-in, or its time is up.
74    Gone,
75    /// Its tries are used up; it has ended.
76    Spent,
77    /// The sign-in, with this try counted.
78    Held,
79}
80
81async fn blocking<T: Send + 'static>(
82    work: impl FnOnce() -> std::io::Result<T> + Send + 'static,
83) -> Result<T, ApiError> {
84    tokio::task::spawn_blocking(work)
85        .await
86        .map_err(|_| ApiError::internal())?
87        .map_err(|_| ApiError::unavailable())
88}
89
90fn registry(gateway: &Gateway) -> Result<Arc<dyn RegistryBackend>, ApiError> {
91    gateway.registry.clone().ok_or_else(ApiError::unavailable)
92}
93
94async fn begin_pending(
95    registry: Arc<dyn RegistryBackend>,
96    pending: Pending,
97    sweep: bool,
98) -> Result<String, ApiError> {
99    let token = new_secret();
100    let key = access_token_digest(&token);
101    let text = serde_json::to_string(&pending).map_err(|_| ApiError::internal())?;
102    let now = unix_timestamp()?;
103    blocking(move || {
104        if sweep {
105            registry.factor_retain(PENDING, &mut |_, text| read_pending(text, now).is_some())?;
106        }
107        registry.factor_update(PENDING, &key, &mut |_| Ok(FactorChange::Put(text.clone())))
108    })
109    .await?;
110    Ok(token)
111}
112
113async fn find_pending(
114    registry: Arc<dyn RegistryBackend>,
115    key: String,
116    now: f64,
117) -> Result<Option<Pending>, ApiError> {
118    // A read writes nothing, so a request that names no sign-in costs the shared store nothing.
119    blocking(move || {
120        Ok(registry
121            .factor_get(PENDING, &key)?
122            .and_then(|text| read_pending(&text, now)))
123    })
124    .await
125}
126
127async fn count_try(
128    registry: Arc<dyn RegistryBackend>,
129    key: String,
130    cap: u32,
131    now: f64,
132) -> Result<Tried, ApiError> {
133    blocking(move || {
134        let mut tried = Tried::Gone;
135        registry.factor_update(PENDING, &key, &mut |held| {
136            let Some(mut pending) = held.and_then(|text| read_pending(text, now)) else {
137                tried = Tried::Gone;
138                return Ok(if held.is_some() {
139                    FactorChange::Remove
140                } else {
141                    FactorChange::Keep
142                });
143            };
144            if pending.tries >= cap {
145                tried = Tried::Spent;
146                return Ok(FactorChange::Remove);
147            }
148            pending.tries += 1;
149            let text = serde_json::to_string(&pending).map_err(std::io::Error::other)?;
150            tried = Tried::Held;
151            Ok(FactorChange::Put(text))
152        })?;
153        Ok(tried)
154    })
155    .await
156}
157
158async fn advance_pending(
159    registry: Arc<dyn RegistryBackend>,
160    key: String,
161    factors: Vec<SignInFactor>,
162    now: f64,
163) -> Result<(), ApiError> {
164    blocking(move || {
165        registry.factor_update(PENDING, &key, &mut |held| {
166            let Some(mut pending) = held.and_then(|text| read_pending(text, now)) else {
167                return Ok(FactorChange::Keep);
168            };
169            pending.factors = factors.clone();
170            Ok(FactorChange::Put(
171                serde_json::to_string(&pending).map_err(std::io::Error::other)?,
172            ))
173        })
174    })
175    .await
176}
177
178/// Takes the pending sign-in, so that exactly one request completes it.
179async fn take_pending(
180    registry: Arc<dyn RegistryBackend>,
181    key: String,
182    now: f64,
183) -> Result<Option<Pending>, ApiError> {
184    blocking(move || {
185        let mut taken = None;
186        registry.factor_update(PENDING, &key, &mut |held| {
187            taken = held.and_then(|text| read_pending(text, now));
188            Ok(if held.is_some() {
189                FactorChange::Remove
190            } else {
191                FactorChange::Keep
192            })
193        })?;
194        Ok(taken)
195    })
196    .await
197}
198
199async fn end_pending(registry: Arc<dyn RegistryBackend>, key: String) {
200    let _ =
201        blocking(move || registry.factor_update(PENDING, &key, &mut |_| Ok(FactorChange::Remove)))
202            .await;
203}
204
205/// The method words of `decision`, once each.
206fn method_names(decision: &SignInDecision) -> Vec<String> {
207    let mut names: Vec<String> = Vec::new();
208    for offer in &decision.methods {
209        if !names.contains(&offer.method) {
210            names.push(offer.method.clone());
211        }
212    }
213    names
214}
215
216/// The `202` answer of a sign-in that waits for its next step.
217fn next_step(token: &str, methods: Vec<String>, seconds: f64) -> Response {
218    let mut response = (
219        StatusCode::ACCEPTED,
220        Json(SignInStep {
221            pending: token.to_owned(),
222            methods,
223            expires_in: seconds,
224        }),
225    )
226        .into_response();
227    response
228        .headers_mut()
229        .insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
230    response
231}
232
233impl Gateway {
234    /// Whether this request is one of the sweeps that drop pending sign-ins gone stale.
235    fn sweeps_now(&self) -> bool {
236        let every = u64::from(self.config.login.forget_every.max(1));
237        self.pending_begun
238            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
239            .is_multiple_of(every)
240    }
241
242    /// Keeps a sign-in that `factors` took as far as they did, to wait for its next step, and
243    /// answers `202`.
244    pub(crate) async fn wait_for_next_step(
245        &self,
246        person: &Person,
247        factors: Vec<SignInFactor>,
248        methods: Vec<String>,
249        from_browser: bool,
250        request: &LoginRequest,
251    ) -> Result<Response, ApiError> {
252        let seconds = self.config.login.pending_seconds;
253        let pending = Pending {
254            person: person.id.clone(),
255            factors,
256            expires: unix_timestamp()? + seconds.as_secs_f64(),
257            tries: 0,
258            browser: from_browser,
259            ttl_seconds: request.ttl_seconds,
260            session_cookie: request.session_cookie,
261        };
262        let token = begin_pending(registry(self)?, pending, self.sweeps_now()).await?;
263        Ok(next_step(&token, methods, seconds.as_secs_f64()))
264    }
265}
266
267/// The person with ID `id`, as the directory has them now.
268async fn person_by_id(providers: &AccessProviders, id: String) -> Result<Option<Person>, ApiError> {
269    let directory = providers.directory.clone();
270    tokio::task::spawn_blocking(move || {
271        directory.lookup(Lookup {
272            by: "id".to_owned(),
273            value: id,
274            ..Default::default()
275        })
276    })
277    .await
278    .map_err(|_| ApiError::internal())?
279    .map_err(|_| ApiError::internal())
280}
281
282fn address_of(connection: Option<Extension<ConnectInfo<SocketAddr>>>) -> Option<SocketAddr> {
283    connection.map(|Extension(ConnectInfo(address))| address)
284}
285
286/// What a page that holds a pending sign-in is offered next: the methods, or `None` when the
287/// sign-in is gone.
288pub(crate) async fn offer_next(
289    gateway: &Gateway,
290    providers: &AccessProviders,
291    headers: &HeaderMap,
292    address: Option<SocketAddr>,
293    token: &str,
294) -> Result<Vec<String>, ApiError> {
295    // Counted against the address before the Registry is read, whether or not the sign-in is
296    // there: a client that names sign-ins at random is held off.
297    let source = gateway.login_guard().source(headers, address);
298    if let Some(wait) = gateway.login_guard().tried_address(source) {
299        return Err(ApiError::too_many_attempts(wait));
300    }
301    let now = unix_timestamp()?;
302    let pending = find_pending(registry(gateway)?, access_token_digest(token), now)
303        .await?
304        .ok_or_else(ApiError::unauthorized)?;
305    let person = person_by_id(providers, pending.person.clone())
306        .await?
307        .ok_or_else(ApiError::unauthorized)?;
308    let context = SignInContext {
309        done: Gateway::passed(&pending.factors),
310        person: Some(person),
311        ..gateway.sign_in_context(purposes::SIGN_IN, headers, address, sign_in::SERVICE)
312    };
313    gateway
314        .decide_sign_in(providers, context)
315        .await
316        .map(|decision| method_names(&decision))
317        .ok_or_else(ApiError::unauthorized)
318}
319
320/// The second-factor providers a method is asked of: those the offer lists, else every one.
321fn asked(providers: &AccessProviders, offered: &[String]) -> Vec<Signer> {
322    if offered.is_empty() {
323        return providers.second.clone();
324    }
325    offered
326        .iter()
327        .filter_map(|id| {
328            providers
329                .second
330                .iter()
331                .find(|signer| signer.id.as_deref() == Some(id))
332                .cloned()
333        })
334        .collect()
335}
336
337/// `POST /v1/auth/login` with a `method` that checks a code, or with a `pending` sign-in:
338/// the next step of a sign-in.
339pub(crate) async fn continue_login(
340    gateway: &Gateway,
341    connection: Option<SocketAddr>,
342    certificates: Option<Vec<Vec<u8>>>,
343    headers: &HeaderMap,
344    request: LoginRequest,
345) -> Result<Response, ApiError> {
346    let from_browser = headers.contains_key(ORIGIN);
347    if from_browser {
348        require_login_origin(gateway, headers)?;
349    }
350    let providers = gateway.access.clone().ok_or_else(ApiError::unavailable)?;
351    let method = request.method.clone().ok_or_else(ApiError::bad_request)?;
352    let context = gateway.sign_in_context(purposes::SIGN_IN, headers, connection, sign_in::SERVICE);
353    let registry = registry(gateway)?;
354    let now = unix_timestamp()?;
355    let Some(token) = request.pending.as_deref() else {
356        // Nothing is pending, so nothing an account's code could follow is offered.
357        let offered = gateway
358            .decide_sign_in(&providers, context)
359            .await
360            .is_some_and(|decision| decision.methods.iter().any(|offer| offer.method == method));
361        return Err(if offered {
362            ApiError::unauthorized()
363        } else {
364            sign_in::not_accepted()
365        });
366    };
367    // Counted against the address before the Registry is read, whether or not the sign-in is
368    // there, so a client naming sign-ins at random is held off and costs the store nothing.
369    let source = gateway.login_guard().source(headers, connection);
370    if let Some(wait) = gateway.login_guard().tried_address(source) {
371        return Err(ApiError::too_many_attempts(wait));
372    }
373    let key = access_token_digest(token);
374    let Some(pending) = find_pending(registry.clone(), key.clone(), now).await? else {
375        return Err(ApiError::unauthorized());
376    };
377    if pending.browser != from_browser {
378        return Err(ApiError::unauthorized());
379    }
380    let Some(person) = person_by_id(&providers, pending.person.clone()).await? else {
381        end_pending(registry, key).await;
382        return Err(ApiError::unauthorized());
383    };
384    let context = SignInContext {
385        done: Gateway::passed(&pending.factors),
386        person: Some(person.clone()),
387        ..context
388    };
389    let offer = gateway
390        .decide_sign_in(&providers, context.clone())
391        .await
392        .and_then(|decision| {
393            decision
394                .methods
395                .into_iter()
396                .find(|offer| offer.method == method)
397        })
398        .ok_or_else(sign_in::not_accepted)?;
399    // Counted before anything is asked, under the account, whatever the address: a refusal is
400    // not judged, and the right code along with the wrong ones.
401    let by_password = method == "password";
402    if !by_password && let Some(wait) = gateway.login_guard().tried_name(&person.id) {
403        return Err(ApiError::too_many_attempts(wait));
404    }
405    match count_try(
406        registry.clone(),
407        key.clone(),
408        gateway.config.login.pending_tries,
409        now,
410    )
411    .await?
412    {
413        Tried::Gone | Tried::Spent => return Err(ApiError::unauthorized()),
414        Tried::Held => {}
415    }
416    if !request.name.is_empty() && !by_password && request.name != person.id {
417        // A code is only ever checked for the person the sign-in named.
418        return Err(ApiError::unauthorized());
419    }
420    let step = match method.as_str() {
421        method_words::TOTP | method_words::RECOVERY_CODE => {
422            second_factor_step(
423                &providers,
424                &person,
425                &method,
426                &offer.providers,
427                request.secret.clone(),
428                source,
429            )
430            .await?
431        }
432        // A certificate the gateway's own TLS proved is named by the page authenticator.
433        "certificate" if certificates.as_ref().is_some_and(|chain| !chain.is_empty()) => {
434            certificate_step(
435                &providers,
436                &person,
437                certificates.unwrap_or_default(),
438                source,
439            )
440            .await?
441        }
442        // `certificate` is only a chain the gateway's own TLS proved; a header never makes one.
443        "certificate" => return Err(ApiError::unauthorized()),
444        "proxy" => {
445            let named = crate::proxy_person(gateway, &providers, headers)
446                .await?
447                .ok_or_else(ApiError::unauthorized)?;
448            if named.id != person.id {
449                return Err(ApiError::unauthorized());
450            }
451            sign_in::step(&method, None, &named)?
452        }
453        "password" => {
454            let (named, provider) = crate::authenticate_password(
455                gateway,
456                &providers,
457                headers,
458                connection,
459                request.clone(),
460                &offer.providers,
461            )
462            .await?;
463            if named.id != person.id {
464                return Err(ApiError::unauthorized());
465            }
466            sign_in::step(&method, provider.as_deref(), &named)?
467        }
468        _ => return Err(ApiError::bad_request()),
469    };
470    let mut factors = pending.factors.clone();
471    factors.push(step);
472    let decision = gateway
473        .decide_sign_in(
474            &providers,
475            SignInContext {
476                done: Gateway::passed(&factors),
477                person: Some(person.clone()),
478                ..context
479            },
480        )
481        .await;
482    match decision {
483        Some(decision) if decision.complete => {
484            // One request takes the sign-in; a second finds it gone.
485            let Some(taken) = take_pending(registry, key, unix_timestamp()?).await? else {
486                return Err(ApiError::unauthorized());
487            };
488            let wants_cookie = from_browser && taken.session_cookie != Some(false);
489            let ttl = crate::sign_in_ttl(
490                &gateway.config.unex().gateway,
491                crate::access_token_ttl(gateway, taken.ttl_seconds)?,
492            );
493            complete_login(gateway, from_browser, wants_cookie, ttl, person, factors).await
494        }
495        Some(decision) if !decision.methods.is_empty() => {
496            advance_pending(registry, key, factors, now).await?;
497            let left = pending.expires - now;
498            Ok(next_step(token, method_names(&decision), left))
499        }
500        _ => {
501            end_pending(registry, key).await;
502            Err(ApiError::unauthorized())
503        }
504    }
505}
506
507/// The step a certificate the gateway's own TLS proved makes, when the page authenticator names
508/// `person` by it.
509async fn certificate_step(
510    providers: &AccessProviders,
511    person: &Person,
512    chain: Vec<Vec<u8>>,
513    source: std::net::IpAddr,
514) -> Result<SignInFactor, ApiError> {
515    let authenticator = providers
516        .page_authenticator
517        .clone()
518        .ok_or_else(ApiError::unauthorized)?;
519    let attempt = Attempt {
520        peer: Some(source.to_string()),
521        secure: Some(true),
522        certificates: Some(chain.into_iter().map(Into::into).collect()),
523        ..Attempt::default()
524    };
525    let verdict = tokio::task::spawn_blocking(move || authenticator.authenticate(attempt))
526        .await
527        .map_err(|_| ApiError::internal())?
528        .map_err(|_| ApiError::internal())?;
529    let Verdict::Valid(lookup) = verdict else {
530        return Err(ApiError::unauthorized());
531    };
532    let named = tokio::task::spawn_blocking({
533        let directory = providers.directory.clone();
534        move || directory.lookup(lookup)
535    })
536    .await
537    .map_err(|_| ApiError::internal())?
538    .map_err(|_| ApiError::internal())?
539    .ok_or_else(ApiError::unauthorized)?;
540    if named.id != person.id {
541        return Err(ApiError::unauthorized());
542    }
543    sign_in::step(
544        "certificate",
545        providers.page_authenticator_id.as_deref(),
546        &named,
547    )
548}
549
550/// Checks a code of `person`'s by the providers the offer lists.
551async fn second_factor_step(
552    providers: &AccessProviders,
553    person: &Person,
554    method: &str,
555    offered: &[String],
556    secret: String,
557    source: std::net::IpAddr,
558) -> Result<SignInFactor, ApiError> {
559    let asked = asked(providers, offered);
560    let attempt = Attempt {
561        name: Some(person.id.clone()),
562        secret: Some(secret),
563        peer: Some(source.to_string()),
564        secure: Some(true),
565        method: Some(method.to_owned()),
566        ..Attempt::default()
567    };
568    let verdict = tokio::task::spawn_blocking(move || {
569        for signer in asked {
570            match signer.authenticator.authenticate(attempt.clone())? {
571                Verdict::Unknown => {}
572                decided => return Ok((decided, signer.id)),
573            }
574        }
575        Ok((Verdict::Unknown, None))
576    })
577    .await
578    .map_err(|_| ApiError::internal())?
579    .map_err(|_: ai6::guatiao::library::ProviderError| ApiError::internal())?;
580    let (Verdict::Valid(lookup), provider) = verdict else {
581        return Err(ApiError::unauthorized());
582    };
583    // The step must name the same person the sign-in is for.
584    if lookup.by != "id" || lookup.value != person.id {
585        return Err(ApiError::unauthorized());
586    }
587    sign_in::step(method, provider.as_deref(), person)
588}
589
590/// The provider settings of the one-time code provider as the `unex` record gives them: every
591/// key optional, the provider's own default standing for what is left out.
592#[derive(Default, Deserialize)]
593#[serde(deny_unknown_fields)]
594struct TotpSettings {
595    issuer: Option<String>,
596    algorithm: Option<String>,
597    digits: Option<u32>,
598    period: Option<u32>,
599    skew: Option<u32>,
600    recovery_codes: Option<u32>,
601    enrol_seconds: Option<u32>,
602    max_records: Option<usize>,
603    lockout_after: Option<u32>,
604    lockout_seconds: Option<u32>,
605    lockout_longest_seconds: Option<u32>,
606}
607
608/// The one-time code provider over the Registry's tables, configured by `config`, ready to build.
609///
610/// # Errors
611///
612/// Why the configuration is refused.
613pub fn totp_builder(
614    registry: &Arc<dyn RegistryBackend>,
615    config: Option<&ProviderConfig>,
616    sealer: &Arc<FactorSealer>,
617) -> Result<TotpBuilder, String> {
618    let settings: TotpSettings = match config {
619        Some(object) => ai6::guatiao_serde::adapt::from_value(object.value())
620            .map_err(|error| error.to_string())?,
621        None => TotpSettings::default(),
622    };
623    let mut builder = TotpAccounts::builder()
624        .table(crate::totp_store::accounts(registry, sealer))
625        .pending(crate::totp_store::enrolments(registry, sealer));
626    if let Some(issuer) = settings.issuer {
627        builder = builder.issuer(issuer);
628    }
629    if let Some(name) = settings.algorithm {
630        builder = builder.algorithm(match name.as_str() {
631            "sha1" => Algorithm::Sha1,
632            "sha256" => Algorithm::Sha256,
633            "sha512" => Algorithm::Sha512,
634            other => return Err(format!("algorithm {other:?} is not sha1, sha256 or sha512")),
635        });
636    }
637    if let Some(digits) = settings.digits {
638        builder = builder.digits(digits);
639    }
640    if let Some(period) = settings.period {
641        builder = builder.period(period);
642    }
643    if let Some(skew) = settings.skew {
644        builder = builder.skew(skew);
645    }
646    if let Some(count) = settings.recovery_codes {
647        builder = builder.recovery_codes(count);
648    }
649    if let Some(seconds) = settings.enrol_seconds {
650        builder = builder.enrol_seconds(seconds);
651    }
652    if let Some(records) = settings.max_records {
653        builder = builder.max_records(records);
654    }
655    if settings.lockout_after.is_some()
656        || settings.lockout_seconds.is_some()
657        || settings.lockout_longest_seconds.is_some()
658    {
659        let default = Lockout::DEFAULT;
660        builder = builder.lockout(Lockout::new(
661            settings.lockout_after.unwrap_or(default.after),
662            settings.lockout_seconds.unwrap_or(default.first_seconds),
663            settings
664                .lockout_longest_seconds
665                .unwrap_or(default.longest_seconds),
666        ));
667    }
668    Ok(builder)
669}
670
671/// The one-time code provider over the Registry's tables, configured by `config`.
672///
673/// # Errors
674///
675/// Why the configuration is refused.
676pub fn totp_provider(
677    registry: &Arc<dyn RegistryBackend>,
678    config: Option<&ProviderConfig>,
679    sealer: &Arc<FactorSealer>,
680) -> Result<Arc<TotpAccounts>, String> {
681    totp_builder(registry, config, sealer)?
682        .build()
683        .map(Arc::new)
684        .map_err(|error| error.to_string())
685}
686
687fn factors_of(gateway: &Gateway) -> Result<Arc<dyn Accounts>, ApiError> {
688    gateway
689        .access
690        .as_ref()
691        .and_then(|providers| providers.factors.clone())
692        .ok_or_else(ApiError::not_found)
693}
694
695#[derive(Deserialize)]
696#[serde(deny_unknown_fields)]
697pub(crate) struct Held {
698    pending: String,
699}
700
701/// The proof a person who already has a factor gives to replace it, besides a fresh sign-in.
702#[derive(Deserialize, Default)]
703#[serde(deny_unknown_fields)]
704pub(crate) struct Begin {
705    /// A code from the factor they have now.
706    #[serde(default)]
707    code: Option<String>,
708}
709
710fn refused_because(reason: &str) -> AdminError {
711    AdminError::Api(ApiError::refused(StatusCode::FORBIDDEN, reason.to_owned()))
712}
713
714fn refused_here() -> AdminError {
715    refused_because("setting up a second factor is not accepted from here")
716}
717
718/// Refuses what cannot be a code before anything is counted or recorded.
719fn code_shaped(code: &str) -> Result<(), AdminError> {
720    if code.is_empty() || code.len() > 64 || code.chars().any(char::is_control) {
721        return Err(AdminError::Refused("that is not a code".to_owned()));
722    }
723    Ok(())
724}
725
726fn no_store(mut response: Response) -> Response {
727    response
728        .headers_mut()
729        .insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
730    response
731}
732
733/// The person, and the sign-in the presented bearer belongs to.
734struct Signed {
735    person: Person,
736    /// The steps the sign-in was opened with.
737    factors: Vec<SignInFactor>,
738    /// When the sign-in was made, Unix seconds.
739    issued_at: f64,
740    /// The IDs of this sign-in's own records, which a revocation of the person's others keeps.
741    keep: Vec<String>,
742}
743
744async fn bearer_steps(gateway: &Gateway, headers: &HeaderMap) -> Result<Signed, ApiError> {
745    let token = bearer(headers)?;
746    let person = resolve_user(gateway, token).await?;
747    let registry = registry(gateway)?;
748    let digest = access_token_digest(token);
749    let record = blocking(move || registry.find_access_token(&digest))
750        .await?
751        .ok_or_else(ApiError::unauthorized)?;
752    let factors = record.factors().to_vec();
753    if sign_in::from_station(&factors) {
754        return Err(ApiError::forbidden());
755    }
756    let mut keep = vec![record.token_id().to_owned()];
757    keep.extend(record.sign_in().map(str::to_owned));
758    Ok(Signed {
759        person,
760        factors,
761        issued_at: record.issued_at(),
762        keep,
763    })
764}
765
766/// Decides `purpose` for `person` with `factors`; whether the steps are enough.
767async fn decided_for(
768    gateway: &Gateway,
769    headers: &HeaderMap,
770    address: Option<SocketAddr>,
771    purpose: &str,
772    person: &Person,
773    factors: &[SignInFactor],
774) -> Result<bool, ApiError> {
775    let providers = gateway.access.clone().ok_or_else(ApiError::unavailable)?;
776    let context = SignInContext {
777        done: Gateway::passed(factors),
778        person: Some(person.clone()),
779        ..gateway.sign_in_context(purpose, headers, address, sign_in::SERVICE)
780    };
781    Ok(gateway
782        .decide_sign_in(&providers, context)
783        .await
784        .is_some_and(|decision| decision.complete))
785}
786
787/// Whether `id` has a factor, and whether one is being set up for them.
788async fn held_by(accounts: Arc<dyn Accounts>, id: String) -> Result<(bool, bool), ApiError> {
789    tokio::task::spawn_blocking(move || {
790        Ok::<_, ai6::guatiao::library::ProviderError>((
791            accounts.accounts()?.iter().any(|info| info.id == id),
792            accounts
793                .waiting()?
794                .iter()
795                .any(|waiting| waiting.shown == id),
796        ))
797    })
798    .await
799    .map_err(|_| ApiError::internal())?
800    .map_err(|_| ApiError::unavailable())
801}
802
803/// Begins a secret for `person`; `proved_current` says the caller proved the secret it replaces.
804async fn begin(
805    gateway: &Gateway,
806    person: &Person,
807    accounts: Arc<dyn Accounts>,
808    proved_current: bool,
809) -> Result<Response, AdminError> {
810    let refusal = gateway
811        .access
812        .as_ref()
813        .and_then(|providers| providers.factor_sealer.as_ref())
814        .map_or_else(
815            || Some("no [unex] factor_key is configured".to_owned()),
816            |sealer| sealer.refusal(),
817        );
818    if let Some(why) = refusal {
819        return Err(AdminError::Conflict(format!(
820            "one-time codes cannot be set up: {why}"
821        )));
822    }
823    // The record of it comes first: an enrolment that cannot be recorded is not made.
824    audit(
825        gateway,
826        person,
827        "account.factor.enrol",
828        None,
829        CONFIG_ACCOUNTS,
830        &person.id,
831    )
832    .await?;
833    let put = AccountPut {
834        name: person.id.clone(),
835        display_name: Some(person.name.clone()),
836        proved_current,
837        ..AccountPut::default()
838    };
839    let outcome = tokio::task::spawn_blocking(move || accounts.put(put))
840        .await
841        .map_err(|_| AdminError::Api(ApiError::internal()))?
842        .map_err(|_| AdminError::Api(ApiError::unavailable()))?;
843    let uri = outcome
844        .secret
845        .ok_or(AdminError::Api(ApiError::internal()))?;
846    Ok(no_store(
847        Json(FactorBegun {
848            uri,
849            recovery_codes: outcome.codes.unwrap_or_default(),
850        })
851        .into_response(),
852    ))
853}
854
855async fn confirm(
856    gateway: &Gateway,
857    person: &Person,
858    accounts: Arc<dyn Accounts>,
859    code: String,
860) -> Result<Response, AdminError> {
861    audit(
862        gateway,
863        person,
864        "account.factor.confirm",
865        None,
866        CONFIG_ACCOUNTS,
867        &person.id,
868    )
869    .await?;
870    let put = AccountPut {
871        name: person.id.clone(),
872        secret: Some(code),
873        ..AccountPut::default()
874    };
875    tokio::task::spawn_blocking(move || accounts.put(put))
876        .await
877        .map_err(|_| AdminError::Api(ApiError::internal()))?
878        .map_err(|error| match error.status {
879            Status::GUATIAO_ERR_BAD_VALUE => AdminError::Refused(
880                "that code is not right, or the enrolment ran out; begin again".to_owned(),
881            ),
882            Status::GUATIAO_ERR_NOT_FOUND => {
883                AdminError::Conflict("no enrolment is waiting; begin one".to_owned())
884            }
885            _ => AdminError::Api(ApiError::unavailable()),
886        })?;
887    Ok(no_store(
888        Json(FactorConfirmed { enrolled: true }).into_response(),
889    ))
890}
891
892/// Ends every sign-in of `person_id` but the ones in `keep`, audited first.
893async fn end_logins(
894    gateway: &Gateway,
895    actor: &Person,
896    person_id: &str,
897    keep: Vec<String>,
898) -> Result<(), AdminError> {
899    audit(
900        gateway,
901        actor,
902        "account.factor.revoke",
903        None,
904        CONFIG_ACCOUNTS,
905        person_id,
906    )
907    .await?;
908    let (registry, person_id) = (registry(gateway)?, person_id.to_owned());
909    blocking(move || registry.revoke_person_logins(&person_id, &keep)).await?;
910    Ok(())
911}
912
913/// `GET /v1/user/factors`.
914pub(crate) async fn state(
915    State(gateway): State<Gateway>,
916    connection: Option<Extension<ConnectInfo<SocketAddr>>>,
917    headers: HeaderMap,
918) -> Result<Json<FactorState>, ApiError> {
919    let signed = bearer_steps(&gateway, &headers).await?;
920    let Ok(accounts) = factors_of(&gateway) else {
921        return Ok(Json(FactorState {
922            configured: false,
923            enrolled: false,
924            enrolling: false,
925            may_enrol: false,
926        }));
927    };
928    let may_enrol = decided_for(
929        &gateway,
930        &headers,
931        address_of(connection),
932        purposes::ENROL,
933        &signed.person,
934        &signed.factors,
935    )
936    .await?;
937    let (enrolled, enrolling) = held_by(accounts, signed.person.id.clone()).await?;
938    Ok(Json(FactorState {
939        configured: true,
940        enrolled,
941        enrolling,
942        may_enrol,
943    }))
944}
945
946/// The signed-in person whom the policy lets set up a factor now (`purpose: enrol`), counted
947/// against the login guard per person and per address before anything is recorded.
948async fn enrolling_person(
949    gateway: &Gateway,
950    connection: Option<Extension<ConnectInfo<SocketAddr>>>,
951    headers: &HeaderMap,
952) -> Result<(Signed, Arc<dyn Accounts>, std::net::IpAddr), AdminError> {
953    let accounts = factors_of(gateway)?;
954    let address = address_of(connection);
955    let signed = bearer_steps(gateway, headers).await?;
956    if !decided_for(
957        gateway,
958        headers,
959        address,
960        purposes::ENROL,
961        &signed.person,
962        &signed.factors,
963    )
964    .await?
965    {
966        return Err(refused_here());
967    }
968    let source = gateway.login_guard().source(headers, address);
969    if let Some(wait) = gateway.login_guard().tried(source, &signed.person.id) {
970        return Err(AdminError::Api(ApiError::too_many_attempts(wait)));
971    }
972    Ok((signed, accounts, source))
973}
974
975/// `POST /v1/user/factors/totp`: begins an enrolment, or a rotation. Needs a sign-in the policy
976/// lets enrol (`purpose: enrol`). A person who has a factor replaces it only with a code from it
977/// (`{"code"}`) or from a sign-in made within `[login] enrol_fresh_seconds`.
978pub(crate) async fn begin_enrolment(
979    State(gateway): State<Gateway>,
980    connection: Option<Extension<ConnectInfo<SocketAddr>>>,
981    headers: HeaderMap,
982    body: Option<Json<Begin>>,
983) -> Result<Response, AdminError> {
984    let (signed, accounts, source) = enrolling_person(&gateway, connection, &headers).await?;
985    let (enrolled, _) = held_by(accounts.clone(), signed.person.id.clone()).await?;
986    if enrolled {
987        let fresh = unix_timestamp()? - signed.issued_at
988            <= gateway.config.login.enrol_fresh_seconds.as_secs_f64();
989        if !fresh {
990            let code = body.and_then(|Json(begin)| begin.code).ok_or_else(|| {
991                refused_because(
992                    "replacing your second factor needs a code from it, or a recent sign-in",
993                )
994            })?;
995            code_shaped(&code)?;
996            let providers = gateway.access.clone().ok_or_else(ApiError::unavailable)?;
997            second_factor_step(
998                &providers,
999                &signed.person,
1000                method_words::TOTP,
1001                &[],
1002                code,
1003                source,
1004            )
1005            .await
1006            .map_err(|_| refused_because("that code is not right"))?;
1007        }
1008    }
1009    // An enrolled person got here only with a current code or a fresh sign-in.
1010    begin(&gateway, &signed.person, accounts, enrolled).await
1011}
1012
1013/// `POST /v1/user/factors/totp/confirm`: the first code from the app makes the factor. Replacing
1014/// a factor ends the person's other sign-ins.
1015pub(crate) async fn confirm_enrolment(
1016    State(gateway): State<Gateway>,
1017    connection: Option<Extension<ConnectInfo<SocketAddr>>>,
1018    headers: HeaderMap,
1019    Json(body): Json<FactorCode>,
1020) -> Result<Response, AdminError> {
1021    code_shaped(&body.code)?;
1022    let (signed, accounts, _) = enrolling_person(&gateway, connection, &headers).await?;
1023    let (replacing, _) = held_by(accounts.clone(), signed.person.id.clone()).await?;
1024    let answered = confirm(&gateway, &signed.person, accounts, body.code).await?;
1025    if replacing {
1026        end_logins(&gateway, &signed.person, &signed.person.id, signed.keep).await?;
1027    }
1028    Ok(answered)
1029}
1030
1031/// The pending sign-in `token` names and its person, when the sign-in policy lets it set up a
1032/// factor now (`purpose: enrol_first`). The address is counted before the Registry is read, and
1033/// the person's own count after the person is known.
1034async fn enrolling_first(
1035    gateway: &Gateway,
1036    connection: Option<SocketAddr>,
1037    headers: &HeaderMap,
1038    token: &str,
1039    counted: bool,
1040) -> Result<(Person, Arc<dyn Accounts>), AdminError> {
1041    let from_browser = headers.contains_key(ORIGIN);
1042    if from_browser {
1043        require_origin(gateway, headers)?;
1044    }
1045    let accounts = factors_of(gateway)?;
1046    let providers = gateway.access.clone().ok_or_else(ApiError::unavailable)?;
1047    let source = gateway.login_guard().source(headers, connection);
1048    if let Some(wait) = gateway.login_guard().tried_address(source) {
1049        return Err(AdminError::Api(ApiError::too_many_attempts(wait)));
1050    }
1051    let now = unix_timestamp()?;
1052    let key = access_token_digest(token);
1053    let registry = registry(gateway)?;
1054    let Some(pending) = find_pending(registry.clone(), key.clone(), now).await? else {
1055        return Err(AdminError::Api(ApiError::unauthorized()));
1056    };
1057    if pending.browser != from_browser {
1058        return Err(AdminError::Api(ApiError::unauthorized()));
1059    }
1060    let person = person_by_id(&providers, pending.person.clone())
1061        .await?
1062        .ok_or(AdminError::Api(ApiError::unauthorized()))?;
1063    let context = SignInContext {
1064        done: Gateway::passed(&pending.factors),
1065        person: Some(person.clone()),
1066        ..gateway.sign_in_context(purposes::ENROL_FIRST, headers, connection, sign_in::SERVICE)
1067    };
1068    let allowed = gateway
1069        .decide_sign_in(&providers, context)
1070        .await
1071        .is_some_and(|decision| decision.complete);
1072    if !allowed {
1073        return Err(refused_here());
1074    }
1075    if let Some(wait) = gateway.login_guard().tried_name(&person.id) {
1076        return Err(AdminError::Api(ApiError::too_many_attempts(wait)));
1077    }
1078    // A code tried here is a guess at the factor being made, so it is counted as any is.
1079    if counted {
1080        let cap = gateway.config.login.pending_tries;
1081        match count_try(registry, key, cap, now).await? {
1082            Tried::Held => {}
1083            Tried::Gone | Tried::Spent => return Err(AdminError::Api(ApiError::unauthorized())),
1084        }
1085    }
1086    Ok((person, accounts))
1087}
1088
1089/// `POST /v1/auth/enrol`: a sign-in that waits for a code begins setting one up, where a rule
1090/// of the policy names `enrol_first`. Whoever holds only the first factor never replaces a factor
1091/// that is there or being made: it is refused.
1092pub(crate) async fn begin_first(
1093    State(gateway): State<Gateway>,
1094    connection: Option<Extension<ConnectInfo<SocketAddr>>>,
1095    headers: HeaderMap,
1096    Json(body): Json<Held>,
1097) -> Result<Response, AdminError> {
1098    let (person, accounts) = enrolling_first(
1099        &gateway,
1100        address_of(connection),
1101        &headers,
1102        &body.pending,
1103        false,
1104    )
1105    .await?;
1106    let (enrolled, enrolling) = held_by(accounts.clone(), person.id.clone()).await?;
1107    if enrolled || enrolling {
1108        return Err(refused_because(
1109            "a second factor is already set up or being set up; sign in with it, or ask an \
1110             administrator to reset it",
1111        ));
1112    }
1113    begin(&gateway, &person, accounts, false).await
1114}
1115
1116/// `POST /v1/auth/enrol/confirm`: the first code from the app. The sign-in then continues with
1117/// the next code.
1118pub(crate) async fn confirm_first(
1119    State(gateway): State<Gateway>,
1120    connection: Option<Extension<ConnectInfo<SocketAddr>>>,
1121    headers: HeaderMap,
1122    Json(body): Json<FactorCode>,
1123) -> Result<Response, AdminError> {
1124    code_shaped(&body.code)?;
1125    let token = body
1126        .pending
1127        .clone()
1128        .ok_or(AdminError::Api(ApiError::bad_request()))?;
1129    let (person, accounts) =
1130        enrolling_first(&gateway, address_of(connection), &headers, &token, true).await?;
1131    confirm(&gateway, &person, accounts, body.code).await
1132}
1133
1134/// `DELETE /v1/user/access/factors/{person}`: an administrator's reset, after which the person
1135/// enrols again and every sign-in they have ends. Needs `account.manage` at `config:accounts`.
1136pub(crate) async fn reset(
1137    State(gateway): State<Gateway>,
1138    headers: HeaderMap,
1139    Path(person_id): Path<String>,
1140) -> Result<StatusCode, AdminError> {
1141    let admin = resolve_user(&gateway, bearer(&headers)?).await?;
1142    crate::authorize_resource_action(
1143        &gateway,
1144        admin.clone(),
1145        CONFIG_ACCOUNTS.to_owned(),
1146        "account.manage",
1147    )
1148    .await?;
1149    let accounts = factors_of(&gateway)?;
1150    if person_id.trim().is_empty() || person_id.chars().any(char::is_control) {
1151        return Err(AdminError::Api(ApiError::bad_request()));
1152    }
1153    audit(
1154        &gateway,
1155        &admin,
1156        "account.factor.reset",
1157        None,
1158        CONFIG_ACCOUNTS,
1159        &person_id,
1160    )
1161    .await?;
1162    let removed = person_id.clone();
1163    tokio::task::spawn_blocking(move || accounts.remove(removed))
1164        .await
1165        .map_err(|_| AdminError::Api(ApiError::internal()))?
1166        .map_err(|error| match error.status {
1167            Status::GUATIAO_ERR_NOT_FOUND => AdminError::Api(ApiError::not_found()),
1168            _ => AdminError::Api(ApiError::unavailable()),
1169        })?;
1170    end_logins(&gateway, &admin, &person_id, Vec::new()).await?;
1171    Ok(StatusCode::NO_CONTENT)
1172}