chadtmiller.com/group-host
atmosphere group host
0
0
Signing in holds at its edges: group tokens, uploads, app passwords
crates/group-host/src/app_passwords.rs+27−15
| @@ -109,15 +109,32 @@ impl Host { | ||
{ | ||
return Ok(true); | ||
} | ||
let dropped = self | ||
.store | ||
.drop_members_app_passwords(&grant.group, &grant.member); | ||
self.forget_app_passwords(&grant.group, &grant.member)?; | ||
Ok(false) | ||
} | ||
| ||
/// Forgets `member`'s app passwords for `group`, and every session | ||
/// signed in with one of them. | ||
fn forget_app_passwords(&self, group: &str, member: &str) -> Result<(), XrpcError> { | ||
let dropped = self.store.drop_members_app_passwords(group, member); | ||
dropped.map_err(XrpcError::internal)?; | ||
let ended = self | ||
.store | ||
.revoke_member_sessions(&grant.group, &grant.member); | ||
let ended = self.store.revoke_member_sessions(group, member); | ||
ended.map_err(XrpcError::internal)?; | ||
Ok(false) | ||
Ok(()) | ||
} | ||
| ||
/// The group's app passwords whose makers could still make them; the | ||
/// rest are forgotten, so none comes back with its maker's roles. | ||
fn app_passwords(&self, group: &str) -> Result<Vec<AppPassword>, XrpcError> { | ||
let held = self.store.app_passwords(group); | ||
let mut kept = Vec::new(); | ||
for p in held.map_err(XrpcError::internal)? { | ||
match self.may_issue(group, &p.member)? { | ||
true => kept.push(p), | ||
false => self.forget_app_passwords(group, &p.member)?, | ||
} | ||
} | ||
Ok(kept) | ||
} | ||
| ||
/// A JWT naming a session, as a PDS's are: an app may read when it | ||
| @@ -242,6 +259,7 @@ pub async fn create_session(State(host): State<Arc<Host>>, Json(body): Json<Valu | ||
.app_password(&group, None, Some(&hash_of(password))); | ||
let p = found.map_err(XrpcError::internal)?.ok_or_else(no)?; | ||
if !host.may_issue(&group, &p.member)? { | ||
host.forget_app_passwords(&group, &p.member)?; | ||
return Err(no()); | ||
} | ||
let now = now_millis(); | ||
| @@ -336,10 +354,7 @@ pub async fn create_app_password( | ||
"a name of 1 to 64 characters", | ||
)); | ||
} | ||
let held = host | ||
.store | ||
.app_passwords(group) | ||
.map_err(XrpcError::internal)?; | ||
let held = host.app_passwords(group)?; | ||
if held.len() >= APP_PASSWORDS_AT_MOST { | ||
let said = format!("a group holds {APP_PASSWORDS_AT_MOST} app passwords at most"); | ||
return Err(XrpcError::new( | ||
| @@ -395,10 +410,7 @@ pub async fn list_app_passwords( | ||
.store | ||
.grants_of(group, now_millis()) | ||
.map_err(XrpcError::internal)?; | ||
let held = host | ||
.store | ||
.app_passwords(group) | ||
.map_err(XrpcError::internal)?; | ||
let held = host.app_passwords(group)?; | ||
let passwords: Vec<Value> = held | ||
.iter() | ||
.filter(|p| configures || p.member == me) | ||
crates/group-host/src/assistants.rs+7−3
| @@ -373,9 +373,13 @@ pub async fn server_metadata(State(host): State<Arc<Host>>) -> Json<Value> { | ||
} | ||
| ||
/// Whether an assistant may be sent back to `uri`: over https, to a | ||
/// loopback address over http, or to an app's own scheme. | ||
/// loopback address over http, or to an app's own scheme; never with a | ||
/// fragment (RFC 6749 §3.1.2). | ||
fn may_return_to(uri: &str) -> bool { | ||
let Ok(url) = reqwest::Url::parse(uri) else { | ||
let Some(url) = reqwest::Url::parse(uri) | ||
.ok() | ||
.filter(|u| u.fragment().is_none()) | ||
else { | ||
return false; | ||
}; | ||
let loopback = matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")); | ||
| @@ -383,7 +387,7 @@ fn may_return_to(uri: &str) -> bool { | ||
"https" => true, | ||
"http" => loopback, | ||
"javascript" | "data" | "file" | "vbscript" => false, | ||
_ => url.fragment().is_none(), | ||
_ => true, | ||
} | ||
} | ||
| ||
crates/group-host/src/console_login.rs+4−2
| @@ -457,10 +457,12 @@ pub async fn callback( | ||
let why = "this browser did not start that sign-in, or it took too long"; | ||
return Ok(failed(StatusCode::BAD_REQUEST, why)); | ||
}; | ||
if q.get("iss").is_some_and(|iss| *iss != p.issuer) { | ||
// Atproto's servers always say who answered: one that does not may | ||
// be another, mixing its answer up with ours. | ||
if q.get("iss") != Some(&p.issuer) { | ||
return Ok(failed( | ||
StatusCode::BAD_REQUEST, | ||
"the answer came from another server", | ||
"the answer came from another server, or did not say which server", | ||
)); | ||
} | ||
let Some(code) = q.get("code") else { | ||
crates/group-host/src/group_tokens.rs+3−2
| @@ -16,7 +16,7 @@ use crate::api::{Params, invalid, param}; | ||
use crate::group::members_space; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::oauth_resource::Refusal; | ||
use crate::oauth_scope::writes_for; | ||
use crate::oauth_scope::{writes_for, writes_in}; | ||
use crate::oauth_store::{Grant, Tokens}; | ||
use crate::rbac::{Access, NS}; | ||
use crate::time::{iso, now_millis}; | ||
| @@ -132,7 +132,8 @@ pub async fn get_group_auth( | ||
let roles = host.roles(group, &me).map_err(XrpcError::internal)?; | ||
let access = host.group_record(group, uri, &format!("{NS}.access"), "self"); | ||
let access = access.map_err(XrpcError::internal)?.unwrap_or_default(); | ||
let writes = writes_for(&access, &roles); | ||
let everything = host.may_issue(group, &me)?; | ||
let writes = writes_in(&access, &roles, &me, everything); | ||
if writes.is_empty() { | ||
return Err(forbidden("no role of yours may act as the group in this space").into()); | ||
} | ||
crates/group-host/src/oauth_clients.rs+66−30
| @@ -17,7 +17,8 @@ use std::time::Duration; | ||
| ||
pub const CLIENT_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; | ||
| ||
/// How long a client's metadata is kept before it is fetched again. | ||
/// How long a client's metadata, or key set, is kept before it is fetched | ||
/// again. | ||
const KEEP_FOR: i64 = 10 * 60_000; | ||
/// How many clients' metadata is kept at once. | ||
const KEEP_AT_MOST: usize = 1000; | ||
| @@ -33,10 +34,33 @@ pub struct Client { | ||
pub metadata: Value, | ||
} | ||
| ||
/// The clients' metadata the host has read, and when. | ||
/// Documents the host has read, by URL, and when. | ||
#[derive(Default)] | ||
struct Kept(std::sync::Mutex<HashMap<String, (i64, Value)>>); | ||
| ||
impl Kept { | ||
/// The document at `url`, if read in the last few minutes. | ||
fn get(&self, url: &str, now: i64) -> Option<Value> { | ||
let kept = self.0.lock().expect("not poisoned").get(url).cloned(); | ||
let (at, value) = kept.filter(|(at, _)| now - at < KEEP_FOR)?; | ||
tracing::debug!(url, at, "kept"); | ||
Some(value) | ||
} | ||
| ||
fn keep(&self, url: &str, now: i64, value: &Value) { | ||
let mut kept = self.0.lock().expect("not poisoned"); | ||
if kept.len() >= KEEP_AT_MOST { | ||
kept.clear(); | ||
} | ||
kept.insert(url.into(), (now, value.clone())); | ||
} | ||
} | ||
| ||
/// The clients' metadata and key sets the host has read, and when. | ||
#[derive(Default)] | ||
pub struct Clients { | ||
kept: std::sync::Mutex<HashMap<String, (i64, Value)>>, | ||
metadata: Kept, | ||
keys: Kept, | ||
} | ||
| ||
fn invalid_metadata(description: impl Into<String>) -> OAuthError { | ||
| @@ -219,19 +243,22 @@ pub fn registered(uris: &[&str], uri: &str) -> bool { | ||
uris.contains(&at.as_str()) | ||
} | ||
| ||
/// The thumbprint of the key of `keys`, by `kid` if it names one, that | ||
/// signed `assertion`, and its claims. | ||
fn signed_by(keys: &Value, kid: &str, assertion: &str) -> Option<(String, Value)> { | ||
let empty = Vec::new(); | ||
let keys = keys["keys"].as_array().unwrap_or(&empty); | ||
keys.iter() | ||
.filter(|k| kid.is_empty() || k["kid"] == kid) | ||
.filter_map(|k| jose::from_jwk(k).ok()) | ||
.find_map(|k| Some((jose::thumbprint(&k), jose::verify(assertion, &k).ok()?.1))) | ||
} | ||
| ||
impl Host { | ||
/// The client `id` names, its metadata fetched and checked, or kept | ||
/// from a fetch in the last few minutes. | ||
pub async fn client(&self, id: &str, now: i64) -> Result<Client, OAuthError> { | ||
let kept = self | ||
.clients | ||
.kept | ||
.lock() | ||
.expect("not poisoned") | ||
.get(id) | ||
.cloned(); | ||
if let Some((at, metadata)) = kept.filter(|(at, _)| now - at < KEEP_FOR) { | ||
tracing::debug!(id, at, "client metadata kept"); | ||
if let Some(metadata) = self.clients.metadata.get(id, now) { | ||
return Ok(Client { | ||
id: id.into(), | ||
metadata, | ||
| @@ -242,11 +269,7 @@ impl Host { | ||
} else { | ||
validate(id, self.fetch_json(id, "client metadata").await?)? | ||
}; | ||
let mut kept = self.clients.kept.lock().expect("not poisoned"); | ||
if kept.len() >= KEEP_AT_MOST { | ||
kept.clear(); | ||
} | ||
kept.insert(id.into(), (now, metadata.clone())); | ||
self.clients.metadata.keep(id, now, &metadata); | ||
Ok(Client { | ||
id: id.into(), | ||
metadata, | ||
| @@ -302,6 +325,22 @@ impl Host { | ||
self.public_json(url, what).await.map_err(invalid_metadata) | ||
} | ||
| ||
/// The key set at `uri`, kept from a fetch in the last few minutes | ||
/// unless asked `again`, and whether it was kept. | ||
async fn client_keys( | ||
&self, | ||
uri: &str, | ||
now: i64, | ||
again: bool, | ||
) -> Result<(Value, bool), OAuthError> { | ||
if let Some(keys) = self.clients.keys.get(uri, now).filter(|_| !again) { | ||
return Ok((keys, true)); | ||
} | ||
let keys = self.fetch_json(uri, "the client's keys").await?; | ||
self.clients.keys.keep(uri, now, &keys); | ||
Ok((keys, false)) | ||
} | ||
| ||
/// How `client` authenticates on a request whose form is `form`: as | ||
/// itself alone, if public; with an assertion signed by one of its | ||
/// keys, for this host, if confidential. | ||
| @@ -326,20 +365,17 @@ impl Host { | ||
}; | ||
let (header, _) = jose::parts(assertion).map_err(|e| invalid_client(e.0))?; | ||
let kid = header["kid"].as_str().unwrap_or_default(); | ||
let keys = match client.metadata.get("jwks") { | ||
Some(jwks) => jwks.clone(), | ||
None => { | ||
let uri = client.metadata["jwks_uri"].as_str().unwrap_or_default(); | ||
self.fetch_json(uri, "the client's keys").await? | ||
} | ||
let uri = client.metadata["jwks_uri"].as_str().unwrap_or_default(); | ||
let (keys, kept) = match client.metadata.get("jwks") { | ||
Some(jwks) => (jwks.clone(), false), | ||
None => self.client_keys(uri, now, false).await?, | ||
}; | ||
let empty = Vec::new(); | ||
let keys = keys["keys"].as_array().unwrap_or(&empty); | ||
let verified = keys | ||
.iter() | ||
.filter(|k| kid.is_empty() || k["kid"] == kid) | ||
.filter_map(|k| jose::from_jwk(k).ok()) | ||
.find_map(|k| Some((jose::thumbprint(&k), jose::verify(assertion, &k).ok()?.1))); | ||
let mut verified = signed_by(&keys, kid, assertion); | ||
if verified.is_none() && kept { | ||
// Keys rotate: one not among those kept has them fetched again. | ||
let (keys, _) = self.client_keys(uri, now, true).await?; | ||
verified = signed_by(&keys, kid, assertion); | ||
} | ||
let verified = verified.ok_or_else(|| invalid_client("no key of the client signed this")); | ||
let (jkt, claims) = verified?; | ||
let issuer = &self.config.public_url; | ||
crates/group-host/src/oauth_scope.rs+41−14
| @@ -10,7 +10,7 @@ | ||
| ||
use crate::Host; | ||
use crate::group::members_space; | ||
use crate::rbac::{Access, NS, actions_for, grants, listed, repo_collections_for}; | ||
use crate::rbac::{self, Access, NS, actions_for, grants, listed, repo_collections_for}; | ||
use crate::scopes::{decoded, is_blob, repo_collections}; | ||
use crate::xrpc::XrpcError; | ||
use atproto::space::SpaceRef; | ||
| @@ -105,6 +105,27 @@ pub fn writes_for(access: &Value, roles: &[String]) -> BTreeMap<String, BTreeSet | ||
out | ||
} | ||
| ||
/// What a holder of `roles`, `member`, may write as the group in a space | ||
/// whose access record is `access`, by collection, `everything` being | ||
/// whether they may do anything as the group. A space for chosen people | ||
/// is written as the group by those of them who may do anything as it; | ||
/// any other, as its `credentialScopes` say. | ||
pub fn writes_in( | ||
access: &Value, | ||
roles: &[String], | ||
member: &str, | ||
everything: bool, | ||
) -> BTreeMap<String, BTreeSet<String>> { | ||
let rules = Access::of(access); | ||
match rules.people { | ||
Some(_) if everything && rules.can_read(roles, member) => { | ||
BTreeMap::from([("*".into(), WRITES.map(String::from).into())]) | ||
} | ||
Some(_) => BTreeMap::new(), | ||
None => writes_for(access, roles), | ||
} | ||
} | ||
| ||
/// Whether those writes include `action` on `collection`. | ||
pub(crate) fn may_write( | ||
writes: &BTreeMap<String, BTreeSet<String>>, | ||
| @@ -154,27 +175,33 @@ impl Host { | ||
.group_record(group, uri, &format!("{NS}.access"), "self") | ||
.map_err(XrpcError::internal)? | ||
.unwrap_or_default(); | ||
let rules = Access::of(&access); | ||
let readable = rules.can_read(roles, member); | ||
// A space for chosen people is written as the group by those | ||
// of them who may do anything as it. | ||
let writable = match rules.people { | ||
Some(_) if readable && everything => { | ||
BTreeMap::from([("*".into(), WRITES.map(String::from).into())]) | ||
} | ||
Some(_) => BTreeMap::new(), | ||
None => writes_for(&access, roles), | ||
}; | ||
rooms.push(Room { | ||
kind: space.kind, | ||
skey: space.skey, | ||
readable, | ||
writable, | ||
readable: Access::of(&access).can_read(roles, member), | ||
writable: writes_in(&access, roles, member, everything), | ||
}); | ||
} | ||
Ok(rooms) | ||
} | ||
| ||
/// Whether a holder of `roles` under `grants`, `member`, may write | ||
/// anything as `group` now: in its repo, its own spaces, or another. | ||
pub fn writes_anything( | ||
&self, | ||
group: &str, | ||
roles: &[String], | ||
grants: &[rbac::Grant], | ||
member: &str, | ||
) -> Result<bool, XrpcError> { | ||
let repo = repo_collections_for(grants, roles); | ||
if !repo.is_empty() || actions_for(grants, roles).contains("group.configure") { | ||
return Ok(true); | ||
} | ||
let rooms = self.rooms(group, roles, member, false)?; | ||
Ok(rooms.iter().any(|r| !r.writable.is_empty())) | ||
} | ||
| ||
/// The scopes of `requested` a holder of `roles` in `group`, `member`, | ||
/// may give an app acting as the group: | ||
/// | ||
crates/group-host/src/token_writes.rs+14−9
| @@ -15,8 +15,8 @@ use crate::Host; | ||
use crate::api::invalid; | ||
use crate::group::{join_policy, members_space, meta_space}; | ||
use crate::oauth_resource::{Acting, Refusal}; | ||
use crate::oauth_scope::{may_write, writes_for}; | ||
use crate::rbac::{self, Access, NS, actions_for, grants, repo_collections_for}; | ||
use crate::oauth_scope::{may_write, writes_in}; | ||
use crate::rbac::{self, NS, actions_for, grants, repo_collections_for}; | ||
use crate::repo::{Asked, Write, record_cid}; | ||
use crate::xrpc::XrpcError; | ||
use atproto::space::SpaceRef; | ||
| @@ -410,6 +410,13 @@ pub async fn apply_writes( | ||
/// A blob for the group's records, of a type the token's scope takes. | ||
pub async fn upload_blob(State(host): State<Arc<Host>>, headers: HeaderMap, body: Body) -> Answer { | ||
let acting = host.acting(&headers, "POST", "/xrpc/com.atproto.repo.uploadBlob")?; | ||
let (group, member) = (&acting.grant.group, &acting.grant.member); | ||
host.active(group)?; | ||
let (roles, grants) = host.standing(&acting)?; | ||
if !host.writes_anything(group, &roles, &grants, member)? { | ||
let no_more = "the member who signed this app in may no longer write anything as the group"; | ||
return Err(forbidden(no_more).into()); | ||
} | ||
let mime = headers | ||
.get(header::CONTENT_TYPE) | ||
.and_then(|v| v.to_str().ok()) | ||
| @@ -419,7 +426,7 @@ pub async fn upload_blob(State(host): State<Arc<Host>>, headers: HeaderMap, body | ||
} | ||
let limit = host.config.blob_upload_limit; | ||
let bytes = crate::xrpc::read_body(body, limit, "BlobTooLarge").await?; | ||
let blob = host.upload_blob(&acting.grant.group, &bytes, mime)?; | ||
let blob = host.upload_blob(group, &bytes, mime)?; | ||
Ok(Json(json!({ "blob": blob }))) | ||
} | ||
| ||
| @@ -448,9 +455,8 @@ impl Host { | ||
let configures = actions_for(&grants, &roles).contains("group.configure"); | ||
let access = self.group_record(group, uri, &format!("{NS}.access"), "self"); | ||
let access = access.map_err(XrpcError::internal)?.unwrap_or_default(); | ||
let rules = Access::of(&access); | ||
let everything = repo_collections_for(&grants, &roles).contains("*"); | ||
let writable = writes_for(&access, &roles); | ||
let writable = writes_in(&access, &roles, &acting.grant.member, everything); | ||
for w in writes { | ||
let (collection, _) = w.path(); | ||
if !acting.permissions.space(space, Some(collection), action(w)) { | ||
| @@ -460,10 +466,9 @@ impl Host { | ||
action(w) | ||
))); | ||
} | ||
let still = match &rules.people { | ||
_ if own => configures, | ||
Some(_) => everything && rules.can_read(&roles, &acting.grant.member), | ||
None => may_write(&writable, collection, action(w)), | ||
let still = match own { | ||
true => configures, | ||
false => may_write(&writable, collection, action(w)), | ||
}; | ||
if !still { | ||
return Err(no_longer(collection)); | ||
crates/group-host/tests/app_passwords.rs+21−1
| @@ -439,7 +439,6 @@ async fn ends_once_its_maker_could_no_longer_make_it() { | ||
); | ||
// Bob is a publisher no more. | ||
put_membership(&h, &did, &bob.did, &["member"]).await; | ||
assert_eq!(sign_in(&h, RIDERS, &password).await.0, 401); | ||
// Its refresh is refused, and that ends every session of his. | ||
let refresh = second["refreshJwt"].as_str().unwrap(); | ||
assert_eq!( | ||
| @@ -453,6 +452,7 @@ async fn ends_once_its_maker_could_no_longer_make_it() { | ||
.0, | ||
401 | ||
); | ||
assert_eq!(sign_in(&h, RIDERS, &password).await.0, 401); | ||
let said = xrpc( | ||
&h, | ||
"com.atproto.repo.createRecord", | ||
| @@ -496,6 +496,26 @@ async fn ends_once_its_maker_could_no_longer_make_it() { | ||
assert_eq!(names(&list(&h, &alice, &did).await.1), Vec::<&str>::new()); | ||
} | ||
| ||
#[tokio::test] | ||
async fn is_forgotten_once_its_maker_could_no_longer_make_it_though_never_used() { | ||
let h = start(&[], false).await; | ||
let (did, [alice, bob, _]) = group(&h).await; | ||
// Laptop is listed no more once Bob is a publisher no more, and does | ||
// not come back with his role. | ||
let laptop = make(&h, &bob, &did, "Laptop").await; | ||
put_membership(&h, &did, &bob.did, &["member"]).await; | ||
assert_eq!(names(&list(&h, &alice, &did).await.1), Vec::<&str>::new()); | ||
put_membership(&h, &did, &bob.did, &["member", "publisher"]).await; | ||
assert_eq!(sign_in(&h, RIDERS, &laptop).await.0, 401); | ||
// Nor does Tablet, refused while he was not one. | ||
let tablet = make(&h, &bob, &did, "Tablet").await; | ||
put_membership(&h, &did, &bob.did, &["member"]).await; | ||
assert_eq!(sign_in(&h, RIDERS, &tablet).await.0, 401); | ||
put_membership(&h, &did, &bob.did, &["member", "publisher"]).await; | ||
assert_eq!(sign_in(&h, RIDERS, &tablet).await.0, 401); | ||
assert_eq!(names(&list(&h, &bob, &did).await.1), Vec::<&str>::new()); | ||
} | ||
| ||
#[tokio::test] | ||
async fn is_revoked_by_its_maker_or_a_configurer() { | ||
let h = start(&[], false).await; | ||
crates/group-host/tests/assistants.rs+3−0
| @@ -583,6 +583,9 @@ async fn refuses_a_request_it_cannot_trust() { | ||
json!([format!("https://app.test/{}", "a".repeat(2048))]), | ||
json!(["javascript:alert(1)"]), | ||
json!(["http://evil.test/cb"]), | ||
json!(["https://app.test/cb#x"]), | ||
json!(["http://127.0.0.1/cb#x"]), | ||
json!(["cursor://anysphere.cursor-retrieval/oauth/callback#x"]), | ||
json!(["not a url"]), | ||
json!([]), | ||
] { | ||
crates/group-host/tests/console_login.rs+6−2
| @@ -120,8 +120,11 @@ async fn authorize( | ||
_ => back.append_pair("code", "c1"), | ||
}; | ||
back.append_pair("state", &pushed["state"]); | ||
let iss = pds.says("iss").as_str().map_or(pds.base(), String::from); | ||
back.append_pair("iss", &iss); | ||
// Unless asked to leave it out, as atproto's servers never may. | ||
if pds.says("iss") != false { | ||
let iss = pds.says("iss").as_str().map_or(pds.base(), String::from); | ||
back.append_pair("iss", &iss); | ||
} | ||
} | ||
Redirect::to(to.as_str()) | ||
} | ||
| @@ -400,6 +403,7 @@ async fn refuses_a_sign_in_it_cannot_trust() { | ||
json!("https://elsewhere.test"), | ||
"came from another server", | ||
), | ||
("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"), | ||
("token", json!("refuse"), "refused: invalid_grant"), | ||