forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

mod.rs175 lines, 6.1 KiBHistoryRawDownload
1//! The OpenID Connect provider of `im` (`docs/contracts.md` section 2): discovery, the signing keys,
2//! the authorization endpoint, the token endpoint and userinfo.
3//!
4//! Who may sign in is decided by the browser session (`auth.rs`); every endpoint here asks the store
5//! and never decides it alone. This module holds what the endpoints share: the token lifetimes, the
6//! JSON and OAuth error answers, the query and form parsing, and the URL builder for redirects.
7
8pub mod authorize;
9pub mod discovery;
10pub mod introspect;
11pub mod logout;
12pub mod revoke;
13pub mod signing;
14pub mod token;
15pub mod userinfo;
16
17#[cfg(test)]
18mod tests;
19
20use std::time::Duration;
21
22use http::header::{CACHE_CONTROL, CONTENT_TYPE, PRAGMA, WWW_AUTHENTICATE};
23use serde_json::Value;
24use topcoat::router::content::Form;
25use topcoat::router::response::Response;
26use topcoat::router::{Body, HeaderValue, StatusCode};
27
28use crate::state::AppState;
29
30/// Lifetime of an authorization code (contracts section 2.3: 60 seconds, single use).
31pub const CODE_TTL: Duration = Duration::from_secs(60);
32
33/// Lifetime of an access token (contracts section 2.3: 10 minutes).
34pub const ACCESS_TTL: Duration = Duration::from_secs(10 * 60);
35
36/// Lifetime of an ID token.
37pub const ID_TOKEN_TTL: Duration = Duration::from_secs(10 * 60);
38
39/// Lifetime of a refresh token, unless its session ends first.
40pub const REFRESH_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60);
41
42/// The largest form body the token endpoint reads, in bytes (task: 16 KiB).
43pub const TOKEN_BODY_LIMIT: usize = 16 * 1024;
44
45/// The audience of a user's access token: this provider's own userinfo endpoint, named by its family
46/// key. A machine token's audience is the target service instead (contracts section 2.6).
47pub const USERINFO_AUDIENCE: &str = "im";
48
49/// Cache policy of the discovery document and the key set. Short, so a key change is seen soon.
50pub const PUBLIC_CACHE: &str = "public, max-age=300";
51
52/// The issuer: the public origin with no trailing slash (`config.base_url`, validated at boot).
53pub fn issuer(app: &AppState) -> &str {
54 &app.config.base_url
55}
56
57/// A JSON answer with `status` and no caching.
58pub fn json_response(status: StatusCode, body: &Value) -> Response {
59 let mut response = Response::new(Body::from(body.to_string()));
60 *response.status_mut() = status;
61 let headers = response.headers_mut();
62 headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
63 headers.insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
64 headers.insert(PRAGMA, HeaderValue::from_static("no-cache"));
65 response
66}
67
68/// An OAuth error at the token endpoint or another RFC 6749 endpoint (section 5.2).
69pub fn oauth_error(status: StatusCode, code: &str) -> Response {
70 json_response(status, &serde_json::json!({ "error": code }))
71}
72
73/// `invalid_client`: 401 with a Basic challenge (RFC 6749 section 5.2).
74pub fn invalid_client() -> Response {
75 let mut response = oauth_error(StatusCode::UNAUTHORIZED, "invalid_client");
76 response.headers_mut().insert(
77 WWW_AUTHENTICATE,
78 HeaderValue::from_static("Basic realm=\"im\""),
79 );
80 response
81}
82
83/// `invalid_grant`: the code or token is not usable. One answer for every reason, so the reason is
84/// not disclosed.
85pub fn invalid_grant() -> Response {
86 oauth_error(StatusCode::BAD_REQUEST, "invalid_grant")
87}
88
89/// The name and value pairs of a query string or a form body, in order. Repeats are kept.
90pub type Pairs = Vec<(String, String)>;
91
92/// Parses a query string or a form body. `None` when it is not valid URL-encoded data.
93pub fn parse_pairs(bytes: &[u8]) -> Option<Pairs> {
94 Form::<Pairs>::from_bytes(bytes).ok().map(|form| form.0)
95}
96
97/// How often a parameter occurs.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum Single<'a> {
100 /// Not present.
101 Absent,
102 /// Present exactly once.
103 One(&'a str),
104 /// Present more than once. Refused by every endpoint.
105 Repeated,
106}
107
108/// How often `name` occurs in `pairs`.
109pub fn single<'a>(pairs: &'a [(String, String)], name: &str) -> Single<'a> {
110 let mut values = pairs
111 .iter()
112 .filter(|(key, _)| key == name)
113 .map(|(_, value)| value.as_str());
114 match (values.next(), values.next()) {
115 (None, _) => Single::Absent,
116 (Some(value), None) => Single::One(value),
117 _ => Single::Repeated,
118 }
119}
120
121/// The value of `name` when it occurs exactly once.
122pub fn one<'a>(pairs: &'a [(String, String)], name: &str) -> Option<&'a str> {
123 match single(pairs, name) {
124 Single::One(value) => Some(value),
125 _ => None,
126 }
127}
128
129/// Percent-encodes a query or form value: every byte except the RFC 3986 unreserved set.
130pub fn encode_value(value: &str) -> String {
131 let mut out = String::with_capacity(value.len());
132 for byte in value.bytes() {
133 if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
134 out.push(char::from(byte));
135 } else {
136 out.push_str(&format!("%{byte:02X}"));
137 }
138 }
139 out
140}
141
142/// Decodes `%XX` escapes. `None` for a bad escape or for bytes that are not UTF-8 once decoded.
143pub fn percent_decode(input: &str) -> Option<String> {
144 let bytes = input.as_bytes();
145 let mut out = Vec::with_capacity(bytes.len());
146 let mut i = 0;
147 while i < bytes.len() {
148 if bytes[i] == b'%' {
149 let hex = std::str::from_utf8(bytes.get(i + 1..i + 3)?).ok()?;
150 out.push(u8::from_str_radix(hex, 16).ok()?);
151 i += 3;
152 } else {
153 out.push(bytes[i]);
154 i += 1;
155 }
156 }
157 String::from_utf8(out).ok()
158}
159
160/// Appends `params` to a redirect URI as a query, encoding every name and value. The registered URI
161/// has no fragment (checked at registration), so the query goes at its end.
162pub fn with_query(uri: &str, params: &[(&str, &str)]) -> String {
163 let separator = if uri.ends_with(['?', '&']) {
164 ""
165 } else if uri.contains('?') {
166 "&"
167 } else {
168 "?"
169 };
170 let query: Vec<String> = params
171 .iter()
172 .map(|(name, value)| format!("{}={}", encode_value(name), encode_value(value)))
173 .collect();
174 format!("{uri}{separator}{}", query.join("&"))
175}