~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
108 lines · 4.3 KB Raw History
//! Silent sign-in, as `spec/OAUTH-CLIENTS.md` says: when the authorization
//! page loads a confidential client's request, the accounts signed in on
//! the device, what each needs, and whether the browser is sent back to the
//! client at once, with a code or an error, rather than shown the page.

use super::super::{LOGIN_LIFE, Request, State, new_id};
use serde_json::{Value as Json, json};

/// Whether an account signed in on the device at `at` needs to sign in again for `r`.
pub(in super::super) fn needs_sign_in(r: &Request, at: u64, now: u64) -> bool {
    r.prompt.as_deref() == Some("login") || now.saturating_sub(at) > LOGIN_LIFE
}

/// Whether account `did` must consent to `r`: asked to, or it never
/// approved this client every scope token the request asks for.
fn needs_consent(st: &State, r: &Request, did: &str) -> bool {
    let approved = st.approved.get(did).and_then(|c| c.get(&r.client_id));
    r.prompt.as_deref() == Some("consent")
        || approved.is_none_or(|a| r.scope.iter().any(|t| !a.contains(t)))
}

/// A request answered at once: the entries to log, and the parameters the
/// browser is sent back to the client with.
pub(in super::super) type SentBack = (Vec<Json>, Vec<(&'static str, String)>);

/// What the page does with request `id`, `r`, of a confidential client,
/// loaded on `device`, whose `login_hint` names the account `hinted`, if
/// any here: None to show the page. `deactivated` says of each account
/// signed in on the device whether it is deactivated, or None if the page
/// does not list it (taken down, or gone): only those it lists count, and
/// a deactivated one is not a hinted one (`spec/LIFECYCLE.md`).
#[allow(clippy::too_many_arguments)]
pub(in super::super) fn decide(
    st: &State,
    issuer: &str,
    id: &str,
    r: &Request,
    device: &str,
    hinted: Option<&str>,
    deactivated: &dyn Fn(&str) -> Option<bool>,
    now: u64,
) -> Option<SentBack> {
    let listed: Vec<(String, u64)> = st
        .signed_in(device)
        .iter()
        .filter(|(d, _)| deactivated(d).is_some())
        .cloned()
        .collect();
    let signed_in = &listed;
    let hinted: Vec<&(String, u64)> = signed_in
        .iter()
        .filter(|(d, _)| Some(d.as_str()) == hinted && deactivated(d) == Some(false))
        .collect();
    let refuse = |error: &str, description: &str| {
        let params = vec![
            ("iss", issuer.to_string()),
            ("state", r.state.clone()),
            ("error", error.to_string()),
            ("error_description", description.to_string()),
        ];
        Some((vec![json!({ "t": "oauthEndRequest", "id": id })], params))
    };
    let approve = |did: &str| {
        let code = format!("cod-{}", new_id(32));
        let entries = vec![
            json!({ "t": "oauthLoad", "id": id, "device": device, "expires": r.expires }),
            json!({ "t": "oauthApprove", "id": id, "code": code, "did": did, "scope": r.scope, "at": now }),
        ];
        Some((
            entries,
            vec![
                ("iss", issuer.to_string()),
                ("state", r.state.clone()),
                ("code", code),
            ],
        ))
    };
    let ready =
        |(did, at): &(String, u64)| !needs_sign_in(r, *at, now) && !needs_consent(st, r, did);
    match r.prompt.as_deref() {
        Some("select_account") if signed_in.is_empty() => {
            refuse("account_selection_required", "No account is signed in")
        }
        Some("none") => match hinted[..] {
            [] => refuse(
                "login_required",
                "No account signed in on this device is the one hinted",
            ),
            [(_, at)] if needs_sign_in(r, *at, now) => {
                refuse("login_required", "The account must sign in again")
            }
            [(did, _)] if needs_consent(st, r, did) => refuse(
                "consent_required",
                "The account has not approved this client for these scopes",
            ),
            [(did, _)] => approve(did),
            _ => refuse(
                "account_selection_required",
                "More than one account is hinted",
            ),
        },
        None if r.login_hint.is_some() => match hinted[..] {
            [one] if ready(one) => approve(&one.0),
            _ => None,
        },
        _ => None,
    }
}