chadtmiller.com/group-host
atmosphere group host
0
0
The console signs people in with atproto-client's OAuth client
.changeset/console-sign-in-by-atproto-client.mdnew+11−0
| @@ -0,0 +1,11 @@ | ||
--- | ||
default: minor | ||
--- | ||
| ||
# The console signs people in with atproto-client's OAuth client | ||
| ||
Signing in to the console, signing up, and signing in to an account to move here go through `atproto-client`'s OAuth client, which holds an authorization server to atproto's profile: it must require PAR, take client metadata documents, say who answers (`iss`, which a callback must carry), and list the methods the profile asks. Before the tokens are taken, at the callback and before each refresh of a move's session, the account's authorization server is read again from its DID and must be the one that issued them. A sign-in refused after its code was redeemed, as another account's, has its grant revoked. What a sign-in gives back is its refresh token, which ends the whole grant, where it was the access token. | ||
| ||
The console's client metadata is a confidential web client's as atproto's profile has it, with a second redirect, `/console/move/callback`, for an account being moved here; it answers 500, saying why, where `CONSOLE_URL` is not https at a public name, as no authorization server takes such a client. A sign-in waiting for the browser is kept in the database whole, and a move keeps its account's session there by the account; a move under way when the host is upgraded is let go, to be signed in to again. An account's server is read at most 16 MiB an answer, and 256 MiB a repo or file, while it moves. | ||
| ||
Each call the host makes to a host others' data names (sending a call on, telling a PDS or a syncer, reading a client's metadata, a group's own domain) is now logged as a `call` line and sends a `traceparent`, as identity calls were. | ||
crates/group-host/src/account_move.rs+237−282
519 lines changed: not loaded until asked for.
crates/group-host/src/authority.rs+2−1
| @@ -33,6 +33,7 @@ use atproto::space_auth::{self, space_host_aud}; | ||
use atproto::{Value, jose, syntax}; | ||
use atproto_client::guard::Guarded; | ||
use atproto_client::identity; | ||
use atproto_client::sender::SendError; | ||
use axum::http::StatusCode; | ||
use futures::future::{OptionFuture, join_all}; | ||
use futures::{StreamExt, stream}; | ||
| @@ -147,7 +148,7 @@ fn syncer_update(update: &SyncerUpdate) -> Json { | ||
} | ||
| ||
/// What a request's answer says of delivering it. | ||
fn delivery(sent: reqwest::Result<reqwest::Response>) -> Delivery { | ||
fn delivery(sent: Result<reqwest::Response, SendError>) -> Delivery { | ||
match sent.map(|r| r.status()) { | ||
Ok(s) if s.is_success() => Delivery::Delivered, | ||
Ok(s) if retryable(s) => Delivery::Retry, | ||
crates/group-host/src/console_login.rs+262−384
646 lines changed: not loaded until asked for.
crates/group-host/src/group_domain.rs+11−5
| @@ -72,12 +72,18 @@ impl Host { | ||
/// name, over https as the host holds any host others' data names. | ||
async fn reaches(&self, domain: &str) -> bool { | ||
let path = "/xrpc/com.atproto.server.describeServer"; | ||
let asked = match &self.config.domain_check_at { | ||
Some(at) => Some(self.http.get(format!("{at}{path}"))), | ||
None => self.guarded.get(&format!("https://{domain}{path}")).ok(), | ||
let answered = match &self.config.domain_check_at { | ||
Some(at) => { | ||
let asked = self.http.get(format!("{at}{path}")); | ||
let asked = asked.header(header::HOST, domain).timeout(LOOKUP); | ||
asked.send().await.ok() | ||
} | ||
None => { | ||
let asked = self.guarded.get(&format!("https://{domain}{path}")).ok(); | ||
let asked = asked.map(|a| a.header(header::HOST, domain).timeout(LOOKUP).send()); | ||
OptionFuture::from(asked).await.and_then(Result::ok) | ||
} | ||
}; | ||
let asked = asked.map(|a| a.header(header::HOST, domain).timeout(LOOKUP).send()); | ||
let answered = OptionFuture::from(asked).await.and_then(Result::ok); | ||
let Some(answer) = answered else { | ||
return false; | ||
}; | ||
crates/group-host/src/lib.rs+11−0
| @@ -95,6 +95,10 @@ pub struct Host { | ||
/// domain. Held to https at public addresses, but for a host on http | ||
/// itself (`PUBLIC_URL`), as on a network of test servers. | ||
pub(crate) guarded: Guarded, | ||
/// The console's OAuth clients: signing people in, and signing in to | ||
/// accounts being moved here (`console_login::clients`). | ||
pub(crate) console: atproto_client::oauth::Client, | ||
pub(crate) moving: atproto_client::oauth::Client, | ||
/// The spaces the index is to read, and its wake. | ||
indexing: std::sync::Mutex<std::collections::BTreeSet<String>>, | ||
index_wake: tokio::sync::Notify, | ||
| @@ -128,7 +132,11 @@ impl Host { | ||
false => Guard::strict(), | ||
}; | ||
let guarded = Guarded::new(guard, client_builder()).expect("a client builds"); | ||
// Each call to a host others' data names traced and logged. | ||
let guarded = guarded.sending(Arc::new(observe::Calls)); | ||
let identity = resolver(&config, guarded.clone()); | ||
let (console, moving) = | ||
console_login::clients(&config, &secrets, &store, &guarded, &identity); | ||
// A clock id of its own, so two hosts' revisions never collide. | ||
let clock = atproto::tid::TidClock::new(u64::from(secrets.signing.public().to_sec1()[1])); | ||
let limits = limits::Limiter::new(config.rate_limits); | ||
| @@ -143,6 +151,8 @@ impl Host { | ||
events: tokio::sync::broadcast::channel(16).0, | ||
http: client(), | ||
guarded, | ||
console, | ||
moving, | ||
indexing: Default::default(), | ||
index_wake: Default::default(), | ||
clients: Default::default(), | ||
| @@ -493,6 +503,7 @@ pub(crate) fn routes(host: Arc<Host>) -> Router { | ||
post(account_move::cancel_account_move), | ||
) | ||
.route("/console/callback", get(console_login::callback)) | ||
.route("/console/move/callback", get(account_move::callback)) | ||
.route("/console/switch", post(console_login::switch)) | ||
.route("/console/logout", post(console_login::logout)) | ||
.merge(token_routes()) | ||
crates/group-host/src/oauth_clients.rs+6−1
| @@ -9,6 +9,7 @@ use crate::Host; | ||
use crate::index_api::capped; | ||
use crate::oauth::OAuthError; | ||
use atproto::jose; | ||
use atproto_client::sender::SendError; | ||
use reqwest::Url; | ||
use serde_json::{Value, json}; | ||
use std::collections::HashMap; | ||
| @@ -247,7 +248,11 @@ impl Host { | ||
let asked = self.guarded.get(url).map_err(|e| unreadable(e.0))?; | ||
let sent = asked.header("accept", "application/json"); | ||
// With its causes: a name the guard would not resolve says so there. | ||
let failed = |e: reqwest::Error| unreadable(format!("{:#}", anyhow::Error::new(e))); | ||
let failed = |e: SendError| { | ||
let causes = anyhow::Error::new(e); | ||
let causes: Vec<String> = causes.chain().skip(1).map(ToString::to_string).collect(); | ||
unreadable(causes.join(": ")) | ||
}; | ||
let res = sent.send().await.map_err(failed)?; | ||
if !res.status().is_success() { | ||
return Err(unreadable(format!("answered {}", res.status()))); | ||
crates/group-host/src/store.rs+22−0
| @@ -555,6 +555,28 @@ pub const MIGRATIONS: &[&str] = &[ | ||
mod_tag.subject, | ||
), | ||
), | ||
// Signing in goes through atproto-client's OAuth client: a request | ||
// waiting for the browser is kept whole by its state, and a move's | ||
// session by its account, so a move names only the account. A move | ||
// under way is let go, to be signed in to again. | ||
" | ||
DROP TABLE console_login; | ||
CREATE TABLE console_request ( | ||
state TEXT PRIMARY KEY, | ||
pending TEXT NOT NULL, | ||
started INTEGER NOT NULL | ||
); | ||
DROP TABLE account_move; | ||
CREATE TABLE account_move ( | ||
mover TEXT PRIMARY KEY, | ||
did TEXT NOT NULL, | ||
started INTEGER NOT NULL | ||
); | ||
CREATE TABLE move_session ( | ||
did TEXT PRIMARY KEY, | ||
session TEXT NOT NULL | ||
); | ||
", | ||
]; | ||
| ||
const NEW_ACCOUNT: &str = "INSERT INTO account (did, handle, signing_key, kem_key, created_at) VALUES (?1, ?2, ?3, ?4, ?5) ON CONFLICT (handle) DO NOTHING"; | ||
crates/group-host/tests/common/mod.rs+19−5
| @@ -52,8 +52,9 @@ pub fn turn(switch: &AtomicBool, to: bool) { | ||
/// made then would be, so opening it runs `to` and those after again: | ||
/// each later migration undone, the last first, statement by statement. | ||
/// A table or index it made is dropped, a rename is reversed, a column it | ||
/// added is dropped, and a table it dropped is made again as an earlier | ||
/// one made it. What only moves rows is left as it is. | ||
/// added is dropped, and a table it dropped is made again as earlier ones | ||
/// made it, with the columns they added to it since. What only moves rows | ||
/// is left as it is. | ||
#[allow(dead_code)] | ||
pub fn rewind(conn: &rusqlite::Connection, to: usize) { | ||
let migrations = group_host::store::MIGRATIONS; | ||
| @@ -92,12 +93,25 @@ pub fn rewind(conn: &rusqlite::Connection, to: usize) { | ||
s.strip_prefix("CREATE TABLE ") | ||
.is_some_and(|r| name(r) == table) | ||
}; | ||
let mut earlier = migrations[..at].iter().flat_map(|m| statements(m)); | ||
earlier.rfind(made).expect("a table made before") | ||
let added = format!("ALTER TABLE {table} ADD COLUMN "); | ||
let earlier: Vec<String> = migrations[..at] | ||
.iter() | ||
.flat_map(|m| statements(m)) | ||
.collect(); | ||
let since = earlier.iter().rposition(made).expect("a table made before"); | ||
let grown = earlier[since + 1..] | ||
.iter() | ||
.filter(|s| s.starts_with(&added)); | ||
let remade: Vec<&String> = std::iter::once(&earlier[since]).chain(grown).collect(); | ||
remade | ||
.iter() | ||
.map(|s| s.as_str()) | ||
.collect::<Vec<_>>() | ||
.join(";\n") | ||
} else { | ||
continue; | ||
}; | ||
conn.execute(&undo, []).unwrap(); | ||
conn.execute_batch(&undo).unwrap(); | ||
} | ||
} | ||
conn.pragma_update(None, "user_version", to as i64).unwrap(); | ||
crates/group-host/tests/common/oauth.rs+24−0
| @@ -456,3 +456,27 @@ pub fn age(h: &Running, sql: &str) { | ||
let conn = rusqlite::Connection::open(h.data.path().join("host.sqlite")).unwrap(); | ||
conn.execute(sql, []).unwrap(); | ||
} | ||
| ||
/// The metadata of an authorization server at `base` calling itself | ||
/// `issuer`, whole as atproto's profile asks of one: PAR required, client | ||
/// metadata documents taken, and each list holding what it must. | ||
pub fn server_metadata(issuer: &str, base: &str) -> Json { | ||
json!({ | ||
"issuer": issuer, | ||
"pushed_authorization_request_endpoint": format!("{base}/par"), | ||
"authorization_endpoint": format!("{base}/authorize"), | ||
"token_endpoint": format!("{base}/token"), | ||
"revocation_endpoint": format!("{base}/revoke"), | ||
"require_pushed_authorization_requests": true, | ||
"authorization_response_iss_parameter_supported": true, | ||
"client_id_metadata_document_supported": true, | ||
"response_types_supported": ["code"], | ||
"grant_types_supported": ["authorization_code", "refresh_token"], | ||
"code_challenge_methods_supported": ["S256"], | ||
"token_endpoint_auth_methods_supported": ["none", "private_key_jwt"], | ||
"token_endpoint_auth_signing_alg_values_supported": ["ES256"], | ||
"scopes_supported": ["atproto"], | ||
"dpop_signing_alg_values_supported": ["ES256"], | ||
"prompt_values_supported": ["login", "consent", "create"], | ||
}) | ||
} | ||
crates/group-host/tests/account_move.rs+78−22
| @@ -57,6 +57,8 @@ struct Old { | ||
spaces: Mutex<bool>, | ||
undescribed: Mutex<bool>, | ||
no_refresh: Mutex<bool>, | ||
/// The error it refuses a refresh with, if it does. | ||
refuse_refresh: Mutex<Option<&'static str>>, | ||
/// Whether it asks for a DPoP nonce without giving one. | ||
nonceless: Mutex<bool>, | ||
} | ||
| @@ -91,18 +93,13 @@ fn nonce_first(headers: &HeaderMap) -> Option<Response> { | ||
} | ||
| ||
async fn resource(State(old): State<Arc<Old>>) -> Json<Json_> { | ||
Json(json!({ "authorization_servers": [old.base()] })) | ||
let base = old.base(); | ||
Json(json!({ "resource": base, "authorization_servers": [base] })) | ||
} | ||
| ||
async fn server(State(old): State<Arc<Old>>) -> Json<Json_> { | ||
let base = old.base(); | ||
Json(json!({ | ||
"issuer": base, | ||
"pushed_authorization_request_endpoint": format!("{base}/par"), | ||
"authorization_endpoint": format!("{base}/authorize"), | ||
"token_endpoint": format!("{base}/token"), | ||
"revocation_endpoint": format!("{base}/revoke"), | ||
})) | ||
Json(common::oauth::server_metadata(&base, &base)) | ||
} | ||
| ||
async fn par( | ||
| @@ -114,7 +111,8 @@ async fn par( | ||
return ask; | ||
} | ||
old.pushed.lock().unwrap().push(form); | ||
Json(json!({"request_uri": "urn:ietf:params:oauth:request_uri:r1"})).into_response() | ||
let uri = json!({"request_uri": "urn:ietf:params:oauth:request_uri:r1", "expires_in": 60}); | ||
Json(uri).into_response() | ||
} | ||
| ||
async fn authorize(State(old): State<Arc<Old>>) -> Redirect { | ||
| @@ -135,6 +133,11 @@ async fn token( | ||
if let Some(ask) = nonce_first(&headers) { | ||
return ask; | ||
} | ||
let refusal = *old.refuse_refresh.lock().unwrap(); | ||
if let Some(error) = refusal.filter(|_| form["grant_type"] == "refresh_token") { | ||
let body = Json(json!({"error": error})); | ||
return (StatusCode::BAD_REQUEST, body).into_response(); | ||
} | ||
let mut given = old.tokens.lock().unwrap(); | ||
let access = format!("at{}", given.len() + 1); | ||
given.push(access.clone()); | ||
| @@ -144,7 +147,7 @@ async fn token( | ||
_ => form["code"].clone(), | ||
}; | ||
let lasts = std::mem::replace(&mut *old.first_lasts.lock().unwrap(), 3600); | ||
let mut tokens = json!({"access_token": access, "refresh_token": format!("r{access}"), "token_type": "DPoP", "sub": sub, "expires_in": lasts}); | ||
let mut tokens = json!({"access_token": access, "refresh_token": format!("r{access}"), "token_type": "DPoP", "sub": sub, "scope": "atproto", "expires_in": lasts}); | ||
if *old.no_refresh.lock().unwrap() { | ||
tokens.as_object_mut().unwrap().remove("refresh_token"); | ||
} | ||
| @@ -560,8 +563,9 @@ async fn moves_an_account_signed_in_at_its_server_and_gives_its_tokens_back() { | ||
assert_eq!(moving["started"], false); | ||
// Signed in again, the tokens before are given back. | ||
w.sign_in_to_move().await; | ||
// (Its own sign-in gave back the person's first, at1.) | ||
assert_eq!(*w.old.revoked.lock().unwrap(), ["at1", "at2", "rat2"]); | ||
// (Its own sign-in gave back the person's first, its grant by its | ||
// refresh token, rat1.) | ||
assert_eq!(*w.old.revoked.lock().unwrap(), ["rat1", "rat2"]); | ||
| ||
// Started: the account copied, its spaces brought, and a code asked | ||
// for; the token lapses partway and is refreshed. | ||
| @@ -618,10 +622,7 @@ async fn moves_an_account_signed_in_at_its_server_and_gives_its_tokens_back() { | ||
.contains(&"admin".to_string()) | ||
); | ||
let revoked = w.old.revoked.lock().unwrap().clone(); | ||
assert!( | ||
revoked.ends_with(&["at4".to_string(), "rat4".to_string()]), | ||
"{revoked:?}" | ||
); | ||
assert!(revoked.ends_with(&["rat4".to_string()]), "{revoked:?}"); | ||
assert_eq!(w.call("getAccountMove", None).await, (200, json!({}))); | ||
} | ||
| ||
| @@ -688,7 +689,7 @@ async fn refreshes_a_token_about_to_lapse_and_says_what_its_server_refused() { | ||
let nothing = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); | ||
kept.pds = format!("http://{}", nothing.local_addr().unwrap()); | ||
drop(nothing); | ||
store.keep_move(&w.person, &kept, now).unwrap(); | ||
store.keep_oauth_session(&kept).unwrap(); | ||
let unreachable = w.call("startAccountMove", Some(json!({}))).await; | ||
assert_eq!(error(&unreachable), (502, "UpstreamFailure")); | ||
// Forgotten before it started, it leaves nothing to discard. | ||
| @@ -804,12 +805,67 @@ async fn gives_back_and_forgets_a_move_kept_a_day() { | ||
// Not yet a day: kept. | ||
assert_eq!(w.h.host.sweep_moves(now).await.unwrap(), 0); | ||
let day = 24 * 60 * 60_000; | ||
store.keep_move(&w.person, &kept, now - day - 1).unwrap(); | ||
store | ||
.keep_move(&w.person, &kept.did, now - day - 1) | ||
.unwrap(); | ||
assert_eq!(w.h.host.sweep_moves(now).await.unwrap(), 1); | ||
let revoked = w.old.revoked.lock().unwrap().clone(); | ||
assert!( | ||
revoked.ends_with(&["at2".to_string(), "rat2".to_string()]), | ||
"{revoked:?}" | ||
); | ||
assert!(revoked.ends_with(&["rat2".to_string()]), "{revoked:?}"); | ||
assert!(store.move_of(&w.person, now).unwrap().is_none()); | ||
} | ||
| ||
#[tokio::test] | ||
async fn signing_in_to_move_another_account_gives_back_the_one_before() { | ||
let w = world().await; | ||
// Their own account first, then the one they mean. | ||
let first = through(&w.h, "/console/move/login", &w.person, Some(&w.cookie)).await; | ||
assert_eq!(first.status(), 303); | ||
assert_eq!(w.call("getAccountMove", None).await.1["did"], w.person); | ||
w.sign_in_to_move().await; | ||
assert_eq!(w.call("getAccountMove", None).await.1["did"], w.did); | ||
// (rat1 the person's own sign-in, rat2 the move of their account.) | ||
assert_eq!(*w.old.revoked.lock().unwrap(), ["rat1", "rat2"]); | ||
} | ||
| ||
#[tokio::test] | ||
async fn a_refresh_refused_ends_the_move_or_says_what_its_server_said() { | ||
let w = world().await; | ||
// A session about to lapse, whose server will not refresh it. | ||
*w.old.first_lasts.lock().unwrap() = 10; | ||
w.sign_in_to_move().await; | ||
*w.old.refuse_refresh.lock().unwrap() = Some("invalid_request"); | ||
let said = w.call("startAccountMove", Some(json!({}))).await; | ||
assert_eq!(error(&said), (502, "UpstreamFailure")); | ||
// Its grant ended: sign in again, and the move is forgotten. | ||
*w.old.refuse_refresh.lock().unwrap() = Some("invalid_grant"); | ||
let said = w.call("startAccountMove", Some(json!({}))).await; | ||
assert_eq!(error(&said), (400, "SignInAgain")); | ||
assert_eq!(w.call("getAccountMove", None).await, (200, json!({}))); | ||
} | ||
| ||
#[test] | ||
fn a_database_from_before_lets_its_sign_ins_under_way_go() { | ||
use group_host::store::{MIGRATIONS, Store}; | ||
let dir = tempfile::tempdir().unwrap(); | ||
let path = dir.path().join("host.sqlite"); | ||
drop(Store::open(&path).unwrap()); | ||
// Back to before sign-ins went through atproto-client, a sign-in and | ||
// a move under way. | ||
let conn = rusqlite::Connection::open(&path).unwrap(); | ||
let at = MIGRATIONS | ||
.iter() | ||
.position(|m| m.contains("CREATE TABLE move_session")) | ||
.unwrap(); | ||
common::rewind(&conn, at); | ||
let login = "INSERT INTO console_login (state, did, issuer, token_endpoint, key, verifier, back, started) VALUES ('s', 'did:plc:a', 'https://pds.example', 'https://pds.example/token', x'00', 'v', '/', 1)"; | ||
conn.execute(login, []).unwrap(); | ||
let moving = "INSERT INTO account_move (mover, did, pds, issuer, token_endpoint, key, access, expires_at, started) VALUES ('did:plc:m', 'did:plc:a', 'https://pds.example', 'https://pds.example', 'https://pds.example/token', x'00', 'at', 1, 1)"; | ||
conn.execute(moving, []).unwrap(); | ||
drop(conn); | ||
// Opened, it lets them go, and keeps what comes after. | ||
let store = Store::open(&path).unwrap(); | ||
assert_eq!(store.request("s").unwrap(), None); | ||
assert!(store.move_of("did:plc:m", 2).unwrap().is_none()); | ||
assert_eq!(store.keep_move("did:plc:m", "did:plc:a", 2).unwrap(), None); | ||
assert_eq!(store.sweep_moves(2).unwrap(), ["did:plc:a"]); | ||
} | ||
crates/group-host/tests/console_login.rs+94−40
| @@ -43,7 +43,7 @@ async fn resource(State(pds): State<Arc<Pds>>) -> Json<Json_> { | ||
Json_::Null => json!([pds.base()]), | ||
other => other, | ||
}; | ||
Json(json!({ "authorization_servers": servers })) | ||
Json(json!({ "resource": pds.base(), "authorization_servers": servers })) | ||
} | ||
| ||
async fn server(State(pds): State<Arc<Pds>>) -> Json<Json_> { | ||
| @@ -52,14 +52,17 @@ async fn server(State(pds): State<Arc<Pds>>) -> Json<Json_> { | ||
.says("issuer") | ||
.as_str() | ||
.map_or(base.clone(), String::from); | ||
let mut meta = json!({ | ||
"issuer": issuer, | ||
"pushed_authorization_request_endpoint": pds.says("par_at").as_str().map_or(format!("{base}/par"), String::from), | ||
"authorization_endpoint": pds.says("authorize").as_str().map_or(format!("{base}/authorize"), String::from), | ||
"token_endpoint": format!("{base}/token"), | ||
}); | ||
if pds.says("revocation") != false { | ||
meta["revocation_endpoint"] = json!(format!("{base}/revoke")); | ||
let mut meta = common::oauth::server_metadata(&issuer, &base); | ||
for (said, field) in [ | ||
("par_at", "pushed_authorization_request_endpoint"), | ||
("authorize", "authorization_endpoint"), | ||
] { | ||
if let Some(url) = pds.says(said).as_str() { | ||
meta[field] = json!(url); | ||
} | ||
} | ||
if pds.says("revocation") == false { | ||
meta.as_object_mut().unwrap().remove("revocation_endpoint"); | ||
} | ||
Json(meta) | ||
} | ||
| @@ -311,21 +314,20 @@ async fn signs_a_person_in_at_their_own_pds_and_out() { | ||
pushed["client_id"], | ||
format!("{}/console/client-metadata.json", h.url) | ||
); | ||
let (_, meta) = h.get_path("/console/client-metadata.json").await; | ||
assert_eq!(meta["client_id"], pushed["client_id"]); | ||
assert_eq!( | ||
meta["redirect_uris"], | ||
json!([format!("{}/console/callback", h.url)]) | ||
); | ||
let key = jose::from_jwk(&meta["jwks"]["keys"][0]).unwrap(); | ||
let (header, claims) = jose::verify(&pushed["client_assertion"], &key).unwrap(); | ||
let (header, claims) = jose::parts(&pushed["client_assertion"]).unwrap(); | ||
assert_eq!(header["kid"], "console"); | ||
assert_eq!( | ||
(claims["iss"].clone(), claims["aud"].clone()), | ||
(json!(pushed["client_id"]), json!(pds.base())) | ||
); | ||
// And it gave back what it was given. | ||
assert_eq!(*pds.revoked.lock().unwrap(), ["at"]); | ||
// A console on http is no client an authorization server takes: its | ||
// metadata says why. | ||
let (status, meta) = h.get_path("/console/client-metadata.json").await; | ||
assert_eq!(status, 500); | ||
let why = meta["message"].as_str().unwrap(); | ||
assert!(why.contains("cannot be an OAuth client's"), "{why}"); | ||
// And it gave back what it was given: its grant, by its refresh token. | ||
assert_eq!(*pds.revoked.lock().unwrap(), ["rt"]); | ||
| ||
// The cookie is who calls the host's methods. | ||
let (status, made) = create_group(&h, Some(&session), "riders.groups.test").await; | ||
| @@ -399,30 +401,31 @@ async fn refuses_a_sign_in_it_cannot_trust() { | ||
for (case, value, said) in [ | ||
("servers", json!([]), "names no authorization server"), | ||
("issuer", json!("https://elsewhere.test"), "calls itself"), | ||
("par", json!("refuse"), "refused: no"), | ||
("par", json!("silent"), "refused: no reason given"), | ||
("par", json!("empty"), "gave no request_uri"), | ||
("par", json!("refuse"), "refused: invalid_request: no"), | ||
("par", json!("silent"), "refused: refused"), | ||
("par", json!("empty"), "no request_uri"), | ||
("authorize", json!("not a url"), "not on http or https"), | ||
("nonce", json!("always"), "refused: use_dpop_nonce"), | ||
("par_at", json!(closed()), "error sending request"), | ||
( | ||
"authorize", | ||
json!("not a url"), | ||
"names no authorization endpoint", | ||
"par_at", | ||
json!("ftp://127.0.0.1/par"), | ||
"not on http or https", | ||
), | ||
("nonce", json!("always"), "asked for a nonce twice"), | ||
("par_at", json!(closed()), "error sending request"), | ||
("par_at", json!("ftp://127.0.0.1/par"), "is not on https"), | ||
( | ||
"iss", | ||
json!("https://elsewhere.test"), | ||
"came from another server", | ||
"answered by https://elsewhere.test", | ||
), | ||
("iss", json!(false), "did not say which server"), | ||
("approve", json!("deny"), "it was refused: access_denied"), | ||
("approve", json!("bare"), "it was refused: no reason given"), | ||
("iss", json!(false), "does not say it is"), | ||
("approve", json!("deny"), "refused: access_denied"), | ||
("approve", json!("bare"), "a callback with no code"), | ||
("token", json!("refuse"), "refused: invalid_grant"), | ||
("sub", json!("did:plc:someone"), "not an atproto DID"), | ||
( | ||
"sub", | ||
json!("did:plc:someone"), | ||
"signed in as \"did:plc:someone\"", | ||
json!("did:plc:aaaaaaaaaaaaaaaaaaaaaaaa"), | ||
"logged in as did:plc:aaaaaaaaaaaaaaaaaaaaaaaa", | ||
), | ||
] { | ||
let before = pds.said.lock().unwrap().clone(); | ||
| @@ -460,7 +463,7 @@ async fn refuses_a_sign_in_it_cannot_trust() { | ||
genesis.did() | ||
}; | ||
let (_, why) = refused(&no_pds_person).await; | ||
assert!(why.contains("names no PDS"), "{why}"); | ||
assert!(why.contains("names no #atproto_pds service"), "{why}"); | ||
let (_, why) = refused("did:plc:unknownunknownunknown").await; | ||
assert!(why.contains("did:plc:unknownunknownunknown"), "{why}"); | ||
| ||
| @@ -482,25 +485,76 @@ async fn refuses_a_sign_in_it_cannot_trust() { | ||
assert_eq!(back.status(), 400); | ||
let back = b.get(location(&approved)).send().await.unwrap(); | ||
assert_eq!(back.status(), 400); | ||
// A sign-in refused once its code was redeemed, as another account's, | ||
// gave back what it was given. | ||
let revoked = std::mem::take(&mut *pds.revoked.lock().unwrap()); | ||
assert_eq!(revoked, ["rt"]); | ||
// A server without revocation is not asked to revoke. | ||
set("revocation", json!(false)); | ||
let (back, _) = sign_in(&h, &did, "/").await; | ||
assert_eq!(back.status(), 303); | ||
assert_eq!(*pds.revoked.lock().unwrap(), Vec::<String>::new()); | ||
set("revocation", json!(true)); | ||
| ||
// One that waited past its time, though this browser started it. | ||
let url = reqwest::Url::parse_with_params( | ||
&format!("{}/console/login", h.url), | ||
&[("handle", did.as_str())], | ||
) | ||
.unwrap(); | ||
let started = b.get(url).send().await.unwrap(); | ||
let login = set_cookie(&started, "group_host_login").unwrap(); | ||
let approved = b.get(location(&started)).send().await.unwrap(); | ||
let state = pds.pushed.lock().unwrap().last().unwrap()["state"].clone(); | ||
let store = &h.host.store; | ||
let mut waiting = store.take_request(&state).unwrap().unwrap(); | ||
waiting.started -= atproto_client::oauth::PENDING_FOR + 1; | ||
store.put_request(&state, &waiting).unwrap(); | ||
let back = b | ||
.get(location(&approved)) | ||
.header("cookie", login) | ||
.send() | ||
.await | ||
.unwrap(); | ||
assert_eq!(back.status(), 400); | ||
assert!(text(back).await.contains("took too long")); | ||
| ||
// Its store failing, it says so. | ||
common::oauth::age(&h, "DROP TABLE console_request"); | ||
let (res, _) = sign_in(&h, &did, "/").await; | ||
assert_eq!(res.status(), 500); | ||
} | ||
| ||
#[tokio::test] | ||
async fn reaches_only_public_servers_for_a_host_on_the_internet() { | ||
let h = start(&[("CONSOLE_URL", "https://console.test")], false).await; | ||
let h = start(&[("CONSOLE_URL", "https://console.example.com")], false).await; | ||
let (did, _) = person(&h, true).await; | ||
let (res, _) = sign_in(&h, &did, "/").await; | ||
assert_eq!(res.status(), 400); | ||
let why = text(res).await; | ||
assert!(why.contains("not on https"), "{why}"); | ||
// Its client metadata, a confidential web client's. | ||
let console = "https://console.example.com"; | ||
let (_, meta) = h.get_path("/console/client-metadata.json").await; | ||
assert_eq!( | ||
meta["client_id"], | ||
"https://console.test/console/client-metadata.json" | ||
format!("{console}/console/client-metadata.json") | ||
); | ||
assert_eq!( | ||
meta["redirect_uris"], | ||
json!([ | ||
format!("{console}/console/callback"), | ||
format!("{console}/console/move/callback") | ||
]) | ||
); | ||
assert_eq!(meta["token_endpoint_auth_method"], "private_key_jwt"); | ||
assert_eq!(meta["application_type"], "web"); | ||
assert_eq!(meta["jwks"]["keys"][0]["kid"], "console"); | ||
assert_eq!(meta["jwks"]["keys"][0]["alg"], "ES256"); | ||
let scope = meta["scope"].as_str().unwrap(); | ||
assert!( | ||
scope.starts_with("atproto rpc:com.atproto.server.createAccount"), | ||
"{scope}" | ||
); | ||
// Its cookies are for https alone. | ||
let out = browser() | ||
| @@ -605,16 +659,16 @@ async fn refuses_a_sign_up_it_cannot_trust() { | ||
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")); | ||
assert!(text(res).await.contains("logs 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); | ||
assert_eq!(res.status().as_u16(), 400); | ||
| ||
// 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); | ||
assert_eq!(res.status().as_u16(), 502); | ||
// Neither who they are nor that they are new. | ||
let res = browser() | ||
.get(format!("{}/console/login", h.url)) | ||