forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

oauth.rs164 lines, 6.0 KiBHistoryRawDownload
1//! The OAuth 2.0 and OpenID Connect rules that are pure text: the scope names, the URI rules of
2//! registered clients, the family-key format, and PKCE (RFC 7636).
3//!
4//! Nothing here touches the database or the network. The registration command and the endpoints use
5//! the same functions, so a value is accepted or refused the same way everywhere.
6
7use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
8use sha2::{Digest, Sha256};
9
10/// Scopes a person grants at sign-in. Every family client is first-party, so there is no consent screen.
11pub const USER_SCOPES: [&str; 3] = ["openid", "profile", "email"];
12
13/// Every scope the provider advertises (contracts section 2.1).
14pub const SUPPORTED_SCOPES: [&str; 5] = [
15 "openid",
16 "profile",
17 "email",
18 "directory.read",
19 "files.service",
20];
21
22/// The longest `state` or `nonce` accepted, in bytes. Longer values are refused, not truncated.
23pub const MAX_ECHO_BYTES: usize = 512;
24
25/// The longest registered URI, in bytes.
26pub const MAX_URI_BYTES: usize = 2048;
27
28/// True for a scope the provider knows.
29pub fn is_supported_scope(scope: &str) -> bool {
30 SUPPORTED_SCOPES.contains(&scope)
31}
32
33/// True for a scope a person can be granted at sign-in.
34pub fn is_user_scope(scope: &str) -> bool {
35 USER_SCOPES.contains(&scope)
36}
37
38/// The S256 code challenge of a verifier: base64url of its SHA-256, without padding.
39pub fn pkce_s256(verifier: &str) -> String {
40 BASE64_URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
41}
42
43/// True for a code challenge: exactly 43 base64url characters (32 bytes, unpadded).
44pub fn is_valid_challenge(challenge: &str) -> bool {
45 challenge.len() == 43
46 && challenge
47 .bytes()
48 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
49}
50
51/// True for a code verifier: 43 to 128 unreserved characters (RFC 7636 section 4.1).
52pub fn is_valid_verifier(verifier: &str) -> bool {
53 (43..=128).contains(&verifier.len())
54 && verifier
55 .bytes()
56 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~'))
57}
58
59/// True for a registrable URI: `https`, or `http` to a loopback host (for development), absolute, with
60/// no fragment, no userinfo (`@`), no whitespace or control characters and no backslash. A registered URI
61/// is ASCII only: a Unicode character, such as a bidi override, could show the URI differently from how it
62/// is stored, so other bytes must be percent-encoded. Redirect URIs, post-logout URIs and back-channel URIs
63/// all use this rule.
64pub fn is_valid_registered_uri(uri: &str) -> bool {
65 if uri.len() > MAX_URI_BYTES
66 || !uri.is_ascii()
67 || uri.bytes().any(|b| b <= 0x20 || b == 0x7f || b == b'\\')
68 || uri.contains('#')
69 {
70 return false;
71 }
72 let Some((scheme, rest)) = uri.split_once("://") else {
73 return false;
74 };
75 // Any `@` before the first `/` after `//` is userinfo, even one that sits where a query would start.
76 // Such a URI names one host to a reader and another to a browser, so it is refused outright.
77 let before_path = &rest[..rest.find('/').unwrap_or(rest.len())];
78 if before_path.contains('@') {
79 return false;
80 }
81 let authority = &rest[..rest.find(['/', '?']).unwrap_or(rest.len())];
82 if authority.is_empty() {
83 return false;
84 }
85 let host = host_of(authority);
86 match scheme {
87 "https" => !host.is_empty(),
88 "http" => is_loopback(host),
89 _ => false,
90 }
91}
92
93/// The host of an authority (`host`, `host:port`, `[v6]:port`).
94fn host_of(authority: &str) -> &str {
95 if let Some(bracketed) = authority.strip_prefix('[') {
96 return bracketed.split(']').next().unwrap_or("");
97 }
98 authority.split(':').next().unwrap_or("")
99}
100
101fn is_loopback(host: &str) -> bool {
102 matches!(host, "localhost" | "127.0.0.1" | "::1")
103}
104
105/// The family key of im's own switcher row. No client may carry it, so a family app can never take the
106/// row that names this service.
107pub const HOME_KEY: &str = "im";
108
109/// True for a family key: `^[a-z][a-z0-9-]{0,31}$`, the same rule as `services.key`.
110pub fn is_valid_family_key(key: &str) -> bool {
111 let bytes = key.as_bytes();
112 (1..=32).contains(&bytes.len())
113 && bytes[0].is_ascii_lowercase()
114 && bytes
115 .iter()
116 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
117}
118
119/// True for a family key a client may carry: a valid family key other than [`HOME_KEY`]. The admin page and
120/// `im client add` both use this, so the reserved key is refused the same way everywhere.
121pub fn is_client_family_key(key: &str) -> bool {
122 key != HOME_KEY && is_valid_family_key(key)
123}
124
125#[cfg(test)]
126mod tests {
127 use super::*;
128
129 #[test]
130 fn the_rfc_7636_example_challenge_matches() {
131 assert_eq!(
132 pkce_s256("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),
133 "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
134 );
135 }
136
137 #[test]
138 fn registered_uris_must_be_exact_https_or_loopback_http() {
139 assert!(is_valid_registered_uri(
140 "https://in.example.com/auth/callback"
141 ));
142 assert!(is_valid_registered_uri(
143 "http://127.0.0.1:7655/auth/callback"
144 ));
145 assert!(is_valid_registered_uri("http://[::1]:7655/auth/callback"));
146 for bad in [
147 "http://in.example.com/auth/callback",
148 "https://in.example.com@evil.example/auth/callback",
149 "https://in.example.com?@evil.example/auth/callback",
150 "https://in.example.com?x=@evil.example/auth/callback",
151 "https://in.example.com/auth/callback#frag",
152 "https:///auth/callback",
153 "https://in.example.com/a b",
154 "https://in.example.com\\evil",
155 "in.example.com/auth/callback",
156 "javascript://in.example.com/x",
157 "https://in.example.com/\u{202e}abc",
158 "https://in.example.com/caf\u{e9}",
159 "https://in.example.com/\u{0}",
160 ] {
161 assert!(!is_valid_registered_uri(bad), "accepted {bad:?}");
162 }
163 }
164}