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

Members take group tokens, configurers see and end every grant

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/sessions
crates/group-host/src/group_tokens.rsnew+255−0
@@ -0,0 +1,255 @@
//! Acting as the group from the console, and seeing who can.
//!
//! `getGroupAuth` gives a member, signed in as themselves, a short-lived
//! token for the group, bound to their DPoP key, to write in one of its
//! spaces what their roles there may write as the group, and the same
//! kinds of record in its public repo, as the access record's
//! `credentialScopes` say a role may publish what it writes. No group
//! password is involved, and there is nothing to refresh.
//!
//! `listGroupTokens` shows a group's configurers every grant that acts as
//! it, whose it is, and what was done with grants lately;
//! `revokeGroupToken` ends one.
//!
//! As the prototype's `methods/groupAuth.ts` and `connectedApps.ts`.
use crate::Host;
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_store::{Grant, Tokens};
use crate::rbac::{Access, NS};
use crate::time::{iso, now_millis};
use crate::xrpc::XrpcError;
use atproto::jose;
use atproto::space::SpaceRef;
use axum::Json;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
/// How long a group token lasts.
const GROUP_TOKEN_TTL: i64 = 15 * 60_000;
/// The client a group token is issued to: the host itself, for the member.
pub const GROUP_AUTH_CLIENT: &str = "getGroupAuth";
/// How much of the log `listGroupTokens` shows.
const ACTIVITY_SHOWN: u32 = 20;
fn forbidden(message: impl Into<String>) -> XrpcError {
XrpcError::new(StatusCode::FORBIDDEN, "Forbidden", message)
}
fn objects(field: &str, items: impl IntoIterator<Item = impl Into<String>>) -> Value {
items
.into_iter()
.map(|i| json!({ field: i.into() }))
.collect()
}
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.
pub fn publishable(
&self,
group: &str,
roles: &[String],
) -> Result<BTreeSet<String>, XrpcError> {
let entries = self
.group_records(group, &members_space(group), &format!("{NS}.space"))
.map_err(XrpcError::internal)?;
let mut out = BTreeSet::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());
crates/group-host/src/group_tokens.rsline 70
review.knotless.dev

