oxedyne/fe2o3/fe2o3_net/src/oauth.rs
24.8 KiB, 17 runs
created by r1870400018:79741, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! OAuth 2.1 for a client that signs its user in through a browser, as the Model Context Protocol's |
| 2 | //! authorisation asks. The protected resource's metadata (RFC 9728), named by its 401's challenge or |
| 3 | //! found at its well-known place, names the authorisation server, whose metadata (RFC 8414, or OpenID |
| 4 | //! Connect discovery) names its endpoints. A client is registered where the server offers it (RFC 7591), |
| 5 | //! the code is asked for with PKCE (RFC 7636) for the resource named (RFC 8707), and comes back to a |
| 6 | //! listener on this computer's loopback (RFC 8252), or to a page of the client's own that hands its query on. |
| 7 | //! |
| 8 | //! No token, code, verifier or client secret goes into an error or a `Debug`: a server's refusal is |
| 9 | //! given by its `error` and `error_description` alone. |
| 10 | |
| 11 | use crate::http::{ |
| 12 | client::url_request, |
| 13 | fields::HeaderName, |
| 14 | header::{ |
| 15 | HttpHeadline, |
| 16 | HttpMethod, |
| 17 | }, |
| 18 | loc::Url, |
| 19 | msg::{ |
| 20 | HttpMessage, |
| 21 | ReadLimits, |
| 22 | }, |
| 23 | pct, |
| 24 | }; |
| 25 | |
| 26 | use oxedyne_fe2o3_core::{ |
| 27 | prelude::*, |
| 28 | sha256, |
| 29 | }; |
| 30 | use oxedyne_fe2o3_jdat::{ |
| 31 | prelude::*, |
| 32 | bdat::limits::DecodeLimits, |
| 33 | }; |
| 34 | use oxedyne_fe2o3_text::base64; |
| 35 | |
| 36 | use std::{ |
| 37 | fmt, |
| 38 | sync::Arc, |
| 39 | time::{ |
| 40 | Duration, |
| 41 | Instant, |
| 42 | SystemTime, |
| 43 | UNIX_EPOCH, |
| 44 | }, |
| 45 | }; |
| 46 | |
| 47 | use tokio::{ |
| 48 | io::{ |
| 49 | AsyncReadExt, |
| 50 | AsyncWriteExt, |
| 51 | }, |
| 52 | net::{ |
| 53 | TcpListener, |
| 54 | TcpStream, |
| 55 | }, |
| 56 | }; |
| 57 | use tokio_rustls::rustls::ClientConfig; |
| 58 | |
| 59 | |
| 60 | const RESOURCE_META: &str = "/.well-known/oauth-protected-resource"; // fixed: RFC 9728 |
| 61 | const SERVER_META: &str = "/.well-known/oauth-authorization-server"; // fixed: RFC 8414 |
| 62 | const OPENID_META: &str = "/.well-known/openid-configuration"; // fixed: OpenID Connect Discovery 1.0 |
| 63 | const SAID_MAX: usize = 200; // fixed: enough of a server's error_description to read |
| 64 | const HEAD_MAX: usize = 8192; // fixed: a browser's request head, which carries no body here |
| 65 | const VERIFIER: usize = 32; // fixed: random bytes of a PKCE verifier, 43 characters, RFC 7636's least |
| 66 | |
| 67 | /// The bounds each request to a server is made within. |
| 68 | #[derive(Clone)] |
| 69 | pub struct Bounds { |
| 70 | pub tls: Option<Arc<ClientConfig>>, // none reads the default trust store, for https only |
| 71 | pub wait: Duration, // for one answer |
| 72 | pub body_max: usize, // bytes of one answer |
| 73 | } |
| 74 | |
| 75 | /// An authorisation server's endpoints, and the resource a token is asked for. |
| 76 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 77 | pub struct Meta { |
| 78 | pub resource: String, // the protected resource's URL, as RFC 8707 names it |
| 79 | pub issuer: String, |
| 80 | pub authorize: String, |
| 81 | pub token: String, |
| 82 | pub register: String, // empty where the server offers no registration |
| 83 | pub scope: String, // the scopes asked for, space separated; empty asks for none |
| 84 | } |
| 85 | |
| 86 | /// A client registered with an authorisation server; the secret is empty for a public client. |
| 87 | #[derive(Clone, Default, PartialEq, Eq)] |
| 88 | pub struct Registered { |
| 89 | pub id: String, |
| 90 | pub secret: String, |
| 91 | } |
| 92 | |
| 93 | /// What a call carries, and what renews it. |
| 94 | #[derive(Clone, Default, PartialEq, Eq)] |
| 95 | pub struct Tokens { |
| 96 | pub access: String, |
| 97 | pub refresh: String, // empty where none was given |
| 98 | pub expires: u64, // seconds since the epoch, 0 where the server gave no lifetime |
| 99 | pub scope: String, |
| 100 | } |
| 101 | |
| 102 | /// Everything kept of one sign-in: the resource it is for, and what renews it. |
| 103 | #[derive(Clone, Default, PartialEq, Eq)] |
| 104 | pub struct Grant { |
| 105 | pub url: String, // the protected resource called with it |
| 106 | pub token_url: String, |
| 107 | pub resource: String, |
| 108 | pub client: Registered, |
| 109 | pub tokens: Tokens, |
| 110 | } |
| 111 | |
| 112 | /// The verifier kept for the exchange, and the challenge sent with the authorisation request. |
| 113 | pub struct Pkce { |
| 114 | pub verifier: String, |
| 115 | pub challenge: String, |
| 116 | } |
| 117 | |
| 118 | impl fmt::Debug for Registered { |
| 119 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 120 | write!(f, "Registered {{ id: {:?}, secret: {} }}", self.id, if self.secret.is_empty() { "none" } else { "[held]" }) |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | impl fmt::Debug for Tokens { |
| 125 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 126 | write!(f, "Tokens {{ access: [held], refresh: {}, expires: {}, scope: {:?} }}", |
| 127 | if self.refresh.is_empty() { "none" } else { "[held]" }, self.expires, self.scope) |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | impl fmt::Debug for Grant { |
| 132 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 133 | write!(f, "Grant {{ url: {:?}, token_url: {:?}, resource: {:?}, client: {:?}, tokens: {:?} }}", |
| 134 | self.url, self.token_url, self.resource, self.client, self.tokens) |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | impl Pkce { |
| 139 | /// A fresh verifier and its S256 challenge. |
| 140 | pub fn new() -> Self { |
| 141 | let verifier = base64::random_url(VERIFIER); |
| 142 | let challenge = base64::encode_url(&sha256::digest(verifier.as_bytes())); |
| 143 | Self { verifier, challenge } |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | impl Default for Pkce { |
| 148 | fn default() -> Self { Self::new() } |
| 149 | } |
| 150 | |
| 151 | impl Tokens { |
| 152 | /// Does the access token end within `margin`? |
| 153 | pub fn due(&self, margin: Duration) -> bool { |
| 154 | self.expires > 0 && now().saturating_add(margin.as_secs()) >= self.expires |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | impl Grant { |
| 159 | |
| 160 | /// The grant as kept in a file of its holder's, JSON. |
| 161 | pub fn to_json(&self) -> Outcome<String> { |
| 162 | mapdat!{ |
| 163 | "url" => self.url.clone(), |
| 164 | "token_url" => self.token_url.clone(), |
| 165 | "resource" => self.resource.clone(), |
| 166 | "client_id" => self.client.id.clone(), |
| 167 | "client_secret" => self.client.secret.clone(), |
| 168 | "access" => self.tokens.access.clone(), |
| 169 | "refresh" => self.tokens.refresh.clone(), |
| 170 | "expires" => self.tokens.expires, |
| 171 | "scope" => self.tokens.scope.clone(), |
| 172 | }.json_canonical() |
| 173 | } |
| 174 | |
| 175 | pub fn of_json(text: &str) -> Outcome<Self> { |
| 176 | let m = match Dat::decode_json_strict(text, &DecodeLimits::default()) { |
| 177 | Ok(m @ Dat::Map(_)) => m, |
| 178 | _ => return Err(err!("A kept grant does not read as a JSON object."; Invalid, Input)), |
| 179 | }; |
| 180 | let g = Self { |
| 181 | url: txt(&m, "url"), |
| 182 | token_url: txt(&m, "token_url"), |
| 183 | resource: txt(&m, "resource"), |
| 184 | client: Registered { id: txt(&m, "client_id"), secret: txt(&m, "client_secret") }, |
| 185 | tokens: Tokens { |
| 186 | access: txt(&m, "access"), |
| 187 | refresh: txt(&m, "refresh"), |
| 188 | expires: m.map_get(&dat!("expires")).ok().flatten().and_then(|d| d.get_u64()).unwrap_or(0), |
| 189 | scope: txt(&m, "scope"), |
| 190 | }, |
| 191 | }; |
| 192 | match g.url.is_empty() || g.token_url.is_empty() || g.tokens.access.is_empty() { |
| 193 | true => Err(err!("A kept grant names no url, token_url or access token."; Invalid, Input, Missing)), |
| 194 | false => Ok(g), |
| 195 | } |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | /// Seconds since the epoch. |
| 200 | pub fn now() -> u64 { |
| 201 | SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) |
| 202 | } |
| 203 | |
| 204 | /// The parameters of a `Bearer` challenge in a `WWW-Authenticate` value, by name in lower case. |
| 205 | pub fn challenge(www: &str) -> Vec<(String, String)> { |
| 206 | let rest = match www.trim_start().get(..6) { |
| 207 | Some(s) if s.eq_ignore_ascii_case("bearer") => &www.trim_start()[6..], |
| 208 | _ => return Vec::new(), |
| 209 | }; |
| 210 | let (mut out, mut it) = (Vec::new(), rest.chars().peekable()); |
| 211 | loop { |
| 212 | while it.peek().is_some_and(|c| c.is_whitespace() || *c == ',') { |
| 213 | it.next(); |
| 214 | } |
| 215 | let name: String = it.by_ref().take_while(|c| *c != '=').collect::<String>().trim().to_ascii_lowercase(); |
| 216 | if name.is_empty() { |
| 217 | return out; |
| 218 | } |
| 219 | let mut value = String::new(); |
| 220 | if it.peek() == Some(&'"') { |
| 221 | it.next(); |
| 222 | while let Some(c) = it.next() { |
| 223 | match c { |
| 224 | '\\' => value.extend(it.next()), |
| 225 | '"' => break, |
| 226 | c => value.push(c), |
| 227 | } |
| 228 | } |
| 229 | } else { |
| 230 | value = it.by_ref().take_while(|c| *c != ',').collect::<String>().trim().to_string(); |
| 231 | } |
| 232 | out.push((name, value)); |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | /// The endpoints that sign a user in to the protected resource at `server`. Its 401 names its metadata, |
| 237 | /// else that is read at its well-known places; a resource that has none is its own authorisation server, |
| 238 | /// with the default endpoints, as the protocol's revision 2025-03-26 has it. |
| 239 | pub async fn discover(server: &str, b: &Bounds) -> Outcome<Meta> { |
| 240 | let u = res!(Url::parse(server)); |
| 241 | let probe = r#"{"jsonrpc":"2.0","id":0,"method":"ping"}"#; // fixed: any request, to be refused with the challenge |
| 242 | let r = res!(call(&u, HttpMethod::POST, &[("Content-Type", "application/json"), |
| 243 | ("Accept", "application/json, text/event-stream")], probe.as_bytes(), b).await); |
| 244 | let ch = match status(&r) { |
| 245 | 401 => challenge(&r.header.fields.get_one(&HeaderName::from("www-authenticate")).map(|v| v.to_string()) |
| 246 | .unwrap_or_default()), |
| 247 | _ => Vec::new(), |
| 248 | }; |
| 249 | let said = |k: &str| ch.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone()).unwrap_or_default(); |
| 250 | let home = origin(&u); |
| 251 | let path = u.target.split('?').next().unwrap_or("").trim_end_matches('/').to_string(); |
| 252 | let mut places = vec![fmt!("{}{}{}", home, RESOURCE_META, path), fmt!("{}{}", home, RESOURCE_META)]; |
| 253 | if !said("resource_metadata").is_empty() { |
| 254 | places.insert(0, said("resource_metadata")); |
| 255 | } |
| 256 | let mut found = None; |
| 257 | for p in places { |
| 258 | if let Some(m) = res!(get_json(&p, b).await) { |
| 259 | found = Some(m); |
| 260 | break; |
| 261 | } |
| 262 | } |
| 263 | let (resource, issuer, scopes) = match &found { |
| 264 | Some(m) => { |
| 265 | let issuer = m.map_get(&dat!("authorization_servers")).ok().flatten().and_then(|d| d.get_string_list()) |
| 266 | .and_then(|l| l.into_iter().next()); |
| 267 | let issuer = res!(issuer.ok_or_else(|| err!("The protected resource {}'s metadata names no authorisation \ |
| 268 | server.", server; Invalid, Input, Missing))); |
| 269 | let res = txt(m, "resource"); |
| 270 | (if res.is_empty() { server.to_string() } else { res }, issuer, |
| 271 | m.map_get(&dat!("scopes_supported")).ok().flatten().and_then(|d| d.get_string_list()).unwrap_or_default()) |
| 272 | }, |
| 273 | None => (server.to_string(), home.clone(), Vec::new()), |
| 274 | }; |
| 275 | let scope = match said("scope").is_empty() { |
| 276 | true => scopes.join(" "), |
| 277 | false => said("scope"), |
| 278 | }; |
| 279 | let iu = res!(Url::parse(&issuer)); |
| 280 | let (io, ip) = (origin(&iu), iu.target.split('?').next().unwrap_or("").trim_end_matches('/').to_string()); |
| 281 | let places = match ip.is_empty() { |
| 282 | true => vec![fmt!("{}{}", io, SERVER_META), fmt!("{}{}", io, OPENID_META)], |
| 283 | false => vec![fmt!("{}{}{}", io, SERVER_META, ip), fmt!("{}{}{}", io, OPENID_META, ip), fmt!("{}{}{}", io, ip, OPENID_META)], |
| 284 | }; |
| 285 | let mut meta = None; |
| 286 | for p in places { |
| 287 | if let Some(m) = res!(get_json(&p, b).await) { |
| 288 | meta = Some(m); |
| 289 | break; |
| 290 | } |
| 291 | } |
| 292 | let m = match meta { |
| 293 | Some(m) => m, |
| 294 | None => return Ok(Meta { resource, issuer, authorize: fmt!("{}/authorize", io), token: fmt!("{}/token", io), |
| 295 | register: fmt!("{}/register", io), scope }), |
| 296 | }; |
| 297 | if let Some(l) = m.map_get(&dat!("code_challenge_methods_supported")).ok().flatten().and_then(|d| d.get_string_list()) { |
| 298 | if !l.iter().any(|x| x == "S256") { |
| 299 | return Err(err!("The authorisation server {} does not offer PKCE's S256, which a sign-in needs.", issuer; |
| 300 | Security, Unimplemented)); |
| 301 | } |
| 302 | } |
| 303 | let (authorize, token) = (txt(&m, "authorization_endpoint"), txt(&m, "token_endpoint")); |
| 304 | if authorize.is_empty() || token.is_empty() { |
| 305 | return Err(err!("The authorisation server {}'s metadata names no authorization_endpoint or token_endpoint.", issuer; |
| 306 | Invalid, Input, Missing)); |
| 307 | } |
| 308 | Ok(Meta { resource, issuer, authorize, token, register: txt(&m, "registration_endpoint"), scope }) |
| 309 | } |
| 310 | |
| 311 | /// A public client registered for `redirect`, which signs in by PKCE alone. |
| 312 | pub async fn register(meta: &Meta, redirect: &str, name: &str, b: &Bounds) -> Outcome<Registered> { |
| 313 | if meta.register.is_empty() { |
| 314 | return Err(err!("The authorisation server {} offers no registration: name a client_id for it.", meta.issuer; |
| 315 | Missing, Configuration)); |
| 316 | } |
| 317 | let ask = mapdat!{ |
| 318 | "client_name" => name.to_string(), |
| 319 | "redirect_uris" => Dat::List(vec![dat!(redirect.to_string())]), |
| 320 | "grant_types" => Dat::List(vec![dat!("authorization_code"), dat!("refresh_token")]), |
| 321 | "response_types" => Dat::List(vec![dat!("code")]), |
| 322 | "token_endpoint_auth_method" => "none", |
| 323 | }; |
| 324 | let body = res!(ask.json_canonical()); |
| 325 | let u = res!(Url::parse(&meta.register)); |
| 326 | let r = res!(call(&u, HttpMethod::POST, &[("Content-Type", "application/json"), ("Accept", "application/json")], |
| 327 | body.as_bytes(), b).await); |
| 328 | let m = match (status(&r), json_of(&r)) { |
| 329 | (200..=299, Some(m)) => m, |
| 330 | (s, m) => return Err(err!("The authorisation server {} refused the registration ({}){}", meta.issuer, s, |
| 331 | refusal(m.as_ref()); Network, Unauthorised)), |
| 332 | }; |
| 333 | match txt(&m, "client_id") { |
| 334 | id if id.is_empty() => Err(err!("The authorisation server {} registered no client_id.", meta.issuer; Invalid, Input, Missing)), |
| 335 | id => Ok(Registered { id, secret: txt(&m, "client_secret") }), |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | /// The address the user signs in at. |
| 340 | pub fn authorize_url(meta: &Meta, client: &Registered, redirect: &str, pkce: &Pkce, state: &str) -> String { |
| 341 | let mut q = vec![("response_type", "code"), ("client_id", client.id.as_str()), ("redirect_uri", redirect), |
| 342 | ("code_challenge", pkce.challenge.as_str()), ("code_challenge_method", "S256"), ("state", state), |
| 343 | ("resource", meta.resource.as_str())]; |
| 344 | if !meta.scope.is_empty() { |
| 345 | q.push(("scope", meta.scope.as_str())); |
| 346 | } |
| 347 | fmt!("{}{}{}", meta.authorize, if meta.authorize.contains('?') { '&' } else { '?' }, form(&q)) |
| 348 | } |
| 349 | |
| 350 | /// The tokens the code is exchanged for. |
| 351 | pub async fn exchange(token_url: &str, client: &Registered, code: &str, verifier: &str, redirect: &str, resource: &str, |
| 352 | b: &Bounds) -> Outcome<Tokens> |
| 353 | { |
| 354 | token_call(token_url, client, &[("grant_type", "authorization_code"), ("code", code), ("code_verifier", verifier), |
| 355 | ("redirect_uri", redirect), ("resource", resource)], b).await |
| 356 | } |
| 357 | |
| 358 | /// The grant's tokens renewed; a server that gives no new refresh token leaves the old one. |
| 359 | pub async fn refresh(g: &Grant, b: &Bounds) -> Outcome<Tokens> { |
| 360 | if g.tokens.refresh.is_empty() { |
| 361 | return Err(err!("The grant for {} holds no refresh token: sign in again.", g.url; Missing, Unauthorised)); |
| 362 | } |
| 363 | let mut t = res!(token_call(&g.token_url, &g.client, &[("grant_type", "refresh_token"), |
| 364 | ("refresh_token", g.tokens.refresh.as_str()), ("resource", g.resource.as_str())], b).await); |
| 365 | if t.refresh.is_empty() { |
| 366 | t.refresh = g.tokens.refresh.clone(); |
| 367 | } |
| 368 | Ok(t) |
| 369 | } |
| 370 | |
| 371 | async fn token_call(token_url: &str, client: &Registered, pairs: &[(&str, &str)], b: &Bounds) -> Outcome<Tokens> { |
| 372 | let mut q: Vec<(&str, &str)> = pairs.iter().filter(|(_, v)| !v.is_empty()).copied().collect(); |
| 373 | q.push(("client_id", client.id.as_str())); |
| 374 | if !client.secret.is_empty() { |
| 375 | q.push(("client_secret", client.secret.as_str())); |
| 376 | } |
| 377 | let u = res!(Url::parse(token_url)); |
| 378 | let body = form(&q); |
| 379 | let r = res!(call(&u, HttpMethod::POST, &[("Content-Type", "application/x-www-form-urlencoded"), |
| 380 | ("Accept", "application/json")], body.as_bytes(), b).await); |
| 381 | let m = match (status(&r), json_of(&r)) { |
| 382 | (200..=299, Some(m)) => m, |
| 383 | (s, m) => return Err(err!("The token endpoint {} refused ({}){}", u.host, s, refusal(m.as_ref()); |
| 384 | Network, Unauthorised)), |
| 385 | }; |
| 386 | let access = txt(&m, "access_token"); |
| 387 | if access.is_empty() || !txt(&m, "token_type").eq_ignore_ascii_case("bearer") { |
| 388 | return Err(err!("The token endpoint {} gave no bearer access token.", u.host; Invalid, Input, Missing)); |
| 389 | } |
| 390 | let life = m.map_get(&dat!("expires_in")).ok().flatten().and_then(|d| d.get_u64()).unwrap_or(0); |
| 391 | Ok(Tokens { access, refresh: txt(&m, "refresh_token"), expires: if life > 0 { now() + life } else { 0 }, |
| 392 | scope: txt(&m, "scope") }) |
| 393 | } |
| 394 | |
| 395 | /// The listener on this computer's loopback that the browser comes back to. Only this computer reaches it; a redirect |
| 396 | /// elsewhere (a page of the client's own) reads what it is brought with `callback`. |
| 397 | pub struct Loopback { |
| 398 | listener: TcpListener, |
| 399 | pub port: u16, |
| 400 | } |
| 401 | |
| 402 | impl Loopback { |
| 403 | |
| 404 | /// On `port`, or one the system picks for 0. |
| 405 | pub async fn bind(port: u16) -> Outcome<Self> { |
| 406 | let listener = res!(TcpListener::bind(("127.0.0.1", port)).await.map_err(|e| err!(e, // fixed: loopback, RFC 8252 |
| 407 | "The sign-in's listener cannot be bound to 127.0.0.1:{}.", port; IO, Network, Init))); |
| 408 | let port = res!(listener.local_addr()).port(); |
| 409 | Ok(Self { listener, port }) |
| 410 | } |
| 411 | |
| 412 | /// Where the authorisation server sends the browser back. |
| 413 | pub fn redirect(&self) -> String { |
| 414 | fmt!("http://127.0.0.1:{}/callback", self.port) |
| 415 | } |
| 416 | |
| 417 | /// A short address that sends the browser on to the sign-in. |
| 418 | pub fn link(&self) -> String { |
| 419 | fmt!("http://127.0.0.1:{}/", self.port) |
| 420 | } |
| 421 | |
| 422 | /// Serves `link()` as a redirect to `authorize` until the browser comes back with the code for `state`, |
| 423 | /// or `wait` has passed. A callback for another state is answered and passed over; a refusal ends it. |
| 424 | pub async fn code(&self, authorize: &str, state: &str, done: &str, wait: Duration) -> Outcome<String> { |
| 425 | let end = Instant::now() + wait; |
| 426 | loop { |
| 427 | let left = end.saturating_duration_since(Instant::now()); |
| 428 | let mut c = match tokio::time::timeout(left, self.listener.accept()).await { |
| 429 | Ok(Ok((c, _))) => c, |
| 430 | Ok(Err(e)) => return Err(err!(e, "The sign-in's listener failed."; IO, Network)), |
| 431 | Err(_) => return Err(err!("No sign-in came back within {} s.", wait.as_secs(); Timeout)), |
| 432 | }; |
| 433 | let target = match tokio::time::timeout(left, head(&mut c)).await { |
| 434 | Ok(Some(t)) => t, |
| 435 | _ => continue, |
| 436 | }; |
| 437 | let (path, query) = target.split_once('?').unwrap_or((target.as_str(), "")); |
| 438 | let (said, back) = match path { |
| 439 | "/" => { |
| 440 | let _ = c.write_all(fmt!("HTTP/1.1 302 Found\r\nLocation: {}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", |
| 441 | authorize).as_bytes()).await; |
| 442 | continue; |
| 443 | }, |
| 444 | "/callback" => callback(query), |
| 445 | _ => { |
| 446 | let _ = c.write_all(page(404, "Not Found", "Nothing is here.").as_bytes()).await; |
| 447 | continue; |
| 448 | }, |
| 449 | }; |
| 450 | if said != state { |
| 451 | let _ = c.write_all(page(400, "Bad Request", "This is not the sign-in asked for.").as_bytes()).await; |
| 452 | continue; |
| 453 | } |
| 454 | match back { |
| 455 | Back::Refused(why) => { |
| 456 | let _ = c.write_all(page(200, "OK", &why).as_bytes()).await; |
| 457 | return Err(err!("{}", why; Unauthorised)); |
| 458 | }, |
| 459 | Back::Bare => { |
| 460 | let _ = c.write_all(page(400, "Bad Request", "The sign-in came back with no code.").as_bytes()).await; |
| 461 | continue; |
| 462 | }, |
| 463 | Back::Code(code) => { |
| 464 | let _ = c.write_all(page(200, "OK", done).as_bytes()).await; |
| 465 | return Ok(code); |
| 466 | }, |
| 467 | } |
| 468 | } |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | /// What a browser brings back to a redirect, read by `callback`. |
| 473 | pub enum Back { |
| 474 | Code(String), // the code, to be exchanged with the verifier of the state it came back with |
| 475 | Refused(String), // the server's refusal, as its error and error_description say it |
| 476 | Bare, // neither |
| 477 | } |
| 478 | |
| 479 | impl fmt::Debug for Back { |
| 480 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 481 | match self { |
| 482 | Self::Code(_) => write!(f, "Code(..)"), |
| 483 | Self::Refused(why) => write!(f, "Refused({:?})", why), |
| 484 | Self::Bare => write!(f, "Bare"), |
| 485 | } |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | /// The query of a redirect's callback, with or without its `?`, read: the state it answers and what it brings. |
| 490 | /// A redirect served by another program (a page that hands the query on) reads it here, as `Loopback` does. |
| 491 | pub fn callback(query: &str) -> (String, Back) { |
| 492 | let got = pct::form(query.trim_start_matches('?').as_bytes()).unwrap_or_default(); |
| 493 | let said = |k: &str| got.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone()).unwrap_or_default(); |
| 494 | let back = match (said("error"), said("code")) { |
| 495 | (e, _) if !e.is_empty() => Back::Refused(fmt!("The sign-in was refused: {}{}", cap(&e), |
| 496 | match said("error_description") { |
| 497 | d if d.is_empty() => String::new(), |
| 498 | d => fmt!(", {}", cap(&d)), |
| 499 | })), |
| 500 | (_, c) if c.is_empty() => Back::Bare, |
| 501 | (_, c) => Back::Code(c), |
| 502 | }; |
| 503 | (said("state"), back) |
| 504 | } |
| 505 | |
| 506 | // A request head's target, if the head is a GET within HEAD_MAX. |
| 507 | async fn head(c: &mut TcpStream) -> Option<String> { |
| 508 | let (mut got, mut buf) = (Vec::new(), [0u8; 1024]); |
| 509 | while !got.windows(4).any(|w| w == b"\r\n\r\n") { |
| 510 | match c.read(&mut buf).await { |
| 511 | Ok(n) if n > 0 && got.len() + n <= HEAD_MAX => got.extend_from_slice(&buf[..n]), |
| 512 | _ => return None, |
| 513 | } |
| 514 | } |
| 515 | let line = String::from_utf8_lossy(&got).lines().next().unwrap_or("").to_string(); |
| 516 | let mut w = line.split(' '); |
| 517 | match (w.next(), w.next()) { |
| 518 | (Some("GET"), Some(t)) => Some(t.to_string()), |
| 519 | _ => None, |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | fn page(code: u16, reason: &str, text: &str) -> String { |
| 524 | let esc: String = text.chars().map(|c| match c { |
| 525 | '<' => "<".to_string(), |
| 526 | '>' => ">".to_string(), |
| 527 | '&' => "&".to_string(), |
| 528 | c => c.to_string(), |
| 529 | }).collect(); |
| 530 | let body = fmt!("<!doctype html><meta charset=\"utf-8\"><title>Sign-in</title><p>{}</p>\n", esc); |
| 531 | fmt!("HTTP/1.1 {} {}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", |
| 532 | code, reason, body.len(), body) |
| 533 | } |
| 534 | |
| 535 | async fn call(u: &Url, method: HttpMethod, headers: &[(&str, &str)], body: &[u8], b: &Bounds) -> Outcome<HttpMessage> { |
| 536 | let limits = ReadLimits { max_body_bytes: Some(b.body_max), ..Default::default() }; |
| 537 | url_request(u, method, &u.target, headers, body, b.tls.clone(), Some(&limits), b.wait).await |
| 538 | } |
| 539 | |
| 540 | // A metadata document, none where there is none at that place. |
| 541 | async fn get_json(at: &str, b: &Bounds) -> Outcome<Option<Dat>> { |
| 542 | let u = res!(Url::parse(at)); |
| 543 | let r = res!(call(&u, HttpMethod::GET, &[("Accept", "application/json")], &[], b).await); |
| 544 | Ok(match status(&r) { |
| 545 | 200 => json_of(&r), |
| 546 | _ => None, |
| 547 | }) |
| 548 | } |
| 549 | |
| 550 | fn status(r: &HttpMessage) -> u16 { |
| 551 | match &r.header.headline { |
| 552 | HttpHeadline::Response { status } => status.clone() as u16, |
| 553 | _ => 0, |
| 554 | } |
| 555 | } |
| 556 | |
| 557 | fn json_of(r: &HttpMessage) -> Option<Dat> { |
| 558 | match std::str::from_utf8(&r.body).ok().map(|t| Dat::decode_json_strict(t.trim(), &DecodeLimits::default())) { |
| 559 | Some(Ok(m @ Dat::Map(_))) => Some(m), |
| 560 | _ => None, |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | // A server's refusal in its own two fields, capped; never the rest of its body. |
| 565 | fn refusal(m: Option<&Dat>) -> String { |
| 566 | match m.map(|m| (txt(m, "error"), txt(m, "error_description"))) { |
| 567 | Some((e, _)) if e.is_empty() => String::new(), |
| 568 | Some((e, d)) if d.is_empty() => fmt!(": {}", cap(&e)), |
| 569 | Some((e, d)) => fmt!(": {}, {}", cap(&e), cap(&d)), |
| 570 | None => String::new(), |
| 571 | } |
| 572 | } |
| 573 | |
| 574 | fn cap(s: &str) -> String { |
| 575 | s.chars().filter(|c| !c.is_control()).take(SAID_MAX).collect() |
| 576 | } |
| 577 | |
| 578 | fn txt(m: &Dat, k: &str) -> String { |
| 579 | m.map_get(&dat!(k)).ok().flatten().and_then(|d| d.get_string()).unwrap_or_default() |
| 580 | } |
| 581 | |
| 582 | fn form(q: &[(&str, &str)]) -> String { |
| 583 | q.iter().map(|(k, v)| fmt!("{}={}", k, pct::encode_component(v))).collect::<Vec<_>>().join("&") |
| 584 | } |
| 585 | |
| 586 | /// A URL's scheme, host and port, as its `Display` writes them. |
| 587 | pub fn origin(u: &Url) -> String { |
| 588 | match u.port == u.scheme.default_port() { |
| 589 | true => fmt!("{}://{}", u.scheme, u.host), |
| 590 | false => fmt!("{}://{}:{}", u.scheme, u.host, u.port), |
| 591 | } |
| 592 | } |