chadtmiller.com/group-host
atmosphere group host
0
0
Apps sign in to a group with app passwords its members make
crates/group-host/src/app_passwords.rsnew+465−0
465 lines changed: not loaded until asked for.
crates/group-host/src/group_members.rs+2−0
| @@ -440,6 +440,8 @@ impl Host { | ||
// And the apps they signed in as the group. | ||
let ended = self.store.revoke_member_grants(group, member); | ||
ended.map_err(XrpcError::internal)?; | ||
let dropped = self.store.drop_members_app_passwords(group, member); | ||
dropped.map_err(XrpcError::internal)?; | ||
let gone = Write::Delete { | ||
collection: format!("{NS}.membership"), | ||
rkey: did_rkey(member), | ||
crates/group-host/src/group_tokens.rs+8−5
| @@ -52,22 +52,25 @@ fn objects(field: &str, items: impl IntoIterator<Item = impl Into<String>>) -> V | ||
| ||
impl Host { | ||
/// The kinds of record a holder of `roles` may write as the group in | ||
/// any of its spaces, and so publish in its repo: `*` for any. | ||
/// any of its spaces, and so publish in its repo, each with the | ||
/// writes they may make of it: `*` for any kind. | ||
pub fn publishable( | ||
&self, | ||
group: &str, | ||
roles: &[String], | ||
) -> Result<BTreeSet<String>, XrpcError> { | ||
) -> Result<BTreeMap<String, BTreeSet<String>>, XrpcError> { | ||
let entries = self | ||
.group_records(group, &members_space(group), &format!("{NS}.space")) | ||
.map_err(XrpcError::internal)?; | ||
let mut out = BTreeSet::new(); | ||
let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new(); | ||
for (_, entry) in entries { | ||
let uri = entry["space"].as_str().unwrap_or_default(); | ||
let access = self.group_record(group, uri, &format!("{NS}.access"), "self"); | ||
let access = access.map_err(XrpcError::internal)?.unwrap_or_default(); | ||
if Access::of(&access).people.is_none() { | ||
out.extend(writes_for(&access, roles).into_keys()); | ||
// A space for chosen people is theirs, not the group's to publish. | ||
let open = Access::of(&access).people.is_none(); | ||
for (collection, actions) in writes_for(&access, roles).into_iter().filter(|_| open) { | ||
out.entry(collection).or_default().extend(actions); | ||
} | ||
} | ||
Ok(out) | ||
crates/group-host/src/lib.rs+25−0
| @@ -4,6 +4,7 @@ | ||
//! says how it is built and what is still to come. | ||
| ||
pub mod api; | ||
pub mod app_passwords; | ||
pub mod authority; | ||
pub mod authority_api; | ||
pub mod authorization; | ||
| @@ -327,6 +328,18 @@ pub fn router(host: Arc<Host>) -> Router { | ||
"/xrpc/fyi.opensocial.declineAuthorization", | ||
post(authorization::decline_authorization), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.createAppPassword", | ||
post(app_passwords::create_app_password), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.listAppPasswords", | ||
get(app_passwords::list_app_passwords), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.revokeAppPassword", | ||
post(app_passwords::revoke_app_password), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.listGroupTokens", | ||
get(group_tokens::list_group_tokens), | ||
| @@ -406,6 +419,18 @@ fn token_routes() -> Router<Arc<Host>> { | ||
&x("com.atproto.server.getSession"), | ||
get(token_writes::get_session), | ||
) | ||
.route( | ||
&x("com.atproto.server.createSession"), | ||
post(app_passwords::create_session), | ||
) | ||
.route( | ||
&x("com.atproto.server.refreshSession"), | ||
post(app_passwords::refresh_session), | ||
) | ||
.route( | ||
&x("com.atproto.server.deleteSession"), | ||
post(app_passwords::delete_session), | ||
) | ||
.route( | ||
&x("fyi.opensocial.getGroupAuth"), | ||
post(group_tokens::get_group_auth), | ||
crates/group-host/src/oauth_dpop.rs+1−1
| @@ -30,7 +30,7 @@ fn invalid(description: impl Into<String>) -> OAuthError { | ||
OAuthError::bad("invalid_dpop_proof", description) | ||
} | ||
| ||
fn hmac(key: &[u8], message: &[u8]) -> Vec<u8> { | ||
pub(crate) fn hmac(key: &[u8], message: &[u8]) -> Vec<u8> { | ||
let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("HMAC takes a key of any length"); | ||
mac.update(message); | ||
mac.finalize().into_bytes().to_vec() | ||
crates/group-host/src/oauth_resource.rs+6−2
| @@ -110,10 +110,13 @@ impl Host { | ||
) | ||
.into()); | ||
}; | ||
let now = now_millis(); | ||
if scheme.eq_ignore_ascii_case("Bearer") { | ||
return self.session(token, now); | ||
} | ||
if !scheme.eq_ignore_ascii_case("DPoP") { | ||
return Err(self.refuse("invalid_token", "this host's tokens are DPoP-bound")); | ||
return Err(self.refuse("invalid_token", "a token is DPoP or Bearer")); | ||
} | ||
let now = now_millis(); | ||
let found = self.store.grant_by_access(&jose::sha256(token), now); | ||
let grant = found.map_err(XrpcError::internal)?; | ||
let grant = | ||
| @@ -122,6 +125,7 @@ impl Host { | ||
let proof = proof.map_err(|e: OAuthError| self.refuse(e.error, e.description))?; | ||
let proof = | ||
proof.ok_or_else(|| self.refuse("invalid_dpop_proof", "DPoP proof required"))?; | ||
// A session from an app password has no key, and is no DPoP token. | ||
if proof.jkt != grant.dpop_jkt { | ||
return Err(self.refuse("invalid_token", "the DPoP key is not the token's")); | ||
} | ||
crates/group-host/src/oauth_store.rs+91−0
| @@ -46,6 +46,39 @@ pub struct Grant { | ||
pub used_at: Option<i64>, | ||
} | ||
| ||
/// An app password of a group's: what it is called, whose it is, and | ||
/// whether its sessions may use chat. Never the password: the host keeps | ||
/// its hash alone. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct AppPassword { | ||
pub name: String, | ||
pub member: String, | ||
pub privileged: bool, | ||
pub created_at: i64, | ||
} | ||
| ||
/// What a session signed in with app password `name` names as its client. | ||
pub fn app_password_client(name: &str) -> String { | ||
format!("app-password:{name}") | ||
} | ||
| ||
const MAKE_PASSWORD: &str = "INSERT OR IGNORE INTO app_password (grp, name, member, hash, privileged, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)"; | ||
const PASSWORDS: &str = | ||
"SELECT name, member, privileged, created_at FROM app_password WHERE grp = ?1"; | ||
const DROP_PASSWORD: &str = "DELETE FROM app_password WHERE grp = ?1 AND name = ?2"; | ||
const DROP_SESSIONS: &str = | ||
"DELETE FROM oauth_token WHERE grp = ?1 AND client_id = ?2 AND source = 'appPassword'"; | ||
const DROP_MEMBERS_PASSWORDS: &str = "DELETE FROM app_password WHERE grp = ?1 AND member = ?2"; | ||
| ||
fn app_password(row: &Row) -> rusqlite::Result<AppPassword> { | ||
Ok(AppPassword { | ||
name: row.get(0)?, | ||
member: row.get(1)?, | ||
privileged: row.get(2)?, | ||
created_at: row.get(3)?, | ||
}) | ||
} | ||
| ||
/// Something done as a group with a grant, or to one. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Activity { | ||
| @@ -304,6 +337,64 @@ impl Store { | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// Keeps `group`'s new app password, by its hash: `false` if the | ||
/// group has one by its name. | ||
pub fn make_app_password(&self, group: &str, p: &AppPassword, hash: &str) -> Result<bool> { | ||
let conn = self.conn(); | ||
let made = conn.execute( | ||
MAKE_PASSWORD, | ||
params![group, p.name, p.member, hash, p.privileged, p.created_at], | ||
)?; | ||
Ok(made > 0) | ||
} | ||
| ||
/// `group`'s app passwords, the newest first. | ||
pub fn app_passwords(&self, group: &str) -> Result<Vec<AppPassword>> { | ||
let conn = self.conn(); | ||
let sql = format!("{PASSWORDS} ORDER BY created_at DESC, name"); | ||
let mut q = conn.prepare(&sql)?; | ||
let rows = q.query_map([group], app_password)?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
| ||
/// `group`'s app password by its name, or by its hash. | ||
pub fn app_password( | ||
&self, | ||
group: &str, | ||
name: Option<&str>, | ||
hash: Option<&str>, | ||
) -> Result<Option<AppPassword>> { | ||
let conn = self.conn(); | ||
let sql = format!("{PASSWORDS} AND (name = ?2 OR hash = ?3)"); | ||
let found = conn.query_row(&sql, params![group, name, hash], app_password); | ||
Ok(found.optional()?) | ||
} | ||
| ||
/// Forgets `group`'s app password `name`, and signs out every session | ||
/// signed in with it. | ||
pub fn drop_app_password(&self, group: &str, name: &str) -> Result<()> { | ||
let mut conn = self.conn(); | ||
let tx = conn.transaction()?; | ||
tx.execute(DROP_PASSWORD, [group, name])?; | ||
tx.execute(DROP_SESSIONS, [group, &app_password_client(name)])?; | ||
tx.commit()?; | ||
Ok(()) | ||
} | ||
| ||
/// Signs out every session `member`'s app passwords for `group` began. | ||
pub fn revoke_member_sessions(&self, group: &str, member: &str) -> Result<usize> { | ||
let sql = | ||
"DELETE FROM oauth_token WHERE grp = ?1 AND member = ?2 AND source = 'appPassword'"; | ||
Ok(self.conn().execute(sql, [group, member])?) | ||
} | ||
| ||
/// Forgets every app password `member` made for `group`. | ||
pub fn drop_members_app_passwords(&self, group: &str, member: &str) -> Result<usize> { | ||
Ok(self | ||
.conn() | ||
.execute(DROP_MEMBERS_PASSWORDS, [group, member])?) | ||
} | ||
| ||
/// Ends every grant `member` approved for `group`: theirs to act with | ||
/// no more once they are out of it. | ||
pub fn revoke_member_grants(&self, group: &str, member: &str) -> Result<usize> { | ||
crates/group-host/src/repo.rs+7−5
| @@ -285,17 +285,18 @@ impl Host { | ||
/// Makes `writes` to `did`'s repo, as one commit. | ||
pub fn write(&self, did: &str, writes: &[Write]) -> Result<Committed, XrpcError> { | ||
let made = self.write_asked(did, writes, &Asked::default())?; | ||
Ok(made.expect("writes that are not puts make a commit")) | ||
Ok(made.expect("writes that are not puts make a commit").0) | ||
} | ||
| ||
/// Makes `writes` to `did`'s repo, as one commit, as `asked` has them: | ||
/// none if, as puts, they change nothing. | ||
/// its commit, and the writes as made, puts resolved; none if, as | ||
/// puts, they change nothing. | ||
pub fn write_asked( | ||
&self, | ||
did: &str, | ||
writes: &[Write], | ||
asked: &Asked, | ||
) -> Result<Option<Committed>, XrpcError> { | ||
) -> Result<Option<(Committed, Vec<Write>)>, XrpcError> { | ||
let _one_at_a_time = self.writing.lock().expect("not poisoned"); | ||
let account = self.store.account(did).map_err(XrpcError::internal)?; | ||
let account = account.ok_or_else(|| { | ||
| @@ -373,10 +374,11 @@ impl Host { | ||
.map_err(XrpcError::internal)?; | ||
self.remove_blobs(orphans.iter().map(|cid| (account.did.as_str(), cid))); | ||
self.announce(); | ||
Ok(Some(Committed { | ||
let committed = Committed { | ||
cid: new.cid, | ||
rev: new.rev, | ||
})) | ||
}; | ||
Ok(Some((committed, writes.clone()))) | ||
} | ||
| ||
/// `write` to `did`'s records, now at `paths`, checked: its path is a | ||
crates/group-host/src/scopes.rs+29−21
| @@ -72,34 +72,42 @@ impl Permissions { | ||
} | ||
} | ||
| ||
/// Whether it holds `transition:generic`, as an app password's session | ||
/// does: the group's repo and blobs, whole, and never a space. | ||
fn generic(&self) -> bool { | ||
self.scopes.iter().any(|s| s == "transition:generic") | ||
} | ||
| ||
/// May it `action` (`create`, `update`, `delete`) a `collection` | ||
/// record in the group's repo? | ||
pub fn repo(&self, collection: &str, action: &str) -> bool { | ||
self.scopes.iter().any(|s| { | ||
let Some(resource) = named(s, "repo") else { | ||
return false; | ||
}; | ||
let resource = match resource { | ||
"" => query(s, "collection"), | ||
r => vec![r], | ||
}; | ||
let covers = resource.iter().any(|c| *c == "*" || *c == collection); | ||
covers && actions(s, &REPO_ACTIONS, &REPO_ACTIONS).contains(&action) | ||
}) | ||
self.generic() | ||
|| self.scopes.iter().any(|s| { | ||
let Some(resource) = named(s, "repo") else { | ||
return false; | ||
}; | ||
let resource = match resource { | ||
"" => query(s, "collection"), | ||
r => vec![r], | ||
}; | ||
let covers = resource.iter().any(|c| *c == "*" || *c == collection); | ||
covers && actions(s, &REPO_ACTIONS, &REPO_ACTIONS).contains(&action) | ||
}) | ||
} | ||
| ||
/// May it upload a blob of type `mime`? | ||
pub fn blob(&self, mime: &str) -> bool { | ||
self.scopes.iter().any(|s| { | ||
let Some(resource) = named(s, "blob") else { | ||
return false; | ||
}; | ||
let accept = match resource { | ||
"" => query(s, "accept"), | ||
r => r.split(',').collect(), | ||
}; | ||
accept.iter().any(|p| mime_matches(p, mime)) | ||
}) | ||
self.generic() | ||
|| self.scopes.iter().any(|s| { | ||
let Some(resource) = named(s, "blob") else { | ||
return false; | ||
}; | ||
let accept = match resource { | ||
"" => query(s, "accept"), | ||
r => r.split(',').collect(), | ||
}; | ||
accept.iter().any(|p| mime_matches(p, mime)) | ||
}) | ||
} | ||
| ||
/// May it `action` (`read`, `read_self`, `create`, `update`, | ||
crates/group-host/src/space.rs+8−7
| @@ -33,26 +33,27 @@ impl Host { | ||
let made = self | ||
.space_write_asked(did, space, writes, &Asked::default()) | ||
.await?; | ||
Ok(made.expect("writes that are not puts make a revision")) | ||
Ok(made.expect("writes that are not puts make a revision").0) | ||
} | ||
| ||
/// Makes `writes` to `did`'s repo in `space` as `asked` has them, and | ||
/// tells the space's authority: none if, as puts, they change nothing. | ||
/// tells the space's authority: its commit, and the writes as made, | ||
/// puts resolved; none if, as puts, they change nothing. | ||
pub async fn space_write_asked( | ||
&self, | ||
did: &str, | ||
space: &str, | ||
writes: &[Write], | ||
asked: &Asked<'_>, | ||
) -> Result<Option<Commit>, XrpcError> { | ||
) -> Result<Option<(Commit, Vec<Write>)>, XrpcError> { | ||
let space = SpaceRef::parse(space).map_err(|e| invalid(e.to_string()))?; | ||
let Some(commit) = self.space_commit(did, &space, writes, asked)? else { | ||
let Some((commit, made)) = self.space_commit(did, &space, writes, asked)? else { | ||
return Ok(None); | ||
}; | ||
if let Err(e) = self.tell_authority(&space, &commit).await { | ||
tracing::warn!(space = %space, repo = did, error = %format!("{e:#}"), "telling the authority failed"); | ||
} | ||
Ok(Some(commit)) | ||
Ok(Some((commit, made))) | ||
} | ||
| ||
async fn tell_authority(&self, space: &SpaceRef, commit: &Commit) -> Result<()> { | ||
| @@ -83,7 +84,7 @@ impl Host { | ||
space: &SpaceRef, | ||
writes: &[Write], | ||
asked: &Asked, | ||
) -> Result<Option<Commit>, XrpcError> { | ||
) -> Result<Option<(Commit, Vec<Write>)>, XrpcError> { | ||
let _one_at_a_time = self.writing.lock().expect("not poisoned"); | ||
let account = self.store.account(did).map_err(XrpcError::internal)?; | ||
let account = account.ok_or_else(|| { | ||
| @@ -151,6 +152,6 @@ impl Host { | ||
rev: new.rev, | ||
data: hash.digest(), | ||
}; | ||
Ok(Some(commit)) | ||
Ok(Some((commit, writes))) | ||
} | ||
} | ||
crates/group-host/src/store.rs+12−0
| @@ -266,6 +266,17 @@ pub const MIGRATIONS: &[&str] = &[ | ||
at INTEGER NOT NULL | ||
); | ||
CREATE INDEX group_activity_grp ON group_activity (grp, seq); | ||
", | ||
" | ||
CREATE TABLE app_password ( | ||
grp TEXT NOT NULL REFERENCES account (did), | ||
name TEXT NOT NULL, | ||
member TEXT NOT NULL, | ||
hash TEXT NOT NULL UNIQUE, | ||
privileged INTEGER NOT NULL, | ||
created_at INTEGER NOT NULL, | ||
PRIMARY KEY (grp, name) | ||
); | ||
", | ||
]; | ||
| ||
| @@ -384,6 +395,7 @@ const DEACTIVATION: &str = "SELECT at, by, stewards FROM deactivation WHERE did | ||
const ACTIVATE: &str = "DELETE FROM deactivation WHERE did = ?1"; | ||
/// What goes with an account, in an order its references allow. | ||
const FORGET_ACCOUNT: &[&str] = &[ | ||
"DELETE FROM app_password WHERE grp = ?1", | ||
"DELETE FROM group_activity WHERE grp = ?1", | ||
"DELETE FROM oauth_token WHERE grp = ?1", | ||
"DELETE FROM oauth_request WHERE grp = ?1", | ||
crates/group-host/src/token_writes.rs+18−14
crates/group-host/tests/app_passwords.rsnew+556−0
556 lines changed: not loaded until asked for.