//! The OAuth 2.0 and OpenID Connect rules that are pure text: the scope names, the URI rules of //! registered clients, the family-key format, and PKCE (RFC 7636). //! //! Nothing here touches the database or the network. The registration command and the endpoints use //! the same functions, so a value is accepted or refused the same way everywhere. use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; use sha2::{Digest, Sha256}; /// Scopes a person grants at sign-in. Every family client is first-party, so there is no consent screen. pub const USER_SCOPES: [&str; 3] = ["openid", "profile", "email"]; /// Every scope the provider advertises (contracts section 2.1). pub const SUPPORTED_SCOPES: [&str; 5] = [ "openid", "profile", "email", "directory.read", "files.service", ]; /// The longest `state` or `nonce` accepted, in bytes. Longer values are refused, not truncated. pub const MAX_ECHO_BYTES: usize = 512; /// The longest registered URI, in bytes. pub const MAX_URI_BYTES: usize = 2048; /// True for a scope the provider knows. pub fn is_supported_scope(scope: &str) -> bool { SUPPORTED_SCOPES.contains(&scope) } /// True for a scope a person can be granted at sign-in. pub fn is_user_scope(scope: &str) -> bool { USER_SCOPES.contains(&scope) } /// The S256 code challenge of a verifier: base64url of its SHA-256, without padding. pub fn pkce_s256(verifier: &str) -> String { BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) } /// True for a code challenge: exactly 43 base64url characters (32 bytes, unpadded). pub fn is_valid_challenge(challenge: &str) -> bool { challenge.len() == 43 && challenge .bytes() .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') } /// True for a code verifier: 43 to 128 unreserved characters (RFC 7636 section 4.1). pub fn is_valid_verifier(verifier: &str) -> bool { (43..=128).contains(&verifier.len()) && verifier .bytes() .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~')) } /// True for a registrable URI: `https`, or `http` to a loopback host (for development), absolute, with /// no fragment, no userinfo (`@`), no whitespace or control characters and no backslash. A registered URI /// is ASCII only: a Unicode character, such as a bidi override, could show the URI differently from how it /// is stored, so other bytes must be percent-encoded. Redirect URIs, post-logout URIs and back-channel URIs /// all use this rule. pub fn is_valid_registered_uri(uri: &str) -> bool { if uri.len() > MAX_URI_BYTES || !uri.is_ascii() || uri.bytes().any(|b| b <= 0x20 || b == 0x7f || b == b'\\') || uri.contains('#') { return false; } let Some((scheme, rest)) = uri.split_once("://") else { return false; }; // Any `@` before the first `/` after `//` is userinfo, even one that sits where a query would start. // Such a URI names one host to a reader and another to a browser, so it is refused outright. let before_path = &rest[..rest.find('/').unwrap_or(rest.len())]; if before_path.contains('@') { return false; } let authority = &rest[..rest.find(['/', '?']).unwrap_or(rest.len())]; if authority.is_empty() { return false; } let host = host_of(authority); match scheme { "https" => !host.is_empty(), "http" => is_loopback(host), _ => false, } } /// The host of an authority (`host`, `host:port`, `[v6]:port`). fn host_of(authority: &str) -> &str { if let Some(bracketed) = authority.strip_prefix('[') { return bracketed.split(']').next().unwrap_or(""); } authority.split(':').next().unwrap_or("") } fn is_loopback(host: &str) -> bool { matches!(host, "localhost" | "127.0.0.1" | "::1") } /// The family key of im's own switcher row. No client may carry it, so a family app can never take the /// row that names this service. pub const HOME_KEY: &str = "im"; /// True for a family key: `^[a-z][a-z0-9-]{0,31}$`, the same rule as `services.key`. pub fn is_valid_family_key(key: &str) -> bool { let bytes = key.as_bytes(); (1..=32).contains(&bytes.len()) && bytes[0].is_ascii_lowercase() && bytes .iter() .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-') } /// True for a family key a client may carry: a valid family key other than [`HOME_KEY`]. The admin page and /// `im client add` both use this, so the reserved key is refused the same way everywhere. pub fn is_client_family_key(key: &str) -> bool { key != HOME_KEY && is_valid_family_key(key) } #[cfg(test)] mod tests { use super::*; #[test] fn the_rfc_7636_example_challenge_matches() { assert_eq!( pkce_s256("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" ); } #[test] fn registered_uris_must_be_exact_https_or_loopback_http() { assert!(is_valid_registered_uri( "https://in.example.com/auth/callback" )); assert!(is_valid_registered_uri( "http://127.0.0.1:7655/auth/callback" )); assert!(is_valid_registered_uri("http://[::1]:7655/auth/callback")); for bad in [ "http://in.example.com/auth/callback", "https://in.example.com@evil.example/auth/callback", "https://in.example.com?@evil.example/auth/callback", "https://in.example.com?x=@evil.example/auth/callback", "https://in.example.com/auth/callback#frag", "https:///auth/callback", "https://in.example.com/a b", "https://in.example.com\\evil", "in.example.com/auth/callback", "javascript://in.example.com/x", "https://in.example.com/\u{202e}abc", "https://in.example.com/caf\u{e9}", "https://in.example.com/\u{0}", ] { assert!(!is_valid_registered_uri(bad), "accepted {bad:?}"); } } }