| author | |
| committer | |
| log | 608212cba743fa289f7d666112d5a4fc6e5b4fa9 |
| tree | accd3d0effb07dcfc4bc1fc15c4b33297371c214 |
| parent | 7e83355b579b72267ab1c4fdfb53e8daf2031581 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
Snow sign on now offers Astheno, but only to accounts an admin links to an
Astheno username on the Users page, at creation or later. The first sign-in
Astheno verifies as that username binds the account, taking over an existing
Shale guest; any other Astheno account is refused and nothing is created.
Shale still turns any provider into a guest, but a linked Astheno identity
signs in as its Snow Globe account instead.
Assisted-by: claude-opus-5.58 files changed, 304 insertions(+), 78 deletions(-)
dashboard/src/auth.rs+6-15| ... | ... | @@ -492,7 +492,10 @@ impl Store { |
| 492 | 492 | } |
| 493 | 493 | Ok(()) |
| 494 | 494 | } |
| 495 | fn next(&self, id: &str, flow: &str, path: &str) -> Result<String> { | |
| 495 | pub(crate) fn next(&self, id: &str, flow: &str, path: &str) -> Result<String> { | |
| 496 | if !array(&user(&self.db.lock().unwrap(), id)?["requiredActions"]).is_empty() { | |
| 497 | return Ok("/account".into()); | |
| 498 | } | |
| 496 | 499 | if flow.is_empty() { |
| 497 | 500 | if !path.starts_with('/') |
| 498 | 501 | || path.starts_with("//") |
| ... | ... | @@ -510,9 +513,6 @@ impl Store { |
| 510 | 513 | "Guest accounts can use Shale. Open Shale to continue.", |
| 511 | 514 | )); |
| 512 | 515 | } |
| 513 | if !array(&user(&db, id)?["requiredActions"]).is_empty() { | |
| 514 | return Ok("/account".into()); | |
| 515 | } | |
| 516 | 516 | let value = pending(&db, flow, "file", false)?; |
| 517 | 517 | if value.is_null() { |
| 518 | 518 | return Err(Error::new( |
| ... | ... | @@ -901,11 +901,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp |
| 901 | 901 | if body["remember"] == false { |
| 902 | 902 | session = session.replace(&format!("; Max-Age={SESSION_TTL}"), ""); |
| 903 | 903 | } |
| 904 | let next = if !array(&user["requiredActions"]).is_empty() { | |
| 905 | "/account".into() | |
| 906 | } else { | |
| 907 | auth.next(&id, string(&body["flow"]), string(&body["next"]))? | |
| 908 | }; | |
| 904 | let next = auth.next(&id, string(&body["flow"]), string(&body["next"]))?; | |
| 909 | 905 | return Ok( |
| 910 | 906 | ([("set-cookie", session)], axum::Json(json!({"next":next}))).into_response(), |
| 911 | 907 | ); |
| ... | ... | @@ -1104,12 +1100,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Resp |
| 1104 | 1100 | if body.get("remember").unwrap_or(&value["remember"]) == false { |
| 1105 | 1101 | session = session.replace(&format!("; Max-Age={SESSION_TTL}"), ""); |
| 1106 | 1102 | } |
| 1107 | let next = | |
| 1108 | if !array(&self::user(&auth.db.lock().unwrap(), id)?["requiredActions"]).is_empty() { | |
| 1109 | "/account".into() | |
| 1110 | } else { | |
| 1111 | auth.next(id, string(&value["flow"]), string(&value["next"]))? | |
| 1112 | }; | |
| 1103 | let next = auth.next(id, string(&value["flow"]), string(&value["next"]))?; | |
| 1113 | 1104 | return Ok(([("set-cookie", session)], axum::Json(json!({"next":next}))).into_response()); |
| 1114 | 1105 | } |
| 1115 | 1106 | if path == "/auth/setup" { |
dashboard/src/guest.rs+219-48| ... | ... | @@ -84,15 +84,16 @@ pub fn provision(auth: &auth::Store, input: Value) -> Result<Value> { |
| 84 | 84 | } |
| 85 | 85 | |
| 86 | 86 | pub fn providers(auth: &auth::Store, next: &str) -> Result<Value> { |
| 87 | if oidc::guest_target(auth, next).is_err() { | |
| 88 | return Ok(json!([])); | |
| 89 | } | |
| 87 | let shale = oidc::guest_target(auth, next).is_ok(); | |
| 90 | 88 | let db = auth.db.lock().unwrap(); |
| 91 | let mut query = db.prepare("SELECT id FROM guest_providers ORDER BY id")?; | |
| 89 | let mut query = | |
| 90 | db.prepare("SELECT id FROM guest_providers WHERE ?1 OR id='astheno' ORDER BY id")?; | |
| 92 | 91 | let mut ids = query |
| 93 | .query_map([], |r| r.get::<_, String>(0))? | |
| 92 | .query_map([shale], |r| r.get::<_, String>(0))? | |
| 94 | 93 | .collect::<std::result::Result<Vec<_>, _>>()?; |
| 95 | ids.push("atproto".into()); | |
| 94 | if shale { | |
| 95 | ids.push("atproto".into()); | |
| 96 | } | |
| 96 | 97 | Ok(json!( |
| 97 | 98 | ids.iter() |
| 98 | 99 | .map(|id| json!({"id":id,"name":known(id).unwrap_or(id)})) |
| ... | ... | @@ -105,6 +106,15 @@ fn registration(auth: &auth::Store, provider: &str) -> Result<(String, String)> |
| 105 | 106 | .optional()?.ok_or_else(|| Error::new(503, "This sign-in provider isn't available. Use your Snow Globe account or try again later.")) |
| 106 | 107 | } |
| 107 | 108 | |
| 109 | /// Shale takes any provider and mints guests; everywhere else only linked Astheno accounts get in. | |
| 110 | fn 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 | ||
| 108 | 118 | async fn response_bytes(mut response: reqwest::Response) -> Result<Vec<u8>> { |
| 109 | 119 | let status = response.status(); |
| 110 | 120 | let endpoint = format!( |
| ... | ... | @@ -507,20 +517,26 @@ fn account( |
| 507 | 517 | .optional()?; |
| 508 | 518 | if let Some(id) = existing { |
| 509 | 519 | let profile = auth::user(&tx, &id)?; |
| 510 | if !is_guest(&profile) || profile["enabled"] != true { | |
| 511 | return Err(Error::new( | |
| 512 | 403, | |
| 513 | "This guest account is disabled. Contact Clover.", | |
| 514 | )); | |
| 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 | )?; | |
| 515 | 528 | } |
| 516 | tx.execute( | |
| 517 | "UPDATE users SET profile=json_patch(profile,?) WHERE id=?", | |
| 518 | sql![json!({"firstName":name,"attributes":{"picture":picture.map(|picture| vec![picture])}}).to_string(), id], | |
| 519 | )?; | |
| 520 | 529 | tx.commit()?; |
| 521 | 530 | return Ok(id); |
| 522 | 531 | } |
| 523 | let id = create(&tx, provider, &username(provider, subject), name, picture)?; | |
| 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 | }; | |
| 524 | 540 | tx.execute( |
| 525 | 541 | "INSERT INTO external_identities VALUES (?,?,?)", |
| 526 | 542 | sql![provider, subject, id], |
| ... | ... | @@ -529,11 +545,94 @@ fn account( |
| 529 | 545 | Ok(id) |
| 530 | 546 | } |
| 531 | 547 | |
| 532 | /// Astheno's per-client subjects require binding reserved names at verified sign-in. | |
| 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. | |
| 533 | 550 | fn claim(auth: &auth::Store, subject: &str, username: &str) -> Result<()> { |
| 534 | auth.db.lock().unwrap().execute( | |
| 535 | "INSERT OR IGNORE INTO external_identities SELECT 'astheno',?,id FROM users WHERE username=? AND id NOT IN (SELECT user_id FROM external_identities)", | |
| 536 | sql![subject, format!("guest-astheno-{username}")], | |
| 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. | |
| 580 | fn 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 | ||
| 595 | fn 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. | |
| 607 | pub 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 | ||
| 628 | pub 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], | |
| 537 | 636 | )?; |
| 538 | 637 | Ok(()) |
| 539 | 638 | } |
| ... | ... | @@ -635,16 +734,7 @@ pub async fn add(auth: &auth::Store, provider: &str, handle: &str) -> Result<Val |
| 635 | 734 | let name = handle.unwrap_or_else(|| did.clone()); |
| 636 | 735 | grant(auth, provider, Some(&did), &name) |
| 637 | 736 | } |
| 638 | _ => { | |
| 639 | let name = handle.to_lowercase(); | |
| 640 | if name.len() > 16 | |
| 641 | || !name.starts_with(|c: char| c.is_ascii_alphanumeric()) | |
| 642 | || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) | |
| 643 | { | |
| 644 | return Err(Error::new(400, "Enter an Astheno username.")); | |
| 645 | } | |
| 646 | grant(auth, provider, None, &name) | |
| 647 | } | |
| 737 | _ => grant(auth, provider, None, &astheno_name(handle)?), | |
| 648 | 738 | } |
| 649 | 739 | } |
| 650 | 740 | |
| ... | ... | @@ -721,8 +811,9 @@ async fn handle(app: &App, request: Request) -> Result<Response> { |
| 721 | 811 | let callback = format!("{}auth/guest/callback/{provider}", auth.origin); |
| 722 | 812 | if parts[3] == "start" { |
| 723 | 813 | auth.limit(headers, "guest")?; |
| 724 | let next = oidc::guest_target( | |
| 814 | let (next, _) = destination( | |
| 725 | 815 | auth, |
| 816 | provider, | |
| 726 | 817 | query.get("next").map(String::as_str).unwrap_or_default(), |
| 727 | 818 | )?; |
| 728 | 819 | if provider == "atproto" { |
| ... | ... | @@ -763,7 +854,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> { |
| 763 | 854 | let state = auth::issue( |
| 764 | 855 | &auth.db.lock().unwrap(), |
| 765 | 856 | "guest", |
| 766 | json!({"provider":provider,"next":next,"verifier":verifier,"nonce":nonce}), | |
| 857 | json!({"provider":provider,"next":next,"flow":query.get("flow"),"verifier":verifier,"nonce":nonce}), | |
| 767 | 858 | 300, |
| 768 | 859 | )?; |
| 769 | 860 | let mut target = url::Url::parse(if provider == "github" { |
| ... | ... | @@ -822,7 +913,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> { |
| 822 | 913 | } |
| 823 | 914 | auth::pending(&db, state, "guest", true)? |
| 824 | 915 | }; |
| 825 | let next = oidc::guest_target(auth, string(&flow["next"]))?; | |
| 916 | let (next, shale) = destination(auth, provider, string(&flow["next"]))?; | |
| 826 | 917 | let result = async { |
| 827 | 918 | let code = query |
| 828 | 919 | .get("code") |
| ... | ... | @@ -833,7 +924,7 @@ async fn handle(app: &App, request: Request) -> Result<Response> { |
| 833 | 924 | "Sign-in wasn't completed. Return to Shale and try again.", |
| 834 | 925 | ) |
| 835 | 926 | })?; |
| 836 | if provider == "atproto" { | |
| 927 | let id = if provider == "atproto" { | |
| 837 | 928 | let profile = tokio::time::timeout( |
| 838 | 929 | Duration::from_secs(45), |
| 839 | 930 | atproto::finish( |
| ... | ... | @@ -860,22 +951,28 @@ async fn handle(app: &App, request: Request) -> Result<Response> { |
| 860 | 951 | id |
| 861 | 952 | ], |
| 862 | 953 | )?; |
| 863 | return auth.create_session(&id, "dashboard", headers, None); | |
| 864 | } | |
| 865 | let (client, secret) = registration(auth, provider)?; | |
| 866 | let (subject, name, picture, handle) = | |
| 867 | exchange(&http()?, provider, &client, &secret, code, &callback, &flow).await?; | |
| 868 | if let Some(handle) = handle { | |
| 869 | claim(auth, &subject, &handle)?; | |
| 870 | } | |
| 871 | let id = account(auth, provider, &subject, &name, picture.as_deref())?; | |
| 872 | auth.create_session(&id, "dashboard", headers, None) | |
| 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)?)) | |
| 873 | 970 | } |
| 874 | 971 | .await; |
| 875 | 972 | match result { |
| 876 | Ok(session) => Ok(( | |
| 973 | Ok((session, location)) => Ok(( | |
| 877 | 974 | StatusCode::FOUND, |
| 878 | [("location", next), ("set-cookie", session)], | |
| 975 | [("location", location), ("set-cookie", session)], | |
| 879 | 976 | axum::response::AppendHeaders([("set-cookie", auth::set_cookie(COOKIE, "", Some(0)))]), |
| 880 | 977 | ) |
| 881 | 978 | .into_response()), |
| ... | ... | @@ -889,7 +986,12 @@ async fn handle(app: &App, request: Request) -> Result<Response> { |
| 889 | 986 | [ |
| 890 | 987 | ( |
| 891 | 988 | "location", |
| 892 | format!("/sign-in?next={}&guest_error=1", encoded(&next)), | |
| 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 | ), | |
| 893 | 995 | ), |
| 894 | 996 | ("set-cookie", auth::set_cookie(COOKIE, "", Some(0))), |
| 895 | 997 | ], |
| ... | ... | @@ -904,7 +1006,7 @@ pub async fn route(State(app): State<Arc<App>>, request: Request) -> Response { |
| 904 | 1006 | Ok(response) => response, |
| 905 | 1007 | Err(error) => Error::new( |
| 906 | 1008 | error.status, |
| 907 | "Guest sign-in couldn't continue. Return to Shale and try again.", | |
| 1009 | "Sign-in couldn't continue. Go back and try again.", | |
| 908 | 1010 | ) |
| 909 | 1011 | .into_response(), |
| 910 | 1012 | }; |
| ... | ... | @@ -1212,6 +1314,75 @@ mod tests { |
| 1212 | 1314 | std::fs::remove_dir_all(path).unwrap(); |
| 1213 | 1315 | } |
| 1214 | 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 | ||
| 1215 | 1386 | #[tokio::test] |
| 1216 | 1387 | async fn adding_needs_a_registered_provider_and_a_plausible_name() { |
| 1217 | 1388 | let path = std::env::temp_dir().join(format!("guest-add-test-{}", uuid::Uuid::new_v4())); |
dashboard/src/users.rs+18-7| ... | ... | @@ -231,8 +231,8 @@ pub async fn route( |
| 231 | 231 | if parts.is_empty() && method == Method::POST { |
| 232 | 232 | let mut profile = profile(&body["profile"], true)?; |
| 233 | 233 | let setup = string(&body["setup"]["kind"]); |
| 234 | if setup != "invite" && setup != "password" { | |
| 235 | return Err(Error::new(400, "Choose an invitation or a password.")); | |
| 234 | if !["invite", "password", "astheno"].contains(&setup) { | |
| 235 | return Err(Error::new(400, "Choose an invitation, a password, or Astheno.")); | |
| 236 | 236 | } |
| 237 | 237 | let hash = if setup == "password" { |
| 238 | 238 | Some( |
| ... | ... | @@ -249,11 +249,11 @@ pub async fn route( |
| 249 | 249 | let id = uuid::Uuid::new_v4().to_string(); |
| 250 | 250 | profile["enabled"] = json!(true); |
| 251 | 251 | profile["emailVerified"] = json!(false); |
| 252 | profile["requiredActions"] = json!([if hash.is_some() { | |
| 253 | "UPDATE_PASSWORD" | |
| 254 | } else { | |
| 255 | "SETUP" | |
| 256 | }]); | |
| 252 | profile["requiredActions"] = match setup { | |
| 253 | "password" => json!(["UPDATE_PASSWORD"]), | |
| 254 | "invite" => json!(["SETUP"]), | |
| 255 | _ => json!([]), | |
| 256 | }; | |
| 257 | 257 | profile["createdTimestamp"] = json!((now() * 1000.0) as i64); |
| 258 | 258 | profile["attributes"] = json!({}); |
| 259 | 259 | { |
| ... | ... | @@ -278,6 +278,9 @@ pub async fn route( |
| 278 | 278 | if let Some(hash) = &hash { |
| 279 | 279 | auth::set_password(&transaction, &id, hash)?; |
| 280 | 280 | } |
| 281 | if setup == "astheno" || !string(&body["astheno"]).is_empty() { | |
| 282 | guest::link(&transaction, &id, string(&body["astheno"]))?; | |
| 283 | } | |
| 281 | 284 | transaction.commit()?; |
| 282 | 285 | } |
| 283 | 286 | return Ok((StatusCode::CREATED,axum::Json(json!({"id":id,"url":if setup=="invite" {Some(app.auth.setup_link(&id)?)}else{None}}))).into_response()); |
| ... | ... | @@ -386,6 +389,14 @@ pub async fn route( |
| 386 | 389 | identity::confirm_key(&transaction,id,&fingerprint)?; |
| 387 | 390 | Value::Null |
| 388 | 391 | } |
| 392 | [_, "astheno"] if method == Method::PUT => { | |
| 393 | guest::link(&transaction, id, string(&body["handle"]))?; | |
| 394 | Value::Null | |
| 395 | } | |
| 396 | [_, "astheno"] if method == Method::DELETE => { | |
| 397 | guest::unlink(&transaction, id)?; | |
| 398 | Value::Null | |
| 399 | } | |
| 389 | 400 | [_, "credentials"] if method == Method::GET => auth::credentials(&transaction, id)?, |
| 390 | 401 | [_, "logout"] if method == Method::POST => { |
| 391 | 402 | transaction.execute("DELETE FROM sessions WHERE user_id=?", [id])?; |
dashboard/web/api.contract.ts+5-1| ... | ... | @@ -229,7 +229,7 @@ export type Api = Hono<{}, { |
| 229 | 229 | }; |
| 230 | 230 | "/users": { |
| 231 | 231 | $get: Endpoint<{users:(User & {sessions:Session[]})[]; groups:Group[]}>; |
| 232 | $post: Endpoint<{ id: string; url: string | null }, { json: { profile: { email: string; firstName: string; lastName: string; username: string; }; groups: string[]; setup: { kind: "invite"; } | { kind: "password"; password: string; }; }; }, 201>; | |
| 232 | $post: Endpoint<{ id: string; url: string | null }, { json: { profile: { email: string; firstName: string; lastName: string; username: string; }; groups: string[]; setup: { kind: "invite"; } | { kind: "password"; password: string; } | { kind: "astheno"; }; astheno?: string; }; }, 201>; | |
| 233 | 233 | }; |
| 234 | 234 | "/users/guests": { |
| 235 | 235 | $post: Endpoint<{ id: string; created: boolean }, { json: { provider: "github" | "astheno" | "atproto"; handle: string; }; }>; |
| ... | ... | @@ -241,6 +241,10 @@ export type Api = Hono<{}, { |
| 241 | 241 | "/users/groups": { |
| 242 | 242 | $put: Endpoint<null, { json: { users: string[]; add: string[]; remove: string[]; }; }, 204, "body">; |
| 243 | 243 | }; |
| 244 | "/users/:id/astheno": { | |
| 245 | $put: Endpoint<null, { param: { id: string; }; json: { handle: string; }; }, 204, "body">; | |
| 246 | $delete: Endpoint<null, { param: { id: string; }; }, 204, "body">; | |
| 247 | }; | |
| 244 | 248 | "/users/:id/groups/:group": { |
| 245 | 249 | $put: Endpoint<null, { param: { id: string; group: string; }; }, 204, "body">; |
| 246 | 250 | $delete: Endpoint<null, { param: { id: string; group: string; }; }, 204, "body">; |
dashboard/web/pages/SignIn.tsx+2-2| ... | ... | @@ -22,7 +22,7 @@ export function SignIn() { |
| 22 | 22 | const [passwordStep, setPasswordStep] = createSignal(false); |
| 23 | 23 | const [visible, setVisible] = createSignal(false); |
| 24 | 24 | const [busy, setBusy] = createSignal(false); |
| 25 | const [error, setError] = createSignal(params.has("guest_error") ? (atproto ? "Sign-in couldn't start. Check your handle and try again." : "Guest sign-in wasn't completed. Choose a provider to try again.") : ""); | |
| 25 | const [error, setError] = createSignal(params.has("guest_error") ? (params.get("guest_error") === "denied" ? "That account can't sign in here. Ask Clover for access." : atproto ? "Sign-in couldn't start. Check your handle and try again." : "Sign-in wasn't completed. Choose a provider to try again.") : ""); | |
| 26 | 26 | const [notice, setNotice] = createSignal(""); |
| 27 | 27 | let conditional: AbortController | undefined; |
| 28 | 28 | let disposed = false; |
| ... | ... | @@ -103,7 +103,7 @@ export function SignIn() { |
| 103 | 103 | }> |
| 104 | 104 | <Show when={!setup && !passwordStep() && status()?.providers?.length}> |
| 105 | 105 | <div id="kc-social-providers" class="guest-providers"> |
| 106 | <For each={status()?.providers}>{(provider) => <a rel="external" data-provider={provider.id} class="pf-v5-c-button pf-m-primary pf-m-block" href={provider.id === "atproto" ? `/sign-in?${statusQuery}&atproto=1` : `/auth/guest/start/${provider.id}?next=${encodeURIComponent(params.get("next") ?? "")}`}>{provider.id === "atproto" ? <span innerHTML={atprotoIcon} /> : provider.id === "astheno" ? <Stone size={18} aria-hidden="true" /> : <img src={githubIcon} width="18" height="18" alt="" />}<span>continue with {provider.name}</span></a>}</For> | |
| 106 | <For each={status()?.providers}>{(provider) => <a rel="external" data-provider={provider.id} class="pf-v5-c-button pf-m-primary pf-m-block" href={provider.id === "atproto" ? `/sign-in?${statusQuery}&atproto=1` : `/auth/guest/start/${provider.id}?${new URLSearchParams({ next: params.get("next") ?? "", flow: params.get("flow") ?? "" })}`}>{provider.id === "atproto" ? <span innerHTML={atprotoIcon} /> : provider.id === "astheno" ? <Stone size={18} aria-hidden="true" /> : <img src={githubIcon} width="18" height="18" alt="" />}<span>continue with {provider.name}</span></a>}</For> | |
| 107 | 107 | </div> |
| 108 | 108 | </Show> |
| 109 | 109 | <div id="kc-form"><div id="kc-form-wrapper"> |
dashboard/web/pages/Users.tsx+36-5| ... | ... | @@ -34,6 +34,8 @@ const GUESTS = { |
| 34 | 34 | atproto: { name: "AT Protocol", field: "AT handle", placeholder: "alice.bsky.social" }, |
| 35 | 35 | } as const; |
| 36 | 36 | |
| 37 | const ASTHENO_HINT = "Whoever holds this Astheno username can sign in as this account, on Snow Globe and Shale. Their first sign-in binds it."; | |
| 38 | ||
| 37 | 39 | const STATES = { all: "users", guests: "guests", disabled: "disabled", pending: "setup pending" } as const; |
| 38 | 40 | |
| 39 | 41 | type Params = { q?: string; group?: string; state?: keyof typeof STATES }; |
| ... | ... | @@ -247,7 +249,7 @@ function List(props: { data: Resource<Data>; ready: Accessor<Data | undefined>; |
| 247 | 249 | title: "New user", |
| 248 | 250 | confirmLabel: "create user", |
| 249 | 251 | body: () => { |
| 250 | const [invite, setInvite] = createSignal(true); | |
| 252 | const [kind, setKind] = createSignal<"invite" | "password" | "astheno">("invite"); | |
| 251 | 253 | return ( |
| 252 | 254 | <> |
| 253 | 255 | <label class="field">username<input name="username" class="search" required autocomplete="off" spellcheck={false} autofocus /></label> |
| ... | ... | @@ -267,11 +269,17 @@ function List(props: { data: Resource<Data>; ready: Accessor<Data | undefined>; |
| 267 | 269 | <div class="field"> |
| 268 | 270 | first sign-in |
| 269 | 271 | <TabBar label="First sign-in"> |
| 270 | <button type="button" aria-pressed={invite()} onClick={() => setInvite(true)}>create an invitation link</button> | |
| 271 | <button type="button" aria-pressed={!invite()} onClick={() => setInvite(false)}>set a password</button> | |
| 272 | <button type="button" aria-pressed={kind() === "invite"} onClick={() => setKind("invite")}>create an invitation link</button> | |
| 273 | <button type="button" aria-pressed={kind() === "password"} onClick={() => setKind("password")}>set a password</button> | |
| 274 | <button type="button" aria-pressed={kind() === "astheno"} onClick={() => setKind("astheno")}>astheno only</button> | |
| 272 | 275 | </TabBar> |
| 276 | <input type="hidden" name="kind" value={kind()} /> | |
| 273 | 277 | </div> |
| 274 | <Show when={!invite()}> | |
| 278 | <label class="field">astheno username{kind() === "astheno" ? "" : " (optional)"} | |
| 279 | <input name="astheno" class="search" required={kind() === "astheno"} maxLength={17} autocomplete="off" spellcheck={false} placeholder="janedoe" /> | |
| 280 | <span class="hint">{ASTHENO_HINT}</span> | |
| 281 | </label> | |
| 282 | <Show when={kind() === "password"}> | |
| 275 | 283 | <label class="field">temporary password |
| 276 | 284 | <input name="password" class="search" type="password" required minLength={8} maxLength={1024} autocomplete="new-password" /> |
| 277 | 285 | <span class="hint">They pick their own at first sign-in</span> |
| ... | ... | @@ -286,7 +294,8 @@ function List(props: { data: Resource<Data>; ready: Accessor<Data | undefined>; |
| 286 | 294 | json: { |
| 287 | 295 | profile: { username: text("username"), email: text("email"), firstName: text("firstName"), lastName: text("lastName") }, |
| 288 | 296 | groups: form.getAll("groups").map(String), |
| 289 | setup: form.has("password") ? { kind: "password", password: text("password") } : { kind: "invite" }, | |
| 297 | setup: text("kind") === "password" ? { kind: "password", password: text("password") } : { kind: text("kind") as "invite" | "astheno" }, | |
| 298 | astheno: text("astheno") || undefined, | |
| 290 | 299 | }, |
| 291 | 300 | })); |
| 292 | 301 | await props.refetch(); |
| ... | ... | @@ -546,6 +555,22 @@ function Profile(props: { user: User; data: Data; refetch: () => unknown }) { |
| 546 | 555 | setSetupLink(""); toast("Revoked the setup link"); |
| 547 | 556 | }); |
| 548 | 557 | |
| 558 | const astheno = () => props.user.attributes?.astheno?.[0]; | |
| 559 | const linkAstheno = () => showTextDialog({ | |
| 560 | title: `Astheno sign-in for ${props.user.username}`, | |
| 561 | label: "Astheno username", | |
| 562 | placeholder: "janedoe", | |
| 563 | body: () => <div class="field"><span class="hint">{ASTHENO_HINT}</span></div>, | |
| 564 | confirmLabel: "link", | |
| 565 | onConfirm: async (handle) => { | |
| 566 | await parseResponse(api.users[":id"].astheno.$put({ param: param(), json: { handle } })); | |
| 567 | await props.refetch(); | |
| 568 | }, | |
| 569 | }); | |
| 570 | const unlinkAstheno = () => run("astheno", async () => { | |
| 571 | await parseResponse(api.users[":id"].astheno.$delete({ param: param() })); | |
| 572 | await props.refetch(); | |
| 573 | }); | |
| 549 | 574 | const setPassword = () => showConfirmDialog({ |
| 550 | 575 | title: `Set ${props.user.username}'s password`, |
| 551 | 576 | body: <><label class="field">new password, at least 8 characters<input name="password" class="search" type="password" required minLength={8} maxLength={1024} autocomplete="new-password" /></label><Checkbox name="temporary" checked>ask for a new one at next sign-in</Checkbox></>, |
| ... | ... | @@ -658,6 +683,12 @@ function Profile(props: { user: User; data: Data; refetch: () => unknown }) { |
| 658 | 683 | ); |
| 659 | 684 | }} |
| 660 | 685 | </Loaded> |
| 686 | <h2 class="card-title opens">astheno</h2> | |
| 687 | <Show when={astheno()} fallback={<p class="muted">Not linked. Only linked accounts can sign in with Astheno.</p>}> | |
| 688 | <p>{astheno()}</p> | |
| 689 | </Show> | |
| 690 | <button class="button small" disabled={!!astheno() || busy() === "astheno"} onClick={linkAstheno}>link</button>{" "} | |
| 691 | <button class="button small" disabled={!astheno() || busy() === "astheno"} onClick={unlinkAstheno}>unlink</button> | |
| 661 | 692 | <h2 class="card-title opens">setup link</h2> |
| 662 | 693 | <p class="muted">One use, valid for 24 hours. A new link replaces the previous one.</p> |
| 663 | 694 | <button class="button small" disabled={!props.user.enabled || busy() === "link"} onClick={createLink}>create setup link</button>{" "} |
tools/dashboard-auth-test.py+17| ... | ... | @@ -300,6 +300,23 @@ def main(): |
| 300 | 300 | replacement = request('/api/users/' + invitation['id'] + '/setup-link', 'POST', {}, cookies)['url'] |
| 301 | 301 | request('/api/users/' + invitation['id'] + '/setup-link', 'DELETE', {}, cookies, 204) |
| 302 | 302 | request('/auth/status?' + replacement.split('?', 1)[1], cookies={}, status=410) |
| 303 | with sqlite3.connect(data / 'accounts.sqlite') as db: | |
| 304 | db.execute("INSERT INTO guest_providers VALUES ('astheno','client','0123456789abcdef')") | |
| 305 | assert request('/auth/status', cookies={})['providers'] == [{'id': 'astheno', 'name': 'Astheno'}] | |
| 306 | identity = {'profile': {'username': 'astheno-only', 'email': '', 'firstName': '', 'lastName': ''}, 'groups': [], 'setup': {'kind': 'astheno'}} | |
| 307 | request('/api/users', 'POST', identity, cookies, 400) | |
| 308 | only = request('/api/users', 'POST', {**identity, 'astheno': ' @Janedoe '}, cookies, 201) | |
| 309 | assert only['url'] is None | |
| 310 | linked = {u['id']: u for u in request('/api/users', cookies=cookies)['users']}[only['id']] | |
| 311 | assert linked['requiredActions'] == [] and linked['attributes']['astheno'] == ['janedoe'] | |
| 312 | request('/api/users/' + invitation['id'] + '/astheno', 'PUT', {'handle': 'janedoe'}, cookies, 409) | |
| 313 | request('/api/users/' + only['id'] + '/astheno', 'PUT', {'handle': 'janedoe'}, cookies, 204) | |
| 314 | request('/api/users/' + only['id'] + '/astheno', 'DELETE', {}, cookies, 204) | |
| 315 | assert 'astheno' not in {u['id']: u for u in request('/api/users', cookies=cookies)['users']}[only['id']].get('attributes', {}) | |
| 316 | redirect = request('/auth/guest/start/astheno?next=%2F', status=302, include_headers=True) | |
| 317 | assert redirect['location'].startswith('https://identity.astheno.software/authorize?') | |
| 318 | request('/auth/guest/start/github?next=%2F', status=400) | |
| 319 | request('/auth/guest/start/atproto?next=%2F', status=400) | |
| 303 | 320 | request('/api/users/' + invitation['id'], 'PATCH', {'enabled': False}, cookies, 204) |
| 304 | 321 | request('/api/me', cookies=newcomer, status=401) |
| 305 | 322 | stop(); start() |
tools/guest-provider.py+1| ... | ... | @@ -6,6 +6,7 @@ https://shale.paperclover.net and callback |
| 6 | 6 | https://snowglobe.paperclover.net/auth/guest/callback/github. |
| 7 | 7 | For Astheno Identity, register a confidential OpenID Connect client with callback |
| 8 | 8 | https://snowglobe.paperclover.net/auth/guest/callback/astheno and openid/profile scopes. |
| 9 | The same client signs in Snow Globe accounts linked to an Astheno username on the Users page. | |
| 9 | 10 | GitHub requests only read:user. Neither provider grants repository access. |
| 10 | 11 | |
| 11 | 12 | Run: python3 tools/guest-provider.py github --client-id CLIENT_ID |