From 608212cba743fa289f7d666112d5a4fc6e5b4fa9 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Fri, 23 Oct 2026 18:18:08 -0700 Subject: [PATCH] Sign in to Snow Globe with granted Astheno accounts 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.5 --- dashboard/src/auth.rs | 21 +-- dashboard/src/guest.rs | 267 +++++++++++++++++++++++++++------ dashboard/src/users.rs | 25 ++- dashboard/web/api.contract.ts | 6 +- dashboard/web/pages/SignIn.tsx | 4 +- dashboard/web/pages/Users.tsx | 41 ++++- tools/dashboard-auth-test.py | 17 +++ tools/guest-provider.py | 1 + 8 files changed, 304 insertions(+), 78 deletions(-) diff --git a/dashboard/src/auth.rs b/dashboard/src/auth.rs index 7f9b5e0db99e87039835b7043af970ca5900d09c..e7f69f029fe32b654812ada76260418ff82c7a86 100644 --- a/dashboard/src/auth.rs +++ b/dashboard/src/auth.rs @@ -492,7 +492,10 @@ impl Store { } Ok(()) } - fn next(&self, id: &str, flow: &str, path: &str) -> Result { + pub(crate) fn next(&self, id: &str, flow: &str, path: &str) -> Result { + if !array(&user(&self.db.lock().unwrap(), id)?["requiredActions"]).is_empty() { + return Ok("/account".into()); + } if flow.is_empty() { if !path.starts_with('/') || path.starts_with("//") @@ -510,9 +513,6 @@ impl Store { "Guest accounts can use Shale. Open Shale to continue.", )); } - if !array(&user(&db, id)?["requiredActions"]).is_empty() { - return Ok("/account".into()); - } let value = pending(&db, flow, "file", false)?; if value.is_null() { return Err(Error::new( @@ -901,11 +901,7 @@ pub async fn route(State(app): State>, request: Request) -> Result>, request: Request) -> Result Result { } pub fn providers(auth: &auth::Store, next: &str) -> Result { - if oidc::guest_target(auth, next).is_err() { - return Ok(json!([])); - } + let shale = oidc::guest_target(auth, next).is_ok(); let db = auth.db.lock().unwrap(); - let mut query = db.prepare("SELECT id FROM guest_providers ORDER BY id")?; + let mut query = + db.prepare("SELECT id FROM guest_providers WHERE ?1 OR id='astheno' ORDER BY id")?; let mut ids = query - .query_map([], |r| r.get::<_, String>(0))? + .query_map([shale], |r| r.get::<_, String>(0))? .collect::, _>>()?; - ids.push("atproto".into()); + if shale { + ids.push("atproto".into()); + } Ok(json!( ids.iter() .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)> .optional()?.ok_or_else(|| Error::new(503, "This sign-in provider isn't available. Use your Snow Globe account or try again later.")) } +/// Shale takes any provider and mints guests; everywhere else only linked Astheno accounts get in. +fn destination(auth: &auth::Store, provider: &str, next: &str) -> Result<(String, bool)> { + match oidc::guest_target(auth, next) { + Ok(next) => Ok((next, true)), + Err(_) if provider == "astheno" => Ok((next.to_owned(), false)), + Err(error) => Err(error), + } +} + async fn response_bytes(mut response: reqwest::Response) -> Result> { let status = response.status(); let endpoint = format!( @@ -507,20 +517,26 @@ fn account( .optional()?; if let Some(id) = existing { let profile = auth::user(&tx, &id)?; - if !is_guest(&profile) || profile["enabled"] != true { - return Err(Error::new( - 403, - "This guest account is disabled. Contact Clover.", - )); + if profile["enabled"] != true { + return Err(Error::new(403, "This account is disabled. Contact Clover.")); + } + if is_guest(&profile) { + tx.execute( + "UPDATE users SET profile=json_patch(profile,?) WHERE id=?", + sql![json!({"firstName":name,"attributes":{"picture":picture.map(|picture| vec![picture])}}).to_string(), id], + )?; } - tx.execute( - "UPDATE users SET profile=json_patch(profile,?) WHERE id=?", - sql![json!({"firstName":name,"attributes":{"picture":picture.map(|picture| vec![picture])}}).to_string(), id], - )?; tx.commit()?; return Ok(id); } - let id = create(&tx, provider, &username(provider, subject), name, picture)?; + let login = username(provider, subject); + let revived: Option = tx + .query_row("SELECT id FROM users WHERE username=?", [&login], |r| r.get(0)) + .optional()?; + let id = match revived { + Some(id) => id, + None => create(&tx, provider, &login, name, picture)?, + }; tx.execute( "INSERT INTO external_identities VALUES (?,?,?)", sql![provider, subject, id], @@ -529,11 +545,94 @@ fn account( Ok(id) } -/// Astheno's per-client subjects require binding reserved names at verified sign-in. +/// Astheno's per-client subjects require binding granted names at verified sign-in. An account an admin linked to +/// the name takes the identity over from a guest; otherwise a guest reserved under the name receives it. fn claim(auth: &auth::Store, subject: &str, username: &str) -> Result<()> { - auth.db.lock().unwrap().execute( - "INSERT OR IGNORE INTO external_identities SELECT 'astheno',?,id FROM users WHERE username=? AND id NOT IN (SELECT user_id FROM external_identities)", - sql![subject, format!("guest-astheno-{username}")], + let mut db = auth.db.lock().unwrap(); + let tx = db.transaction()?; + let linked: Option = tx + .query_row( + "SELECT id FROM users WHERE json_extract(profile,'$.attributes.astheno[0]')=? AND id NOT IN (SELECT user_id FROM external_identities)", + [username], + |r| r.get(0), + ) + .optional()?; + if let Some(id) = linked { + tx.execute( + "DELETE FROM external_identities WHERE provider='astheno' AND subject=? AND user_id IN (SELECT id FROM users WHERE json_extract(profile,'$.kind')='guest')", + [subject], + )?; + tx.execute( + "INSERT OR IGNORE INTO external_identities VALUES ('astheno',?,?)", + sql![subject, id], + )?; + } else { + tx.execute( + "INSERT OR IGNORE INTO external_identities SELECT 'astheno',?,id FROM users WHERE username=? AND id NOT IN (SELECT user_id FROM external_identities)", + sql![subject, format!("guest-astheno-{username}")], + )?; + } + tx.commit()?; + Ok(()) +} + +/// Snow Globe sign-in admits only accounts an admin linked to this identity. +fn member(auth: &auth::Store, provider: &str, subject: &str) -> Result { + let db = auth.db.lock().unwrap(); + let id: Option = db + .query_row( + "SELECT user_id FROM external_identities WHERE provider=? AND subject=?", + sql![provider, subject], + |r| r.get(0), + ) + .optional()?; + id.filter(|id| { + auth::user(&db, id).is_ok_and(|user| !is_guest(&user) && user["enabled"] == true) + }) + .ok_or_else(|| Error::new(403, "This account isn't linked to a Snow Globe account.")) +} + +fn astheno_name(handle: &str) -> Result { + let name = handle.to_lowercase(); + if name.len() > 16 + || !name.starts_with(|c: char| c.is_ascii_alphanumeric()) + || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) + { + return Err(Error::new(400, "Enter an Astheno username.")); + } + Ok(name) +} + +/// Grants Snow Globe sign-in to whoever Astheno verifies as this username; the first such sign-in binds the account. +pub fn link(db: &Connection, id: &str, handle: &str) -> Result<()> { + let name = astheno_name(handle.trim().trim_start_matches('@'))?; + if is_guest(&auth::user(db, id)?) { + return Err(Error::new(400, "Guests sign in with their own provider.")); + } + unlink(db, id)?; + let taken: bool = db.query_row( + "SELECT EXISTS(SELECT 1 FROM users WHERE json_extract(profile,'$.attributes.astheno[0]')=?)", + [&name], + |r| r.get(0), + )?; + if taken { + return Err(Error::new(409, "Another account already has that Astheno username.")); + } + db.execute( + "UPDATE users SET profile=json_patch(profile,?) WHERE id=?", + sql![json!({"attributes":{"astheno":[name]}}).to_string(), id], + )?; + Ok(()) +} + +pub fn unlink(db: &Connection, id: &str) -> Result<()> { + db.execute( + "DELETE FROM external_identities WHERE provider='astheno' AND user_id=?", + [id], + )?; + db.execute( + "UPDATE users SET profile=json_patch(profile,'{\"attributes\":{\"astheno\":null}}') WHERE id=?", + [id], )?; Ok(()) } @@ -635,16 +734,7 @@ pub async fn add(auth: &auth::Store, provider: &str, handle: &str) -> Result { - let name = handle.to_lowercase(); - if name.len() > 16 - || !name.starts_with(|c: char| c.is_ascii_alphanumeric()) - || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) - { - return Err(Error::new(400, "Enter an Astheno username.")); - } - grant(auth, provider, None, &name) - } + _ => grant(auth, provider, None, &astheno_name(handle)?), } } @@ -721,8 +811,9 @@ async fn handle(app: &App, request: Request) -> Result { let callback = format!("{}auth/guest/callback/{provider}", auth.origin); if parts[3] == "start" { auth.limit(headers, "guest")?; - let next = oidc::guest_target( + let (next, _) = destination( auth, + provider, query.get("next").map(String::as_str).unwrap_or_default(), )?; if provider == "atproto" { @@ -763,7 +854,7 @@ async fn handle(app: &App, request: Request) -> Result { let state = auth::issue( &auth.db.lock().unwrap(), "guest", - json!({"provider":provider,"next":next,"verifier":verifier,"nonce":nonce}), + json!({"provider":provider,"next":next,"flow":query.get("flow"),"verifier":verifier,"nonce":nonce}), 300, )?; let mut target = url::Url::parse(if provider == "github" { @@ -822,7 +913,7 @@ async fn handle(app: &App, request: Request) -> Result { } auth::pending(&db, state, "guest", true)? }; - let next = oidc::guest_target(auth, string(&flow["next"]))?; + let (next, shale) = destination(auth, provider, string(&flow["next"]))?; let result = async { let code = query .get("code") @@ -833,7 +924,7 @@ async fn handle(app: &App, request: Request) -> Result { "Sign-in wasn't completed. Return to Shale and try again.", ) })?; - if provider == "atproto" { + let id = if provider == "atproto" { let profile = tokio::time::timeout( Duration::from_secs(45), atproto::finish( @@ -860,22 +951,28 @@ async fn handle(app: &App, request: Request) -> Result { id ], )?; - return auth.create_session(&id, "dashboard", headers, None); - } - let (client, secret) = registration(auth, provider)?; - let (subject, name, picture, handle) = - exchange(&http()?, provider, &client, &secret, code, &callback, &flow).await?; - if let Some(handle) = handle { - claim(auth, &subject, &handle)?; - } - let id = account(auth, provider, &subject, &name, picture.as_deref())?; - auth.create_session(&id, "dashboard", headers, None) + id + } else { + let (client, secret) = registration(auth, provider)?; + let (subject, name, picture, handle) = + exchange(&http()?, provider, &client, &secret, code, &callback, &flow).await?; + if let Some(handle) = handle { + claim(auth, &subject, &handle)?; + } + if shale { + account(auth, provider, &subject, &name, picture.as_deref())? + } else { + member(auth, provider, &subject)? + } + }; + let session = auth.create_session(&id, "dashboard", headers, None)?; + Ok::<_, Error>((session, auth.next(&id, string(&flow["flow"]), &next)?)) } .await; match result { - Ok(session) => Ok(( + Ok((session, location)) => Ok(( StatusCode::FOUND, - [("location", next), ("set-cookie", session)], + [("location", location), ("set-cookie", session)], axum::response::AppendHeaders([("set-cookie", auth::set_cookie(COOKIE, "", Some(0)))]), ) .into_response()), @@ -889,7 +986,12 @@ async fn handle(app: &App, request: Request) -> Result { [ ( "location", - format!("/sign-in?next={}&guest_error=1", encoded(&next)), + format!( + "/sign-in?next={}&flow={}&guest_error={}", + encoded(&next), + encoded(string(&flow["flow"])), + if error.status == 403 { "denied" } else { "1" } + ), ), ("set-cookie", auth::set_cookie(COOKIE, "", Some(0))), ], @@ -904,7 +1006,7 @@ pub async fn route(State(app): State>, request: Request) -> Response { Ok(response) => response, Err(error) => Error::new( error.status, - "Guest sign-in couldn't continue. Return to Shale and try again.", + "Sign-in couldn't continue. Go back and try again.", ) .into_response(), }; @@ -1212,6 +1314,75 @@ mod tests { std::fs::remove_dir_all(path).unwrap(); } + #[test] + fn only_granted_astheno_names_reach_snow_globe_accounts() { + let path = std::env::temp_dir().join(format!("guest-link-test-{}", uuid::Uuid::new_v4())); + let auth = auth::Store::new( + &path, + "https://snowglobe.paperclover.net", + "https://file.paperclover.net", + "auth.paperclover.net", + ) + .unwrap(); + let add = |id: &str, name: &str| { + auth.db.lock().unwrap().execute("INSERT INTO users(id,profile) VALUES (?,?)", [id, &json!({"username":name,"enabled":true,"requiredActions":[]}).to_string()]).unwrap(); + }; + add("snow", "snow"); + add("meghan", "meghan"); + let link = |id: &str, handle: &str| link(&auth.db.lock().unwrap(), id, handle); + // What the callback does after Astheno verifies `handle` as `subject`. + let shale = |subject: &str, handle: &str| { + claim(&auth, subject, handle).unwrap(); + account(&auth, "astheno", subject, handle, None).unwrap() + }; + let snow = |subject: &str, handle: &str| { + claim(&auth, subject, handle).unwrap(); + member(&auth, "astheno", subject) + }; + + // Ungranted names are Shale guests and never reach an account, even one with the same username. + let guest = shale("sub-clover", "clover"); + let impostor = shale("sub-snow", "snow"); + assert!(is_guest(&auth::user(&auth.db.lock().unwrap(), &impostor).unwrap())); + assert_eq!(snow("sub-snow", "snow").unwrap_err().status, 403); + assert_eq!(snow("sub-clover", "clover").unwrap_err().status, 403); + + // A grant binds the first verified sign-in, taking over an existing guest. + link("snow", " @Clover ").unwrap(); + link("meghan", "meghan").unwrap(); + assert_eq!(snow("sub-clover", "clover").unwrap(), "snow"); + assert_eq!(shale("sub-clover", "clover"), "snow"); + assert!(auth::user(&auth.db.lock().unwrap(), "snow").unwrap()["firstName"].is_null()); + assert_eq!(shale("sub-meghan", "meghan"), "meghan"); + assert_eq!(snow("sub-meghan", "meghan").unwrap(), "meghan"); + + // Once bound, another subject presenting the name is just a guest. + assert_ne!(shale("sub-reused", "meghan"), "meghan"); + assert_eq!(snow("sub-reused", "meghan").unwrap_err().status, 403); + + // Names are unique, guests can't be linked, and names must be plausible. + assert_eq!(link("meghan", "clover").unwrap_err().status, 409); + assert_eq!(link(&impostor, "snow").unwrap_err().status, 400); + assert_eq!(link("meghan", "has space").unwrap_err().status, 400); + + // Disabling or unlinking ends access; the guest it replaced comes back on Shale. + auth.db.lock().unwrap().execute("UPDATE users SET profile=json_set(profile,'$.enabled',json('false')) WHERE id='snow'", []).unwrap(); + assert_eq!(snow("sub-clover", "clover").unwrap_err().status, 403); + unlink(&auth.db.lock().unwrap(), "snow").unwrap(); + assert_eq!(snow("sub-clover", "clover").unwrap_err().status, 403); + assert_eq!(shale("sub-clover", "clover"), guest); + + // Snow Globe offers only Astheno, once it is registered. + assert_eq!(providers(&auth, "/").unwrap(), json!([])); + provision(&auth, json!({"provider":"astheno","enabled":true,"clientId":"client","clientSecret":"0123456789abcdef"})).unwrap(); + provision(&auth, json!({"provider":"github","enabled":true,"clientId":"client","clientSecret":"0123456789abcdef"})).unwrap(); + assert_eq!(providers(&auth, "/").unwrap(), json!([{"id":"astheno","name":"Astheno"}])); + assert_eq!(destination(&auth, "github", "/").unwrap_err().status, 400); + assert_eq!(destination(&auth, "astheno", "/").unwrap(), ("/".to_owned(), false)); + drop(auth); + std::fs::remove_dir_all(path).unwrap(); + } + #[tokio::test] async fn adding_needs_a_registered_provider_and_a_plausible_name() { let path = std::env::temp_dir().join(format!("guest-add-test-{}", uuid::Uuid::new_v4())); diff --git a/dashboard/src/users.rs b/dashboard/src/users.rs index 4a5fb834a67f58a93c5484101547d97aa8fabd05..f2852a0403300ac3d830b168a29f67c18446d0f1 100644 --- a/dashboard/src/users.rs +++ b/dashboard/src/users.rs @@ -231,8 +231,8 @@ pub async fn route( if parts.is_empty() && method == Method::POST { let mut profile = profile(&body["profile"], true)?; let setup = string(&body["setup"]["kind"]); - if setup != "invite" && setup != "password" { - return Err(Error::new(400, "Choose an invitation or a password.")); + if !["invite", "password", "astheno"].contains(&setup) { + return Err(Error::new(400, "Choose an invitation, a password, or Astheno.")); } let hash = if setup == "password" { Some( @@ -249,11 +249,11 @@ pub async fn route( let id = uuid::Uuid::new_v4().to_string(); profile["enabled"] = json!(true); profile["emailVerified"] = json!(false); - profile["requiredActions"] = json!([if hash.is_some() { - "UPDATE_PASSWORD" - } else { - "SETUP" - }]); + profile["requiredActions"] = match setup { + "password" => json!(["UPDATE_PASSWORD"]), + "invite" => json!(["SETUP"]), + _ => json!([]), + }; profile["createdTimestamp"] = json!((now() * 1000.0) as i64); profile["attributes"] = json!({}); { @@ -278,6 +278,9 @@ pub async fn route( if let Some(hash) = &hash { auth::set_password(&transaction, &id, hash)?; } + if setup == "astheno" || !string(&body["astheno"]).is_empty() { + guest::link(&transaction, &id, string(&body["astheno"]))?; + } transaction.commit()?; } 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( identity::confirm_key(&transaction,id,&fingerprint)?; Value::Null } + [_, "astheno"] if method == Method::PUT => { + guest::link(&transaction, id, string(&body["handle"]))?; + Value::Null + } + [_, "astheno"] if method == Method::DELETE => { + guest::unlink(&transaction, id)?; + Value::Null + } [_, "credentials"] if method == Method::GET => auth::credentials(&transaction, id)?, [_, "logout"] if method == Method::POST => { transaction.execute("DELETE FROM sessions WHERE user_id=?", [id])?; diff --git a/dashboard/web/api.contract.ts b/dashboard/web/api.contract.ts index 9fb1fb88e141b0d456c5f3baded7abcdb66e6748..98834fa0df4b2e4429d6bfcbdbe92b2d01a34f6d 100644 --- a/dashboard/web/api.contract.ts +++ b/dashboard/web/api.contract.ts @@ -229,7 +229,7 @@ export type Api = Hono<{}, { }; "/users": { $get: Endpoint<{users:(User & {sessions:Session[]})[]; groups:Group[]}>; - $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>; + $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>; }; "/users/guests": { $post: Endpoint<{ id: string; created: boolean }, { json: { provider: "github" | "astheno" | "atproto"; handle: string; }; }>; @@ -241,6 +241,10 @@ export type Api = Hono<{}, { "/users/groups": { $put: Endpoint; }; + "/users/:id/astheno": { + $put: Endpoint; + $delete: Endpoint; + }; "/users/:id/groups/:group": { $put: Endpoint; $delete: Endpoint; diff --git a/dashboard/web/pages/SignIn.tsx b/dashboard/web/pages/SignIn.tsx index d6320f51c2158db4374d93c8c0f3c759014b4c0f..81d80eac002349dda3652bd4d9edbfcf43c70630 100644 --- a/dashboard/web/pages/SignIn.tsx +++ b/dashboard/web/pages/SignIn.tsx @@ -22,7 +22,7 @@ export function SignIn() { const [passwordStep, setPasswordStep] = createSignal(false); const [visible, setVisible] = createSignal(false); const [busy, setBusy] = createSignal(false); - 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.") : ""); + 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.") : ""); const [notice, setNotice] = createSignal(""); let conditional: AbortController | undefined; let disposed = false; @@ -103,7 +103,7 @@ export function SignIn() { }>
diff --git a/dashboard/web/pages/Users.tsx b/dashboard/web/pages/Users.tsx index af1fd3e8581e83bc27f715868e4785a15a52ce76..38fdb13d4b84676197b5925c7dce921a5a8a733c 100644 --- a/dashboard/web/pages/Users.tsx +++ b/dashboard/web/pages/Users.tsx @@ -34,6 +34,8 @@ const GUESTS = { atproto: { name: "AT Protocol", field: "AT handle", placeholder: "alice.bsky.social" }, } as const; +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."; + const STATES = { all: "users", guests: "guests", disabled: "disabled", pending: "setup pending" } as const; type Params = { q?: string; group?: string; state?: keyof typeof STATES }; @@ -247,7 +249,7 @@ function List(props: { data: Resource; ready: Accessor; title: "New user", confirmLabel: "create user", body: () => { - const [invite, setInvite] = createSignal(true); + const [kind, setKind] = createSignal<"invite" | "password" | "astheno">("invite"); return ( <> @@ -267,11 +269,17 @@ function List(props: { data: Resource; ready: Accessor;
first sign-in - - + + + +
- + +