chadtmiller.com/group-host
atmosphere group host
0
0
The console signs in with one OAuth client on atproto-client 0.6
.changeset/console-one-oauth-client.mdnew+10−0
| @@ -0,0 +1,10 @@ | ||
--- | ||
default: patch | ||
--- | ||
| ||
# The console signs in with one OAuth client, and checks service auth by atproto-client | ||
| ||
The console signs people in, and signs in to accounts being moved here, with one OAuth client on atproto-client 0.6. A sign-in coming back to the other one's callback (the console's at a move's, or a move's at the console's) is refused as one this browser did not start, approved or not. A move finished or cancelled while its account's session was being refreshed stays ended: the refreshed tokens are given back, and the move answers `NotFound`. | ||
| ||
Service auth sent to the host's own methods, to `notifyRepoUpdate` and `notifyCredentialsRevoked`, and an account's token for moving here, are checked with atproto-client's `verify_any`, for the audiences each took before. A token's audience and method are now checked before any key is read: `notifyRepoUpdate` checks its `space` is well formed first, and a token for an account not hosted here is refused by `notifyCredentialsRevoked` before its signature. | ||
An account's token for moving here whose DID can't be resolved is refused `InvalidToken`, as one whose DID names no key is, where it was `InvalidRequest`. | ||
crates/group-host/src/account_move.rs+29−20
| @@ -5,8 +5,8 @@ | ||
//! The person, signed in to the console, signs in to the account too | ||
//! (`/console/move/login`), approving at its server what a move needs and | ||
//! no more: a `createAccount` token for this host, its identity, and | ||
//! reading its own repos and files in spaces. The console's second OAuth | ||
//! client (`console_login::clients`) keeps that session in the database, | ||
//! reading its own repos and files in spaces. The console's OAuth client | ||
//! (`console_login::client`) keeps that session in the database, | ||
//! by the account ([`Moves`]), and the host keeps which account each | ||
//! person is moving, one at a time, until the move is finished or | ||
//! forgotten, and then gives the session back. Its calls to the account's | ||
| @@ -62,8 +62,13 @@ impl SessionStore for Moves { | ||
self.0.oauth_session(did).map_err(unstored) | ||
} | ||
| ||
/// A session kept only while its account's move is: one whose move | ||
/// was finished, cancelled or swept meanwhile has ended. | ||
fn put(&self, session: &Session) -> Result<(), StoreError> { | ||
self.0.keep_oauth_session(session).map_err(unstored) | ||
match self.0.keep_oauth_session(session).map_err(unstored)? { | ||
true => Ok(()), | ||
false => Err(StoreError::Ended), | ||
} | ||
} | ||
| ||
fn delete(&self, did: &str) -> Result<(), StoreError> { | ||
| @@ -73,7 +78,7 @@ impl SessionStore for Moves { | ||
| ||
const MOVE_OF: &str = "SELECT s.session FROM account_move m JOIN move_session s ON s.did = m.did WHERE m.mover = ?1 AND m.started > ?2"; | ||
const KEEP_MOVE: &str = "INSERT INTO account_move (mover, did, started) VALUES (?1, ?2, ?3) ON CONFLICT (mover) DO UPDATE SET did = ?2, started = ?3"; | ||
const KEEP_SESSION: &str = "INSERT INTO move_session (did, session) VALUES (?1, ?2) ON CONFLICT (did) DO UPDATE SET session = ?2"; | ||
const KEEP_SESSION: &str = "INSERT INTO move_session (did, session) SELECT ?1, ?2 WHERE EXISTS (SELECT 1 FROM account_move WHERE did = ?1) ON CONFLICT (did) DO UPDATE SET session = ?2"; | ||
| ||
impl Store { | ||
/// The session of the account `mover` signed in to move, while it is | ||
| @@ -124,12 +129,12 @@ impl Store { | ||
Ok(found.map(|s| serde_json::from_str(&s)).transpose()?) | ||
} | ||
| ||
/// Keeps `session`, in place of any for its account. | ||
pub fn keep_oauth_session(&self, session: &Session) -> Result<()> { | ||
/// Keeps `session`, in place of any for its account, while the account | ||
/// is being moved: whether it is. | ||
pub fn keep_oauth_session(&self, session: &Session) -> Result<bool> { | ||
let kept = serde_json::to_string(session)?; | ||
self.conn() | ||
.execute(KEEP_SESSION, params![session.did, kept])?; | ||
Ok(()) | ||
let conn = self.conn(); | ||
Ok(conn.execute(KEEP_SESSION, params![session.did, kept])? == 1) | ||
} | ||
| ||
/// Forgets the session kept for `did`. | ||
| @@ -208,19 +213,21 @@ impl Host { | ||
/// Gives `did`'s session back to its server, as far as it hears, and | ||
/// forgets it. | ||
async fn give_back(&self, did: &str) { | ||
let given = self.moving.revoke(did).await; | ||
let given = self.console.revoke(did).await; | ||
tracing::debug!(?given, did, "gave back a moving account's session"); | ||
} | ||
| ||
/// `did`'s session, refreshed if it is about to lapse, or `now_anyway`. | ||
async fn moving_session(&self, did: &str, now_anyway: bool) -> Result<Session, XrpcError> { | ||
let session = match now_anyway { | ||
true => self.moving.refresh(did).await, | ||
false => self.moving.session(did).await, | ||
true => self.console.refresh(did).await.map(|r| r.session), | ||
false => self.console.session(did).await, | ||
}; | ||
session.map_err(|e| match e { | ||
login::Error::NoRefresh(_) => sign_in_again(), | ||
e if e.refusal().is_some_and(|r| r.error == "invalid_grant") => sign_in_again(), | ||
// Finished or cancelled while it was refreshed. | ||
login::Error::Ended(_) => none_here(), | ||
e => upstream(e), | ||
}) | ||
} | ||
| @@ -235,8 +242,8 @@ impl Host { | ||
at_most: usize, | ||
) -> Result<(Xrpc, Auth), XrpcError> { | ||
let session = self.moving_session(did, renew).await?; | ||
let auth = self.moving.auth(&session).map_err(upstream)?; | ||
Ok((self.moving.pds(&session).at_most(at_most), auth)) | ||
let auth = self.console.auth(&session).map_err(upstream)?; | ||
Ok((self.console.pds(&session).at_most(at_most), auth)) | ||
} | ||
| ||
/// `call` of the account's server, as the account `did`, made once | ||
| @@ -404,18 +411,20 @@ pub async fn callback( | ||
RawQuery(query): RawQuery, | ||
) -> Result<Response, XrpcError> { | ||
let query = query.unwrap_or_default(); | ||
let at = host.move_callback(); | ||
let back = come_back(&host, &headers, &query, &host.moving, &at).await?; | ||
let (session, started) = match back { | ||
let (session, started) = match come_back(&host, &headers, &query, true).await? { | ||
Ok(back) => back, | ||
Err(refused) => return Ok(refused), | ||
}; | ||
// Only a move's sign-in comes back here, carrying who moves it. | ||
// A move's sign-in carries who moves it. Its session is kept while the | ||
// move is, in place of any kept for the account before, which is given | ||
// back, as is the account they were moving before, if another. | ||
let mover = started.mover.unwrap_or_default(); | ||
let before = host.store.keep_move(&mover, &session.did, now_millis()); | ||
if let Some(before) = before.map_err(XrpcError::internal)? { | ||
host.give_back(&before).await; | ||
} | ||
let kept = host.console.keep(&session).await; | ||
kept.map_err(XrpcError::internal)?; | ||
tracing::info!(did = session.did, mover, "signed in to an account to move"); | ||
let done = [(header::SET_COOKIE, done(&host))]; | ||
Ok((done, Redirect::to(&started.back)).into_response()) | ||
| @@ -511,8 +520,8 @@ pub async fn finish_account_move( | ||
let done = host | ||
.complete_import_as(&me, &m.did, &signed["operation"]) | ||
.await?; | ||
host.give_back(&m.did).await; | ||
host.store.forget_move(&me).map_err(XrpcError::internal)?; | ||
host.give_back(&m.did).await; | ||
Ok(Json(done)) | ||
} | ||
| ||
| @@ -528,7 +537,7 @@ pub async fn cancel_account_move(State(host): State<Arc<Host>>, headers: HeaderM | ||
if pending.is_some_and(|p| p.founder == me) { | ||
host.forget(&m.did); | ||
} | ||
host.give_back(&m.did).await; | ||
host.store.forget_move(&me).map_err(XrpcError::internal)?; | ||
host.give_back(&m.did).await; | ||
Ok(Json(json!({}))) | ||
} | ||
crates/group-host/src/authority_api.rs+11−6
| @@ -10,6 +10,7 @@ use crate::space::NOTIFY_REPO_UPDATE; | ||
use crate::space_api::{credential, forbidden, now, refused, service_caller}; | ||
use crate::store::{Registration, Space}; | ||
use crate::xrpc::XrpcError; | ||
use atproto::service_auth::Claims; | ||
use atproto::space::SpaceRef; | ||
use atproto::space_auth::{self, Kind, Make, space_host_aud}; | ||
use atproto::{PublicKey, Value as Drisl, syntax, tid}; | ||
| @@ -214,9 +215,18 @@ pub async fn notify_repo_update( | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let caller = service_caller(&host, &headers, NOTIFY_REPO_UPDATE).await?; | ||
let uri = text(&body, "space")?; | ||
let space = space_ref(uri)?; | ||
let for_authority = |claims: &Claims| { | ||
let aud = &claims.aud; | ||
match *aud == space.authority || *aud == space_host_aud(&space.authority) { | ||
true => Ok(()), | ||
false => Err(forbidden( | ||
"notifyRepoUpdate is not for this space's authority", | ||
)), | ||
} | ||
}; | ||
let caller = service_caller(&host, &headers, NOTIFY_REPO_UPDATE, for_authority).await?; | ||
let (repo, rev) = (text(&body, "repo")?, text(&body, "repoRev")?); | ||
if !syntax::is_tid(rev) { | ||
return Err(invalid("repoRev is a TID")); | ||
| @@ -229,11 +239,6 @@ pub async fn notify_repo_update( | ||
if caller.account() != repo { | ||
return Err(forbidden("notifyRepoUpdate's issuer is not the repo")); | ||
} | ||
if caller.aud != space.authority && caller.aud != space_host_aud(&space.authority) { | ||
return Err(forbidden( | ||
"notifyRepoUpdate is not for this space's authority", | ||
)); | ||
} | ||
let hosted = host.store.space(uri).map_err(XrpcError::internal)?; | ||
let hosted = hosted.ok_or_else(not_found)?; | ||
let ahead = tid::micros(rev).unwrap_or_default() / 1_000_000; | ||
crates/group-host/src/console_login.rs+77−79
| @@ -7,10 +7,10 @@ | ||
//! only once the account's own authorization server, followed again from | ||
//! its DID, is the one that issued them. It asks for `atproto` alone: the | ||
//! console's methods act as the group, never as the person, so the host | ||
//! needs only to know who they are. Once their PDS says so, it revokes | ||
//! what it was given, and keeps nothing of theirs. A request waiting for | ||
//! the browser to come back is kept in the database by its state | ||
//! ([`Requests`]), so any of the host's processes answers it. | ||
//! needs only to know who they are. Once their PDS says so, it gives back | ||
//! what it was given unkept, and keeps nothing of theirs. A request | ||
//! waiting for the browser to come back is kept in the database by its | ||
//! state ([`Requests`]), so any of the host's processes answers it. | ||
//! | ||
//! The browser holds only a cookie the host signed, naming the person, | ||
//! HttpOnly and SameSite=Lax; where the console is on https, named | ||
| @@ -74,24 +74,21 @@ const TAKES: i64 = login::PENDING_FOR as i64 * 1000; | ||
const KID: &str = "console"; | ||
| ||
/// What a sign-in carries to the browser's return, beside what the OAuth | ||
/// client keeps: the page to go back to, the secret the browser that | ||
/// started it holds in its cookie, and, for an account being moved here, | ||
/// who is moving it. | ||
/// client keeps: the page to go back to, and, for an account being moved | ||
/// here, who is moving it. | ||
#[derive(Debug, Serialize, Deserialize)] | ||
pub(crate) struct Started { | ||
pub back: String, | ||
browser: String, | ||
#[serde(default, skip_serializing_if = "Option::is_none")] | ||
pub mover: Option<String>, | ||
} | ||
| ||
/// The requests waiting for the browser to come back, in the database: | ||
/// both of the console's OAuth clients keep theirs here. | ||
/// The requests waiting for the browser to come back, in the database. | ||
pub(crate) struct Requests(pub Store); | ||
| ||
/// A store's failure, as the OAuth client takes it. | ||
pub(crate) fn unstored(e: anyhow::Error) -> StoreError { | ||
StoreError(format!("{e:#}")) | ||
StoreError::Failed(format!("{e:#}")) | ||
} | ||
| ||
impl StateStore for Requests { | ||
| @@ -126,15 +123,6 @@ impl Store { | ||
Ok(found.map(|p| serde_json::from_str(&p)).transpose()?) | ||
} | ||
| ||
/// The request `state` names, left as it is. | ||
pub fn request(&self, state: &str) -> anyhow::Result<Option<login::Pending>> { | ||
let sql = "SELECT pending FROM console_request WHERE state = ?1"; | ||
let conn = self.conn(); | ||
let found = conn.query_row(sql, [state], |r| r.get(0)).optional(); | ||
let found: Option<String> = found?; | ||
Ok(found.map(|p| serde_json::from_str(&p)).transpose()?) | ||
} | ||
| ||
/// Notes that `did` signed out of the console at `at`. | ||
pub fn sign_out(&self, did: &str, at: i64) -> anyhow::Result<()> { | ||
self.conn().execute(SIGN_OUT, params![did, at])?; | ||
| @@ -169,32 +157,29 @@ fn client_id(config: &Config) -> String { | ||
format!("{}/console/client-metadata.json", config.console_url) | ||
} | ||
| ||
/// The console's two OAuth clients, under its one client id and key, each | ||
/// call they make through [`observe::Calls`]: one signing people in, who | ||
/// keeps no session past its callback, and one signing in to accounts | ||
/// being moved here, keeping their sessions in the database until the move | ||
/// is done ([`crate::account_move::Moves`]). They are two, each with a | ||
/// callback of its own, as a sign-in ends any session its client keeps | ||
/// for the same account: someone signing in to the console as an account | ||
/// would otherwise end its move. | ||
pub(crate) fn clients( | ||
/// The console's OAuth client, under its client id and key, each call it | ||
/// makes through [`observe::Calls`]: signing people in, whose sessions it | ||
/// never keeps, and signing in to accounts being moved here, whose | ||
/// sessions it keeps in the database until the move is done | ||
/// ([`crate::account_move::Moves`]). | ||
pub(crate) fn client( | ||
config: &Config, | ||
secrets: &Secrets, | ||
store: &Store, | ||
guarded: &Guarded, | ||
identity: &Resolver, | ||
) -> (login::Client, login::Client) { | ||
let id = client_id(config); | ||
let requests: Arc<dyn StateStore> = Arc::new(Requests(store.clone())); | ||
let client = || { | ||
let credentials = login::Credentials::private_key_jwt(console_key(secrets), KID); | ||
let credentials = credentials.expect("a P-256 key"); | ||
login::Client::new(&id, credentials, guarded.clone(), identity.clone()) | ||
.states(requests.clone()) | ||
.sending(Arc::new(observe::Calls)) | ||
}; | ||
let moves = Arc::new(crate::account_move::Moves(store.clone())); | ||
(client(), client().sessions(moves)) | ||
) -> login::Client { | ||
let credentials = login::Credentials::private_key_jwt(console_key(secrets), KID); | ||
let credentials = credentials.expect("a P-256 key"); | ||
login::Client::new( | ||
&client_id(config), | ||
credentials, | ||
guarded.clone(), | ||
identity.clone(), | ||
) | ||
.states(Arc::new(Requests(store.clone()))) | ||
.sessions(Arc::new(crate::account_move::Moves(store.clone()))) | ||
.sending(Arc::new(observe::Calls)) | ||
} | ||
| ||
fn failed(status: StatusCode, why: impl Into<String>) -> Response { | ||
| @@ -203,9 +188,11 @@ fn failed(status: StatusCode, why: impl Into<String>) -> Response { | ||
(status, format!("Signing in failed: {why}")).into_response() | ||
} | ||
| ||
/// Why a sign-in could not start or finish, as the browser is told. | ||
/// Why a sign-in could not start or finish, as the browser is told: by | ||
/// what failed, a failed callback's cause. | ||
fn refused(e: &login::Error) -> Response { | ||
use login::Error; | ||
let e = e.cause(); | ||
let (status, why) = match e { | ||
Error::UnknownState => (StatusCode::BAD_REQUEST, TOOK_TOO_LONG.to_string()), | ||
Error::Identity(_) | Error::Handle { .. } => ( | ||
| @@ -424,8 +411,8 @@ pub async fn login( | ||
} | ||
| ||
/// Starts a sign-in to `q`'s `handle`, for `mover` where it is an account | ||
/// they are moving here: asking what a move needs, by the client that keeps | ||
/// moves' sessions. | ||
/// they are moving here: asking what a move needs, coming back to the | ||
/// move's callback. | ||
pub(crate) async fn sign_in( | ||
host: &Host, | ||
q: &HashMap<String, String>, | ||
| @@ -440,17 +427,15 @@ pub(crate) async fn sign_in( | ||
(None, true) => host.config.signup_pds.as_str(), | ||
(None, false) => return failed(StatusCode::BAD_REQUEST, "say who you are"), | ||
}; | ||
let (client, redirect_uri, scope) = match mover { | ||
let (redirect_uri, scope) = match mover { | ||
Some(_) => ( | ||
&host.moving, | ||
host.move_callback(), | ||
format!("atproto {}", host.move_scope()), | ||
), | ||
None => (&host.console, host.console_callback(), "atproto".into()), | ||
None => (host.console_callback(), "atproto".into()), | ||
}; | ||
let started = Started { | ||
back: back_to(q.get("back")), | ||
browser: jose::random(16), | ||
mover, | ||
}; | ||
let carried = serde_json::to_string(&started).expect("JSON"); | ||
| @@ -460,45 +445,61 @@ pub(crate) async fn sign_in( | ||
prompt: create.then_some("create"), | ||
app_state: Some(&carried), | ||
}; | ||
let to = match client.authorize(input, &ask).await { | ||
let to = match host.console.authorize(input, &ask).await { | ||
Ok(to) => to, | ||
Err(e) => return refused(&e), | ||
}; | ||
let held = cookie(host, STARTED, &started.browser, TAKES / 1000); | ||
([(header::SET_COOKIE, held)], Redirect::to(&to)).into_response() | ||
let held = cookie(host, STARTED, &to.state, TAKES / 1000); | ||
([(header::SET_COOKIE, held)], Redirect::to(&to.url)).into_response() | ||
} | ||
| ||
/// The session the browser's return, `query`, grants by `client`, at its | ||
/// `callback`, and what its sign-in carried: only in the browser that | ||
/// started it, at the callback it was started for, and for an account | ||
/// being moved, while the one moving it is still the one signed in. Else | ||
/// the answer refusing it. The request is answered once; one refused | ||
/// before its code is redeemed is left to lapse. | ||
/// What a sign-in carried, if it was started for the callback it came back | ||
/// to: a move's if `moving`. | ||
fn carried(app_state: Option<&str>, moving: bool) -> Option<Started> { | ||
let started = serde_json::from_str::<Started>(app_state?).ok()?; | ||
(started.mover.is_some() == moving).then_some(started) | ||
} | ||
| ||
/// The session the browser's return, `query`, grants, not yet kept, and | ||
/// what its sign-in carried: only in the browser that started it, by the | ||
/// cookie naming its state, at the callback it was started for (a move's, | ||
/// if `moving`), and for an account being moved, while the one moving it | ||
/// is still the one signed in. Else the answer refusing it, and a session | ||
/// granted given back; a sign-in refused at the other callback is told as | ||
/// one this browser did not start. A request answered elsewhere is left | ||
/// to lapse. | ||
pub(crate) async fn come_back( | ||
host: &Host, | ||
headers: &HeaderMap, | ||
query: &str, | ||
client: &login::Client, | ||
callback: &str, | ||
moving: bool, | ||
) -> Result<Result<(Session, Started), Response>, XrpcError> { | ||
let state = Callback::parse(query).state.unwrap_or_default(); | ||
let pending = host.store.request(&state).map_err(XrpcError::internal)?; | ||
let started = pending | ||
.filter(|p| p.redirect_uri == callback) | ||
.and_then(|p| serde_json::from_str::<Started>(&p.app_state?).ok()) | ||
.filter(|s| host.cookie_of(headers, STARTED) == Some(s.browser.as_str())); | ||
let Some(started) = started else { | ||
let state = Callback::parse(query).state; | ||
if state.is_none() || host.cookie_of(headers, STARTED) != state.as_deref() { | ||
return Ok(Err(failed(StatusCode::BAD_REQUEST, TOOK_TOO_LONG))); | ||
} | ||
let came = match host.console.callback_unkept(query).await { | ||
Ok(came) => came, | ||
Err(e) if e.app_state().is_some() && carried(e.app_state(), moving).is_none() => { | ||
return Ok(Err(failed(StatusCode::BAD_REQUEST, TOOK_TOO_LONG))); | ||
} | ||
Err(e) => return Ok(Err(refused(&e))), | ||
}; | ||
let started = carried(came.app_state.as_deref(), moving); | ||
let caller = host.console_caller(headers).map_err(XrpcError::internal)?; | ||
if started.mover.is_some() && caller != started.mover { | ||
let why = "sign in to the console again first"; | ||
return Ok(Err(failed(StatusCode::FORBIDDEN, why))); | ||
let again = "sign in to the console again first"; | ||
let checked = match started { | ||
Some(s) if s.mover.is_some() && caller != s.mover => Err((StatusCode::FORBIDDEN, again)), | ||
Some(s) => Ok(s), | ||
None => Err((StatusCode::BAD_REQUEST, TOOK_TOO_LONG)), | ||
}; | ||
match checked { | ||
Ok(started) => Ok(Ok((came.session, started))), | ||
Err((status, why)) => { | ||
host.console.discard(came.session).await; | ||
Ok(Err(failed(status, why))) | ||
} | ||
} | ||
Ok(match client.callback(query).await { | ||
Ok((session, _)) => Ok((session, started)), | ||
Err(e) => Err(refused(&e)), | ||
}) | ||
} | ||
| ||
/// The browser comes back from approving: the code is exchanged, the | ||
| @@ -509,16 +510,13 @@ pub async fn callback( | ||
RawQuery(query): RawQuery, | ||
) -> Result<Response, XrpcError> { | ||
let query = query.unwrap_or_default(); | ||
let at = host.console_callback(); | ||
let back = come_back(&host, &headers, &query, &host.console, &at).await?; | ||
let (session, started) = match back { | ||
let (session, started) = match come_back(&host, &headers, &query, false).await? { | ||
Ok(back) => back, | ||
Err(refused) => return Ok(refused), | ||
}; | ||
let did = session.did; | ||
let did = session.did.clone(); | ||
// Knowing who they are is all the host wanted: it keeps nothing. | ||
let revoked = host.console.revoke(&did).await; | ||
tracing::debug!(?revoked, "gave back the console's tokens"); | ||
host.console.discard(session).await; | ||
let now = now_millis(); | ||
let session = cookie(&host, COOKIE, &host.session_cookie(&did, now), LASTS / 1000); | ||
// The account in use before, if another, is kept beside it. | ||
crates/group-host/src/group_api.rs+7−5
| @@ -17,6 +17,7 @@ use crate::scopes::covers; | ||
use crate::space_api::{service_caller, unauthorized}; | ||
use crate::token_writes::missing; | ||
use crate::xrpc::XrpcError; | ||
use atproto::service_auth::Claims; | ||
use atproto::space::SpaceRef; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
| @@ -47,13 +48,14 @@ pub(crate) async fn caller( | ||
if !headers.contains_key(header::AUTHORIZATION) { | ||
return host.console_caller(headers).map_err(XrpcError::internal); | ||
} | ||
let claims = service_caller(host, headers, lxm).await?; | ||
if !for_host(host, &claims.aud) { | ||
return Err(unauthorized( | ||
let ours = |claims: &Claims| match for_host(host, &claims.aud) { | ||
true => Ok(()), | ||
false => Err(unauthorized( | ||
"BadJwtAudience", | ||
format!("a token for {}, not this host", claims.aud), | ||
)); | ||
} | ||
)), | ||
}; | ||
let claims = service_caller(host, headers, lxm, ours).await?; | ||
Ok(Some(claims.account().to_string())) | ||
} | ||
| ||
crates/group-host/src/import.rs+5−5
| @@ -39,6 +39,7 @@ use anyhow::Result; | ||
use atproto::plc::Signed; | ||
use atproto::service_auth; | ||
use atproto::{Cid, PublicKey, did}; | ||
use atproto_client::service_auth::verify_any; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, StatusCode, header}; | ||
| @@ -359,14 +360,13 @@ async fn proof(host: &Host, jwt: &str) -> Result<String, XrpcError> { | ||
if !did.starts_with("did:plc:") { | ||
return Err(not_plc()); | ||
} | ||
let doc = host.identity.document_now(&did).await; | ||
let doc = doc.map_err(|e| invalid(format!("could not resolve {did}: {e:#}")))?; | ||
let key = did::signing_key(&doc).map_err(|_| bad("its DID names no key"))?; | ||
let now = (now_millis() / 1000) as u64; | ||
let claims = service_auth::verify(jwt, &key, now).map_err(|e| bad(&e.0))?; | ||
if !for_host(host, &claims.aud) || claims.lxm.as_deref() != Some(CREATE_ACCOUNT) { | ||
return Err(bad("not for this host's createAccount")); | ||
} | ||
let now = (now_millis() / 1000) as u64; | ||
let auds = [claims.aud.as_str()]; | ||
let checked = verify_any(&host.identity, jwt, &auds, CREATE_ACCOUNT, now).await; | ||
checked.map_err(|e| bad(&e.to_string()))?; | ||
Ok(did) | ||
} | ||
| ||
crates/group-host/src/lib.rs+3−6
| @@ -95,10 +95,9 @@ 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`). | ||
/// The console's OAuth client, signing people in and signing in to | ||
/// accounts being moved here (`console_login::client`). | ||
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, | ||
| @@ -135,8 +134,7 @@ impl Host { | ||
// 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); | ||
let console = console_login::client(&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); | ||
| @@ -152,7 +150,6 @@ impl Host { | ||
http: client(), | ||
guarded, | ||
console, | ||
moving, | ||
indexing: Default::default(), | ||
index_wake: Default::default(), | ||
clients: Default::default(), | ||
crates/group-host/src/space_api.rs+21−16
| @@ -16,6 +16,7 @@ use atproto::space::{ | ||
}; | ||
use atproto::space_auth::{self, CLOCK_SKEW, CREDENTIAL_MAX_AGE, Expect, Kind, TokenError}; | ||
use atproto::{Cid, drisl, syntax}; | ||
use atproto_client::service_auth::{Error as Unverified, verify_any}; | ||
use axum::Json; | ||
use axum::extract::{Query, Request, State}; | ||
use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header}; | ||
| @@ -482,30 +483,33 @@ pub async fn list_blobs( | ||
} | ||
| ||
/// The claims of the request's service auth (`Authorization: Bearer`), | ||
/// signed by its issuer's key and for `lxm`. | ||
/// for `lxm`, for an audience `ours` takes (else its refusal), and signed | ||
/// by its issuer's key: the audience is judged before any key is read. | ||
pub(crate) async fn service_caller( | ||
host: &Host, | ||
headers: &HeaderMap, | ||
lxm: &str, | ||
ours: impl FnOnce(&Claims) -> Result<(), XrpcError>, | ||
) -> Result<Claims, XrpcError> { | ||
let bearer = headers | ||
.get(header::AUTHORIZATION) | ||
.and_then(|v| v.to_str().ok()) | ||
.and_then(|a| a.strip_prefix("Bearer ")); | ||
let token = bearer.ok_or_else(|| unauthorized("AuthMissing", "service auth is required"))?; | ||
let bad = |e: service_auth::AuthError| unauthorized("BadJwt", e.0); | ||
let (_, claims) = service_auth::parts(token).map_err(bad)?; | ||
let check = |key: &atproto::PublicKey| service_auth::verify(token, key, now()); | ||
let checked = host.identity.with_key(claims.account(), check).await; | ||
let checked = checked | ||
.ok_or_else(|| unauthorized("BadJwtIss", format!("no signing key for {}", claims.iss)))?; | ||
let claims = checked.map_err(bad)?; | ||
let (_, claims) = service_auth::parts(token).map_err(|e| unauthorized("BadJwt", e.0))?; | ||
if claims.lxm.as_deref() != Some(lxm) { | ||
return Err(unauthorized( | ||
"BadJwtLexiconMethod", | ||
format!("a token not for {lxm}"), | ||
)); | ||
} | ||
ours(&claims)?; | ||
let auds = [claims.aud.as_str()]; | ||
let checked = verify_any(&host.identity, token, &auds, lxm, now()).await; | ||
checked.map_err(|e| match e { | ||
Unverified::NoKey(_) => unauthorized("BadJwtIss", e.to_string()), | ||
e => unauthorized("BadJwt", e.to_string()), | ||
})?; | ||
Ok(claims) | ||
} | ||
| ||
| @@ -520,7 +524,15 @@ pub async fn notify_credentials_revoked( | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Result<Json<Value>, XrpcError> { | ||
let claims = service_caller(&host, &headers, NOTIFY_REVOKED).await?; | ||
let hosted_here = |claims: &Claims| { | ||
let hosted = host.store.account(&claims.aud); | ||
let hosted = hosted.map_err(XrpcError::internal)?; | ||
match hosted.is_some_and(|a| a.did == claims.aud) { | ||
true => Ok(()), | ||
false => Err(forbidden("revocation audience is not a repo hosted here")), | ||
} | ||
}; | ||
let claims = service_caller(&host, &headers, NOTIFY_REVOKED, hosted_here).await?; | ||
let space = body["space"].as_str().unwrap_or_default(); | ||
let space = SpaceRef::parse(space).map_err(|e| invalid(e.to_string()))?; | ||
let jtis: Option<Vec<String>> = body["credentials"].as_array().and_then(|c| { | ||
| @@ -534,13 +546,6 @@ pub async fn notify_credentials_revoked( | ||
if claims.account() != space.authority { | ||
return Err(forbidden("revocation issuer is not the space authority")); | ||
} | ||
let hosted = host | ||
.store | ||
.account(&claims.aud) | ||
.map_err(XrpcError::internal)?; | ||
if !hosted.is_some_and(|a| a.did == claims.aud) { | ||
return Err(forbidden("revocation audience is not a repo hosted here")); | ||
} | ||
let until = now() + CREDENTIAL_MAX_AGE + 2 * CLOCK_SKEW; | ||
host.store | ||
.revoke(&space.to_string(), &jtis, until as i64, now() as i64) | ||
crates/group-host/tests/account_move.rs+69−2
| @@ -61,6 +61,9 @@ struct Old { | ||
refuse_refresh: Mutex<Option<&'static str>>, | ||
/// Whether it asks for a DPoP nonce without giving one. | ||
nonceless: Mutex<bool>, | ||
/// The move to forget as it refreshes a session: one cancelled | ||
/// meanwhile. | ||
ends_move: Mutex<Option<(group_host::store::Store, String)>>, | ||
} | ||
| ||
impl Old { | ||
| @@ -138,6 +141,11 @@ async fn token( | ||
let body = Json(json!({"error": error})); | ||
return (StatusCode::BAD_REQUEST, body).into_response(); | ||
} | ||
if form["grant_type"] == "refresh_token" | ||
&& let Some((store, mover)) = old.ends_move.lock().unwrap().take() | ||
{ | ||
store.forget_move(&mover).unwrap(); | ||
} | ||
let mut given = old.tokens.lock().unwrap(); | ||
let access = format!("at{}", given.len() + 1); | ||
given.push(access.clone()); | ||
| @@ -689,7 +697,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_oauth_session(&kept).unwrap(); | ||
assert!(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. | ||
| @@ -843,6 +851,65 @@ async fn a_refresh_refused_ends_the_move_or_says_what_its_server_said() { | ||
assert_eq!(w.call("getAccountMove", None).await, (200, json!({}))); | ||
} | ||
| ||
#[tokio::test] | ||
async fn a_move_ended_while_its_session_was_refreshed_stays_ended() { | ||
let w = world().await; | ||
*w.old.first_lasts.lock().unwrap() = 10; | ||
w.sign_in_to_move().await; | ||
// Cancelled as its server refreshes it: the refreshed session is not | ||
// kept, and its tokens are given back. | ||
*w.old.ends_move.lock().unwrap() = Some((w.h.host.store.clone(), w.person.clone())); | ||
let said = w.call("startAccountMove", Some(json!({}))).await; | ||
assert_eq!(error(&said), (400, "NotFound")); | ||
let given = w.old.tokens.lock().unwrap().last().cloned().unwrap(); | ||
let revoked = w.old.revoked.lock().unwrap().clone(); | ||
assert!(revoked.contains(&format!("r{given}")), "{revoked:?}"); | ||
assert_eq!(w.call("getAccountMove", None).await, (200, json!({}))); | ||
} | ||
| ||
#[tokio::test] | ||
async fn a_console_sign_in_coming_back_to_the_move_callback_is_refused() { | ||
let w = world().await; | ||
let b = browser(); | ||
let url = reqwest::Url::parse_with_params( | ||
&format!("{}/console/login", w.h.url), | ||
&[("handle", w.did.as_str())], | ||
) | ||
.unwrap(); | ||
// Approved, then refused: either way, at the move's callback it is a | ||
// sign-in this browser did not start there, and nothing is kept. | ||
for refusal in [None, Some("access_denied")] { | ||
let started = b.get(url.clone()).send().await.unwrap(); | ||
let login = set_cookie(&started, "group_host_login").unwrap(); | ||
let approved = b.get(location(&started)).send().await.unwrap(); | ||
let mut back = reqwest::Url::parse(&location(&approved)).unwrap(); | ||
back.set_path("/console/move/callback"); | ||
if let Some(error) = refusal { | ||
let state = back | ||
.query_pairs() | ||
.find(|(k, _)| k == "state") | ||
.unwrap() | ||
.1 | ||
.into_owned(); | ||
back.query_pairs_mut() | ||
.clear() | ||
.append_pair("error", error) | ||
.append_pair("state", &state) | ||
.append_pair("iss", &w.old.base()); | ||
} | ||
let cookies = format!("{login}; {}", w.cookie); | ||
let res = b.get(back).header("cookie", cookies).send().await.unwrap(); | ||
assert_eq!(res.status(), 400); | ||
assert!( | ||
res.text() | ||
.await | ||
.unwrap() | ||
.contains("did not start that sign-in") | ||
); | ||
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}; | ||
| @@ -864,7 +931,7 @@ fn a_database_from_before_lets_its_sign_ins_under_way_go() { | ||
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_eq!(store.take_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/import.rs+2−1
| @@ -551,7 +551,8 @@ async fn refuses_the_account_signed_in_a_did_web_and_one_whose_did_names_no_key( | ||
json!({"serviceJwt": token("did:plc:nobody", &w.key, &w.h.host.config.service_did, CREATE_ACCOUNT)}), | ||
) | ||
.await; | ||
assert_eq!(error(&said), (400, "InvalidRequest")); | ||
// A DID that resolves to nothing has no key to check its token by. | ||
assert_eq!(error(&said), (400, "InvalidToken")); | ||
// A DID whose document names no key. | ||
let rotation = Keypair::generate(Curve::K256); | ||
let mut op = Op::atproto( | ||