writes_for(...).into_keys() discards the actions, and may_repo then allows any action on those collections in the repo. A role that may only create in a space could update or delete the same collection in the repo, for any grant whose scope is broad enough. Group tokens are safe because scopes_for limits the actions; OAuth grants are not.

}
}
Ok(out)
}
/// `member`'s standing to act as `group`: may they configure it?
fn configures(&self, group: &str, member: &str) -> Result<(), XrpcError> {
group_of(self, group)?;
if !self.may_do(group, member, "group.configure")? {
return Err(forbidden("missing group.configure"));
}
Ok(())
}
}
/// The scopes the writes a role holds in `space` become: each collection
/// with its actions, in the space and in the group's repo, and the files
/// those records hold.
fn scopes_for(space: &SpaceRef, writes: &BTreeMap<String, BTreeSet<String>>) -> Vec<String> {
let mut out = vec!["atproto".to_string()];
let at = format!(
"space:{}?authority={}&skey={}",
space.kind, space.authority, space.skey
);
for (collection, actions) in writes {
let actions: Vec<String> = actions.iter().map(|a| format!("action={a}")).collect();
let actions = actions.join("&");
out.push(format!(
"{at}&collection={collection}&action=read&{actions}"
));
out.push(format!("repo:{collection}?{actions}"));
}
let any = writes.contains_key("*");
out.push(if any { "blob:*/*" } else { "blob:image/*" }.into());
out
}
/// A token to act as the group in one of its spaces, for the caller's
/// DPoP key, as far as their roles there let them write.
pub async fn get_group_auth(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Result<Json<Value>, Refusal> {
let nsid = format!("{NS}.getGroupAuth");
let me = signed_in(&host, &headers, &nsid).await?;
let group = body["group"]
.as_str()
.ok_or_else(|| invalid("group is required"))?;
let uri = body["space"]
.as_str()
.ok_or_else(|| invalid("space is required"))?;
group_of(&host, group)?;
host.active(group)?;
let space = SpaceRef::parse(uri).ok().filter(|s| s.authority == group);
let space = space.ok_or_else(|| invalid("not one of this group's spaces"))?;
let now = now_millis();
let proof = host.dpop_proof(&headers, "POST", &format!("/xrpc/{nsid}"), None, now);
let proof = proof.map_err(|e| host.refuse(e.error, e.description))?;
let proof = proof.ok_or_else(|| host.refuse("invalid_dpop_proof", "DPoP proof required"))?;
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);
if writes.is_empty() {
return Err(forbidden("no role of yours may act as the group in this space").into());
}
let scope = scopes_for(&space, &writes).join(" ");
let access_token = jose::random(32);
let tokens = Tokens {
access_hash: &jose::sha256(&access_token),
access_expires: now + GROUP_TOKEN_TTL,
// Never handed out: a group token is not refreshed.
refresh_hash: &jose::sha256(&jose::random(32)),
expires_at: now + GROUP_TOKEN_TTL,
};
let grant = Grant {
id: format!("tok-{}", jose::random(16)),
group: group.into(),
member: me.clone(),
client_id: GROUP_AUTH_CLIENT.into(),
client_auth: json!({"method": "none"}),
scope: scope.clone(),
dpop_jkt: proof.jkt,
access_expires: tokens.access_expires,
expires_at: tokens.expires_at,
created_at: now,
source: GROUP_AUTH_CLIENT.into(),
used_at: None,
};
host.store
.issue(&grant, &tokens)
.map_err(XrpcError::internal)?;
let took = format!("took a token for {uri}");
host.record(group, &me, Some(GROUP_AUTH_CLIENT), &took)
.map_err(XrpcError::internal)?;
let collections: Vec<&String> = writes.keys().collect();
Ok(Json(json!({
"did": group,
"accessJwt": access_token,
"pds": host.config.public_url,
"collections": objects("collection", collections.iter().map(|c| c.as_str())),
"repoCollections": objects("collection", collections.iter().map(|c| c.as_str())),
"scope": scope,
"expiresAt": iso(tokens.expires_at),
})))
}
/// Every grant that acts as the group, and what grants did lately, for
/// one who configures it.
pub async fn list_group_tokens(
State(host): State<Arc<Host>>,
Query(p): Query<Params>,
headers: HeaderMap,
) -> Result<Json<Value>, XrpcError> {
let me = signed_in(&host, &headers, &format!("{NS}.listGroupTokens")).await?;
let group = param(&p, "group")?;
host.configures(group, &me)?;
let grants = host
.store
.grants_of(group, now_millis())
.map_err(XrpcError::internal)?;
let sessions: Vec<Value> = grants
.iter()
.map(|g| {
let mut view = json!({
"tokenId": g.id,
"clientId": g.client_id,
"member": g.member,
"source": g.source,
"scope": g.scope,
"grantedAt": iso(g.created_at),
"expiresAt": iso(g.expires_at),
});
if let Some(used) = g.used_at {
view["lastUsedAt"] = json!(iso(used));
}
view
})
.collect();
let log = host
.store
.activity(group, ACTIVITY_SHOWN)
.map_err(XrpcError::internal)?;
let activity: Vec<Value> = log
.iter()
.map(|a| {
let mut view = json!({"member": a.member, "action": a.action, "at": iso(a.at)});
if let Some(client) = &a.client_id {
view["clientId"] = json!(client);
}
view
})
.collect();
Ok(Json(json!({"sessions": sessions, "activity": activity})))
}
/// Ends one grant that acts as the group, for one who configures it.
pub async fn revoke_group_token(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Result<Json<Value>, XrpcError> {
let me = signed_in(&host, &headers, &format!("{NS}.revokeGroupToken")).await?;
let group = body["group"]
.as_str()
.ok_or_else(|| invalid("group is required"))?;
let id = body["tokenId"]
.as_str()
.ok_or_else(|| invalid("tokenId is required"))?;
host.configures(group, &me)?;
let grant = host.store.grant_by_id(id).map_err(XrpcError::internal)?;
let Some(grant) = grant.filter(|g| g.group == group) else {
return Err(XrpcError::new(
StatusCode::BAD_REQUEST,
"NotFound",
"no such grant of this group",
));
};
host.store.end_grant(id).map_err(XrpcError::internal)?;
let ended = format!("revoked {}'s grant to {}", grant.member, grant.client_id);
host.record(group, &me, Some(&grant.client_id), &ended)
.map_err(XrpcError::internal)?;
Ok(Json(json!({})))
}
crates/group-host/src/lib.rs+13−0
@@ -19,6 +19,7 @@ pub mod group_join;
pub mod group_lifecycle;
pub mod group_members;
pub mod group_spaces;
pub mod group_tokens;
pub mod identity;
pub mod index;
pub mod index_api;
@@ -326,6 +327,14 @@ pub fn router(host: Arc<Host>) -> Router {
"/xrpc/fyi.opensocial.declineAuthorization",
post(authorization::decline_authorization),
)
.route(
"/xrpc/fyi.opensocial.listGroupTokens",
get(group_tokens::list_group_tokens),
)
.route(
"/xrpc/fyi.opensocial.revokeGroupToken",
post(group_tokens::revoke_group_token),
)
.route("/oauth/authorize", get(oauth::authorize))
.merge(token_routes())
.merge(oauth_routes())
@@ -397,6 +406,10 @@ fn token_routes() -> Router<Arc<Host>> {
&x("com.atproto.server.getSession"),
get(token_writes::get_session),
)
.route(
&x("fyi.opensocial.getGroupAuth"),
post(group_tokens::get_group_auth),
)
.layer(axum::middleware::from_fn(oauth::cors))
}
crates/group-host/src/oauth.rs+10−0
@@ -474,10 +474,20 @@ async fn exchange(host: &Host, headers: &HeaderMap, form: OAuthForm) -> Result<V
access_expires: tokens.access_expires,
expires_at: tokens.expires_at,
created_at: now,
source: "oauth".into(),
used_at: None,
};
host.store
.issue(&grant, &tokens)
.map_err(OAuthError::internal)?;
let signed_in = format!("signed in {}", grant.client_id);
host.record(
&grant.group,
&grant.member,
Some(&grant.client_id),
&signed_in,
)
.map_err(OAuthError::internal)?;
tracing::info!(
group = grant.group,
member = grant.member,
crates/group-host/src/oauth_resource.rs+21−1
@@ -71,7 +71,24 @@ impl IntoResponse for Refusal {
}
impl Host {
fn refuse(&self, error: &'static str, description: impl Into<String>) -> Refusal {
/// Keeps word in `group`'s log of what was done as it.
pub fn record(
&self,
group: &str,
member: &str,
client: Option<&str>,
action: &str,
) -> anyhow::Result<()> {
let activity = crate::oauth_store::Activity {
member: member.into(),
client_id: client.map(String::from),
action: action.into(),
at: now_millis(),
};
self.store.record_activity(group, &activity)
}
pub(crate) fn refuse(&self, error: &'static str, description: impl Into<String>) -> Refusal {
Refusal::Token {
error,
description: description.into(),
@@ -108,6 +125,9 @@ impl Host {
if proof.jkt != grant.dpop_jkt {
return Err(self.refuse("invalid_token", "the DPoP key is not the token's"));
}
self.store
.touch(&grant.id, now)
.map_err(XrpcError::internal)?;
let permissions = Permissions::new(&grant.scope, &grant.group);
Ok(Acting { grant, permissions })
}
crates/group-host/src/oauth_store.rs+79−2
@@ -40,6 +40,19 @@ pub struct Grant {
/// When its refresh token lapses.
pub expires_at: i64,
pub created_at: i64,
/// How it was given: `oauth`, or `getGroupAuth`.
pub source: String,
/// When it was last used, to the minute.
pub used_at: Option<i64>,
}
/// Something done as a group with a grant, or to one.
#[derive(Debug, Clone, PartialEq)]
pub struct Activity {
pub member: String,
pub client_id: Option<String>,
pub action: String,
pub at: i64,
}
const PUSH: &str = "INSERT INTO oauth_request (id, client_id, client_auth, parameters, expires_at) VALUES (?1, ?2, ?3, ?4, ?5)";
@@ -48,8 +61,13 @@ const REQUEST: &str = "SELECT id, client_id, client_auth, parameters, expires_at
const APPROVE: &str = "UPDATE oauth_request SET grp = ?2, member = ?3, scope = ?4, code = ?5, expires_at = ?6 WHERE id = ?1 AND code IS NULL AND expires_at > ?7";
const DROP: &str = "DELETE FROM oauth_request WHERE id = ?1 AND code IS NULL AND expires_at > ?2";
const REDEEM: &str = "DELETE FROM oauth_request WHERE code = ?1 RETURNING id, client_id, client_auth, parameters, expires_at, grp, member, scope";
const ISSUE: &str = "INSERT INTO oauth_token (id, grp, member, client_id, client_auth, scope, dpop_jkt, access_hash, access_expires, refresh_hash, expires_at, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)";
const GRANT_COLUMNS: &str = "id, grp, member, client_id, client_auth, scope, dpop_jkt, access_expires, expires_at, created_at";
const ISSUE: &str = "INSERT INTO oauth_token (id, grp, member, client_id, client_auth, scope, dpop_jkt, access_hash, access_expires, refresh_hash, expires_at, created_at, source) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)";
const GRANT_COLUMNS: &str = "id, grp, member, client_id, client_auth, scope, dpop_jkt, access_expires, expires_at, created_at, source, used_at";
const TOUCH: &str = "UPDATE oauth_token SET used_at = ?2 WHERE id = ?1 AND (used_at IS NULL OR used_at <= ?2 - 60000)";
const END_GRANT: &str = "DELETE FROM oauth_token WHERE id = ?1";
const RECORD: &str =
"INSERT INTO group_activity (grp, member, client_id, action, at) VALUES (?1, ?2, ?3, ?4, ?5)";
const ACTIVITY: &str = "SELECT member, client_id, action, at FROM group_activity WHERE grp = ?1 ORDER BY seq DESC LIMIT ?2";
const ROTATE: &str = "UPDATE oauth_token SET access_hash = ?2, access_expires = ?3, refresh_hash = ?4, expires_at = ?5 WHERE refresh_hash = ?1 AND expires_at > ?6";
const REVOKE: &str = "DELETE FROM oauth_token WHERE access_hash = ?1 OR refresh_hash = ?1";
const REVOKE_MEMBER: &str = "DELETE FROM oauth_token WHERE grp = ?1 AND member = ?2";
@@ -83,6 +101,17 @@ fn grant(row: &Row) -> rusqlite::Result<Grant> {
access_expires: row.get(7)?,
expires_at: row.get(8)?,
created_at: row.get(9)?,
source: row.get(10)?,
used_at: row.get(11)?,
})
}
fn activity(row: &Row) -> rusqlite::Result<Activity> {
Ok(Activity {
member: row.get(0)?,
client_id: row.get(1)?,
action: row.get(2)?,
at: row.get(3)?,
})
}
@@ -178,6 +207,7 @@ impl Store {
tokens.refresh_hash,
tokens.expires_at,
grant.created_at,
grant.source,
],
)?;
Ok(())
@@ -227,6 +257,53 @@ impl Store {
Ok(conn.execute(REVOKE, [hash])? > 0)
}
/// The grant `id`, of any group.
pub fn grant_by_id(&self, id: &str) -> Result<Option<Grant>> {
let conn = self.conn();
let sql = format!("SELECT {GRANT_COLUMNS} FROM oauth_token WHERE id = ?1");
let found = conn.query_row(&sql, [id], grant);
Ok(found.optional()?)
}
/// `group`'s grants that last past `now`, the newest first.
pub fn grants_of(&self, group: &str, now: i64) -> Result<Vec<Grant>> {
let conn = self.conn();
let sql = format!(
"SELECT {GRANT_COLUMNS} FROM oauth_token WHERE grp = ?1 AND expires_at > ?2 ORDER BY created_at DESC, id"
);
let mut q = conn.prepare(&sql)?;
let rows = q.query_map(params![group, now], grant)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// Notes that grant `id` was used `now`, at most once a minute.
pub fn touch(&self, id: &str, now: i64) -> Result<()> {
self.conn().execute(TOUCH, params![id, now])?;
Ok(())
}
/// Ends the grant `id`.
pub fn end_grant(&self, id: &str) -> Result<bool> {
Ok(self.conn().execute(END_GRANT, [id])? > 0)
}
/// Keeps `activity` in `group`'s log.
pub fn record_activity(&self, group: &str, activity: &Activity) -> Result<()> {
let a = activity;
let values = params![group, a.member, a.client_id, a.action, a.at];
let recorded = self.conn().execute(RECORD, values);
recorded?;
Ok(())
}
/// The latest `limit` of `group`'s log, the newest first.
pub fn activity(&self, group: &str, limit: u32) -> Result<Vec<Activity>> {
let conn = self.conn();
let mut q = conn.prepare(ACTIVITY)?;
let rows = q.query_map(params![group, limit], activity)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// 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+112−2
@@ -35,6 +35,14 @@ pub enum Write {
}
impl Write {
/// The record it puts: none for a delete.
pub fn value(&self) -> Option<&serde_json::Value> {
match self {
Write::Create { value, .. } | Write::Update { value, .. } => Some(value),
Write::Delete { .. } => None,
}
}
/// Where it writes: its collection and record key.
pub fn path(&self) -> (&str, &str) {
match self {
@@ -58,6 +66,89 @@ pub(crate) struct Checked {
pub blobs: Vec<Cid>,
}
/// A check of a write before it is made, by the writes as resolved.
pub type Allow<'a> = &'a (dyn Fn(&[Write]) -> Result<(), XrpcError> + Sync);
/// What a write asks of the repo as it is when the write is made, all
/// asked under the write lock, so no other write comes between the asking
/// and the commit.
#[derive(Default, Clone, Copy)]
pub struct Asked<'a> {
/// The commit the repo must be at.
pub swap_commit: Option<&'a str>,
/// The CID of the record the first write's path must hold, or
/// `Some(None)` for none there.
pub swap_record: Option<Option<&'a str>>,
/// The writes put records: each create or update is whichever what is
/// there makes it, and a put of the record there already, or a delete
/// where there is none, changes nothing and is left out.
pub put: bool,
/// Asked of the writes as resolved, before any is made.
pub allow: Option<Allow<'a>>,
}
fn invalid_swap(message: impl Into<String>) -> XrpcError {
XrpcError::new(StatusCode::BAD_REQUEST, "InvalidSwap", message)
}
/// `writes` against the records at `paths`, as `asked` has them: swaps
/// checked, puts resolved, allowed, and only those that change something.
pub(crate) fn resolve(
writes: &[Write],
paths: &BTreeMap<String, Cid>,
asked: &Asked,
) -> Result<Vec<Write>, XrpcError> {
let current = |w: &Write| {
let (collection, rkey) = w.path();
paths.get(&format!("{collection}/{rkey}")).copied()
};
if let (Some(swap), Some(first)) = (asked.swap_record, writes.first())
&& swap != current(first).map(|c| c.to_string()).as_deref()
{
return Err(invalid_swap("the record is not the one swapped"));
}
let resolved: Vec<Write> = writes
.iter()
.map(|w| match (asked.put, w.value()) {
(true, Some(value)) => {
let (collection, rkey) = w.path();
let (collection, rkey, value) = (collection.into(), rkey.into(), value.clone());
match current(w) {
Some(_) => Write::Update {
collection,
rkey,
value,
},
None => Write::Create {
collection,
rkey,
value,
},
}
}
_ => w.clone(),
})
.collect();
if let Some(allow) = asked.allow {
allow(&resolved)?;
}
let mut changing = Vec::new();
for w in resolved {
let unchanged = asked.put
&& match &w {
Write::Delete { .. } => current(&w).is_none(),
Write::Update {
collection, value, ..
} => current(&w) == Some(record(collection, value)?.0),
Write::Create { .. } => false,
};
if !unchanged {
changing.push(w);
}
}
Ok(changing)
}
/// A commit made: its CID and revision.
#[derive(Debug, Clone, PartialEq)]
pub struct Committed {
@@ -193,6 +284,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"))
}
/// Makes `writes` to `did`'s repo, as one commit, as `asked` has them:
/// none if, as puts, they change nothing.
pub fn write_asked(
&self,
did: &str,
writes: &[Write],
asked: &Asked,
) -> Result<Option<Committed>, 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(|| {
@@ -208,10 +311,17 @@ impl Host {
.head(&account.did)
.map_err(XrpcError::internal)?
.expect("an account has a repo");
if let Some(swap) = asked.swap_commit.filter(|s| *s != head.cid.to_string()) {
return Err(invalid_swap(format!("the repo is not at {swap}")));
}
let mut paths = self
.store
.paths(&account.did)
.map_err(XrpcError::internal)?;
let writes = &resolve(writes, &paths, asked)?;
if asked.put && writes.is_empty() {
return Ok(None);
}
let before = Tree::build(&paths);
let mut changes: Vec<Change> = Vec::new();
let mut ops = Vec::new();
@@ -263,10 +373,10 @@ impl Host {
.map_err(XrpcError::internal)?;
self.remove_blobs(orphans.iter().map(|cid| (account.did.as_str(), cid)));
self.announce();
Ok(Committed {
Ok(Some(Committed {
cid: new.cid,
rev: new.rev,
})
}))
}
/// `write` to `did`'s records, now at `paths`, checked: its path is a
crates/group-host/src/space.rs+28−6
@@ -7,7 +7,7 @@
use crate::Host;
use crate::authority::{Access, DELIVER_FOR};
use crate::repo::{Checked, Write, invalid};
use crate::repo::{Asked, Checked, Write, invalid, resolve};
use crate::store::{Change, Notice, SpaceHead};
use crate::time::now_millis;
use crate::xrpc::XrpcError;
@@ -30,12 +30,29 @@ impl Host {
space: &str,
writes: &[Write],
) -> Result<Commit, XrpcError> {
let made = self
.space_write_asked(did, space, writes, &Asked::default())
.await?;
Ok(made.expect("writes that are not puts make a revision"))
}
/// 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.
pub async fn space_write_asked(
&self,
did: &str,
space: &str,
writes: &[Write],
asked: &Asked<'_>,
) -> Result<Option<Commit>, XrpcError> {
let space = SpaceRef::parse(space).map_err(|e| invalid(e.to_string()))?;
let commit = self.space_commit(did, &space, writes)?;
let Some(commit) = 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(commit)
Ok(Some(commit))
}
async fn tell_authority(&self, space: &SpaceRef, commit: &Commit) -> Result<()> {
@@ -65,7 +82,8 @@ impl Host {
did: &str,
space: &SpaceRef,
writes: &[Write],
) -> Result<Commit, XrpcError> {
asked: &Asked,
) -> Result<Option<Commit>, 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(|| {
@@ -89,8 +107,12 @@ impl Host {
.store
.space_paths(&account.did, &uri)
.map_err(XrpcError::internal)?;
let writes = resolve(writes, &paths, asked)?;
if asked.put && writes.is_empty() {
return Ok(None);
}
let mut changes = Vec::new();
for write in writes {
for write in &writes {
let Checked { path, put, blobs } = self.check(&account.did, write, &paths)?;
let (collection, rkey) = write.path();
let prev = match &put {
@@ -129,6 +151,6 @@ impl Host {
rev: new.rev,
data: hash.digest(),
};
Ok(commit)
Ok(Some(commit))
}
}
crates/group-host/src/store.rs+14−0
@@ -253,6 +253,19 @@ pub const MIGRATIONS: &[&str] = &[
created_at INTEGER NOT NULL
);
CREATE INDEX oauth_token_member ON oauth_token (grp, member);
",
"
ALTER TABLE oauth_token ADD COLUMN source TEXT NOT NULL DEFAULT 'oauth';
ALTER TABLE oauth_token ADD COLUMN used_at INTEGER;
CREATE TABLE group_activity (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
grp TEXT NOT NULL REFERENCES account (did),
member TEXT NOT NULL,
client_id TEXT,
action TEXT NOT NULL,
at INTEGER NOT NULL
);
CREATE INDEX group_activity_grp ON group_activity (grp, seq);
",
];
@@ -371,6 +384,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 group_activity WHERE grp = ?1",
"DELETE FROM oauth_token WHERE grp = ?1",
"DELETE FROM oauth_request WHERE grp = ?1",
"DELETE FROM invite WHERE grp = ?1",
crates/group-host/src/token_writes.rs+185−180
@@ -20,7 +20,7 @@ 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::repo::{Write, record_cid};
use crate::repo::{Asked, Write, record_cid};
use crate::xrpc::XrpcError;
use atproto::space::SpaceRef;
use axum::Json;
@@ -81,32 +81,6 @@ impl Host {
Ok(acting)
}
/// The write a body asks for at `collection`/`rkey`: a create where
/// there is no record, else an update; `None` for a put of what is
/// there already.
fn put(
&self,
current: Option<atproto::Cid>,
collection: &str,
rkey: &str,
value: &Value,
) -> Result<Option<Write>, XrpcError> {
let (collection, rkey, value) = (collection.to_string(), rkey.to_string(), value.clone());
Ok(match current {
None => Some(Write::Create {
collection,
rkey,
value,
}),
Some(cid) if cid == record_cid(&collection, &value)? => None,
Some(_) => Some(Write::Update {
collection,
rkey,
value,
}),
})
}
/// Refuses a write to the group's own meta or members space that the
/// host would not make itself, and to any space's access record.
fn guard(&self, group: &str, space: &str, writes: &[Write]) -> Result<(), XrpcError> {
@@ -165,6 +139,32 @@ impl Host {
}
}
impl Host {
/// Keeps word in the group's log of each of `writes`, made with
/// `acting`'s grant, in `space` if one.
fn wrote(
&self,
acting: &Acting,
space: Option<&str>,
writes: &[Write],
) -> Result<(), XrpcError> {
let g = &acting.grant;
for w in writes {
let (collection, rkey) = w.path();
let at = space.map(|s| format!(" in {s}")).unwrap_or_default();
let done = match w {
Write::Create { .. } => "created",
Write::Update { .. } => "updated",
Write::Delete { .. } => "deleted",
};
let action = format!("{done} {collection}/{rkey}{at}");
let recorded = self.record(&g.group, &g.member, Some(&g.client_id), &action);
recorded.map_err(XrpcError::internal)?;
}
Ok(())
}
}
/// A write's result, as `applyWrites` lists them.
fn result(kind: &str, uri: String, write: &Write) -> Result<Value, XrpcError> {
let (collection, _) = write.path();
@@ -253,7 +253,9 @@ impl Host {
/// and its member's roles still let them.
fn may_repo(&self, acting: &Acting, writes: &[Write]) -> Result<(), XrpcError> {
let (roles, grants) = self.standing(acting)?;
let repo = repo_collections_for(&grants, &roles);
let mut repo = repo_collections_for(&grants, &roles);
// A role may publish what it may write as the group in a space.
repo.extend(self.publishable(&acting.grant.group, &roles)?);
for w in writes {
let (collection, _) = w.path();
if !acting.permissions.repo(collection, action(w)) {
@@ -265,49 +267,19 @@ impl Host {
}
Ok(())
}
fn repo_record(
&self,
group: &str,
collection: &str,
rkey: &str,
) -> Result<Option<atproto::Cid>, XrpcError> {
let found = self
.store
.record(group, collection, rkey)
.map_err(XrpcError::internal)?;
Ok(found.map(|r| r.cid))
}
}
fn invalid_swap(message: impl Into<String>) -> XrpcError {
XrpcError::new(StatusCode::BAD_REQUEST, "InvalidSwap", message)
}
impl Host {
/// Refuses a write whose `swapCommit` is not the repo's head.
fn swap_commit(&self, group: &str, body: &Value) -> Result<(), XrpcError> {
let Some(swap) = body["swapCommit"].as_str() else {
return Ok(());
};
let head = self.store.head(group).map_err(XrpcError::internal)?;
if head.is_none_or(|h| h.cid.to_string() != swap) {
return Err(invalid_swap(format!("the repo is not at {swap}")));
}
Ok(())
}
}
/// Refuses a write whose `swapRecord` is not the record there now: a CID,
/// or null for none.
fn swap_record(body: &Value, current: Option<atproto::Cid>) -> Result<(), XrpcError> {
let Some(swap) = body.get("swapRecord") else {
return Ok(());
/// What a body asks of the repo as it stands when the write is made.
fn swaps(body: &Value) -> Result<(Option<&str>, Option<Option<&str>>), XrpcError> {
let record = match body.get("swapRecord") {
None => None,
Some(Value::Null) => Some(None),
Some(v) => Some(Some(
v.as_str()
.ok_or_else(|| invalid("swapRecord is a CID, or null"))?,
)),
};
if swap.as_str() != current.map(|c| c.to_string()).as_deref() {
return Err(invalid_swap("the record is not the one swapped"));
}
Ok(())
Ok((body["swapCommit"].as_str(), record))
}
/// `at://` of a record in the group's repo.
@@ -331,39 +303,65 @@ pub async fn create_record(
rkey: rkey.clone(),
value: body["record"].clone(),
};
host.may_repo(&acting, std::slice::from_ref(&write))?;
host.swap_commit(group, &body)?;
let committed = host.write(group, std::slice::from_ref(&write))?;
let (swap_commit, _) = swaps(&body)?;
let allow = |w: &[Write]| host.may_repo(&acting, w);
let asked = Asked {
swap_commit,
allow: Some(&allow),
..Asked::default()
};
let committed = host.write_asked(group, std::slice::from_ref(&write), &asked)?;
host.wrote(&acting, None, std::slice::from_ref(&write))?;
Ok(Json(json!({
"uri": repo_uri(group, &collection, &rkey),
"cid": record_cid(&collection, &body["record"])?.to_string(),
"commit": commit_view(&committed),
"commit": committed.as_ref().map(commit_view),
"validationStatus": "unknown",
})))
}
/// Puts a record, or deletes one, as one write whose create or update is
/// whichever the repo makes it as it is written.
async fn put_or_delete(
host: &Host,
nsid: &str,
headers: &HeaderMap,
body: &Value,
delete: bool,
) -> Answer {
let acting = host.writer(headers, nsid, body)?;
let group = &acting.grant.group;
let write = one(body, delete)?;
let (collection, rkey) = write.path();
let (swap_commit, swap_record) = swaps(body)?;
let allow = |w: &[Write]| host.may_repo(&acting, w);
let asked = Asked {
swap_commit,
swap_record,
put: true,
allow: Some(&allow),
};
// A put of what is there, or a delete of what is not, makes no commit.
let committed = host.write_asked(group, std::slice::from_ref(&write), &asked)?;
let mut out = json!({});
if let Some(c) = &committed {
out["commit"] = commit_view(c);
host.wrote(&acting, None, std::slice::from_ref(&write))?;
crates/group-host/src/token_writes.rsline 349
review.knotless.dev

write is the unresolved Update that one builds, so a put that created the record is logged as "updated". The same happens in space_writes.

}
if !delete {
out["uri"] = json!(repo_uri(group, collection, rkey));
out["cid"] = json!(record_cid(collection, &body["record"])?.to_string());
out["validationStatus"] = json!("unknown");
}
Ok(Json(out))
}
pub async fn put_record(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let acting = host.writer(&headers, "com.atproto.repo.putRecord", &body)?;
let group = &acting.grant.group;
let (collection, rkey) = (text(&body, "collection")?, text(&body, "rkey")?);
let current = host.repo_record(group, collection, rkey)?;
swap_record(&body, current)?;
host.swap_commit(group, &body)?;
let mut out = json!({
"uri": repo_uri(group, collection, rkey),
"cid": record_cid(collection, &body["record"])?.to_string(),
"validationStatus": "unknown",
});
// A put of what is there already changes nothing, and makes no commit.
if let Some(write) = host.put(current, collection, rkey, &body["record"])? {
host.may_repo(&acting, std::slice::from_ref(&write))?;
out["commit"] = commit_view(&host.write(group, &[write])?);
}
Ok(Json(out))
put_or_delete(&host, "com.atproto.repo.putRecord", &headers, &body, false).await
}
pub async fn delete_record(
@@ -371,26 +369,14 @@ pub async fn delete_record(
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let acting = host.writer(&headers, "com.atproto.repo.deleteRecord", &body)?;
let group = &acting.grant.group;
let (collection, rkey) = (
text(&body, "collection")?.to_string(),
text(&body, "rkey")?.to_string(),
);
let write = Write::Delete {
collection: collection.clone(),
rkey: rkey.clone(),
};
host.may_repo(&acting, std::slice::from_ref(&write))?;
let current = host.repo_record(group, &collection, &rkey)?;
swap_record(&body, current)?;
host.swap_commit(group, &body)?;
// Gone already is gone, as a PDS has it.
if current.is_none() {
return Ok(Json(json!({})));
}
let committed = host.write(group, &[write])?;
Ok(Json(json!({"commit": commit_view(&committed)})))
put_or_delete(
&host,
"com.atproto.repo.deleteRecord",
&headers,
&body,
true,
)
.await
}
pub async fn apply_writes(
@@ -401,15 +387,21 @@ pub async fn apply_writes(
let acting = host.writer(&headers, "com.atproto.repo.applyWrites", &body)?;
let group = &acting.grant.group;
let writes = listed(&host, "repo", &body)?;
host.may_repo(&acting, &writes)?;
host.swap_commit(group, &body)?;
let committed = host.write(group, &writes)?;
let (swap_commit, _) = swaps(&body)?;
let allow = |w: &[Write]| host.may_repo(&acting, w);
let asked = Asked {
swap_commit,
allow: Some(&allow),
..Asked::default()
};
let committed = host.write_asked(group, &writes, &asked)?;
host.wrote(&acting, None, &writes)?;
let results: Vec<Value> = writes
.iter()
.map(|w| result("repo", repo_uri(group, w.path().0, w.path().1), w))
.collect::<Result<_, _>>()?;
Ok(Json(
json!({"commit": commit_view(&committed), "results": results}),
json!({"commit": committed.as_ref().map(commit_view), "results": results}),
))
}
@@ -479,50 +471,91 @@ impl Host {
}
self.guard(group, uri, writes)
}
fn space_record_cid(
&self,
group: &str,
space: &str,
collection: &str,
rkey: &str,
) -> Result<Option<atproto::Cid>, XrpcError> {
let found = self
.store
.space_record(group, space, collection, rkey)
.map_err(XrpcError::internal)?;
Ok(found.map(|r| r.cid))
}
}
fn space_uri(space: &str, group: &str, collection: &str, rkey: &str) -> String {
format!("{space}/{group}/{collection}/{rkey}")
}
/// Makes `writes` in the space a body names, as `put` has them: its
/// commit, if any.
async fn space_writes(
host: &Host,
nsid: &str,
headers: &HeaderMap,
body: &Value,
writes: impl FnOnce(&Host) -> Result<Vec<Write>, XrpcError>,
put: bool,
) -> Result<(String, String, Vec<Write>, bool), Refusal> {
let acting = host.writer(headers, nsid, body)?;
let (uri, space) = space_of(body)?;
let group = acting.grant.group.clone();
let writes = writes(host)?;
let allow = |w: &[Write]| host.may_space(&acting, &uri, &space, w);
let asked = Asked {
put,
allow: Some(&allow),
..Asked::default()
};
let made = host
.space_write_asked(&group, &uri, &writes, &asked)
.await?;
if made.is_some() {
host.wrote(&acting, Some(&uri), &writes)?;
}
Ok((uri, group, writes, made.is_some()))
}
/// The one write a put or delete body asks for.
fn one(body: &Value, delete: bool) -> Result<Write, XrpcError> {
let (collection, rkey) = (
text(body, "collection")?.to_string(),
text(body, "rkey")?.to_string(),
);
Ok(match delete {
true => Write::Delete { collection, rkey },
false => Write::Update {
collection,
rkey,
value: body["record"].clone(),
},
})
}
/// A record view of a space write: its URI, CID and validation.
fn space_record_view(
uri: &str,
group: &str,
write: &Write,
body: &Value,
) -> Result<Value, XrpcError> {
let (collection, rkey) = write.path();
Ok(json!({
"uri": space_uri(uri, group, collection, rkey),
"cid": record_cid(collection, &body["record"])?.to_string(),
"validationStatus": "unknown",
}))
}
pub async fn space_create_record(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let acting = host.writer(&headers, "com.atproto.space.createRecord", &body)?;
let (uri, space) = space_of(&body)?;
let group = acting.grant.group.clone();
let collection = text(&body, "collection")?.to_string();
let rkey = body["rkey"]
.as_str()
.map_or_else(|| host.clock.next(), String::from);
let write = Write::Create {
collection: collection.clone(),
rkey: rkey.clone(),
value: body["record"].clone(),
let make = |_: &Host| {
let collection = text(&body, "collection")?.to_string();
Ok(vec![Write::Create {
collection,
rkey: rkey.clone(),
value: body["record"].clone(),
}])
};
host.may_space(&acting, &uri, &space, std::slice::from_ref(&write))?;
host.space_write(&group, &uri, &[write]).await?;
Ok(Json(json!({
"uri": space_uri(&uri, &group, &collection, &rkey),
"cid": record_cid(&collection, &body["record"])?.to_string(),
"validationStatus": "unknown",
})))
let nsid = "com.atproto.space.createRecord";
let (uri, group, writes, _) = space_writes(&host, nsid, &headers, &body, make, false).await?;
Ok(Json(space_record_view(&uri, &group, &writes[0], &body)?))
}
pub async fn space_put_record(
@@ -530,20 +563,10 @@ pub async fn space_put_record(
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let acting = host.writer(&headers, "com.atproto.space.putRecord", &body)?;
let (uri, space) = space_of(&body)?;
let group = acting.grant.group.clone();
let (collection, rkey) = (text(&body, "collection")?, text(&body, "rkey")?);
let current = host.space_record_cid(&group, &uri, collection, rkey)?;
if let Some(write) = host.put(current, collection, rkey, &body["record"])? {
host.may_space(&acting, &uri, &space, std::slice::from_ref(&write))?;
host.space_write(&group, &uri, &[write]).await?;
}
Ok(Json(json!({
"uri": space_uri(&uri, &group, collection, rkey),
"cid": record_cid(collection, &body["record"])?.to_string(),
"validationStatus": "unknown",
})))
let make = |_: &Host| Ok(vec![one(&body, false)?]);
let nsid = "com.atproto.space.putRecord";
let (uri, group, writes, _) = space_writes(&host, nsid, &headers, &body, make, true).await?;
Ok(Json(space_record_view(&uri, &group, &writes[0], &body)?))
}
pub async fn space_delete_record(
@@ -551,24 +574,9 @@ pub async fn space_delete_record(
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let acting = host.writer(&headers, "com.atproto.space.deleteRecord", &body)?;
let (uri, space) = space_of(&body)?;
let group = acting.grant.group.clone();
let (collection, rkey) = (
text(&body, "collection")?.to_string(),
text(&body, "rkey")?.to_string(),
);
let write = Write::Delete {
collection: collection.clone(),
rkey: rkey.clone(),
};
host.may_space(&acting, &uri, &space, std::slice::from_ref(&write))?;
if host
.space_record_cid(&group, &uri, &collection, &rkey)?
.is_some()
{
host.space_write(&group, &uri, &[write]).await?;
}
let make = |_: &Host| Ok(vec![one(&body, true)?]);
let nsid = "com.atproto.space.deleteRecord";
space_writes(&host, nsid, &headers, &body, make, true).await?;
Ok(Json(json!({})))
}
@@ -577,12 +585,9 @@ pub async fn space_apply_writes(
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let acting = host.writer(&headers, "com.atproto.space.applyWrites", &body)?;
let (uri, space) = space_of(&body)?;
let group = acting.grant.group.clone();
let writes = listed(&host, "space", &body)?;
host.may_space(&acting, &uri, &space, &writes)?;
host.space_write(&group, &uri, &writes).await?;
let make = |h: &Host| listed(h, "space", &body);
let nsid = "com.atproto.space.applyWrites";
let (uri, group, writes, _) = space_writes(&host, nsid, &headers, &body, make, false).await?;
let results: Vec<Value> = writes
.iter()
.map(|w| result("space", space_uri(&uri, &group, w.path().0, w.path().1), w))
crates/group-host/tests/group_tokens.rsnew+287−0
@@ -0,0 +1,287 @@
//! Acting as the group from the console with a group token, and seeing and
//! ending the grants that act as it, with what they did.
mod common;
use common::groups::*;
use common::oauth::*;
use common::spaces::*;
use common::{Running, start};
use group_host::group::members_space;
use group_host::repo::Write;
use serde_json::{Value as Json, json};
const CALENDAR: &str = "com.example.calendar";
const EVENT: &str = "com.example.event";
const GET_GROUP_AUTH: &str = "fyi.opensocial.getGroupAuth";
async fn membership(h: &Running, did: &str, who: &str, roles: &[&str]) {
let roles: Vec<Json> = roles.iter().map(|r| json!({"role": r})).collect();
let value = json!({"$type": format!("{NS}.membership"), "member": who, "roles": roles, "createdAt": "2026-11-03T00:00:00Z"});
let write = Write::Create {
collection: format!("{NS}.membership"),
rkey: who.into(),
value,
};
h.host
.space_write(did, &members_space(did), &[write])
.await
.unwrap();
}
/// Riders, Alice's, with a calendar where members add events as the group
/// and admins write anything; Bob a member, Carol not one.
async fn group(h: &Running) -> (String, String, [Authority; 3]) {
let [alice, bob, carol] = people(h).await;
let did = start_group(
h,
&alice,
json!({"handle": RIDERS, "displayName": "Riders"}),
)
.await;
let lxm = format!("{NS}.createSpace");
let body = json!({
"group": did,
"spaceType": CALENDAR,
"skey": "rides",
"readableBy": [{"role": "member"}],
"credentialScopes": [
{"role": "member", "scopes": [{"collection": format!("{EVENT}?action=create")}]},
{"role": "admin", "scopes": [{"collection": "*"}]},
],
});
let (status, made) = post(h, &lxm, &body, &[auth(h, &alice, &lxm)]).await;
assert_eq!(status, 200, "{made}");
membership(h, &did, &bob.did, &["member"]).await;
(
did,
made["uri"].as_str().unwrap().to_string(),
[alice, bob, carol],
)
}
/// Asks for a group token as `who`, proved by `app`'s key, once more with
/// the nonce if asked.
async fn group_auth(h: &Running, app: &App, who: &Authority, body: &Json) -> Said {
let send = || {
let (k, v) = auth(h, who, GET_GROUP_AUTH);
h.http
.post(format!("{}/xrpc/{GET_GROUP_AUTH}", h.url))
.json(body)
.header(k, v)
.header(
"dpop",
app.proof_with(h, "POST", &format!("/xrpc/{GET_GROUP_AUTH}"), |_| {}),
)
};
let said = app.said(send()).await;
let stale = said
.headers
.get("www-authenticate")
.is_some_and(|v| v.to_str().unwrap().contains("use_dpop_nonce"));
if !stale {
return said;
}
app.said(send()).await
}
fn record(collection: &str) -> Json {
json!({"$type": collection, "text": "ride", "createdAt": "2026-11-03T00:00:00Z"})
}
#[tokio::test]
async fn gives_a_member_a_token_for_what_their_roles_write_in_a_space() {
let h = start(&[], false).await;
let (did, calendar, [alice, bob, _]) = group(&h).await;
let app = App::new("console");
let said = group_auth(&h, &app, &bob, &json!({"group": did, "space": calendar})).await;
assert_eq!(said.status, 200, "{}", said.body);
let body = &said.body;
assert_eq!(body["did"], did.as_str());
assert_eq!(body["pds"], "https://host.test");
assert_eq!(body["collections"], json!([{"collection": EVENT}]));
assert_eq!(body["repoCollections"], json!([{"collection": EVENT}]));
let scope = body["scope"].as_str().unwrap();
assert_eq!(
scope,
format!(
"atproto space:{CALENDAR}?authority={did}&skey=rides&collection={EVENT}&action=read&action=create repo:{EVENT}?action=create blob:image/*"
)
);
assert!(body["expiresAt"].is_string());
let token = body["accessJwt"].as_str().unwrap();
// It writes events, in the calendar and the group's repo, and no more.
let in_space =
json!({"repo": did, "space": calendar, "collection": EVENT, "record": record(EVENT)});
let said = app
.call(&h, "com.atproto.space.createRecord", token, Some(&in_space))
.await;
assert_eq!(said.status, 200, "{}", said.body);
let in_repo = json!({"repo": did, "collection": EVENT, "record": record(EVENT)});
let said = app
.call(&h, "com.atproto.repo.createRecord", token, Some(&in_repo))
.await;
assert_eq!(said.status, 200, "{}", said.body);
let post = json!({"repo": did, "collection": "app.bsky.feed.post", "record": record("app.bsky.feed.post")});
let said = app
.call(&h, "com.atproto.repo.createRecord", token, Some(&post))
.await;
assert_eq!(said.error(), (403, "ScopeMissing"));
// An admin's is for anything there, and any file.
let said = group_auth(&h, &app, &alice, &json!({"group": did, "space": calendar})).await;
assert_eq!(
said.body["collections"],
json!([{"collection": "*"}, {"collection": EVENT}])
);
assert!(said.body["scope"].as_str().unwrap().ends_with("blob:*/*"));
}
#[tokio::test]
async fn refuses_a_group_token_it_should_not_give() {
let h = start(&[], false).await;
let (did, calendar, [alice, _, carol]) = group(&h).await;
let app = App::new("console");
let ask = async |who: &Authority, body: Json| group_auth(&h, &app, who, &body).await;
let refused = [
(ask(&carol, json!({"group": did, "space": calendar})).await, (403, "Forbidden")),
(ask(&alice, json!({"group": did, "space": format!("at://{}/space/{CALENDAR}/rides", alice.did)})).await, (400, "InvalidRequest")),
(ask(&alice, json!({"group": did, "space": "nonsense"})).await, (400, "InvalidRequest")),
(ask(&alice, json!({"group": "did:plc:nothing", "space": calendar})).await, (400, "GroupNotFound")),
(ask(&alice, json!({"space": calendar})).await, (400, "InvalidRequest")),
(ask(&alice, json!({"group": did})).await, (400, "InvalidRequest")),
];
for (said, error) in refused {
assert_eq!(said.error(), error, "{}", said.body);
}
// Without a proof, or service auth.
let (k, v) = auth(&h, &alice, GET_GROUP_AUTH);
let bare = h
.http
.post(format!("{}/xrpc/{GET_GROUP_AUTH}", h.url))
.json(&json!({"group": did, "space": calendar}));
assert_eq!(
app.said(bare.header(k, v)).await.error(),
(401, "invalid_dpop_proof")
);
let said = app
.said(
h.http
.post(format!("{}/xrpc/{GET_GROUP_AUTH}", h.url))
.json(&json!({"group": did, "space": calendar})),
)
.await;
assert_eq!(said.error(), (401, "AuthMissing"));
// Nor while the group is switched off.
let lxm = format!("{NS}.deactivateGroup");
post(&h, &lxm, &json!({"group": did}), &[auth(&h, &alice, &lxm)]).await;
let said = ask(&alice, json!({"group": did, "space": calendar})).await;
assert_eq!(said.error(), (400, "RepoDeactivated"));
}
#[tokio::test]
async fn shows_its_configurers_who_acts_as_the_group_and_lets_them_end_it() {
let h = start(&[], false).await;
let (did, calendar, [alice, bob, _]) = group(&h).await;
let app = App::loopback("atproto repo:app.bsky.feed.post");
let tokens = app.sign_in(&h, &alice, &did).await;
let token = tokens["access_token"].as_str().unwrap();
let write = json!({"repo": did, "collection": "app.bsky.feed.post", "rkey": "one", "record": record("app.bsky.feed.post")});
assert_eq!(
app.call(&h, "com.atproto.repo.createRecord", token, Some(&write))
.await
.status,
200
);
let console = App::new("console");
let given = group_auth(
&h,
&console,
&bob,
&json!({"group": did, "space": calendar}),
)
.await;
assert_eq!(given.status, 200, "{}", given.body);
let lxm = format!("{NS}.listGroupTokens");
let list = async |who: &Authority, group: &str| {
get(&h, &lxm, &format!("group={group}"), &[auth(&h, who, &lxm)]).await
};
let (status, listed) = list(&alice, &did).await;
assert_eq!(status, 200, "{listed}");
let sessions = listed["sessions"].as_array().unwrap();
assert_eq!(sessions.len(), 2);
let oauth = sessions.iter().find(|s| s["source"] == "oauth").unwrap();
assert_eq!(oauth["clientId"], app.id.as_str());
assert_eq!(oauth["member"], alice.did.as_str());
assert_eq!(oauth["scope"], "atproto repo:app.bsky.feed.post");
assert!(oauth["lastUsedAt"].is_string() && oauth["grantedAt"].is_string());
let groups = sessions
.iter()
.find(|s| s["source"] == "getGroupAuth")
.unwrap();
assert_eq!(groups["member"], bob.did.as_str());
assert_eq!(groups.get("lastUsedAt"), None);
let actions: Vec<&str> = listed["activity"]
.as_array()
.unwrap()
.iter()
.map(|a| a["action"].as_str().unwrap())
.collect();
assert_eq!(
actions,
[
format!("took a token for {calendar}"),
"created app.bsky.feed.post/one".to_string(),
format!("signed in {}", app.id),
]
);
assert_eq!(listed["activity"][1]["clientId"], app.id.as_str());
// Only for its configurers.
assert_eq!(list(&bob, &did).await.0, 403);
assert_eq!(list(&alice, "did:plc:nothing").await.0, 400);
let lxm = format!("{NS}.revokeGroupToken");
let revoke =
async |who: &Authority, body: Json| post(&h, &lxm, &body, &[auth(&h, who, &lxm)]).await;
let id = oauth["tokenId"].as_str().unwrap();
assert_eq!(
revoke(&bob, json!({"group": did, "tokenId": id})).await.0,
403
);
assert_eq!(revoke(&alice, json!({"group": did})).await.0, 400);
assert_eq!(revoke(&alice, json!({"tokenId": id})).await.0, 400);
assert_eq!(
revoke(&alice, json!({"group": did, "tokenId": "tok-nothing"}))
.await
.1["error"],
"NotFound"
);
let (status, done) = revoke(&alice, json!({"group": did, "tokenId": id})).await;
assert_eq!(status, 200, "{done}");
assert_eq!(
app.call(&h, "com.atproto.repo.createRecord", token, Some(&write))
.await
.error(),
(401, "invalid_token")
);
let (_, listed) = list(&alice, &did).await;
assert_eq!(listed["sessions"].as_array().unwrap().len(), 1);
assert_eq!(
listed["activity"][0]["action"],
format!("revoked {}'s grant to {}", alice.did, app.id)
);
// Not another group's.
let other = start_group(
&h,
&alice,
json!({"handle": "hikers.groups.test", "displayName": "Hikers"}),
)
.await;
let theirs = groups["tokenId"].as_str().unwrap();
let said = revoke(&alice, json!({"group": other, "tokenId": theirs})).await;
assert_eq!(said.1["error"], "NotFound");
}
crates/group-host/tests/tokens.rs+79−0
docs/design/README.md+3−2
docs/design/signing-in.md+30−4