1use crate::*;
2use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
3use openssl::{
4 bn::{BigNum, BigNumContext},
5 ec::{EcGroup, EcKey, EcPoint},
6 ecdsa::EcdsaSig,
7 hash::MessageDigest,
8 nid::Nid,
9 pkey::PKey,
10 sign::Verifier,
11};
12use rusqlite::{Connection, OptionalExtension, params as sql};
13use sha2::{Digest, Sha256};
14
15const COOKIE: &str = "__Host-snow-guest";
16const ASTHENO: &str = "https://identity.astheno.software";
17
18pub fn is_guest(user: &Value) -> bool {
19 user["kind"] == "guest"
20}
21
22pub fn initialise(db: &Connection) -> Result<()> {
23 db.execute_batch("CREATE TABLE IF NOT EXISTS guest_providers (id TEXT PRIMARY KEY, client_id TEXT NOT NULL, secret TEXT NOT NULL);
24 CREATE TABLE IF NOT EXISTS external_identities (provider TEXT NOT NULL, subject TEXT NOT NULL, user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, PRIMARY KEY(provider,subject), UNIQUE(user_id));
25 DROP TRIGGER IF EXISTS guest_no_groups;
26 CREATE TRIGGER guest_no_groups BEFORE INSERT ON memberships WHEN (SELECT json_extract(profile,'$.kind') FROM users WHERE id=NEW.user_id)='guest' BEGIN SELECT RAISE(ABORT,'guest accounts cannot join groups'); END;
27 DROP TRIGGER IF EXISTS guest_no_group_updates;
28 CREATE TRIGGER IF NOT EXISTS guest_no_credentials BEFORE INSERT ON credentials WHEN (SELECT json_extract(profile,'$.kind') FROM users WHERE id=NEW.user_id)='guest' BEGIN SELECT RAISE(ABORT,'guest accounts use external sign-in'); END;
29 CREATE TRIGGER IF NOT EXISTS guest_kind_fixed BEFORE UPDATE OF profile ON users WHEN json_extract(OLD.profile,'$.kind')='guest' AND coalesce(json_extract(NEW.profile,'$.kind'),'')!='guest' BEGIN SELECT RAISE(ABORT,'guest account kind is fixed'); END;")?;
30 Ok(())
31}
32
33fn known(provider: &str) -> Result<&str> {
34 match provider {
35 "github" => Ok("GitHub"),
36 "astheno" => Ok("Astheno"),
37 "atproto" => Ok("AT / tangled / bsky"),
38 _ => Err(Error::new(
39 404,
40 "Choose a provider on the Shale sign-in page.",
41 )),
42 }
43}
44
45/// Root-owned CLI only. Secrets stay in the private accounts database and its backups.
46pub fn provision(auth: &auth::Store, input: Value) -> Result<Value> {
47 let provider = string(&input["provider"]);
48 known(provider)?;
49 if provider == "atproto" {
50 return Err(Error::new(
51 400,
52 "AT Protocol uses public client metadata; no client secret is needed.",
53 ));
54 }
55 let mut db = auth.db.lock().unwrap();
56 let tx = db.transaction()?;
57 tx.execute(
58 "DELETE FROM pending WHERE kind='guest' AND json_extract(data,'$.provider')=?",
59 [provider],
60 )?;
61 tx.execute("DELETE FROM sessions WHERE user_id IN (SELECT user_id FROM external_identities WHERE provider=?)", [provider])?;
62 if input["enabled"] == false {
63 tx.execute("DELETE FROM guest_providers WHERE id=?", [provider])?;
64 } else {
65 let id = string(&input["clientId"]);
66 let secret = string(&input["clientSecret"]);
67 if id.is_empty()
68 || id.len() > 256
69 || secret.len() < 16
70 || secret.len() > 2048
71 || id.chars().chain(secret.chars()).any(char::is_control)
72 {
73 return Err(Error::new(
74 400,
75 "Provide the registered client ID and secret.",
76 ));
77 }
78 tx.execute("INSERT INTO guest_providers VALUES (?,?,?) ON CONFLICT(id) DO UPDATE SET client_id=excluded.client_id,secret=excluded.secret", sql![provider,id,secret])?;
79 }
80 tx.commit()?;
81 Ok(
82 json!({"provider":provider,"enabled":input["enabled"]!=false,"callback":format!("{}auth/guest/callback/{provider}",auth.origin)}),
83 )
84}
85
86pub fn providers(auth: &auth::Store, next: &str) -> Result<Value> {
87 let shale = oidc::guest_target(auth, next).is_ok();
88 let db = auth.db.lock().unwrap();
89 let mut query =
90 db.prepare("SELECT id FROM guest_providers WHERE ?1 OR id='astheno' ORDER BY id")?;
91 let mut ids = query
92 .query_map([shale], |r| r.get::<_, String>(0))?
93 .collect::<std::result::Result<Vec<_>, _>>()?;
94 if shale {
95 ids.push("atproto".into());
96 }
97 Ok(json!(
98 ids.iter()
99 .map(|id| json!({"id":id,"name":known(id).unwrap_or(id)}))
100 .collect::<Vec<_>>()
101 ))
102}
103
104fn registration(auth: &auth::Store, provider: &str) -> Result<(String, String)> {
105 auth.db.lock().unwrap().query_row("SELECT client_id,secret FROM guest_providers WHERE id=?", [provider], |r|Ok((r.get(0)?,r.get(1)?)))
106 .optional()?.ok_or_else(|| Error::new(503, "This sign-in provider isn't available. Use your Snow Globe account or try again later."))
107}
108
109/// Shale takes any provider and mints guests; everywhere else only linked Astheno accounts get in.
110fn destination(auth: &auth::Store, provider: &str, next: &str) -> Result<(String, bool)> {
111 match oidc::guest_target(auth, next) {
112 Ok(next) => Ok((next, true)),
113 Err(_) if provider == "astheno" => Ok((next.to_owned(), false)),
114 Err(error) => Err(error),
115 }
116}
117
118async fn response_bytes(mut response: reqwest::Response) -> Result<Vec<u8>> {
119 let status = response.status();
120 let endpoint = format!(
121 "{}{}",
122 response.url().host_str().unwrap_or_default(),
123 response.url().path()
124 );
125 if response.content_length().is_some_and(|n| n > 65536) {
126 return Err(Error::new(
127 502,
128 "The provider couldn't complete sign-in. Return to Shale and try again.",
129 ));
130 }
131 let mut data = Vec::new();
132 while let Some(chunk) = response.chunk().await? {
133 if data.len() + chunk.len() > 65536 {
134 return Err(Error::new(
135 502,
136 "The provider couldn't complete sign-in. Return to Shale and try again.",
137 ));
138 }
139 data.extend_from_slice(&chunk);
140 }
141 if !status.is_success() {
142 let error: Value = serde_json::from_slice(&data).unwrap_or(Value::Null);
143 let code = string(&error["error_description"])
144 .split(':')
145 .next()
146 .unwrap_or_default();
147 let code = if code.starts_with('E')
148 && code.len() <= 8
149 && code[1..].bytes().all(|c| c.is_ascii_digit())
150 {
151 code
152 } else {
153 "unknown"
154 };
155 eprintln!("guest provider response: {endpoint} status {status} code {code}");
156 return Err(Error::new(
157 502,
158 "The provider couldn't complete sign-in. Return to Shale and try again.",
159 ));
160 }
161 Ok(data)
162}
163
164fn json_bytes(bytes: &[u8]) -> Result<Value> {
165 serde_json::from_slice(bytes).map_err(|_| {
166 Error::new(
167 502,
168 "The provider couldn't complete sign-in. Return to Shale and try again.",
169 )
170 })
171}
172
173/// Astheno signs ID tokens with P-256. Never trust claims before verifying the signature.
174fn signed_claims(
175 token: &str,
176 keys: &Value,
177 client: &str,
178 nonce: &str,
179 id_token: bool,
180) -> Result<Value> {
181 let reject = |reason: &str| {
182 eprintln!(
183 "guest token verification: {} {reason}",
184 if id_token { "id_token" } else { "userinfo" }
185 );
186 Error::new(
187 502,
188 "The provider couldn't verify your sign-in. Return to Shale and try again.",
189 )
190 };
191 if token.len() > 32768 {
192 return Err(reject("size"));
193 }
194 let parts: Vec<_> = token.split('.').collect();
195 if parts.len() != 3 {
196 return Err(reject("format"));
197 }
198 let header: Value = serde_json::from_slice(
199 &URL_SAFE_NO_PAD
200 .decode(parts[0])
201 .map_err(|_| reject("header_encoding"))?,
202 )
203 .map_err(|_| reject("header_json"))?;
204 if header
205 .get("kid")
206 .is_some_and(|id| id.as_str().is_none_or(str::is_empty))
207 || header["alg"] != "ES256"
208 || header.get("crit").is_some()
209 || header.get("jku").is_some()
210 || header.get("jwk").is_some()
211 {
212 return Err(reject("header"));
213 }
214 let matching: Vec<_> = array(&keys["keys"])
215 .iter()
216 .filter(|key| {
217 header
218 .get("kid")
219 .is_none_or(|id| key.get("kid") == Some(id))
220 && key["kty"] == "EC"
221 && key["crv"] == "P-256"
222 && key.get("alg").is_none_or(|v| v == "ES256")
223 && key.get("use").is_none_or(|v| v == "sig")
224 })
225 .collect();
226 if matching.len() != 1 {
227 return Err(reject("key_selection"));
228 }
229 let key = matching[0];
230 let x = URL_SAFE_NO_PAD
231 .decode(string(&key["x"]))
232 .map_err(|_| reject("key_x"))?;
233 let y = URL_SAFE_NO_PAD
234 .decode(string(&key["y"]))
235 .map_err(|_| reject("key_y"))?;
236 if x.len() != 32 || y.len() != 32 {
237 return Err(reject("key_coordinates"));
238 }
239 let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1)?;
240 let mut point = EcPoint::new(&group)?;
241 let x = BigNum::from_slice(&x)?;
242 let y = BigNum::from_slice(&y)?;
243 let mut context = BigNumContext::new()?;
244 point.set_affine_coordinates_gfp(&group, &x, &y, &mut context)?;
245 let ec = EcKey::from_public_key(&group, &point)?;
246 ec.check_key()?;
247 let key = PKey::from_ec_key(ec)?;
248 let raw = URL_SAFE_NO_PAD
249 .decode(parts[2])
250 .map_err(|_| reject("signature_encoding"))?;
251 if raw.len() != 64 {
252 return Err(reject("signature_length"));
253 }
254 let signature = EcdsaSig::from_private_components(
255 BigNum::from_slice(&raw[..32])?,
256 BigNum::from_slice(&raw[32..])?,
257 )?
258 .to_der()?;
259 let mut verify = Verifier::new(MessageDigest::sha256(), &key)?;
260 verify.update(format!("{}.{}", parts[0], parts[1]).as_bytes())?;
261 if !verify.verify(&signature)? {
262 return Err(reject("signature"));
263 }
264 let claims: Value = serde_json::from_slice(
265 &URL_SAFE_NO_PAD
266 .decode(parts[1])
267 .map_err(|_| reject("claims_encoding"))?,
268 )
269 .map_err(|_| reject("claims_json"))?;
270 let time = now() as i64;
271 let audience = claims["aud"].as_str().is_some_and(|a| a == client)
272 || array(&claims["aud"])
273 .iter()
274 .any(|a| a.as_str() == Some(client));
275 for (reason, invalid) in [
276 ("issuer", claims["iss"] != ASTHENO),
277 ("audience", !audience),
278 (
279 "authorized_party",
280 (claims["aud"].is_array()
281 && array(&claims["aud"]).len() > 1
282 && claims["azp"] != client)
283 || claims.get("azp").is_some_and(|a| a != client),
284 ),
285 (
286 "subject",
287 string(&claims["sub"]).is_empty() || string(&claims["sub"]).len() > 512,
288 ),
289 (
290 "expiration",
291 (id_token || claims.get("exp").is_some())
292 && claims["exp"].as_i64().is_none_or(|t| t <= time),
293 ),
294 (
295 "issued_at",
296 (id_token || claims.get("iat").is_some())
297 && claims["iat"].as_i64().is_none_or(|t| t > time + 60),
298 ),
299 (
300 "not_before",
301 claims
302 .get("nbf")
303 .is_some_and(|t| t.as_i64().is_none_or(|n| n > time + 60)),
304 ),
305 ("nonce", id_token && claims["nonce"].as_str() != Some(nonce)),
306 ] {
307 if invalid {
308 return Err(reject(reason));
309 }
310 }
311 Ok(claims)
312}
313
314async fn exchange(
315 http: &reqwest::Client,
316 provider: &str,
317 client: &str,
318 secret: &str,
319 code: &str,
320 callback: &str,
321 flow: &Value,
322) -> Result<(String, String, Option<String>, Option<String>)> {
323 let form = [
324 ("client_id", client),
325 ("client_secret", secret),
326 ("grant_type", "authorization_code"),
327 ("code", code),
328 ("redirect_uri", callback),
329 ("code_verifier", string(&flow["verifier"])),
330 ];
331 if provider == "github" {
332 let token = json_bytes(
333 &response_bytes(
334 http.post("https://github.com/login/oauth/access_token")
335 .form(&form)
336 .send()
337 .await?,
338 )
339 .await?,
340 )?;
341 if token["token_type"]
342 .as_str()
343 .is_none_or(|s| !s.eq_ignore_ascii_case("bearer"))
344 || string(&token["access_token"]).is_empty()
345 || string(&token["scope"])
346 .split([',', ' '])
347 .filter(|s| !s.is_empty())
348 .any(|s| s != "read:user")
349 {
350 return Err(Error::new(
351 502,
352 "GitHub couldn't complete sign-in. Return to Shale and try again.",
353 ));
354 }
355 let profile = json_bytes(
356 &response_bytes(
357 http.get("https://api.github.com/user")
358 .bearer_auth(string(&token["access_token"]))
359 .send()
360 .await?,
361 )
362 .await?,
363 )?;
364 let id = profile["id"].as_u64().filter(|n| *n > 0).ok_or_else(|| {
365 Error::new(
366 502,
367 "GitHub couldn't verify your account. Return to Shale and try again.",
368 )
369 })?;
370 let login = profile["login"]
371 .as_str()
372 .filter(|s| !s.is_empty() && s.len() <= 64)
373 .ok_or_else(|| {
374 Error::new(
375 502,
376 "GitHub couldn't verify your account. Return to Shale and try again.",
377 )
378 })?;
379 return Ok((id.to_string(), login.to_owned(), None, None));
380 }
381 let mut form = form.to_vec();
382 form.push(("state", "none"));
383 let token = json_bytes(
384 &response_bytes(
385 http.post(format!("{ASTHENO}/api/token"))
386 .basic_auth(client, Some(secret))
387 .form(&form)
388 .send()
389 .await?,
390 )
391 .await?,
392 )?;
393 if string(&token["access_token"]).is_empty()
394 || token["token_type"]
395 .as_str()
396 .is_none_or(|s| !s.eq_ignore_ascii_case("bearer"))
397 {
398 return Err(Error::new(
399 502,
400 "Astheno couldn't complete sign-in. Return to Shale and try again.",
401 ));
402 }
403 let keys =
404 json_bytes(&response_bytes(http.get(format!("{ASTHENO}/api/jwks")).send().await?).await?)?;
405 let claims = token
406 .get("id_token")
407 .map(|token| signed_claims(string(token), &keys, client, string(&flow["nonce"]), true))
408 .transpose()?;
409 if let Some(hash) = claims
410 .as_ref()
411 .and_then(|claims| claims["at_hash"].as_str())
412 {
413 if hash
414 != URL_SAFE_NO_PAD
415 .encode(&Sha256::digest(string(&token["access_token"]).as_bytes())[..16])
416 {
417 return Err(Error::new(
418 502,
419 "Astheno couldn't verify your sign-in. Return to Shale and try again.",
420 ));
421 }
422 }
423 let bytes = response_bytes(
424 http.get(format!("{ASTHENO}/api/userinfo"))
425 .bearer_auth(string(&token["access_token"]))
426 .send()
427 .await?,
428 )
429 .await?;
430 let profile = if bytes.iter().find(|b| !b.is_ascii_whitespace()) == Some(&b'{') {
431 json_bytes(&bytes)?
432 } else {
433 signed_claims(std::str::from_utf8(&bytes)?, &keys, client, "", false)?
434 };
435 if string(&profile["sub"]).is_empty()
436 || string(&profile["sub"]).len() > 512
437 || claims
438 .as_ref()
439 .is_some_and(|claims| profile["sub"] != claims["sub"])
440 {
441 return Err(Error::new(
442 502,
443 "Astheno couldn't verify your account. Return to Shale and try again.",
444 ));
445 }
446 let name = profile["preferred_username"]
447 .as_str()
448 .or(profile["name"].as_str())
449 .unwrap_or("Astheno guest")
450 .chars()
451 .take(128)
452 .collect();
453 let picture = profile["picture"]
454 .as_str()
455 .filter(|value| value.len() <= 2048)
456 .and_then(|value| url::Url::parse(value).ok())
457 .filter(|url| {
458 url.scheme() == "https"
459 && url.host_str().is_some()
460 && url.username().is_empty()
461 && url.password().is_none()
462 })
463 .map(String::from);
464 Ok((
465 string(&profile["sub"]).to_owned(),
466 name,
467 picture,
468 profile["preferred_username"]
469 .as_str()
470 .map(str::to_lowercase),
471 ))
472}
473
474fn username(provider: &str, subject: &str) -> String {
475 let suffix = if provider == "github" {
476 subject.to_owned()
477 } else {
478 mcp::hash(subject)[..24].to_owned()
479 };
480 format!("guest-{provider}-{suffix}")
481}
482
483fn create(
484 db: &Connection,
485 provider: &str,
486 username: &str,
487 name: &str,
488 picture: Option<&str>,
489) -> Result<String> {
490 let id = uuid::Uuid::new_v4().to_string();
491 let mut profile = json!({"kind":"guest","guestProvider":provider,"username":username,"enabled":true,"email":null,"emailVerified":false,"firstName":name,"lastName":null,"requiredActions":[],"attributes":{},"createdTimestamp":(now()*1000.0) as i64});
492 if let Some(picture) = picture {
493 profile["attributes"]["picture"] = json!([picture]);
494 }
495 db.execute(
496 "INSERT INTO users(id,profile) VALUES (?,?)",
497 sql![id, profile.to_string()],
498 )?;
499 Ok(id)
500}
501
502fn account(
503 auth: &auth::Store,
504 provider: &str,
505 subject: &str,
506 name: &str,
507 picture: Option<&str>,
508) -> Result<String> {
509 let mut db = auth.db.lock().unwrap();
510 let tx = db.transaction()?;
511 let existing: Option<String> = tx
512 .query_row(
513 "SELECT user_id FROM external_identities WHERE provider=? AND subject=?",
514 sql![provider, subject],
515 |r| r.get(0),
516 )
517 .optional()?;
518 if let Some(id) = existing {
519 let profile = auth::user(&tx, &id)?;
520 if profile["enabled"] != true {
521 return Err(Error::new(403, "This account is disabled. Contact Clover."));
522 }
523 if is_guest(&profile) {
524 tx.execute(
525 "UPDATE users SET profile=json_patch(profile,?) WHERE id=?",
526 sql![json!({"firstName":name,"attributes":{"picture":picture.map(|picture| vec![picture])}}).to_string(), id],
527 )?;
528 }
529 tx.commit()?;
530 return Ok(id);
531 }
532 let login = username(provider, subject);
533 let revived: Option<String> = tx
534 .query_row("SELECT id FROM users WHERE username=?", [&login], |r| r.get(0))
535 .optional()?;
536 let id = match revived {
537 Some(id) => id,
538 None => create(&tx, provider, &login, name, picture)?,
539 };
540 tx.execute(
541 "INSERT INTO external_identities VALUES (?,?,?)",
542 sql![provider, subject, id],
543 )?;
544 tx.commit()?;
545 Ok(id)
546}
547
548/// Astheno's per-client subjects require binding granted names at verified sign-in. An account an admin linked to
549/// the name takes the identity over from a guest; otherwise a guest reserved under the name receives it.
550fn claim(auth: &auth::Store, subject: &str, username: &str) -> Result<()> {
551 let mut db = auth.db.lock().unwrap();
552 let tx = db.transaction()?;
553 let linked: Option<String> = tx
554 .query_row(
555 "SELECT id FROM users WHERE json_extract(profile,'$.attributes.astheno[0]')=? AND id NOT IN (SELECT user_id FROM external_identities)",
556 [username],
557 |r| r.get(0),
558 )
559 .optional()?;
560 if let Some(id) = linked {
561 tx.execute(
562 "DELETE FROM external_identities WHERE provider='astheno' AND subject=? AND user_id IN (SELECT id FROM users WHERE json_extract(profile,'$.kind')='guest')",
563 [subject],
564 )?;
565 tx.execute(
566 "INSERT OR IGNORE INTO external_identities VALUES ('astheno',?,?)",
567 sql![subject, id],
568 )?;
569 } else {
570 tx.execute(
571 "INSERT OR IGNORE INTO external_identities SELECT 'astheno',?,id FROM users WHERE username=? AND id NOT IN (SELECT user_id FROM external_identities)",
572 sql![subject, format!("guest-astheno-{username}")],
573 )?;
574 }
575 tx.commit()?;
576 Ok(())
577}
578
579/// Snow Globe sign-in admits only accounts an admin linked to this identity.
580fn member(auth: &auth::Store, provider: &str, subject: &str) -> Result<String> {
581 let db = auth.db.lock().unwrap();
582 let id: Option<String> = db
583 .query_row(
584 "SELECT user_id FROM external_identities WHERE provider=? AND subject=?",
585 sql![provider, subject],
586 |r| r.get(0),
587 )
588 .optional()?;
589 id.filter(|id| {
590 auth::user(&db, id).is_ok_and(|user| !is_guest(&user) && user["enabled"] == true)
591 })
592 .ok_or_else(|| Error::new(403, "This account isn't linked to a Snow Globe account."))
593}
594
595fn astheno_name(handle: &str) -> Result<String> {
596 let name = handle.to_lowercase();
597 if name.len() > 16
598 || !name.starts_with(|c: char| c.is_ascii_alphanumeric())
599 || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
600 {
601 return Err(Error::new(400, "Enter an Astheno username."));
602 }
603 Ok(name)
604}
605
606/// Grants Snow Globe sign-in to whoever Astheno verifies as this username; the first such sign-in binds the account.
607pub fn link(db: &Connection, id: &str, handle: &str) -> Result<()> {
608 let name = astheno_name(handle.trim().trim_start_matches('@'))?;
609 if is_guest(&auth::user(db, id)?) {
610 return Err(Error::new(400, "Guests sign in with their own provider."));
611 }
612 unlink(db, id)?;
613 let taken: bool = db.query_row(
614 "SELECT EXISTS(SELECT 1 FROM users WHERE json_extract(profile,'$.attributes.astheno[0]')=?)",
615 [&name],
616 |r| r.get(0),
617 )?;
618 if taken {
619 return Err(Error::new(409, "Another account already has that Astheno username."));
620 }
621 db.execute(
622 "UPDATE users SET profile=json_patch(profile,?) WHERE id=?",
623 sql![json!({"attributes":{"astheno":[name]}}).to_string(), id],
624 )?;
625 Ok(())
626}
627
628pub fn unlink(db: &Connection, id: &str) -> Result<()> {
629 db.execute(
630 "DELETE FROM external_identities WHERE provider='astheno' AND user_id=?",
631 [id],
632 )?;
633 db.execute(
634 "UPDATE users SET profile=json_patch(profile,'{\"attributes\":{\"astheno\":null}}') WHERE id=?",
635 [id],
636 )?;
637 Ok(())
638}
639
640fn grant(auth: &auth::Store, provider: &str, subject: Option<&str>, name: &str) -> Result<Value> {
641 let mut db = auth.db.lock().unwrap();
642 let tx = db.transaction()?;
643 let known: Vec<String> = match subject {
644 Some(subject) => vec![subject.to_owned()],
645 None => tx
646 .prepare("SELECT subject FROM external_identities JOIN users ON users.id=user_id WHERE provider=? AND lower(json_extract(profile,'$.firstName'))=?")?
647 .query_map(sql![provider, name], |r| r.get(0))?
648 .collect::<std::result::Result<_, _>>()?,
649 };
650 if known.len() > 1 {
651 return Err(Error::new(
652 409,
653 "Several accounts have signed in with that name. Find them under guests.",
654 ));
655 }
656 let username = match known.first() {
657 Some(subject) => username(provider, subject),
658 None => format!("guest-{provider}-{name}"),
659 };
660 let existing: Option<String> = tx
661 .query_row("SELECT id FROM users WHERE username=?", [&username], |r| r.get(0))
662 .optional()?;
663 let id = match &existing {
664 Some(id) => id.clone(),
665 None => {
666 let id = create(&tx, provider, &username, name, None)?;
667 if let Some(subject) = subject {
668 tx.execute(
669 "INSERT INTO external_identities VALUES (?,?,?)",
670 sql![provider, subject, id],
671 )?;
672 }
673 id
674 }
675 };
676 tx.commit()?;
677 Ok(json!({"id":id,"created":existing.is_none()}))
678}
679
680async fn github_user(http: &reqwest::Client, login: &str) -> Result<(u64, String)> {
681 if login.is_empty()
682 || login.len() > 39
683 || login.starts_with('-')
684 || !login.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
685 {
686 return Err(Error::new(400, "Enter a GitHub username."));
687 }
688 let unavailable = || Error::new(502, "GitHub didn't answer. Try again in a minute.");
689 let response = http
690 .get(format!("https://api.github.com/users/{login}"))
691 .send()
692 .await
693 .map_err(|_| unavailable())?;
694 if response.status() == StatusCode::NOT_FOUND {
695 return Err(Error::new(404, format!("GitHub has no user named {login}.")));
696 }
697 let profile = json_bytes(&response_bytes(response).await.map_err(|_| unavailable())?)
698 .map_err(|_| unavailable())?;
699 match (profile["id"].as_u64(), profile["login"].as_str()) {
700 (Some(id), Some(name)) if id > 0 && name.eq_ignore_ascii_case(login) => {
701 Ok((id, name.to_owned()))
702 }
703 _ => Err(unavailable()),
704 }
705}
706
707pub async fn add(auth: &auth::Store, provider: &str, handle: &str) -> Result<Value> {
708 let label = known(provider)?;
709 let registered: bool = auth.db.lock().unwrap().query_row(
710 "SELECT ?1='atproto' OR EXISTS(SELECT 1 FROM guest_providers WHERE id=?1)",
711 [provider],
712 |r| r.get(0),
713 )?;
714 if !registered {
715 return Err(Error::new(
716 409,
717 format!("{label} sign-in isn't set up. Register it with tools/guest-provider.py {provider}."),
718 ));
719 }
720 let handle = handle.trim().trim_start_matches('@');
721 match provider {
722 "github" => {
723 let (id, login) = github_user(&http()?, handle).await?;
724 grant(auth, provider, Some(&id.to_string()), &login)
725 }
726 "atproto" => {
727 let (did, _, handle) = atproto::resolve(handle).await.map_err(|_| {
728 Error::new(404, "Couldn't find that AT handle. Check the spelling.")
729 })?;
730 let name = handle.unwrap_or_else(|| did.clone());
731 grant(auth, provider, Some(&did), &name)
732 }
733 _ => grant(auth, provider, None, &astheno_name(handle)?),
734 }
735}
736
737fn http() -> Result<reqwest::Client> {
738 Ok(reqwest::Client::builder()
739 .timeout(Duration::from_secs(10))
740 .redirect(reqwest::redirect::Policy::none())
741 .user_agent("Snow Globe guest sign-in")
742 .default_headers({
743 let mut headers = HeaderMap::new();
744 headers.insert("accept", "application/json".parse().unwrap());
745 headers
746 })
747 .build()?)
748}
749
750fn fields(query: &str) -> Result<HashMap<String, String>> {
751 let mut map = HashMap::new();
752 for (k, v) in url::form_urlencoded::parse(query.as_bytes()) {
753 if v.len() > 8192 || map.insert(k.into_owned(), v.into_owned()).is_some() {
754 return Err(Error::new(
755 400,
756 "Sign-in expired. Return to Shale and try again.",
757 ));
758 }
759 }
760 Ok(map)
761}
762
763async fn handle(app: &App, request: Request) -> Result<Response> {
764 if request.method() != Method::GET {
765 return Err(Error::new(405, "Use the Shale sign-in page."));
766 }
767 let auth = &app.auth;
768 let headers = request.headers();
769 let parts: Vec<_> = request.uri().path().split('/').collect();
770 if parts.len() != 5 {
771 return Err(Error::new(404, "Use the Shale sign-in page."));
772 }
773 let provider = parts[4];
774 known(provider)?;
775 if provider == "atproto" && parts[3] == "metadata" {
776 return Ok(axum::Json(atproto::metadata(auth)).into_response());
777 }
778 if provider == "atproto" && parts[3] == "avatar" {
779 let query = fields(request.uri().query().unwrap_or_default())?;
780 let subject = query.get("subject").map(String::as_str).unwrap_or_default();
781 let picture: Option<String> = auth.db.lock().unwrap().query_row(
782 "SELECT json_extract(profile,'$.attributes.picture[0]') FROM users JOIN external_identities ON user_id=users.id WHERE provider='atproto' AND subject=? AND json_extract(profile,'$.enabled')=1",
783 [subject], |row| row.get(0)).optional()?.flatten();
784 let (mime, data) = picture
785 .as_deref()
786 .and_then(|s| s.strip_prefix("data:"))
787 .and_then(|s| s.split_once(";base64,"))
788 .filter(|(mime, _)| matches!(*mime, "image/png" | "image/jpeg" | "image/webp"))
789 .ok_or_else(|| Error::new(404, "Profile picture unavailable."))?;
790 return Ok((
791 [
792 ("content-type", mime),
793 ("x-content-type-options", "nosniff"),
794 ],
795 base64::engine::general_purpose::STANDARD.decode(data)?,
796 )
797 .into_response());
798 }
799 let query = fields(request.uri().query().unwrap_or_default())?;
800 let current = auth.session(headers, "dashboard")?;
801 if !current.is_null() && !is_guest(&current) {
802 return Err(Error::new(
803 403,
804 "You're signed into Snow Globe. Open Shale to use your account.",
805 ));
806 }
807 let callback = format!("{}auth/guest/callback/{provider}", auth.origin);
808 if parts[3] == "start" {
809 auth.limit(headers, "guest")?;
810 let (next, _) = destination(
811 auth,
812 provider,
813 query.get("next").map(String::as_str).unwrap_or_default(),
814 )?;
815 if provider == "atproto" {
816 let result = tokio::time::timeout(
817 Duration::from_secs(45),
818 atproto::start(
819 auth,
820 query
821 .get("identifier")
822 .map(String::as_str)
823 .unwrap_or_default(),
824 &next,
825 ),
826 )
827 .await;
828 return match result {
829 Ok(Ok((target, state))) => Ok((
830 StatusCode::FOUND,
831 [
832 ("location", target),
833 ("set-cookie", auth::set_cookie(COOKIE, &state, Some(300))),
834 ],
835 )
836 .into_response()),
837 _ => Ok((
838 StatusCode::FOUND,
839 [(
840 "location",
841 format!("/sign-in?next={}&atproto=1&guest_error=1", encoded(&next)),
842 )],
843 )
844 .into_response()),
845 };
846 }
847 let (client, _) = registration(auth, provider)?;
848 let verifier = mcp::secret();
849 let nonce = mcp::secret();
850 let state = auth::issue(
851 &auth.db.lock().unwrap(),
852 "guest",
853 json!({"provider":provider,"next":next,"flow":query.get("flow"),"verifier":verifier,"nonce":nonce}),
854 300,
855 )?;
856 let mut target = url::Url::parse(if provider == "github" {
857 "https://github.com/login/oauth/authorize"
858 } else {
859 "https://identity.astheno.software/authorize"
860 })?;
861 target.query_pairs_mut().extend_pairs([
862 ("client_id", client.as_str()),
863 ("redirect_uri", &callback),
864 ("response_type", "code"),
865 (
866 "scope",
867 if provider == "github" {
868 "read:user"
869 } else {
870 "openid profile"
871 },
872 ),
873 ("state", &state),
874 ("nonce", &nonce),
875 (
876 "code_challenge",
877 &URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())),
878 ),
879 ("code_challenge_method", "S256"),
880 ]);
881 return Ok((
882 StatusCode::FOUND,
883 [
884 ("location", target.to_string()),
885 ("set-cookie", auth::set_cookie(COOKIE, &state, Some(300))),
886 ],
887 )
888 .into_response());
889 }
890 if parts[3] != "callback" {
891 return Err(Error::new(404, "Use the Shale sign-in page."));
892 }
893 let state = query.get("state").map(String::as_str).unwrap_or_default();
894 let binding = auth::cookie(headers, COOKIE).unwrap_or_default();
895 if state.is_empty() || !bool::from(state.as_bytes().ct_eq(binding.as_bytes())) {
896 return Err(Error::new(
897 403,
898 "Sign-in expired. Return to Shale and try again.",
899 ));
900 }
901 let flow = {
902 let db = auth.db.lock().unwrap();
903 let flow = auth::pending(&db, state, "guest", false)?;
904 if flow.is_null() || flow["provider"] != provider {
905 return Err(Error::new(
906 403,
907 "Sign-in expired. Return to Shale and try again.",
908 ));
909 }
910 auth::pending(&db, state, "guest", true)?
911 };
912 let (next, shale) = destination(auth, provider, string(&flow["next"]))?;
913 let result = async {
914 let code = query
915 .get("code")
916 .filter(|s| !s.is_empty() && s.len() <= 4096 && !query.contains_key("error"))
917 .ok_or_else(|| {
918 Error::new(
919 400,
920 "Sign-in wasn't completed. Return to Shale and try again.",
921 )
922 })?;
923 let id = if provider == "atproto" {
924 let profile = tokio::time::timeout(
925 Duration::from_secs(45),
926 atproto::finish(
927 auth,
928 &flow,
929 code,
930 query.get("iss").map(String::as_str).unwrap_or_default(),
931 ),
932 )
933 .await
934 .map_err(|_| Error::new(502, "Your provider took too long. Try signing in again."))??;
935 let id = account(
936 auth,
937 provider,
938 &profile.did,
939 &profile.name,
940 profile.picture.as_deref(),
941 )?;
942 auth.db.lock().unwrap().execute(
943 "UPDATE users SET profile=json_patch(profile,?) WHERE id=?",
944 sql![
945 json!({"attributes":{"profileUrl":profile.url.map(|url|vec![url])}})
946 .to_string(),
947 id
948 ],
949 )?;
950 id
951 } else {
952 let (client, secret) = registration(auth, provider)?;
953 let (subject, name, picture, handle) =
954 exchange(&http()?, provider, &client, &secret, code, &callback, &flow).await?;
955 if let Some(handle) = handle {
956 claim(auth, &subject, &handle)?;
957 }
958 if shale {
959 account(auth, provider, &subject, &name, picture.as_deref())?
960 } else {
961 member(auth, provider, &subject)?
962 }
963 };
964 let session = auth.create_session(&id, "dashboard", headers, None)?;
965 Ok::<_, Error>((session, auth.next(&id, string(&flow["flow"]), &next)?))
966 }
967 .await;
968 match result {
969 Ok((session, location)) => Ok((
970 StatusCode::FOUND,
971 [("location", location), ("set-cookie", session)],
972 axum::response::AppendHeaders([("set-cookie", auth::set_cookie(COOKIE, "", Some(0)))]),
973 )
974 .into_response()),
975 Err(error) => {
976 eprintln!(
977 "guest callback {provider}: {}: {}",
978 error.status, error.message
979 );
980 Ok((
981 StatusCode::FOUND,
982 [
983 (
984 "location",
985 format!(
986 "/sign-in?next={}&flow={}&guest_error={}",
987 encoded(&next),
988 encoded(string(&flow["flow"])),
989 if error.status == 403 { "denied" } else { "1" }
990 ),
991 ),
992 ("set-cookie", auth::set_cookie(COOKIE, "", Some(0))),
993 ],
994 )
995 .into_response())
996 }
997 }
998}
999
1000pub async fn route(State(app): State<Arc<App>>, request: Request) -> Response {
1001 let mut response = match handle(&app, request).await {
1002 Ok(response) => response,
1003 Err(error) => Error::new(
1004 error.status,
1005 "Sign-in couldn't continue. Go back and try again.",
1006 )
1007 .into_response(),
1008 };
1009 response
1010 .headers_mut()
1011 .insert("cache-control", "no-store".parse().unwrap());
1012 response
1013}
1014
1015#[cfg(test)]
1016mod tests {
1017 use super::*;
1018
1019 #[test]
1020 fn atproto_did_is_the_account_key_and_guests_stay_separate() {
1021 let path =
1022 std::env::temp_dir().join(format!("atproto-guest-test-{}", uuid::Uuid::new_v4()));
1023 let auth = auth::Store::new(
1024 &path,
1025 "https://snowglobe.example.com",
1026 "https://file.example.com",
1027 "auth.example.com",
1028 )
1029 .unwrap();
1030 let did = "did:plc:ewvi7nxzyoun6zhxrhs64oiz";
1031 let first = account(&auth, "atproto", did, "alice.example.com", None).unwrap();
1032 assert_eq!(
1033 first,
1034 account(&auth, "atproto", did, "new.example.com", None).unwrap()
1035 );
1036 assert_ne!(
1037 first,
1038 account(&auth, "github", "42", "new.example.com", None).unwrap()
1039 );
1040 assert_ne!(
1041 first,
1042 account(
1043 &auth,
1044 "atproto",
1045 "did:web:other.example.com",
1046 "new.example.com",
1047 None
1048 )
1049 .unwrap()
1050 );
1051 assert!(
1052 auth.create_session(&first, "file", &HeaderMap::new(), None)
1053 .is_err()
1054 );
1055 assert!(auth.setup_link(&first).is_err());
1056 assert_eq!(providers(&auth, "/").unwrap(), json!([]));
1057 let db = auth.db.lock().unwrap();
1058 let profile = auth::user(&db, &first).unwrap();
1059 assert!(is_guest(&profile));
1060 assert!(profile["email"].is_null());
1061 assert_eq!(profile["firstName"], "new.example.com");
1062 assert!(auth::set_password(&db, &first, "unused").is_err());
1063 drop(db);
1064 drop(auth);
1065 std::fs::remove_dir_all(path).unwrap();
1066 }
1067
1068 // The P-256 tokens were produced independently with Python cryptography.
1069 #[test]
1070 fn external_signature_issuer_audience_nonce_and_time_are_required() {
1071 let vector: Value = serde_json::from_str(include_str!("../tests/guest-jwt.json")).unwrap();
1072 let token = string(&vector["valid"]);
1073 let claims =
1074 signed_claims(token, &vector["keys"], "fixture", "fixture-nonce", true).unwrap();
1075 assert_eq!(claims["sub"], "external-123");
1076 let unnamed = &vector["withoutKid"];
1077 let unnamed_token = string(&unnamed["token"]);
1078 assert_eq!(
1079 signed_claims(
1080 unnamed_token,
1081 &unnamed["keys"],
1082 "fixture",
1083 "fixture-nonce",
1084 true
1085 )
1086 .unwrap()["sub"],
1087 "external-123"
1088 );
1089 let mut ambiguous = unnamed["keys"].clone();
1090 ambiguous["keys"]
1091 .as_array_mut()
1092 .unwrap()
1093 .push(unnamed["keys"]["keys"][0].clone());
1094 assert!(
1095 signed_claims(unnamed_token, &ambiguous, "fixture", "fixture-nonce", true).is_err()
1096 );
1097 assert!(
1098 signed_claims(
1099 unnamed_token,
1100 &vector["keys"],
1101 "fixture",
1102 "fixture-nonce",
1103 true
1104 )
1105 .is_err()
1106 );
1107 for (name, token) in vector["invalid"].as_object().unwrap() {
1108 assert!(
1109 signed_claims(
1110 string(token),
1111 &vector["keys"],
1112 "fixture",
1113 "fixture-nonce",
1114 true
1115 )
1116 .is_err(),
1117 "{name}"
1118 );
1119 }
1120 let mut corrupt = token.to_owned().into_bytes();
1121 let index = token.rfind('.').unwrap() + 3;
1122 corrupt[index] = if corrupt[index] == b'A' { b'B' } else { b'A' };
1123 assert!(
1124 signed_claims(
1125 std::str::from_utf8(&corrupt).unwrap(),
1126 &vector["keys"],
1127 "fixture",
1128 "fixture-nonce",
1129 true
1130 )
1131 .is_err()
1132 );
1133 assert!(
1134 signed_claims(token, &json!({"keys":[]}), "fixture", "fixture-nonce", true).is_err()
1135 );
1136 let mut duplicate = vector["keys"].clone();
1137 duplicate["keys"]
1138 .as_array_mut()
1139 .unwrap()
1140 .push(vector["keys"]["keys"][0].clone());
1141 assert!(signed_claims(token, &duplicate, "fixture", "fixture-nonce", true).is_err());
1142 let mut parts: Vec<_> = token.split('.').map(str::to_owned).collect();
1143 parts[0] = URL_SAFE_NO_PAD.encode(br#"{"alg":"none","kid":"test-key"}"#);
1144 assert!(
1145 signed_claims(
1146 &parts.join("."),
1147 &vector["keys"],
1148 "fixture",
1149 "fixture-nonce",
1150 true
1151 )
1152 .is_err()
1153 );
1154 }
1155
1156 #[test]
1157 fn signed_userinfo_requires_identity_and_signature_but_not_id_token_times_or_nonce() {
1158 let vector: Value = serde_json::from_str(include_str!("../tests/guest-jwt.json")).unwrap();
1159 let userinfo = &vector["userinfo"];
1160 let token = string(&userinfo["token"]);
1161 assert_eq!(
1162 signed_claims(token, &userinfo["keys"], "fixture", "", false).unwrap()["sub"],
1163 "external-123"
1164 );
1165 assert!(signed_claims(token, &userinfo["keys"], "fixture", "fixture-nonce", true).is_err());
1166 assert!(signed_claims(token, &userinfo["keys"], "other", "", false).is_err());
1167 assert!(signed_claims(token, &vector["keys"], "fixture", "", false).is_err());
1168 for reason in ["issuer", "audience", "expiry", "future", "subject"] {
1169 assert!(
1170 signed_claims(
1171 string(&vector["invalid"][reason]),
1172 &vector["keys"],
1173 "fixture",
1174 "",
1175 false
1176 )
1177 .is_err(),
1178 "{reason}"
1179 );
1180 }
1181 }
1182
1183 #[test]
1184 fn identities_never_link_by_name_or_email_and_cannot_gain_credentials_or_groups() {
1185 let path = std::env::temp_dir().join(format!("guest-test-{}", uuid::Uuid::new_v4()));
1186 let auth = auth::Store::new(
1187 &path,
1188 "https://snowglobe.paperclover.net",
1189 "https://file.paperclover.net",
1190 "auth.paperclover.net",
1191 )
1192 .unwrap();
1193 {
1194 let db = auth.db.lock().unwrap();
1195 db.execute("INSERT INTO users(id,profile) VALUES ('owner',?)", [json!({"username":"clover","enabled":true,"email":"same@example.invalid","emailVerified":true}).to_string()]).unwrap();
1196 db.execute("INSERT INTO roles VALUES ('admin','infra-admin') ON CONFLICT(name) DO UPDATE SET id=excluded.id", [])
1197 .unwrap();
1198 }
1199 let first = account(&auth, "github", "123", "clover", None).unwrap();
1200 let repeat = account(&auth, "github", "123", "renamed", None).unwrap();
1201 let other = account(
1202 &auth,
1203 "astheno",
1204 "123",
1205 "clover",
1206 Some("https://identity.astheno.software/avatar/123"),
1207 )
1208 .unwrap();
1209 assert_eq!(first, repeat);
1210 assert_ne!(first, "owner");
1211 assert_ne!(first, other);
1212 assert_eq!(
1213 auth::user(&auth.db.lock().unwrap(), &other).unwrap()["attributes"]["picture"][0],
1214 "https://identity.astheno.software/avatar/123"
1215 );
1216 account(&auth, "astheno", "123", "clover", None).unwrap();
1217 assert!(
1218 auth::user(&auth.db.lock().unwrap(), &other).unwrap()["attributes"]
1219 .get("picture")
1220 .is_none()
1221 );
1222 {
1223 let db = auth.db.lock().unwrap();
1224 let profile = auth::user(&db, &first).unwrap();
1225 assert!(is_guest(&profile));
1226 assert_eq!(profile["firstName"], "renamed");
1227 assert!(profile["email"].is_null());
1228 assert_eq!(profile["groups"], json!([]));
1229 assert!(
1230 db.execute("INSERT INTO memberships VALUES (?,'admin')", [&first])
1231 .is_err()
1232 );
1233 assert!(auth::set_password(&db, &first, "a-password-hash").is_err());
1234 assert!(
1235 db.execute(
1236 "UPDATE users SET profile=json_remove(profile,'$.kind') WHERE id=?",
1237 [&first]
1238 )
1239 .is_err()
1240 );
1241 db.execute(
1242 "UPDATE users SET profile=json_set(profile,'$.enabled',json('false')) WHERE id=?",
1243 [&first],
1244 )
1245 .unwrap();
1246 }
1247 assert!(account(&auth, "github", "123", "clover", None).is_err());
1248 assert!(
1249 auth.create_session(&other, "file", &HeaderMap::new(), None)
1250 .is_err()
1251 );
1252 assert!(auth.setup_link(&other).is_err());
1253 drop(auth);
1254 std::fs::remove_dir_all(path).unwrap();
1255 }
1256
1257 #[test]
1258 fn added_guests_are_the_accounts_their_first_sign_in_finds() {
1259 let path = std::env::temp_dir().join(format!("guest-add-test-{}", uuid::Uuid::new_v4()));
1260 let auth = auth::Store::new(
1261 &path,
1262 "https://snowglobe.paperclover.net",
1263 "https://file.paperclover.net",
1264 "auth.paperclover.net",
1265 )
1266 .unwrap();
1267 for (provider, subject) in [("github", "123"), ("atproto", "did:plc:ewvi7nxzyoun6zhxrhs64oiz")] {
1268 let added = grant(&auth, provider, Some(subject), "octo").unwrap();
1269 let id = string(&added["id"]);
1270 assert_eq!(added["created"], true);
1271 assert_eq!(account(&auth, provider, subject, "renamed", None).unwrap(), id);
1272 assert_eq!(grant(&auth, provider, Some(subject), "octo").unwrap()["created"], false);
1273 }
1274
1275 let reserved = string(&grant(&auth, "astheno", None, "alice").unwrap()["id"]).to_owned();
1276 let identities = |id: &str| -> i64 {
1277 auth.db.lock().unwrap().query_row("SELECT count(*) FROM external_identities WHERE user_id=?", [id], |r| r.get(0)).unwrap()
1278 };
1279 assert_eq!(identities(&reserved), 0);
1280 claim(&auth, "sub-2", "mallory").unwrap();
1281 assert_eq!(identities(&reserved), 0);
1282 let stranger = account(&auth, "astheno", "sub-2", "mallory", None).unwrap();
1283 assert_ne!(stranger, reserved);
1284 claim(&auth, "sub-1", "alice").unwrap();
1285 assert_eq!(account(&auth, "astheno", "sub-1", "alice", None).unwrap(), reserved);
1286 claim(&auth, "sub-3", "alice").unwrap();
1287 let impostor = account(&auth, "astheno", "sub-3", "alice", None).unwrap();
1288 assert_ne!(impostor, reserved);
1289
1290 let earlier = account(&auth, "astheno", "sub-9", "carol", None).unwrap();
1291 let added = grant(&auth, "astheno", None, "carol").unwrap();
1292 assert_eq!((string(&added["id"]), &added["created"]), (earlier.as_str(), &json!(false)));
1293 account(&auth, "astheno", "sub-5", "dave", None).unwrap();
1294 account(&auth, "astheno", "sub-6", "dave", None).unwrap();
1295 assert_eq!(grant(&auth, "astheno", None, "dave").unwrap_err().status, 409);
1296 drop(auth);
1297 std::fs::remove_dir_all(path).unwrap();
1298 }
1299
1300 #[test]
1301 fn only_granted_astheno_names_reach_snow_globe_accounts() {
1302 let path = std::env::temp_dir().join(format!("guest-link-test-{}", uuid::Uuid::new_v4()));
1303 let auth = auth::Store::new(
1304 &path,
1305 "https://snowglobe.paperclover.net",
1306 "https://file.paperclover.net",
1307 "auth.paperclover.net",
1308 )
1309 .unwrap();
1310 let add = |id: &str, name: &str| {
1311 auth.db.lock().unwrap().execute("INSERT INTO users(id,profile) VALUES (?,?)", [id, &json!({"username":name,"enabled":true,"requiredActions":[]}).to_string()]).unwrap();
1312 };
1313 add("snow", "snow");
1314 add("meghan", "meghan");
1315 let link = |id: &str, handle: &str| link(&auth.db.lock().unwrap(), id, handle);
1316 // What the callback does after Astheno verifies `handle` as `subject`.
1317 let shale = |subject: &str, handle: &str| {
1318 claim(&auth, subject, handle).unwrap();
1319 account(&auth, "astheno", subject, handle, None).unwrap()
1320 };
1321 let snow = |subject: &str, handle: &str| {
1322 claim(&auth, subject, handle).unwrap();
1323 member(&auth, "astheno", subject)
1324 };
1325
1326 // Ungranted names are Shale guests and never reach an account, even one with the same username.
1327 let guest = shale("sub-clover", "clover");
1328 let impostor = shale("sub-snow", "snow");
1329 assert!(is_guest(&auth::user(&auth.db.lock().unwrap(), &impostor).unwrap()));
1330 assert_eq!(snow("sub-snow", "snow").unwrap_err().status, 403);
1331 assert_eq!(snow("sub-clover", "clover").unwrap_err().status, 403);
1332
1333 // A grant binds the first verified sign-in, taking over an existing guest.
1334 link("snow", " @Clover ").unwrap();
1335 link("meghan", "meghan").unwrap();
1336 assert_eq!(snow("sub-clover", "clover").unwrap(), "snow");
1337 assert_eq!(shale("sub-clover", "clover"), "snow");
1338 assert!(auth::user(&auth.db.lock().unwrap(), "snow").unwrap()["firstName"].is_null());
1339 assert_eq!(shale("sub-meghan", "meghan"), "meghan");
1340 assert_eq!(snow("sub-meghan", "meghan").unwrap(), "meghan");
1341
1342 // Once bound, another subject presenting the name is just a guest.
1343 assert_ne!(shale("sub-reused", "meghan"), "meghan");
1344 assert_eq!(snow("sub-reused", "meghan").unwrap_err().status, 403);
1345
1346 // Names are unique, guests can't be linked, and names must be plausible.
1347 assert_eq!(link("meghan", "clover").unwrap_err().status, 409);
1348 assert_eq!(link(&impostor, "snow").unwrap_err().status, 400);
1349 assert_eq!(link("meghan", "has space").unwrap_err().status, 400);
1350
1351 // Disabling or unlinking ends access; the guest it replaced comes back on Shale.
1352 auth.db.lock().unwrap().execute("UPDATE users SET profile=json_set(profile,'$.enabled',json('false')) WHERE id='snow'", []).unwrap();
1353 assert_eq!(snow("sub-clover", "clover").unwrap_err().status, 403);
1354 unlink(&auth.db.lock().unwrap(), "snow").unwrap();
1355 assert_eq!(snow("sub-clover", "clover").unwrap_err().status, 403);
1356 assert_eq!(shale("sub-clover", "clover"), guest);
1357
1358 // Snow Globe offers only Astheno, once it is registered.
1359 assert_eq!(providers(&auth, "/").unwrap(), json!([]));
1360 provision(&auth, json!({"provider":"astheno","enabled":true,"clientId":"client","clientSecret":"0123456789abcdef"})).unwrap();
1361 provision(&auth, json!({"provider":"github","enabled":true,"clientId":"client","clientSecret":"0123456789abcdef"})).unwrap();
1362 assert_eq!(providers(&auth, "/").unwrap(), json!([{"id":"astheno","name":"Astheno"}]));
1363 assert_eq!(destination(&auth, "github", "/").unwrap_err().status, 400);
1364 assert_eq!(destination(&auth, "astheno", "/").unwrap(), ("/".to_owned(), false));
1365 drop(auth);
1366 std::fs::remove_dir_all(path).unwrap();
1367 }
1368
1369 #[tokio::test]
1370 async fn adding_needs_a_registered_provider_and_a_plausible_name() {
1371 let path = std::env::temp_dir().join(format!("guest-add-test-{}", uuid::Uuid::new_v4()));
1372 let auth = auth::Store::new(
1373 &path,
1374 "https://snowglobe.paperclover.net",
1375 "https://file.paperclover.net",
1376 "auth.paperclover.net",
1377 )
1378 .unwrap();
1379 assert_eq!(add(&auth, "astheno", "alice").await.unwrap_err().status, 409);
1380 assert_eq!(add(&auth, "gitlab", "alice").await.unwrap_err().status, 404);
1381 provision(&auth, json!({"provider":"astheno","enabled":true,"clientId":"client","clientSecret":"0123456789abcdef"})).unwrap();
1382 for name in ["", "has space", "-alice", "a-name-over-sixteen"] {
1383 assert_eq!(add(&auth, "astheno", name).await.unwrap_err().status, 400, "{name}");
1384 }
1385 let added = add(&auth, "astheno", " @Alice ").await.unwrap();
1386 assert_eq!(
1387 auth::user(&auth.db.lock().unwrap(), string(&added["id"])).unwrap()["username"],
1388 "guest-astheno-alice"
1389 );
1390 drop(auth);
1391 std::fs::remove_dir_all(path).unwrap();
1392 }
1393}