1use crate::*;
2use base64::{
3 Engine,
4 engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
5};
6use openssl::{hash::MessageDigest, pkey::PKey, rsa::Rsa, sign::Signer};
7use rusqlite::{Connection, OptionalExtension, params as sql};
8use sha2::{Digest, Sha256};
9
10const SCOPES: &[&str] = &["openid", "profile", "email", "groups", "offline_access"];
11const ACCESS_TTL: i64 = 300;
12
13pub fn initialise(db: &Connection) -> Result<()> {
14 db.execute_batch("CREATE TABLE IF NOT EXISTS oidc_clients (id TEXT PRIMARY KEY, secret_hash TEXT NOT NULL, config TEXT NOT NULL);
15 CREATE TABLE IF NOT EXISTS oidc_key (id INTEGER PRIMARY KEY CHECK(id=1), pem TEXT NOT NULL);
16 CREATE TABLE IF NOT EXISTS oidc_tokens (hash TEXT PRIMARY KEY,kind TEXT NOT NULL,user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,client_id TEXT NOT NULL REFERENCES oidc_clients(id) ON DELETE CASCADE,session_hash TEXT NOT NULL REFERENCES sessions(hash) ON DELETE CASCADE,expires INTEGER NOT NULL,family TEXT NOT NULL,scope TEXT NOT NULL,auth_time INTEGER NOT NULL);
17 CREATE INDEX IF NOT EXISTS oidc_token_family ON oidc_tokens(family);")?;
18 let exists: bool = db.query_row("SELECT EXISTS(SELECT 1 FROM oidc_key)", [], |r| r.get(0))?;
19 if !exists {
20 let pem = PKey::from_rsa(Rsa::generate(2048)?)?.private_key_to_pem_pkcs8()?;
21 db.execute(
22 "INSERT OR IGNORE INTO oidc_key VALUES (1,?)",
23 [String::from_utf8(pem)?],
24 )?;
25 }
26 Ok(())
27}
28
29fn invalid(code: &str) -> Error {
30 Error::new(400, code)
31}
32fn fields(value: &str) -> Result<HashMap<String, String>> {
33 let mut fields = HashMap::new();
34 for (name, value) in url::form_urlencoded::parse(value.as_bytes()) {
35 if fields
36 .insert(name.into_owned(), value.into_owned())
37 .is_some()
38 {
39 return Err(invalid("invalid_request"));
40 }
41 }
42 Ok(fields)
43}
44fn client(db: &Connection, id: &str) -> Result<Value> {
45 let value: Option<String> = db
46 .query_row("SELECT config FROM oidc_clients WHERE id=?", [id], |r| {
47 r.get(0)
48 })
49 .optional()?;
50 value
51 .map(|s| serde_json::from_str(&s).map_err(Error::from))
52 .transpose()?
53 .ok_or_else(|| invalid("invalid_client"))
54}
55
56fn guest_client(id: &str) -> bool {
57 id == "shale" || id == "shale-dev" || id.starts_with("shale-preview-")
58}
59
60fn guests_allowed(id: &str, config: &Value) -> bool {
61 config["allowGuests"] == true && guest_client(id)
62}
63
64pub(crate) fn sign_in_target(auth: &auth::Store, next: &str) -> Result<(url::Url, Value)> {
65 if next.len() > 8192 || next.contains('\\') || next.chars().any(char::is_control) {
66 return Err(invalid("invalid_request"));
67 }
68 let target = auth
69 .origin
70 .join(next)
71 .map_err(|_| invalid("invalid_request"))?;
72 if target.origin() != auth.origin.origin()
73 || target.path() != "/auth/oidc/authorize"
74 || target.fragment().is_some()
75 || !target.username().is_empty()
76 || target.password().is_some()
77 {
78 return Err(invalid("invalid_request"));
79 }
80 let query = fields(target.query().unwrap_or_default())?;
81 let id = query
82 .get("client_id")
83 .map(String::as_str)
84 .unwrap_or_default();
85 let config = client(&auth.db.lock().unwrap(), id)?;
86 if query.get("response_type").map(String::as_str) != Some("code")
87 || !array(&config["redirectUris"])
88 .iter()
89 .any(|v| v.as_str() == query.get("redirect_uri").map(String::as_str))
90 {
91 return Err(invalid("access_denied"));
92 }
93 Ok((target, config))
94}
95
96pub(crate) fn guest_target(auth: &auth::Store, next: &str) -> Result<String> {
97 let (target, config) = sign_in_target(auth, next)?;
98 let query = fields(target.query().unwrap_or_default())?;
99 if !guests_allowed(
100 query
101 .get("client_id")
102 .map(String::as_str)
103 .unwrap_or_default(),
104 &config,
105 ) {
106 return Err(invalid("access_denied"));
107 }
108 Ok(format!(
109 "{}?{}",
110 target.path(),
111 target.query().unwrap_or_default()
112 ))
113}
114
115pub fn username(auth: &auth::Store, user_id: &str, client_id: &str) -> Result<String> {
116 let db = auth.db.lock().unwrap();
117 let user = auth::user(&db, user_id)?;
118 if user["enabled"] != true {
119 return Err(Error::new(403, "This account is disabled."));
120 }
121 let config = client(&db, client_id)?;
122 let username = string(&user["username"]);
123 Ok(config["usernameAliases"][username]
124 .as_str()
125 .unwrap_or(username)
126 .to_owned())
127}
128
129/// Only the root-owned deployment CLI can register first-party clients.
130pub fn provision(auth: &auth::Store, input: Value) -> Result<Value> {
131 let request = &input["request"];
132 let id = string(&request["clientId"]);
133 let stage = string(&input["stageId"]);
134 if id.is_empty() || id.len() > 128 || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
135 {
136 return Err(invalid("invalid_client"));
137 }
138 let mut db = auth.db.lock().unwrap();
139 let tx = db.transaction()?;
140 if input["operation"] == "delete" {
141 if stage.is_empty() || id != stage {
142 return Err(invalid("invalid_client"));
143 }
144 tx.execute("DELETE FROM oidc_clients WHERE id=?", [id])?;
145 tx.commit()?;
146 return Ok(json!({}));
147 }
148 let redirects = array(&request["redirectUris"]);
149 if redirects.is_empty() || redirects.len() > 64 {
150 return Err(invalid("invalid_redirect_uri"));
151 }
152 for value in redirects {
153 let value = value
154 .as_str()
155 .ok_or_else(|| invalid("invalid_redirect_uri"))?;
156 let uri = url::Url::parse(value).map_err(|_| invalid("invalid_redirect_uri"))?;
157 let site = auth
158 .origin
159 .host_str()
160 .unwrap()
161 .strip_prefix("snowglobe.")
162 .unwrap_or_default();
163 let host = uri.host_str().unwrap_or_default();
164 let allowed = match uri.scheme() {
165 "https" => !site.is_empty() && host.ends_with(&format!(".{site}")),
166 "http" => host.ends_with(".localhost"),
167 _ => false,
168 };
169 if !allowed
170 || !uri.username().is_empty()
171 || uri.password().is_some()
172 || uri.fragment().is_some()
173 || value.contains('*')
174 {
175 return Err(invalid("invalid_redirect_uri"));
176 }
177 }
178 if !stage.is_empty()
179 && (id != stage
180 || redirects.iter().any(|v| {
181 url::Url::parse(string(v))
182 .ok()
183 .and_then(|u| u.host_str().map(str::to_owned))
184 .is_none_or(|h| !h.starts_with(&format!("{stage}.")))
185 }))
186 {
187 return Err(invalid("invalid_redirect_uri"));
188 }
189 let aliases = request["usernameAliases"]
190 .as_object()
191 .cloned()
192 .unwrap_or_default();
193 let mut unique = std::collections::HashSet::new();
194 for (name, alias) in &aliases {
195 let alias = alias
196 .as_str()
197 .filter(|a| !a.is_empty())
198 .ok_or_else(|| invalid("invalid_alias"))?;
199 let matches: i64 =
200 tx.query_row("SELECT count(*) FROM users WHERE username=?", [name], |r| {
201 r.get(0)
202 })?;
203 if matches != 1 || !unique.insert(alias) {
204 return Err(invalid("invalid_alias"));
205 }
206 }
207 let previous = &input["existing"];
208 if previous["clientId"].as_str().is_some_and(|old| old != id) {
209 return Err(invalid("invalid_client"));
210 }
211 let secret = previous["clientSecret"]
212 .as_str()
213 .filter(|s| s.len() >= 24)
214 .map(str::to_owned)
215 .unwrap_or_else(mcp::secret);
216 let allow_guests = request["allowGuests"] == true;
217 if allow_guests
218 && (!guest_client(id)
219 || redirects.iter().any(|v| {
220 url::Url::parse(string(v)).is_ok_and(|u| {
221 let site = auth
222 .origin
223 .host_str()
224 .unwrap()
225 .strip_prefix("snowglobe.")
226 .unwrap_or_default();
227 let host = if id == "shale-dev" {
228 "git1.localhost".to_owned()
229 } else {
230 format!("{id}.{site}")
231 };
232 u.path() != "/-/callback"
233 || u.host_str() != Some(host.as_str())
234 || u.query().is_some()
235 })
236 }))
237 {
238 return Err(invalid("access_denied"));
239 }
240 let config = json!({"name":request["name"], "redirectUris":redirects, "usernameAliases":aliases, "allowGuests":allow_guests, "usernameRequired":request["usernameRequired"]==true});
241 let old: Option<(String, String)> = tx
242 .query_row(
243 "SELECT secret_hash,config FROM oidc_clients WHERE id=?",
244 [id],
245 |r| Ok((r.get(0)?, r.get(1)?)),
246 )
247 .optional()?;
248 if old
249 .as_ref()
250 .is_some_and(|old| old != &(mcp::hash(&secret), config.to_string()))
251 {
252 tx.execute("DELETE FROM oidc_tokens WHERE client_id=?", [id])?;
253 tx.execute(
254 "DELETE FROM pending WHERE kind='oidc-code' AND json_extract(data,'$.client')=?",
255 [id],
256 )?;
257 }
258 tx.execute("INSERT INTO oidc_clients VALUES (?,?,?) ON CONFLICT(id) DO UPDATE SET secret_hash=excluded.secret_hash,config=excluded.config", sql![id,mcp::hash(&secret),config.to_string()])?;
259 tx.commit()?;
260 Ok(
261 json!({"clientId":id,"clientSecret":secret,"issuerUrl":auth.origin.origin().ascii_serialization()}),
262 )
263}
264
265fn public_key(db: &Connection) -> Result<(PKey<openssl::pkey::Private>, String)> {
266 let pem: String = db.query_row("SELECT pem FROM oidc_key WHERE id=1", [], |r| r.get(0))?;
267 let key = PKey::private_key_from_pem(pem.as_bytes())?;
268 let kid = URL_SAFE_NO_PAD.encode(Sha256::digest(key.public_key_to_der()?));
269 Ok((key, kid))
270}
271fn jwt(db: &Connection, claims: &Value) -> Result<String> {
272 let (key, kid) = public_key(db)?;
273 let data = format!(
274 "{}.{}",
275 URL_SAFE_NO_PAD.encode(serde_json::to_vec(
276 &json!({"alg":"RS256","typ":"JWT","kid":kid})
277 )?),
278 URL_SAFE_NO_PAD.encode(serde_json::to_vec(claims)?)
279 );
280 let mut signer = Signer::new(MessageDigest::sha256(), &key)?;
281 signer.update(data.as_bytes())?;
282 Ok(format!(
283 "{data}.{}",
284 URL_SAFE_NO_PAD.encode(signer.sign_to_vec()?)
285 ))
286}
287fn claims(user: &Value, config: &Value, scopes: &str) -> Value {
288 let mut value = json!({"sub":user["id"]});
289 let scopes: Vec<_> = scopes.split_whitespace().collect();
290 // Shale requests only openid but needs a stable username to bind its account.
291 if scopes.contains(&"profile") || config["usernameRequired"] == true {
292 let username = string(&user["username"]);
293 value["preferred_username"] = config["usernameAliases"][username]
294 .as_str()
295 .map(|v| json!(v))
296 .unwrap_or_else(|| json!(username));
297 }
298 if scopes.contains(&"profile") {
299 let name = format!(
300 "{} {}",
301 string(&user["firstName"]),
302 string(&user["lastName"])
303 );
304 if !name.trim().is_empty() {
305 value["name"] = json!(name.trim());
306 }
307 for (claim, field) in [("given_name", "firstName"), ("family_name", "lastName")] {
308 if !string(&user[field]).is_empty() {
309 value[claim] = user[field].clone();
310 }
311 }
312 }
313 if scopes.contains(&"email") && !string(&user["email"]).is_empty() {
314 value["email"] = user["email"].clone();
315 value["email_verified"] = json!(user["emailVerified"] == true);
316 }
317 if scopes.contains(&"groups") {
318 value["groups"] = json!(
319 array(&user["groups"])
320 .iter()
321 .map(|g| format!("role:{}", string(&g["name"])))
322 .collect::<Vec<_>>()
323 );
324 }
325 value
326}
327fn eligible(db: &Connection, user_id: &str, session: &str) -> Result<Value> {
328 let valid: bool = db.query_row("SELECT EXISTS(SELECT 1 FROM sessions WHERE hash=? AND user_id=? AND client='dashboard' AND expires>?)",sql![session,user_id,now() as i64],|r|r.get(0))?;
329 let user = auth::user(db, user_id).map_err(|_| invalid("invalid_grant"))?;
330 if !valid || user["enabled"] != true || !array(&user["requiredActions"]).is_empty() {
331 return Err(invalid("invalid_grant"));
332 }
333 Ok(user)
334}
335fn authenticated_client(
336 db: &Connection,
337 headers: &HeaderMap,
338 form: &HashMap<String, String>,
339) -> Result<String> {
340 let (id, secret) = if let Some(header) = headers.get("authorization") {
341 let header = header
342 .to_str()
343 .ok()
344 .and_then(|h| h.strip_prefix("Basic "))
345 .ok_or_else(|| invalid("invalid_client"))?;
346 let raw = String::from_utf8(
347 STANDARD
348 .decode(header)
349 .map_err(|_| invalid("invalid_client"))?,
350 )
351 .map_err(|_| invalid("invalid_client"))?;
352 let (id, secret) = raw
353 .split_once(':')
354 .ok_or_else(|| invalid("invalid_client"))?;
355 let decode = |s: &str| -> String {
356 url::form_urlencoded::parse(format!("x={s}").as_bytes())
357 .next()
358 .unwrap()
359 .1
360 .into_owned()
361 };
362 let (id, secret) = (decode(id), decode(secret));
363 // Shale repeats Basic credentials in its form; require the same secret.
364 if form.get("client_secret").is_some_and(|supplied| {
365 !(id == "shale" || id.starts_with("shale-preview-"))
366 || mcp::hash(supplied) != mcp::hash(&secret)
367 }) {
368 return Err(invalid("invalid_request"));
369 }
370 (id, secret)
371 } else {
372 (
373 form.get("client_id").cloned().unwrap_or_default(),
374 form.get("client_secret").cloned().unwrap_or_default(),
375 )
376 };
377 if secret.is_empty()
378 || form
379 .get("client_id")
380 .is_some_and(|supplied| supplied != &id)
381 {
382 return Err(invalid("invalid_client"));
383 }
384 let stored: Option<String> = db
385 .query_row(
386 "SELECT secret_hash FROM oidc_clients WHERE id=?",
387 [&id],
388 |r| r.get(0),
389 )
390 .optional()?;
391 if stored.is_none_or(|s| !bool::from(s.as_bytes().ct_eq(mcp::hash(&secret).as_bytes()))) {
392 return Err(invalid("invalid_client"));
393 }
394 Ok(id)
395}
396fn tokens(db: &Connection, auth: &auth::Store, data: &Value, nonce: Option<&str>) -> Result<Value> {
397 let user = eligible(db, string(&data["user"]), string(&data["session"]))?;
398 let config = client(db, string(&data["client"]))?;
399 if guest::is_guest(&user) && !guests_allowed(string(&data["client"]), &config) {
400 return Err(invalid("access_denied"));
401 }
402 let scope = string(&data["scope"]);
403 let access = mcp::secret();
404 let family = string(&data["family"]);
405 let issued = now() as i64;
406 let mut value = claims(&user, &config, scope);
407 value["iss"] = json!(auth.origin.origin().ascii_serialization());
408 value["aud"] = data["client"].clone();
409 value["iat"] = json!(issued);
410 value["exp"] = json!(issued + ACCESS_TTL);
411 value["auth_time"] = data["auth_time"].clone();
412 value["at_hash"] = json!(URL_SAFE_NO_PAD.encode(&Sha256::digest(access.as_bytes())[..16]));
413 if let Some(nonce) = nonce {
414 value["nonce"] = json!(nonce);
415 }
416 let id_token = jwt(db, &value)?;
417 let mut output = json!({"access_token":access,"token_type":"Bearer","expires_in":ACCESS_TTL,"id_token":id_token,"scope":scope});
418 for (kind, token, expires) in [
419 ("access", access, issued + ACCESS_TTL),
420 ("refresh", mcp::secret(), issued + 30 * 86400),
421 ] {
422 db.execute(
423 "INSERT INTO oidc_tokens VALUES (?,?,?,?,?,?,?,?,?)",
424 sql![
425 mcp::hash(&token),
426 kind,
427 string(&data["user"]),
428 string(&data["client"]),
429 string(&data["session"]),
430 expires,
431 family,
432 scope,
433 data["auth_time"].as_i64().unwrap_or(issued)
434 ],
435 )?;
436 if kind == "refresh" {
437 output["refresh_token"] = json!(token);
438 }
439 }
440 Ok(output)
441}
442
443async fn handle(app: &App, request: Request) -> Result<Response> {
444 let auth = &app.auth;
445 let path = request.uri().path().to_owned();
446 let method = request.method().clone();
447 let headers = request.headers().clone();
448 let query = fields(request.uri().query().unwrap_or_default())?;
449 let issuer = auth.origin.origin().ascii_serialization();
450 if path == "/.well-known/openid-configuration" && method == Method::GET {
451 return Ok(axum::Json(json!({"issuer":issuer,"authorization_endpoint":format!("{issuer}/auth/oidc/authorize"),"token_endpoint":format!("{issuer}/auth/oidc/token"),"userinfo_endpoint":format!("{issuer}/auth/oidc/userinfo"),"jwks_uri":format!("{issuer}/auth/oidc/jwks"),"revocation_endpoint":format!("{issuer}/auth/oidc/revoke"),"response_types_supported":["code"],"response_modes_supported":["query"],"grant_types_supported":["authorization_code","refresh_token"],"subject_types_supported":["public"],"id_token_signing_alg_values_supported":["RS256"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post"],"code_challenge_methods_supported":["S256"],"scopes_supported":SCOPES,"claims_supported":["sub","preferred_username","name","given_name","family_name","email","email_verified","groups","auth_time","nonce"]})).into_response());
452 }
453 if path == "/auth/oidc/jwks" && method == Method::GET {
454 let (key, kid) = public_key(&auth.db.lock().unwrap())?;
455 let rsa = key.rsa()?;
456 return Ok(axum::Json(json!({"keys":[{"kty":"RSA","use":"sig","alg":"RS256","kid":kid,"n":URL_SAFE_NO_PAD.encode(rsa.n().to_vec()),"e":URL_SAFE_NO_PAD.encode(rsa.e().to_vec())}]})).into_response());
457 }
458 if path == "/auth/oidc/authorize" && method == Method::GET {
459 let id = query
460 .get("client_id")
461 .map(String::as_str)
462 .unwrap_or_default();
463 let redirect = query
464 .get("redirect_uri")
465 .map(String::as_str)
466 .unwrap_or_default();
467 let config = client(&auth.db.lock().unwrap(), id)?;
468 if !array(&config["redirectUris"])
469 .iter()
470 .any(|v| v.as_str() == Some(redirect))
471 {
472 return Err(invalid("invalid_redirect_uri"));
473 }
474 if query.get("response_type").map(String::as_str) != Some("code")
475 || query.get("response_mode").is_some_and(|m| m != "query")
476 {
477 return Err(invalid("unsupported_response_type"));
478 }
479 let scope = query.get("scope").map(String::as_str).unwrap_or_default();
480 if !scope.split_whitespace().any(|s| s == "openid")
481 || scope.split_whitespace().any(|s| !SCOPES.contains(&s))
482 {
483 return Err(invalid("invalid_scope"));
484 }
485 let challenge = query.get("code_challenge");
486 if challenge.is_some_and(|c| {
487 c.len() != 43
488 || !c
489 .chars()
490 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
491 }) || (challenge.is_some()
492 && query.get("code_challenge_method").map(String::as_str) != Some("S256"))
493 || (challenge.is_none() && query.contains_key("code_challenge_method"))
494 {
495 return Err(invalid("invalid_request"));
496 }
497 if query.values().any(|v| v.len() > 4096) {
498 return Err(invalid("invalid_request"));
499 }
500 let prompt = query.get("prompt").map(String::as_str).unwrap_or_default();
501 if !matches!(prompt, "" | "none" | "login") {
502 return Err(invalid("invalid_request"));
503 }
504 let user = auth.session(&headers, "dashboard")?;
505 if guest::is_guest(&user) && !guests_allowed(id, &config) {
506 return Err(Error::new(403, "access_denied"));
507 }
508 let session = mcp::hash(&auth::cookie(&headers, "__Host-snow-session").unwrap_or_default());
509 let auth_time: i64 = auth
510 .db
511 .lock()
512 .unwrap()
513 .query_row(
514 "SELECT auth_time FROM sessions WHERE hash=?",
515 [&session],
516 |r| r.get(0),
517 )
518 .optional()?
519 .unwrap_or(0);
520 let max_age = query
521 .get("max_age")
522 .map(|n| {
523 n.parse::<i64>()
524 .ok()
525 .filter(|n| *n >= 0)
526 .ok_or_else(|| invalid("invalid_request"))
527 })
528 .transpose()?;
529 let reauth_token = query
530 .get("snow_reauth")
531 .map(String::as_str)
532 .unwrap_or_default();
533 let reauth_state =
534 auth::pending(&auth.db.lock().unwrap(), reauth_token, "oidc-reauth", false)?;
535 let reauthed = reauth_state["client"] == id
536 && reauth_state["redirect"] == redirect
537 && reauth_state["session"]
538 .as_str()
539 .is_some_and(|old| old != session);
540 let reauth = prompt == "login" && !reauthed
541 || max_age.is_some_and(|age| now() as i64 - auth_time > age);
542 let mut target = url::Url::parse(redirect)?;
543 if user.is_null() || reauth {
544 if prompt == "none" {
545 target
546 .query_pairs_mut()
547 .append_pair("error", "login_required");
548 if let Some(state) = query.get("state") {
549 target.query_pairs_mut().append_pair("state", state);
550 }
551 return Ok((StatusCode::FOUND, [("location", target.to_string())]).into_response());
552 }
553 let mut next = auth.origin.join(&request.uri().to_string())?;
554 if prompt == "login" {
555 let token = if reauth_state["client"] == id && reauth_state["redirect"] == redirect
556 {
557 reauth_token.to_owned()
558 } else {
559 auth::issue(
560 &auth.db.lock().unwrap(),
561 "oidc-reauth",
562 json!({"client":id,"redirect":redirect,"session":session}),
563 900,
564 )?
565 };
566 let pairs: Vec<_> = next
567 .query_pairs()
568 .filter(|(key, _)| key != "snow_reauth")
569 .map(|(k, v)| (k.into_owned(), v.into_owned()))
570 .collect();
571 next.set_query(None);
572 next.query_pairs_mut()
573 .extend_pairs(pairs)
574 .append_pair("snow_reauth", &token);
575 }
576 return Ok((
577 StatusCode::FOUND,
578 [(
579 "location",
580 format!(
581 "/sign-in?next={}",
582 encoded(&format!(
583 "{}?{}",
584 next.path(),
585 next.query().unwrap_or_default()
586 ))
587 ),
588 )],
589 )
590 .into_response());
591 }
592 if !array(&user["requiredActions"]).is_empty() {
593 return Ok((StatusCode::FOUND, [("location", "/account")]).into_response());
594 }
595 if reauthed {
596 auth::pending(&auth.db.lock().unwrap(), reauth_token, "oidc-reauth", true)?;
597 }
598 let data = json!({"user":user["id"],"client":id,"redirect":redirect,"scope":scope,"challenge":challenge,"nonce":query.get("nonce"),"session":session,"auth_time":auth_time,"family":mcp::secret()});
599 let code = auth::issue(&auth.db.lock().unwrap(), "oidc-code", data, 60)?;
600 target.query_pairs_mut().append_pair("code", &code);
601 if let Some(state) = query.get("state") {
602 target.query_pairs_mut().append_pair("state", state);
603 }
604 return Ok((StatusCode::FOUND, [("location", target.to_string())]).into_response());
605 }
606 if path == "/auth/oidc/userinfo" && matches!(method, Method::GET | Method::POST) {
607 let token = headers
608 .get("authorization")
609 .and_then(|h| h.to_str().ok())
610 .and_then(|h| h.strip_prefix("Bearer "))
611 .ok_or_else(|| Error::new(401, "invalid_token"))?;
612 let db = auth.db.lock().unwrap();
613 let data: Option<(String,String,String,String)> = db.query_row("SELECT user_id,client_id,session_hash,scope FROM oidc_tokens WHERE hash=? AND kind='access' AND expires>?",sql![mcp::hash(token),now() as i64],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?))).optional()?;
614 let (user, client_id, session, scope) =
615 data.ok_or_else(|| Error::new(401, "invalid_token"))?;
616 let profile =
617 eligible(&db, &user, &session).map_err(|_| Error::new(401, "invalid_token"))?;
618 let config = client(&db, &client_id)?;
619 if guest::is_guest(&profile) && !guests_allowed(&client_id, &config) {
620 return Err(Error::new(401, "invalid_token"));
621 }
622 return Ok(axum::Json(claims(&profile, &config, &scope)).into_response());
623 }
624 if method != Method::POST || !matches!(path.as_str(), "/auth/oidc/token" | "/auth/oidc/revoke")
625 {
626 return Err(Error::new(404, "not_found"));
627 }
628 if headers
629 .get("content-type")
630 .and_then(|h| h.to_str().ok())
631 .is_none_or(|t| t.split(';').next() != Some("application/x-www-form-urlencoded"))
632 {
633 return Err(invalid("invalid_request"));
634 }
635 let body = axum::body::to_bytes(request.into_body(), 16384).await?;
636 let form = fields(std::str::from_utf8(&body).map_err(|_| invalid("invalid_request"))?)?;
637 let mut db = auth.db.lock().unwrap();
638 let tx = db.transaction()?;
639 let id = authenticated_client(&tx, &headers, &form)?;
640 if path.ends_with("/revoke") {
641 tx.execute("DELETE FROM oidc_tokens WHERE client_id=? AND family=(SELECT family FROM oidc_tokens WHERE hash=? AND client_id=?)",sql![id,mcp::hash(form.get("token").map(String::as_str).unwrap_or_default()),id])?;
642 tx.commit()?;
643 return Ok(StatusCode::OK.into_response());
644 }
645 let grant = form
646 .get("grant_type")
647 .map(String::as_str)
648 .unwrap_or_default();
649 let data = if grant == "authorization_code" {
650 let code = form.get("code").map(String::as_str).unwrap_or_default();
651 let data = auth::pending(&tx, code, "oidc-code", false)?;
652 if data.is_null()
653 || data["client"] != id
654 || data["redirect"].as_str() != form.get("redirect_uri").map(String::as_str)
655 {
656 return Err(invalid("invalid_grant"));
657 }
658 if let Some(challenge) = data["challenge"].as_str() {
659 let verifier = form
660 .get("code_verifier")
661 .map(String::as_str)
662 .unwrap_or_default();
663 if !(43..=128).contains(&verifier.len())
664 || !verifier
665 .chars()
666 .all(|c| c.is_ascii_alphanumeric() || "-._~".contains(c))
667 || URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) != challenge
668 {
669 return Err(invalid("invalid_grant"));
670 }
671 }
672 auth::pending(&tx, code, "oidc-code", true)?;
673 data
674 } else if grant == "refresh_token" {
675 let hash = mcp::hash(
676 form.get("refresh_token")
677 .map(String::as_str)
678 .unwrap_or_default(),
679 );
680 let data: Option<(String,String,String,String,String,i64)> = tx.query_row("SELECT kind,user_id,session_hash,family,scope,auth_time FROM oidc_tokens WHERE hash=? AND client_id=? AND expires>?",sql![hash,id,now() as i64],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?))).optional()?;
681 let (kind, user, session, family, scope, auth_time) =
682 data.ok_or_else(|| invalid("invalid_grant"))?;
683 if kind == "refresh-used" {
684 tx.execute("DELETE FROM oidc_tokens WHERE family=?", [family])?;
685 tx.commit()?;
686 return Err(invalid("invalid_grant"));
687 }
688 if kind != "refresh" || form.get("scope").is_some_and(|s| s != &scope) {
689 return Err(invalid("invalid_grant"));
690 }
691 tx.execute(
692 "UPDATE oidc_tokens SET kind='refresh-used' WHERE hash=?",
693 [hash],
694 )?;
695 tx.execute(
696 "DELETE FROM oidc_tokens WHERE family=? AND kind='access'",
697 [&family],
698 )?;
699 json!({"user":user,"client":id,"session":session,"family":family,"scope":scope,"auth_time":auth_time})
700 } else {
701 return Err(invalid("unsupported_grant_type"));
702 };
703 tx.execute("DELETE FROM oidc_tokens WHERE expires<=?", [now() as i64])?;
704 let output = tokens(&tx, auth, &data, data["nonce"].as_str())?;
705 tx.commit()?;
706 Ok(axum::Json(output).into_response())
707}
708
709pub async fn route(State(app): State<Arc<App>>, request: Request) -> Response {
710 let mut response = match handle(&app, request).await {
711 Ok(response) => response,
712 Err(error) => {
713 if error.status >= 500 {
714 eprintln!("OIDC: {}", error.message);
715 }
716 (
717 StatusCode::from_u16(error.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
718 axum::Json(
719 json!({"error":if error.status>=500 {"server_error"} else {&error.message}}),
720 ),
721 )
722 .into_response()
723 }
724 };
725 response
726 .headers_mut()
727 .insert("cache-control", "no-store".parse().unwrap());
728 response
729 .headers_mut()
730 .insert("pragma", "no-cache".parse().unwrap());
731 response
732}