~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

Someone with no account makes one at the host's sign-up PDS, and comes back signed in

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/sign-up
crates/group-host/src/actors.rs+3−2
@@ -21,15 +21,16 @@ type Answer = Result<Json<Value>, XrpcError>;
/// Who is asking, by the console's cookie or service auth: nothing, for
/// no one.
pub async fn get_viewer(State(host): State<Arc<Host>>, headers: HeaderMap) -> Answer {
let signup = host.config.signup_pds.as_str();
let Some(me) = caller(&host, &headers, &format!("{NS}.getViewer")).await? else {
return Ok(Json(json!({})));
return Ok(Json(json!({ "signUpAt": signup })));
};
let mut actor = json!({"did": me, "canCreateGroup": host.may_found(&me)});
let doc = host.identity.document(&me).await.ok();
if let Some(handle) = doc.as_ref().and_then(did::handle) {
actor["handle"] = json!(handle);
}
Ok(Json(json!({ "actor": actor })))
Ok(Json(json!({ "actor": actor, "signUpAt": signup })))
}
impl Host {
crates/group-host/src/config.rs+10−0
@@ -50,6 +50,10 @@ pub struct Config {
/// typeahead.waow.tech for plc.directory, which knows the whole
/// network; `plc` for any other directory, a network of its own.
pub actor_search: String,
/// Where someone with no account makes one, `SIGNUP_PDS`, with no
/// trailing slash: the PDS the console's "Create one" signs them up at,
/// by its authorization server's sign-up (`prompt=create`).
pub signup_pds: String,
}
/// The service that finds anyone on the network by what is typed.
@@ -130,6 +134,11 @@ impl Config {
if reqwest::Url::parse(&console_url).is_err() {
bail!("CONSOLE_URL is no URL: {console_url}");
}
let signup_pds = var("SIGNUP_PDS").unwrap_or_else(|| "https://bsky.social".into());
let signup_pds = signup_pds.trim_end_matches('/').to_string();
if reqwest::Url::parse(&signup_pds).is_err() {
bail!("SIGNUP_PDS is no URL: {signup_pds}");
}
Ok(Config {
port,
public_url,
@@ -145,6 +154,7 @@ impl Config {
console_url,
provisioning_clients,
actor_search,
signup_pds,
})
}
crates/group-host/src/console_login.rs+51−8
@@ -309,6 +309,12 @@ impl Host {
.await
.map_err(|e| format!("{did}: {e:#}"))?;
let pds = did::pds(&doc).ok_or_else(|| format!("{did} names no PDS"))?;
let server = self.authorization_server(&pds).await?;
Ok((did, pds, server))
}
/// The metadata of the authorization server `pds` names.
async fn authorization_server(&self, pds: &str) -> Result<Value, String> {
let resource = self
.public_json(
&format!("{pds}/.well-known/oauth-protected-resource"),
@@ -326,7 +332,21 @@ impl Host {
if server["issuer"] != issuer {
return Err(format!("{issuer} calls itself {}", server["issuer"]));
}
Ok((did, pds, server))
Ok(server)
}
/// A sign-up at `p`'s server come back with `sub`, the account made:
/// the sign-in, now naming it, once the account's own authorization
/// server is the one that answered, as a sign-in checks it before.
async fn signed_up(&self, p: Pending, sub: &str) -> Result<Pending, String> {
let (did, pds, server) = self.sign_in_at(sub).await?;
if server["issuer"] != p.issuer.as_str() {
return Err(format!(
"{did} signs in at {}, not {}",
server["issuer"], p.issuer
));
}
Ok(Pending { did, pds, ..p })
}
}
@@ -353,7 +373,8 @@ pub async fn client_metadata(State(host): State<Arc<Host>>) -> Json<Value> {
}
/// Starts signing `handle` in: pushes the request to their PDS's
/// authorization server, and sends the browser there to approve it.
/// authorization server, and sends the browser there to approve it. With
/// `create`, and no handle, signs someone up instead, at `SIGNUP_PDS`.
pub async fn login(
State(host): State<Arc<Host>>,
Query(q): Query<HashMap<String, String>>,
@@ -369,10 +390,20 @@ pub(crate) async fn sign_in(
scope: &str,
mover: Option<String>,
) -> Result<Response, XrpcError> {
let Some(identifier) = q.get("handle").filter(|h| !h.trim().is_empty()) else {
return Ok(failed(StatusCode::BAD_REQUEST, "say who you are"));
let identifier = q.get("handle").filter(|h| !h.trim().is_empty());
// A sign-up names no one yet: the account it makes is checked as it
// comes back. Never for an account being moved, which is someone's.
let create = identifier.is_none() && q.contains_key("create") && mover.is_none();
let found = match (identifier, create) {
(Some(who), _) => host.sign_in_at(who).await,
(None, true) => {
let pds = host.config.signup_pds.clone();
let server = host.authorization_server(&pds).await;
server.map(|s| (String::new(), pds, s))
}
(None, false) => return Ok(failed(StatusCode::BAD_REQUEST, "say who you are")),
};
let (did, pds, server) = match host.sign_in_at(identifier).await {
let (did, pds, server) = match found {
Ok(found) => found,
Err(why) => return Ok(failed(StatusCode::BAD_REQUEST, why)),
};
@@ -382,6 +413,10 @@ pub(crate) async fn sign_in(
let (verifier, state) = (jose::random(32), jose::random(16));
let callback = host.console_callback();
let challenge = jose::sha256(&verifier);
let hint = match identifier {
Some(who) => ("login_hint", who.as_str()),
None => ("prompt", "create"),
};
let form = [
("response_type", "code"),
("code_challenge", challenge.as_str()),
@@ -389,7 +424,7 @@ pub(crate) async fn sign_in(
("redirect_uri", callback.as_str()),
("scope", scope),
("state", state.as_str()),
("login_hint", identifier.as_str()),
hint,
];
let pushed = host
.console_post(
@@ -487,8 +522,16 @@ pub async fn callback(
Ok(t) => t,
Err(why) => return Ok(failed(StatusCode::BAD_GATEWAY, why)),
};
if tokens["sub"] != p.did.as_str() {
let why = format!("signed in as {}, not {}", tokens["sub"], p.did);
let sub = tokens["sub"].as_str().unwrap_or_default();
let p = match p.did.is_empty() {
true => match host.signed_up(p, sub).await {
Ok(p) => p,
Err(why) => return Ok(failed(StatusCode::FORBIDDEN, why)),
},
false => p,
};
if sub != p.did {
let why = format!("signed in as {sub:?}, not {}", p.did);
return Ok(failed(StatusCode::FORBIDDEN, why));
}
let done = cookie(&host, STARTED, "", 0);
crates/group-host/tests/actors.rs+4−1
@@ -49,11 +49,14 @@ fn dids(said: &Json) -> Vec<&str> {
async fn says_who_is_asking() {
let h = start(&[], false).await;
let [alice, ..] = people(&h).await;
assert_eq!(viewer(&h, None).await, json!({}));
// No one, and where someone with no account makes one.
let signup = json!("https://bsky.social");
assert_eq!(viewer(&h, None).await, json!({"signUpAt": signup}));
let said = viewer(&h, Some(&alice)).await;
assert_eq!(said["actor"]["did"], alice.did.as_str());
assert_eq!(said["actor"]["handle"], "authority.test");
assert_eq!(said["actor"]["canCreateGroup"], true);
assert_eq!(said["signUpAt"], signup);
let h = start(&[("GROUP_FOUNDERS", "did:plc:someone")], false).await;
let [alice, ..] = people(&h).await;
assert_eq!(
crates/group-host/tests/config.rs+9−0
@@ -125,3 +125,12 @@ fn a_handle_is_looked_for_where_the_directory_is() {
let refused = config(&[("ACTOR_SEARCH", "somewhere")]).unwrap_err();
assert!(refused.to_string().contains("ACTOR_SEARCH"), "{refused}");
}
#[test]
fn someone_signs_up_at_bluesky_unless_told() {
assert_eq!(config(&[]).unwrap().signup_pds, "https://bsky.social");
let told = config(&[("SIGNUP_PDS", "https://pds.next.test/")]).unwrap();
assert_eq!(told.signup_pds, "https://pds.next.test");
let refused = config(&[("SIGNUP_PDS", "not a url")]).unwrap_err();
assert!(refused.to_string().contains("SIGNUP_PDS"), "{refused}");
}
crates/group-host/tests/console_login.rs+125−0
@@ -499,3 +499,128 @@ async fn reaches_only_public_servers_for_a_host_on_the_internet() {
let set = out.headers()["set-cookie"].to_str().unwrap();
assert!(set.ends_with("; Secure"), "{set}");
}
/// A PDS and its authorization server, standing alone: for a host whose
/// `SIGNUP_PDS` it is, made before the host is.
async fn signup_pds() -> Arc<Pds> {
let pds = Arc::new(Pds::default());
let router = Router::new()
.route("/.well-known/oauth-protected-resource", get(resource))
.route("/.well-known/oauth-authorization-server", get(server))
.route("/par", post(par))
.route("/authorize", get(authorize))
.route("/token", post(token))
.route("/revoke", post(revoke))
.with_state(pds.clone());
*pds.base.lock().unwrap() = serve(router).await;
pds
}
/// An account at `pds`, as signing up there makes one: its DID.
async fn account_at(h: &Running, pds: &str) -> String {
let key = Keypair::generate(Curve::K256);
let rotation = Keypair::generate(Curve::K256);
let op = Op::atproto(
&key.public().did_key(),
&[rotation.public().did_key()],
"new.test",
pds,
);
let genesis = op.sign(None, &rotation);
let url = format!("{}/{}", plc_url(h), genesis.did());
let res = h
.http
.post(url)
.json(&genesis.to_json())
.send()
.await
.unwrap();
assert!(res.status().is_success());
genesis.did()
}
/// Signs someone up from the console, going back to `back`: the last
/// answer.
async fn sign_up(h: &Running, back: &str) -> reqwest::Response {
let b = browser();
let url = reqwest::Url::parse_with_params(
&format!("{}/console/login", h.url),
&[("create", ""), ("back", back)],
)
.unwrap();
let started = b.get(url).send().await.unwrap();
if started.status() != 303 {
return started;
}
let login = set_cookie(&started, "group_host_login").unwrap();
let approved = b.get(location(&started)).send().await.unwrap();
b.get(location(&approved))
.header("cookie", login)
.send()
.await
.unwrap()
}
#[tokio::test]
async fn signs_someone_up_at_the_sign_up_pds() {
let pds = signup_pds().await;
let h = start_reachable(&[("SIGNUP_PDS", &format!("{}/", pds.base()))]).await;
assert_eq!(h.host.config.signup_pds, pds.base());
let did = account_at(&h, &pds.base()).await;
pds.said.lock().unwrap()["sub"] = json!(did);
let back = sign_up(&h, "/new").await;
assert_eq!(
(back.status().as_u16(), location(&back)),
(303, "/new".to_string())
);
// Asked to make an account, for no one in particular.
let pushed = pds.pushed.lock().unwrap().last().cloned().unwrap();
assert_eq!(pushed["prompt"], "create");
assert!(!pushed.contains_key("login_hint"));
let session = set_cookie(&back, COOKIE_NAME).unwrap();
let (status, view) = viewer(&h, &session).await;
assert_eq!((status, view["actor"]["did"].clone()), (200, json!(did)));
assert_eq!(view["signUpAt"], pds.base());
}
#[tokio::test]
async fn refuses_a_sign_up_it_cannot_trust() {
let pds = signup_pds().await;
let h = start_reachable(&[("SIGNUP_PDS", &pds.base())]).await;
// An account another server answers for, though this one said it made it.
let (elsewhere, _other) = person(&h, true).await;
pds.said.lock().unwrap()["sub"] = json!(elsewhere);
let res = sign_up(&h, "/").await;
assert_eq!(res.status().as_u16(), 403);
assert!(text(res).await.contains("signs in at"));
// No account at all.
pds.said.lock().unwrap()["sub"] = json!("");
let res = sign_up(&h, "/").await;
assert_eq!(res.status().as_u16(), 403);
// A sign-up PDS that cannot be reached.
let away = start_reachable(&[("SIGNUP_PDS", "http://127.0.0.1:9")]).await;
let res = sign_up(&away, "/").await;
assert_eq!(res.status().as_u16(), 400);
// Neither who they are nor that they are new.
let res = browser()
.get(format!("{}/console/login", h.url))
.send()
.await
.unwrap();
assert!(text(res).await.contains("say who you are"));
}
const COOKIE_NAME: &str = "group_host_session";
async fn viewer(h: &Running, cookie: &str) -> (u16, Json_) {
let res = h
.http
.get(format!("{}/xrpc/{NS}.getViewer", h.url))
.header("cookie", cookie)
.send()
.await
.unwrap();
(res.status().as_u16(), res.json().await.unwrap_or_default())
}
deploy/docker-compose.yml+1−0
@@ -37,6 +37,7 @@ services:
GROUP_FOUNDERS: ${GROUP_HOST_FOUNDERS:-}
PROVISIONING_CLIENTS: ${GROUP_HOST_PROVISIONING_CLIENTS:-}
PDS_CRAWLERS: ${GROUP_HOST_CRAWLERS:-}
SIGNUP_PDS: ${GROUP_HOST_SIGNUP_PDS:-https://bsky.social}
BLOB_UPLOAD_LIMIT: ${GROUP_HOST_BLOB_UPLOAD_LIMIT:-52428800}
RUST_LOG: ${GROUP_HOST_LOG:-info}
volumes:
docs/design/signing-in.md+10−0
@@ -51,6 +51,16 @@ authorization server, pushes the request with PKCE and a fresh DPoP key,
and sends the browser there. On return it exchanges the code, checks the
token names the DID that started, and revokes the access token at once.
Someone with no account follows "Create one", which makes one at the
host's `SIGNUP_PDS` (Bluesky's, unless set) and signs them in with it.
The host pushes a request to that PDS's authorization server as for a
sign-in, with `prompt=create` and no handle, and the server shows its
sign-up. On return the token's `sub` is the account it made, which no
one named before: the host resolves it, as it would a handle typed, and
signs them in only if that account's own authorization server is the one
that answered. The sign-in field's example handle is under the sign-up
PDS's own name, `you.bsky.social` or `you.pds.next.opensocial.fyi`.
As they type, the field suggests the accounts whose handle matches,
with each one's picture, name and handle where they are known; picking
one signs in as it at once. The browser asks the host
docs/reference/api.md+2−2
@@ -101,7 +101,7 @@ same writes ([membership](../design/membership.md#invites)).
| Method | What it does |
| --- | --- |
| `GET fyi.opensocial.getViewer` | who is asking, by the console's cookie or service auth |
| `GET fyi.opensocial.getViewer` | who is asking, by the console's cookie or service auth, and where someone with no account makes one (`signUpAt`, `SIGNUP_PDS`) |
| `GET fyi.opensocial.getActor` | a person's DID and handle, to someone signed in: themselves, or anyone the host shows (a member of a group here, or someone asking to join one); to themselves also whether they may start a group |
| `GET fyi.opensocial.getActorGroups` | the groups here a person is in, as far as the caller shares them |
| `GET fyi.opensocial.searchActors` | accounts whose handle matches what is typed, from where `ACTOR_SEARCH` says; anyone may ask |
@@ -235,7 +235,7 @@ Groups between hosts, and accounts here to become groups ([moving](../design/mov
| Route | What it does |
| --- | --- |
| `GET /console/login`, `GET /console/callback`, `POST /console/logout` | signing in to the console as oneself, and out |
| `GET /console/login`, `GET /console/callback`, `POST /console/logout` | signing in to the console as oneself (`?handle=`), or signing up at `SIGNUP_PDS` (`?create`), and out |
| `GET /console/move/login` | signing in to an account to move here |
| `GET /console/client-metadata.json` | the host's metadata as the console's OAuth client |
docs/reference/config.md+1−0
@@ -23,6 +23,7 @@ trimmed of spaces and a trailing `/`.
| `CONSOLE_URL` | where the console is: where the host sends a member to approve an app or an MCP client (`/authorize`), the console's OAuth client id and callback when people sign in (`/console/…`), and, when `https`, whether the session cookie is `Secure` | `PUBLIC_URL` |
| `PROVISIONING_CLIENTS` | the apps the host makes groups for with `provisionGroup`, comma-separated OAuth client ids, each matched as written, a trailing `/` included; `*` for any | none |
| `ACTOR_SEARCH` | where `searchActors` looks for a handle being typed: `plc`, the handles in `PLC_URL`'s own export, read a page at a time and kept a minute; or the URL of a service answering `tech.waow.typeahead.searchActors` | typeahead.waow.tech's, when `PLC_URL` is `https://plc.directory`; else `plc` |
| `SIGNUP_PDS` | the PDS where someone with no account makes one, from the console's "Create one": its authorization server's sign-up (`prompt=create`); a trailing `/` dropped | `https://bsky.social` |
| `PDS_CRAWLERS` | relays told of news with `requestCrawl`, comma-separated, a trailing `/` dropped: at most every 20 minutes, and the first time after a start | none |
| `RUST_LOG` | what it logs, as `tracing-subscriber`'s filter reads it; lines are JSON | `info` |
docs/deploying.md+1−0
harness/e2e/flows.spec.mjs+3−1
lexicons/fyi/opensocial/getViewer.json+5−0
web/src/lib/organisms/SignInDialog.svelte+9−4
web/src/lib/organisms/SiteHeader.svelte+3−3
web/src/routes/+layout.svelte+1−1
web/src/routes/+layout.ts+3−2