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' AND (SELECT name FROM roles WHERE id=NEW.role_id)!='knife-native' BEGIN SELECT RAISE(ABORT,'guest accounts can only join knife-native'); END;
27 CREATE TRIGGER IF NOT EXISTS guest_no_group_updates BEFORE UPDATE ON memberships WHEN (SELECT json_extract(profile,'$.kind') FROM users WHERE id=NEW.user_id)='guest' AND (SELECT name FROM roles WHERE id=NEW.role_id)!='knife-native' BEGIN SELECT RAISE(ABORT,'guest accounts can only join knife-native'); END;
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. Open the right one under guests and join it to knife-native.",
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.execute(
677 "INSERT OR IGNORE INTO memberships SELECT ?,id FROM roles WHERE name='knife-native'",
678 [&id],
679 )?;
680 tx.commit()?;
681 Ok(json!({"id":id,"created":existing.is_none()}))
682}
683
684async fn github_user(http: &reqwest::Client, login: &str) -> Result<(u64, String)> {
685 if login.is_empty()
686 || login.len() > 39
687 || login.starts_with('-')
688 || !login.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
689 {
690 return Err(Error::new(400, "Enter a GitHub username."));
691 }
692 let unavailable = || Error::new(502, "GitHub didn't answer. Try again in a minute.");
693 let response = http
694 .get(format!("https://api.github.com/users/{login}"))
695 .send()
696 .await
697 .map_err(|_| unavailable())?;
698 if response.status() == StatusCode::NOT_FOUND {
699 return Err(Error::new(404, format!("GitHub has no user named {login}.")));
700 }
701 let profile = json_bytes(&response_bytes(response).await.map_err(|_| unavailable())?)
702 .map_err(|_| unavailable())?;
703 match (profile["id"].as_u64(), profile["login"].as_str()) {
704 (Some(id), Some(name)) if id > 0 && name.eq_ignore_ascii_case(login) => {
705 Ok((id, name.to_owned()))
706 }
707 _ => Err(unavailable()),
708 }
709}
710
711pub async fn add(auth: &auth::Store, provider: &str, handle: &str) -> Result<Value> {
712 let label = known(provider)?;
713 let registered: bool = auth.db.lock().unwrap().query_row(
714 "SELECT ?1='atproto' OR EXISTS(SELECT 1 FROM guest_providers WHERE id=?1)",
715 [provider],
716 |r| r.get(0),
717 )?;
718 if !registered {
719 return Err(Error::new(
720 409,
721 format!("{label} sign-in isn't set up. Register it with tools/guest-provider.py {provider}."),
722 ));
723 }
724 let handle = handle.trim().trim_start_matches('@');
725 match provider {
726 "github" => {
727 let (id, login) = github_user(&http()?, handle).await?;
728 grant(auth, provider, Some(&id.to_string()), &login)
729 }
730 "atproto" => {
731 let (did, _, handle) = atproto::resolve(handle).await.map_err(|_| {
732 Error::new(404, "Couldn't find that AT handle. Check the spelling.")
733 })?;
734 let name = handle.unwrap_or_else(|| did.clone());
735 grant(auth, provider, Some(&did), &name)
736 }
737 _ => grant(auth, provider, None, &astheno_name(handle)?),
738 }
739}
740
741fn http() -> Result<reqwest::Client> {
742 Ok(reqwest::Client::builder()
743 .timeout(Duration::from_secs(10))
744 .redirect(reqwest::redirect::Policy::none())
745 .user_agent("Snow Globe guest sign-in")
746 .default_headers({
747 let mut headers = HeaderMap::new();
748 headers.insert("accept", "application/json".parse().unwrap());
749 headers
750 })
751 .build()?)
752}
753
754fn fields(query: &str) -> Result<HashMap<String, String>> {
755 let mut map = HashMap::new();
756 for (k, v) in url::form_urlencoded::parse(query.as_bytes()) {
757 if v.len() > 8192 || map.insert(k.into_owned(), v.into_owned()).is_some() {
758 return Err(Error::new(
759 400,
760 "Sign-in expired. Return to Shale and try again.",
761 ));
762 }
763 }
764 Ok(map)
765}
766
767async fn handle(app: &App, request: Request) -> Result<Response> {
768 if request.method() != Method::GET {
769 return Err(Error::new(405, "Use the Shale sign-in page."));
770 }
771 let auth = &app.auth;
772 let headers = request.headers();
773 let parts: Vec<_> = request.uri().path().split('/').collect();
774 if parts.len() != 5 {
775 return Err(Error::new(404, "Use the Shale sign-in page."));
776 }
777 let provider = parts[4];
778 known(provider)?;
779 if provider == "atproto" && parts[3] == "metadata" {
780 return Ok(axum::Json(atproto::metadata(auth)).into_response());
781 }
782 if provider == "atproto" && parts[3] == "avatar" {
783 let query = fields(request.uri().query().unwrap_or_default())?;
784 let subject = query.get("subject").map(String::as_str).unwrap_or_default();
785 let picture: Option<String> = auth.db.lock().unwrap().query_row(
786 "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",
787 [subject], |row| row.get(0)).optional()?.flatten();
788 let (mime, data) = picture
789 .as_deref()
790 .and_then(|s| s.strip_prefix("data:"))
791 .and_then(|s| s.split_once(";base64,"))
792 .filter(|(mime, _)| matches!(*mime, "image/png" | "image/jpeg" | "image/webp"))
793 .ok_or_else(|| Error::new(404, "Profile picture unavailable."))?;
794 return Ok((
795 [
796 ("content-type", mime),
797 ("x-content-type-options", "nosniff"),
798 ],
799 base64::engine::general_purpose::STANDARD.decode(data)?,
800 )
801 .into_response());
802 }
803 let query = fields(request.uri().query().unwrap_or_default())?;
804 let current = auth.session(headers, "dashboard")?;
805 if !current.is_null() && !is_guest(&current) {
806 return Err(Error::new(
807 403,
808 "You're signed into Snow Globe. Open Shale to use your account.",
809 ));
810 }
811 let callback = format!("{}auth/guest/callback/{provider}", auth.origin);
812 if parts[3] == "start" {
813 auth.limit(headers, "guest")?;
814 let (next, _) = destination(
815 auth,
816 provider,
817 query.get("next").map(String::as_str).unwrap_or_default(),
818 )?;
819 if provider == "atproto" {
820 let result = tokio::time::timeout(
821 Duration::from_secs(45),
822 atproto::start(
823 auth,
824 query
825 .get("identifier")
826 .map(String::as_str)
827 .unwrap_or_default(),
828 &next,
829 ),
830 )
831 .await;
832 return match result {
833 Ok(Ok((target, state))) => Ok((
834 StatusCode::FOUND,
835 [
836 ("location", target),
837 ("set-cookie", auth::set_cookie(COOKIE, &state, Some(300))),
838 ],
839 )
840 .into_response()),
841 _ => Ok((
842 StatusCode::FOUND,
843 [(
844 "location",
845 format!("/sign-in?next={}&atproto=1&guest_error=1", encoded(&next)),
846 )],
847 )
848 .into_response()),
849 };
850 }
851 let (client, _) = registration(auth, provider)?;
852 let verifier = mcp::secret();
853 let nonce = mcp::secret();
854 let state = auth::issue(
855 &auth.db.lock().unwrap(),
856 "guest",
857 json!({"provider":provider,"next":next,"flow":query.get("flow"),"verifier":verifier,"nonce":nonce}),
858 300,
859 )?;
860 let mut target = url::Url::parse(if provider == "github" {
861 "https://github.com/login/oauth/authorize"
862 } else {
863 "https://identity.astheno.software/authorize"
864 })?;
865 target.query_pairs_mut().extend_pairs([
866 ("client_id", client.as_str()),
867 ("redirect_uri", &callback),
868 ("response_type", "code"),
869 (
870 "scope",
871 if provider == "github" {
872 "read:user"
873 } else {
874 "openid profile"
875 },
876 ),
877 ("state", &state),
878 ("nonce", &nonce),
879 (
880 "code_challenge",
881 &URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())),
882 ),
883 ("code_challenge_method", "S256"),
884 ]);
885 return Ok((
886 StatusCode::FOUND,
887 [
888 ("location", target.to_string()),
889 ("set-cookie", auth::set_cookie(COOKIE, &state, Some(300))),
890 ],
891 )
892 .into_response());
893 }
894 if parts[3] != "callback" {
895 return Err(Error::new(404, "Use the Shale sign-in page."));
896 }
897 let state = query.get("state").map(String::as_str).unwrap_or_default();
898 let binding = auth::cookie(headers, COOKIE).unwrap_or_default();
899 if state.is_empty() || !bool::from(state.as_bytes().ct_eq(binding.as_bytes())) {
900 return Err(Error::new(
901 403,
902 "Sign-in expired. Return to Shale and try again.",
903 ));
904 }
905 let flow = {
906 let db = auth.db.lock().unwrap();
907 let flow = auth::pending(&db, state, "guest", false)?;
908 if flow.is_null() || flow["provider"] != provider {
909 return Err(Error::new(
910 403,
911 "Sign-in expired. Return to Shale and try again.",
912 ));
913 }
914 auth::pending(&db, state, "guest", true)?
915 };
916 let (next, shale) = destination(auth, provider, string(&flow["next"]))?;
917 let result = async {
918 let code = query
919 .get("code")
920 .filter(|s| !s.is_empty() && s.len() <= 4096 && !query.contains_key("error"))
921 .ok_or_else(|| {
922 Error::new(
923 400,
924 "Sign-in wasn't completed. Return to Shale and try again.",
925 )
926 })?;
927 let id = if provider == "atproto" {
928 let profile = tokio::time::timeout(
929 Duration::from_secs(45),
930 atproto::finish(
931 auth,
932 &flow,
933 code,
934 query.get("iss").map(String::as_str).unwrap_or_default(),
935 ),
936 )
937 .await
938 .map_err(|_| Error::new(502, "Your provider took too long. Try signing in again."))??;
939 let id = account(
940 auth,
941 provider,
942 &profile.did,
943 &profile.name,
944 profile.picture.as_deref(),
945 )?;
946 auth.db.lock().unwrap().execute(
947 "UPDATE users SET profile=json_patch(profile,?) WHERE id=?",
948 sql![
949 json!({"attributes":{"profileUrl":profile.url.map(|url|vec![url])}})
950 .to_string(),
951 id
952 ],
953 )?;
954 id
955 } else {
956 let (client, secret) = registration(auth, provider)?;
957 let (subject, name, picture, handle) =
958 exchange(&http()?, provider, &client, &secret, code, &callback, &flow).await?;
959 if let Some(handle) = handle {
960 claim(auth, &subject, &handle)?;
961 }
962 if shale {
963 account(auth, provider, &subject, &name, picture.as_deref())?
964 } else {
965 member(auth, provider, &subject)?
966 }
967 };
968 let session = auth.create_session(&id, "dashboard", headers, None)?;
969 Ok::<_, Error>((session, auth.next(&id, string(&flow["flow"]), &next)?))
970 }
971 .await;
972 match result {
973 Ok((session, location)) => Ok((
974 StatusCode::FOUND,
975 [("location", location), ("set-cookie", session)],
976 axum::response::AppendHeaders([("set-cookie", auth::set_cookie(COOKIE, "", Some(0)))]),
977 )
978 .into_response()),
979 Err(error) => {
980 eprintln!(
981 "guest callback {provider}: {}: {}",
982 error.status, error.message
983 );
984 Ok((
985 StatusCode::FOUND,
986 [
987 (
988 "location",
989 format!(
990 "/sign-in?next={}&flow={}&guest_error={}",
991 encoded(&next),
992 encoded(string(&flow["flow"])),
993 if error.status == 403 { "denied" } else { "1" }
994 ),
995 ),
996 ("set-cookie", auth::set_cookie(COOKIE, "", Some(0))),
997 ],
998 )
999 .into_response())
1000 }
1001 }
1002}
1003
1004pub async fn route(State(app): State<Arc<App>>, request: Request) -> Response {
1005 let mut response = match handle(&app, request).await {
1006 Ok(response) => response,
1007 Err(error) => Error::new(
1008 error.status,
1009 "Sign-in couldn't continue. Go back and try again.",
1010 )
1011 .into_response(),
1012 };
1013 response
1014 .headers_mut()
1015 .insert("cache-control", "no-store".parse().unwrap());
1016 response
1017}
1018
1019#[cfg(test)]
1020mod tests {
1021 use super::*;
1022
1023 #[test]
1024 fn atproto_did_is_the_account_key_and_guests_stay_separate() {
1025 let path =
1026 std::env::temp_dir().join(format!("atproto-guest-test-{}", uuid::Uuid::new_v4()));
1027 let auth = auth::Store::new(
1028 &path,
1029 "https://snowglobe.example.com",
1030 "https://file.example.com",
1031 "auth.example.com",
1032 )
1033 .unwrap();
1034 let did = "did:plc:ewvi7nxzyoun6zhxrhs64oiz";
1035 let first = account(&auth, "atproto", did, "alice.example.com", None).unwrap();
1036 assert_eq!(
1037 first,
1038 account(&auth, "atproto", did, "new.example.com", None).unwrap()
1039 );
1040 assert_ne!(
1041 first,
1042 account(&auth, "github", "42", "new.example.com", None).unwrap()
1043 );
1044 assert_ne!(
1045 first,
1046 account(
1047 &auth,
1048 "atproto",
1049 "did:web:other.example.com",
1050 "new.example.com",
1051 None
1052 )
1053 .unwrap()
1054 );
1055 assert!(
1056 auth.create_session(&first, "file", &HeaderMap::new(), None)
1057 .is_err()
1058 );
1059 assert!(auth.setup_link(&first).is_err());
1060 assert_eq!(providers(&auth, "/").unwrap(), json!([]));
1061 let db = auth.db.lock().unwrap();
1062 let profile = auth::user(&db, &first).unwrap();
1063 assert!(is_guest(&profile));
1064 assert!(profile["email"].is_null());
1065 assert_eq!(profile["firstName"], "new.example.com");
1066 assert!(auth::set_password(&db, &first, "unused").is_err());
1067 drop(db);
1068 drop(auth);
1069 std::fs::remove_dir_all(path).unwrap();
1070 }
1071
1072 // The P-256 tokens were produced independently with Python cryptography.
1073 #[test]
1074 fn external_signature_issuer_audience_nonce_and_time_are_required() {
1075 let vector: Value = serde_json::from_str(include_str!("../tests/guest-jwt.json")).unwrap();
1076 let token = string(&vector["valid"]);
1077 let claims =
1078 signed_claims(token, &vector["keys"], "fixture", "fixture-nonce", true).unwrap();
1079 assert_eq!(claims["sub"], "external-123");
1080 let unnamed = &vector["withoutKid"];
1081 let unnamed_token = string(&unnamed["token"]);
1082 assert_eq!(
1083 signed_claims(
1084 unnamed_token,
1085 &unnamed["keys"],
1086 "fixture",
1087 "fixture-nonce",
1088 true
1089 )
1090 .unwrap()["sub"],
1091 "external-123"
1092 );
1093 let mut ambiguous = unnamed["keys"].clone();
1094 ambiguous["keys"]
1095 .as_array_mut()
1096 .unwrap()
1097 .push(unnamed["keys"]["keys"][0].clone());
1098 assert!(
1099 signed_claims(unnamed_token, &ambiguous, "fixture", "fixture-nonce", true).is_err()
1100 );
1101 assert!(
1102 signed_claims(
1103 unnamed_token,
1104 &vector["keys"],
1105 "fixture",
1106 "fixture-nonce",
1107 true
1108 )
1109 .is_err()
1110 );
1111 for (name, token) in vector["invalid"].as_object().unwrap() {
1112 assert!(
1113 signed_claims(
1114 string(token),
1115 &vector["keys"],
1116 "fixture",
1117 "fixture-nonce",
1118 true
1119 )
1120 .is_err(),
1121 "{name}"
1122 );
1123 }
1124 let mut corrupt = token.to_owned().into_bytes();
1125 let index = token.rfind('.').unwrap() + 3;
1126 corrupt[index] = if corrupt[index] == b'A' { b'B' } else { b'A' };
1127 assert!(
1128 signed_claims(
1129 std::str::from_utf8(&corrupt).unwrap(),
1130 &vector["keys"],
1131 "fixture",
1132 "fixture-nonce",
1133 true
1134 )
1135 .is_err()
1136 );
1137 assert!(
1138 signed_claims(token, &json!({"keys":[]}), "fixture", "fixture-nonce", true).is_err()
1139 );
1140 let mut duplicate = vector["keys"].clone();
1141 duplicate["keys"]
1142 .as_array_mut()
1143 .unwrap()
1144 .push(vector["keys"]["keys"][0].clone());
1145 assert!(signed_claims(token, &duplicate, "fixture", "fixture-nonce", true).is_err());
1146 let mut parts: Vec<_> = token.split('.').map(str::to_owned).collect();
1147 parts[0] = URL_SAFE_NO_PAD.encode(br#"{"alg":"none","kid":"test-key"}"#);
1148 assert!(
1149 signed_claims(
1150 &parts.join("."),
1151 &vector["keys"],
1152 "fixture",
1153 "fixture-nonce",
1154 true
1155 )
1156 .is_err()
1157 );
1158 }
1159
1160 #[test]
1161 fn signed_userinfo_requires_identity_and_signature_but_not_id_token_times_or_nonce() {
1162 let vector: Value = serde_json::from_str(include_str!("../tests/guest-jwt.json")).unwrap();
1163 let userinfo = &vector["userinfo"];
1164 let token = string(&userinfo["token"]);
1165 assert_eq!(
1166 signed_claims(token, &userinfo["keys"], "fixture", "", false).unwrap()["sub"],
1167 "external-123"
1168 );
1169 assert!(signed_claims(token, &userinfo["keys"], "fixture", "fixture-nonce", true).is_err());
1170 assert!(signed_claims(token, &userinfo["keys"], "other", "", false).is_err());
1171 assert!(signed_claims(token, &vector["keys"], "fixture", "", false).is_err());
1172 for reason in ["issuer", "audience", "expiry", "future", "subject"] {
1173 assert!(
1174 signed_claims(
1175 string(&vector["invalid"][reason]),
1176 &vector["keys"],
1177 "fixture",
1178 "",
1179 false
1180 )
1181 .is_err(),
1182 "{reason}"
1183 );
1184 }
1185 }
1186
1187 #[test]
1188 fn identities_stay_separate_and_guests_can_only_join_native_access() {
1189 let path = std::env::temp_dir().join(format!("guest-test-{}", uuid::Uuid::new_v4()));
1190 let auth = auth::Store::new(
1191 &path,
1192 "https://snowglobe.paperclover.net",
1193 "https://file.paperclover.net",
1194 "auth.paperclover.net",
1195 )
1196 .unwrap();
1197 {
1198 let db = auth.db.lock().unwrap();
1199 db.execute("INSERT INTO users(id,profile) VALUES ('owner',?)", [json!({"username":"clover","enabled":true,"email":"same@example.invalid","emailVerified":true}).to_string()]).unwrap();
1200 db.execute("INSERT INTO roles VALUES ('admin','infra-admin') ON CONFLICT(name) DO UPDATE SET id=excluded.id", [])
1201 .unwrap();
1202 }
1203 let first = account(&auth, "github", "123", "clover", None).unwrap();
1204 let repeat = account(&auth, "github", "123", "renamed", None).unwrap();
1205 let other = account(
1206 &auth,
1207 "astheno",
1208 "123",
1209 "clover",
1210 Some("https://identity.astheno.software/avatar/123"),
1211 )
1212 .unwrap();
1213 assert_eq!(first, repeat);
1214 assert_ne!(first, "owner");
1215 assert_ne!(first, other);
1216 assert_eq!(
1217 auth::user(&auth.db.lock().unwrap(), &other).unwrap()["attributes"]["picture"][0],
1218 "https://identity.astheno.software/avatar/123"
1219 );
1220 account(&auth, "astheno", "123", "clover", None).unwrap();
1221 assert!(
1222 auth::user(&auth.db.lock().unwrap(), &other).unwrap()["attributes"]
1223 .get("picture")
1224 .is_none()
1225 );
1226 {
1227 let db = auth.db.lock().unwrap();
1228 let profile = auth::user(&db, &first).unwrap();
1229 assert!(is_guest(&profile));
1230 assert_eq!(profile["firstName"], "renamed");
1231 assert!(profile["email"].is_null());
1232 assert_eq!(profile["groups"], json!([]));
1233 assert!(
1234 db.execute("INSERT INTO memberships VALUES (?,'admin')", [&first])
1235 .is_err()
1236 );
1237 db.execute("INSERT INTO memberships SELECT ?,id FROM roles WHERE name='knife-native'", [&first]).unwrap();
1238 assert_eq!(auth::user(&db, &first).unwrap()["groups"][0]["name"], "knife-native");
1239 assert!(db.execute("UPDATE memberships SET role_id='admin' WHERE user_id=?", [&first]).is_err());
1240 assert!(auth::set_password(&db, &first, "a-password-hash").is_err());
1241 assert!(
1242 db.execute(
1243 "UPDATE users SET profile=json_remove(profile,'$.kind') WHERE id=?",
1244 [&first]
1245 )
1246 .is_err()
1247 );
1248 db.execute(
1249 "UPDATE users SET profile=json_set(profile,'$.enabled',json('false')) WHERE id=?",
1250 [&first],
1251 )
1252 .unwrap();
1253 }
1254 assert!(account(&auth, "github", "123", "clover", None).is_err());
1255 assert!(
1256 auth.create_session(&other, "file", &HeaderMap::new(), None)
1257 .is_err()
1258 );
1259 assert!(auth.setup_link(&other).is_err());
1260 drop(auth);
1261 std::fs::remove_dir_all(path).unwrap();
1262 }
1263
1264 fn members(auth: &auth::Store, id: &str) -> Value {
1265 auth::user(&auth.db.lock().unwrap(), id).unwrap()["groups"].clone()
1266 }
1267
1268 #[test]
1269 fn added_guests_are_the_accounts_their_first_sign_in_finds() {
1270 let path = std::env::temp_dir().join(format!("guest-add-test-{}", uuid::Uuid::new_v4()));
1271 let auth = auth::Store::new(
1272 &path,
1273 "https://snowglobe.paperclover.net",
1274 "https://file.paperclover.net",
1275 "auth.paperclover.net",
1276 )
1277 .unwrap();
1278 for (provider, subject) in [("github", "123"), ("atproto", "did:plc:ewvi7nxzyoun6zhxrhs64oiz")] {
1279 let added = grant(&auth, provider, Some(subject), "octo").unwrap();
1280 let id = string(&added["id"]);
1281 assert_eq!(added["created"], true);
1282 assert_eq!(members(&auth, id)[0]["name"], "knife-native");
1283 assert_eq!(account(&auth, provider, subject, "renamed", None).unwrap(), id);
1284 assert_eq!(grant(&auth, provider, Some(subject), "octo").unwrap()["created"], false);
1285 assert_eq!(members(&auth, id).as_array().unwrap().len(), 1);
1286 }
1287
1288 let reserved = string(&grant(&auth, "astheno", None, "alice").unwrap()["id"]).to_owned();
1289 let identities = |id: &str| -> i64 {
1290 auth.db.lock().unwrap().query_row("SELECT count(*) FROM external_identities WHERE user_id=?", [id], |r| r.get(0)).unwrap()
1291 };
1292 assert_eq!(identities(&reserved), 0);
1293 claim(&auth, "sub-2", "mallory").unwrap();
1294 assert_eq!(identities(&reserved), 0);
1295 let stranger = account(&auth, "astheno", "sub-2", "mallory", None).unwrap();
1296 assert_ne!(stranger, reserved);
1297 assert_eq!(members(&auth, &stranger), json!([]));
1298 claim(&auth, "sub-1", "alice").unwrap();
1299 assert_eq!(account(&auth, "astheno", "sub-1", "alice", None).unwrap(), reserved);
1300 assert_eq!(members(&auth, &reserved)[0]["name"], "knife-native");
1301 claim(&auth, "sub-3", "alice").unwrap();
1302 let impostor = account(&auth, "astheno", "sub-3", "alice", None).unwrap();
1303 assert_ne!(impostor, reserved);
1304 assert_eq!(members(&auth, &impostor), json!([]));
1305
1306 let earlier = account(&auth, "astheno", "sub-9", "carol", None).unwrap();
1307 let added = grant(&auth, "astheno", None, "carol").unwrap();
1308 assert_eq!((string(&added["id"]), &added["created"]), (earlier.as_str(), &json!(false)));
1309 assert_eq!(members(&auth, &earlier)[0]["name"], "knife-native");
1310 account(&auth, "astheno", "sub-5", "dave", None).unwrap();
1311 account(&auth, "astheno", "sub-6", "dave", None).unwrap();
1312 assert_eq!(grant(&auth, "astheno", None, "dave").unwrap_err().status, 409);
1313 drop(auth);
1314 std::fs::remove_dir_all(path).unwrap();
1315 }
1316
1317 #[test]
1318 fn only_granted_astheno_names_reach_snow_globe_accounts() {
1319 let path = std::env::temp_dir().join(format!("guest-link-test-{}", uuid::Uuid::new_v4()));
1320 let auth = auth::Store::new(
1321 &path,
1322 "https://snowglobe.paperclover.net",
1323 "https://file.paperclover.net",
1324 "auth.paperclover.net",
1325 )
1326 .unwrap();
1327 let add = |id: &str, name: &str| {
1328 auth.db.lock().unwrap().execute("INSERT INTO users(id,profile) VALUES (?,?)", [id, &json!({"username":name,"enabled":true,"requiredActions":[]}).to_string()]).unwrap();
1329 };
1330 add("snow", "snow");
1331 add("meghan", "meghan");
1332 let link = |id: &str, handle: &str| link(&auth.db.lock().unwrap(), id, handle);
1333 // What the callback does after Astheno verifies `handle` as `subject`.
1334 let shale = |subject: &str, handle: &str| {
1335 claim(&auth, subject, handle).unwrap();
1336 account(&auth, "astheno", subject, handle, None).unwrap()
1337 };
1338 let snow = |subject: &str, handle: &str| {
1339 claim(&auth, subject, handle).unwrap();
1340 member(&auth, "astheno", subject)
1341 };
1342
1343 // Ungranted names are Shale guests and never reach an account, even one with the same username.
1344 let guest = shale("sub-clover", "clover");
1345 let impostor = shale("sub-snow", "snow");
1346 assert!(is_guest(&auth::user(&auth.db.lock().unwrap(), &impostor).unwrap()));
1347 assert_eq!(snow("sub-snow", "snow").unwrap_err().status, 403);
1348 assert_eq!(snow("sub-clover", "clover").unwrap_err().status, 403);
1349
1350 // A grant binds the first verified sign-in, taking over an existing guest.
1351 link("snow", " @Clover ").unwrap();
1352 link("meghan", "meghan").unwrap();
1353 assert_eq!(snow("sub-clover", "clover").unwrap(), "snow");
1354 assert_eq!(shale("sub-clover", "clover"), "snow");
1355 assert!(auth::user(&auth.db.lock().unwrap(), "snow").unwrap()["firstName"].is_null());
1356 assert_eq!(shale("sub-meghan", "meghan"), "meghan");
1357 assert_eq!(snow("sub-meghan", "meghan").unwrap(), "meghan");
1358
1359 // Once bound, another subject presenting the name is just a guest.
1360 assert_ne!(shale("sub-reused", "meghan"), "meghan");
1361 assert_eq!(snow("sub-reused", "meghan").unwrap_err().status, 403);
1362
1363 // Names are unique, guests can't be linked, and names must be plausible.
1364 assert_eq!(link("meghan", "clover").unwrap_err().status, 409);
1365 assert_eq!(link(&impostor, "snow").unwrap_err().status, 400);
1366 assert_eq!(link("meghan", "has space").unwrap_err().status, 400);
1367
1368 // Disabling or unlinking ends access; the guest it replaced comes back on Shale.
1369 auth.db.lock().unwrap().execute("UPDATE users SET profile=json_set(profile,'$.enabled',json('false')) WHERE id='snow'", []).unwrap();
1370 assert_eq!(snow("sub-clover", "clover").unwrap_err().status, 403);
1371 unlink(&auth.db.lock().unwrap(), "snow").unwrap();
1372 assert_eq!(snow("sub-clover", "clover").unwrap_err().status, 403);
1373 assert_eq!(shale("sub-clover", "clover"), guest);
1374
1375 // Snow Globe offers only Astheno, once it is registered.
1376 assert_eq!(providers(&auth, "/").unwrap(), json!([]));
1377 provision(&auth, json!({"provider":"astheno","enabled":true,"clientId":"client","clientSecret":"0123456789abcdef"})).unwrap();
1378 provision(&auth, json!({"provider":"github","enabled":true,"clientId":"client","clientSecret":"0123456789abcdef"})).unwrap();
1379 assert_eq!(providers(&auth, "/").unwrap(), json!([{"id":"astheno","name":"Astheno"}]));
1380 assert_eq!(destination(&auth, "github", "/").unwrap_err().status, 400);
1381 assert_eq!(destination(&auth, "astheno", "/").unwrap(), ("/".to_owned(), false));
1382 drop(auth);
1383 std::fs::remove_dir_all(path).unwrap();
1384 }
1385
1386 #[tokio::test]
1387 async fn adding_needs_a_registered_provider_and_a_plausible_name() {
1388 let path = std::env::temp_dir().join(format!("guest-add-test-{}", uuid::Uuid::new_v4()));
1389 let auth = auth::Store::new(
1390 &path,
1391 "https://snowglobe.paperclover.net",
1392 "https://file.paperclover.net",
1393 "auth.paperclover.net",
1394 )
1395 .unwrap();
1396 assert_eq!(add(&auth, "astheno", "alice").await.unwrap_err().status, 409);
1397 assert_eq!(add(&auth, "gitlab", "alice").await.unwrap_err().status, 404);
1398 provision(&auth, json!({"provider":"astheno","enabled":true,"clientId":"client","clientSecret":"0123456789abcdef"})).unwrap();
1399 for name in ["", "has space", "-alice", "a-name-over-sixteen"] {
1400 assert_eq!(add(&auth, "astheno", name).await.unwrap_err().status, 400, "{name}");
1401 }
1402 let added = add(&auth, "astheno", " @Alice ").await.unwrap();
1403 assert_eq!(
1404 auth::user(&auth.db.lock().unwrap(), string(&added["id"])).unwrap()["username"],
1405 "guest-astheno-alice"
1406 );
1407 drop(auth);
1408 std::fs::remove_dir_all(path).unwrap();
1409 }
1410}