chadtmiller.com/group-host
atmosphere group host
0
0
Inboxes are memberspaces their owners' apps make, without checkAccess
crates/group-host/src/group_invites.rs+9−49
| @@ -1,11 +1,13 @@ | ||
//! Invites. A group invites someone by writing an invite in its own repo | ||
//! in the invitee's inbox: a space under the invitee's own DID, at their | ||
//! PDS, which lets this host say who may write there | ||
//! (`com.atproto.managedspace.checkAccess`). An app writes it as the | ||
//! group, through `com.atproto.space.*` with a session for the group, and | ||
//! takes it back by deleting it. The invitee's apps read it there; the | ||
//! host keeps its own list of what it sent, which is what redeems an | ||
//! invite, as the inbox is its owner's to read, not the group's. | ||
//! PDS, which their app makes as a memberspace that tracks anyone's | ||
//! writes and names no members, so any group may write there and only its | ||
//! owner reads it. An app writes it as the group, through | ||
//! `com.atproto.space.*` with a session for the group, and takes it back | ||
//! by deleting it; each write is told to the invitee's PDS. The invitee's | ||
//! apps read it there; the host keeps its own list of what it sent, which | ||
//! is what redeems an invite, as the inbox is its owner's to read, not the | ||
//! group's. | ||
//! | ||
//! An invite is redeemed by asking to join: admitted at once, whatever | ||
//! the group's join policy, with its default roles. | ||
| @@ -13,7 +15,7 @@ | ||
use crate::Host; | ||
use crate::api::{Params, invalid, page, param}; | ||
use crate::group::meta_space; | ||
use crate::group_api::{caller, group_of, signed_in}; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::group_members::{Members, acting}; | ||
use crate::lexicons::check_record; | ||
use crate::mcp::McpGrant; | ||
| @@ -35,9 +37,6 @@ use std::sync::Arc; | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
| ||
/// The method a space's authority asks this host what a repo may do. | ||
pub const CHECK_ACCESS: &str = "com.atproto.managedspace.checkAccess"; | ||
| ||
fn bad(error: &'static str, message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_REQUEST, error, message) | ||
} | ||
| @@ -472,42 +471,3 @@ pub async fn decline_invite( | ||
host.take_back(&invite).await?; | ||
Ok(Json(json!({}))) | ||
} | ||
| ||
/// Whether an account may read or write a space this host manages for | ||
/// its authority: someone's inbox, which its owner reads and groups here | ||
/// write their invites in. Asked by the space's authority, with service | ||
/// auth for this host (`<host DID>#opensocial`, the managing app an inbox | ||
/// names). | ||
pub async fn check_access( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Answer { | ||
let asker = caller(&host, &headers, CHECK_ACCESS).await?; | ||
let asker = asker | ||
.ok_or_else(|| crate::space_api::unauthorized("AuthMissing", "service auth is required"))?; | ||
let space = SpaceRef::parse(param(&p, "space")?).map_err(|e| invalid(e.to_string()))?; | ||
if asker != space.authority { | ||
return Err(XrpcError::new( | ||
StatusCode::FORBIDDEN, | ||
"Forbidden", | ||
"only the space's authority asks", | ||
)); | ||
} | ||
let inbox = space.kind == format!("{NS}.invites"); | ||
// Its owner reads it; a group here writes in it. Without a repo, no | ||
// one is asking as anyone, and may do neither. | ||
let (read, write) = match p.get("repo").filter(|_| inbox) { | ||
Some(repo) => { | ||
let group = host | ||
.store | ||
.account(repo) | ||
.map_err(XrpcError::internal)? | ||
.is_some_and(|a| &a.did == repo) | ||
&& group_of(&host, repo).is_ok(); | ||
(repo == &space.authority, group) | ||
} | ||
None => (false, false), | ||
}; | ||
Ok(Json(json!({ "read": read, "write": write }))) | ||
} | ||
crates/group-host/src/lexicons.rs+0−2
| @@ -123,8 +123,6 @@ pub const FILES: &[&str] = &[ | ||
lexicon!("upstream/com/atproto/identity/resolveHandle"), | ||
lexicon!("upstream/com/atproto/label/defs"), | ||
lexicon!("upstream/com/atproto/label/record"), | ||
lexicon!("upstream/com/atproto/managedspace/checkAccess"), | ||
lexicon!("upstream/com/atproto/managedspace/policy"), | ||
lexicon!("upstream/com/atproto/moderation/defs"), | ||
lexicon!("upstream/com/atproto/repo/strongRef"), | ||
lexicon!("upstream/com/atproto/server/defs"), | ||
crates/group-host/src/lib.rs+0−4
| @@ -305,10 +305,6 @@ pub(crate) fn routes(host: Arc<Host>) -> Router { | ||
"/xrpc/fyi.opensocial.declineInvite", | ||
post(group_invites::decline_invite), | ||
) | ||
.route( | ||
"/xrpc/com.atproto.managedspace.checkAccess", | ||
get(group_invites::check_access), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.getAuthorization", | ||
get(authorization::get_authorization), | ||
crates/group-host/tests/interop.rs+6−4
| @@ -427,7 +427,9 @@ async fn an_invite_into_an_inbox_on_the_reference_pds() { | ||
let service = h.host.config.service_did.clone(); | ||
assert!(service.starts_with("did:web:localhost"), "{service}"); | ||
| ||
// Alice's inbox, at her PDS, a space this host manages for her. | ||
// Alice's inbox, at her PDS, as her app makes it: a memberspace that | ||
// tracks anyone's writes and names no members, so groups write in it | ||
// and only she reads it. | ||
let alice = &net.accounts[0]; | ||
let session = call( | ||
&net.pds, | ||
| @@ -444,14 +446,14 @@ async fn an_invite_into_an_inbox_on_the_reference_pds() { | ||
&json!({ | ||
"spaceType": "fyi.opensocial.invites", | ||
"skey": "self", | ||
"policy": {"$type": "com.atproto.managedspace.policy", "managingApp": format!("{service}#opensocial")}, | ||
"policy": {"$type": "com.atproto.memberspace.policy", "publicWrite": true}, | ||
}), | ||
) | ||
.await; | ||
let inbox = created["space"].as_str().unwrap().to_string(); | ||
| ||
// A group here invites her: its write is told to her PDS, which asks | ||
// this host whether the group may write there. | ||
// A group here invites her: its write is told to her PDS, which takes | ||
// it, as the inbox takes anyone's. | ||
let founder = common::spaces::authority(&h, false, true).await; | ||
let group = common::groups::start_group( | ||
&h, | ||
crates/group-host/tests/invites.rs+1−79
| @@ -1,7 +1,6 @@ | ||
//! Invites: written as the group in the invitee's inbox, through | ||
//! `com.atproto.space.*` with a group token, listed, taken back by | ||
//! deleting them, turned down, and redeemed by asking to join; and who | ||
//! may read and write an inbox, as its authority asks. | ||
//! deleting them, turned down, and redeemed by asking to join. | ||
| ||
mod common; | ||
| ||
| @@ -446,83 +445,6 @@ async fn invites_are_taken_back_turned_down_or_lapse() { | ||
assert!(h.host.store.invited(&did, erin).unwrap().is_some()); | ||
} | ||
| ||
const CHECK: &str = "com.atproto.managedspace.checkAccess"; | ||
| ||
async fn check(h: &Running, asker: &Authority, space: &str, repo: Option<&str>) -> (u16, Json) { | ||
let repo = repo.map(|r| format!("&repo={r}")).unwrap_or_default(); | ||
get( | ||
h, | ||
CHECK, | ||
&format!("space={space}{repo}&clientId=https://app.test/client.json"), | ||
&[auth(h, asker, CHECK)], | ||
) | ||
.await | ||
} | ||
| ||
#[tokio::test] | ||
async fn an_inbox_is_its_owners_to_read_and_groups_here_to_write() { | ||
let h = start(&[], false).await; | ||
let [alice, bob, carol] = people(&h).await; | ||
let did = start_group( | ||
&h, | ||
&alice, | ||
json!({"handle": RIDERS, "displayName": "Riders"}), | ||
) | ||
.await; | ||
let inbox = inbox_of(&bob.did); | ||
let access = |read: bool, write: bool| (200, json!({"read": read, "write": write})); | ||
assert_eq!( | ||
check(&h, &bob, &inbox, Some(&did)).await, | ||
access(false, true) | ||
); | ||
assert_eq!( | ||
check(&h, &bob, &inbox, Some(&carol.did)).await, | ||
access(false, false) | ||
); | ||
let plain = h.host.create_account("plain.groups.test").await.unwrap(); | ||
assert_eq!( | ||
check(&h, &bob, &inbox, Some(&plain)).await, | ||
access(false, false) | ||
); | ||
assert_eq!( | ||
check(&h, &bob, &inbox, Some(&bob.did)).await, | ||
access(true, false) | ||
); | ||
// Asked for no repo, it answers what anyone may do: nothing. | ||
assert_eq!(check(&h, &bob, &inbox, None).await, access(false, false)); | ||
// A space that is no inbox, this host manages nothing in. | ||
let other = format!("at://{}/space/xyz.app.board/self", bob.did); | ||
assert_eq!( | ||
check(&h, &bob, &other, Some(&did)).await, | ||
access(false, false) | ||
); | ||
assert_eq!( | ||
check(&h, &bob, &other, Some(&bob.did)).await, | ||
access(false, false) | ||
); | ||
// Only its authority asks. | ||
assert_eq!( | ||
error(&check(&h, &carol, &inbox, Some(&did)).await), | ||
(403, "Forbidden") | ||
); | ||
assert_eq!( | ||
error(&check(&h, &bob, "nope", Some(&did)).await), | ||
(400, "InvalidRequest") | ||
); | ||
// Its authority asks with a token for this method alone. | ||
let wrong = "com.atproto.managedspace.checkUserAccess"; | ||
let (status, _) = get( | ||
&h, | ||
CHECK, | ||
&format!("space={inbox}&repo={did}"), | ||
&[auth(&h, &bob, wrong)], | ||
) | ||
.await; | ||
assert!(status == 401 || status == 403, "{status}"); | ||
let (status, _) = get(&h, CHECK, &format!("space={inbox}&repo={did}"), &[]).await; | ||
assert_eq!(status, 401); | ||
} | ||
| ||
#[test] | ||
fn reads_a_datetime() { | ||
assert_eq!(millis_of("1970-01-01T00:00:00Z"), Some(0)); | ||
docs/design/membership.md+10−9
| @@ -189,12 +189,11 @@ where they already look. That's their inbox, | ||
`at://<invitee>/space/fyi.opensocial.invites/self`, a space of their own | ||
at their PDS. The invite is an `fyi.opensocial.invite` record in the | ||
group's repo there, with a `createdAt` and an optional `message` and | ||
`expiresAt`. An inbox's policy is `com.atproto.managedspace.policy`, | ||
which names this host as its managing app (`<host DID>#opensocial`). So | ||
the host answers `com.atproto.managedspace.checkAccess` for it, when the | ||
inbox's authority asks with service auth. A group on this host may write | ||
one and its owner may read it. With no account named, nobody may do | ||
either. | ||
`expiresAt`. The invitee's own app makes the inbox, with atproto's | ||
baseline `com.atproto.memberspace.policy`, `publicWrite` set and no | ||
members. So any group may write an invite there and only the invitee | ||
reads the space. The invitee's PDS keeps each group that writes there | ||
among the inbox's writers. | ||
| ||
An app invites someone by writing that record as the group, through | ||
`com.atproto.space.createRecord` (or `putRecord`, or `applyWrites` with | ||
| @@ -214,9 +213,11 @@ each write the same way it would check its own: | ||
- The host refuses to delete an invite that isn't waiting | ||
(`InviteNotFound`). | ||
| ||
The group tells the invitee's PDS about the write at once. If that | ||
fails, it retries with the wait doubling from 10 seconds up to an hour, | ||
and gives up after a day. | ||
The group tells the invitee's PDS about the write at once, with | ||
`com.atproto.space.notifyRepoUpdate`. If that fails, it retries with the | ||
wait doubling from 10 seconds up to an hour, and gives up after a day. A | ||
PDS that refuses it outright isn't asked again, and the invite still | ||
waits on the host's list. | ||
| ||
The inbox is the invitee's to read. So the host keeps its own list of | ||
invites sent, one per group and invitee, kept in step with each write, | ||
docs/design/spaces.md+5−4
| @@ -58,10 +58,11 @@ repo, the space, the revision and that digest. | ||
| ||
The group also writes in spaces it isn't the authority for. An invite | ||
goes in the group's repo in the invitee's inbox, | ||
`at://<invitee>/space/fyi.opensocial.invites/self`. The inbox's authority | ||
asks this host who may use it, with | ||
`com.atproto.managedspace.checkAccess`. Its owner may read, and a group | ||
here may write ([membership](membership.md)). | ||
`at://<invitee>/space/fyi.opensocial.invites/self`. The invitee's app | ||
makes it a `com.atproto.memberspace.policy` space with `publicWrite` set | ||
and no members, so any group may write there and only its owner reads | ||
it. The host tells the invitee's PDS of each write | ||
([membership](membership.md#invites)). | ||
| ||
Details: | ||
| ||
docs/reference/api.md+0−1
| @@ -80,7 +80,6 @@ spaces through the atproto methods below. | ||
| `GET fyi.opensocial.listInvites` | lists the group's invites that are still waiting, each with the invitee's handle | | ||
| `GET fyi.opensocial.getActorInvites` | lists the caller's own invites from groups here | | ||
| `POST fyi.opensocial.declineInvite` | turns an invite down | | ||
| `GET com.atproto.managedspace.checkAccess` | tells an inbox's authority whether an account (`repo`) may read or write an inbox the host keeps, as `{read, write}` | | ||
| ||
A group's roles, what each may do, and who holds them are records in its | ||
members space: `fyi.opensocial.role`, the `fyi.opensocial.permissions` | ||
harness/e2e/flows.spec.mjs+18−0
| @@ -12,7 +12,9 @@ import { | ||
approve, | ||
didKey, | ||
hydrating, | ||
inboxWriters, | ||
joins, | ||
makeInbox, | ||
signIn, | ||
signInDialog, | ||
signedInAs, | ||
| @@ -228,6 +230,9 @@ async function send() { | ||
} | ||
| ||
test('inviting someone from the dialog', async () => { | ||
// Bob's app has made his inbox, where groups write their invites to | ||
// him. A PDS that does not speak the space alpha keeps no space. | ||
const inbox = world.spaces ? await makeInbox(who.bob) : undefined; | ||
await page.goto(url('/g/hikers.groups.test')); | ||
const dialog = page.getByRole('dialog', { name: 'Invite someone' }); | ||
const invite = page.getByRole('button', { name: 'Invite someone' }); | ||
| @@ -252,6 +257,13 @@ test('inviting someone from the dialog', async () => { | ||
await page.getByRole('button', { name: 'Cancel invite' }).click(); | ||
await expect(page.locator('.invites', { hasText: 'bob.test' })).toHaveCount(0); | ||
await send(); | ||
// His PDS took Hikers' invite: the group writes in his inbox. | ||
if (inbox) { | ||
const resolved = await fetch( | ||
`${world.host}/xrpc/com.atproto.identity.resolveHandle?handle=hikers.groups.test` | ||
).then((r) => r.json()); | ||
await expect.poll(() => inboxWriters(who.bob, inbox)).toContain(resolved.did); | ||
} | ||
}); | ||
| ||
test("turning down an invitation from the group's page", async () => { | ||
| @@ -628,8 +640,14 @@ test("a site's page reaches the console without the session of whoever opens it" | ||
await page.getByRole('button', { name: 'Publish a site' }).click(); | ||
const publishing = page.getByRole('dialog', { name: 'Publish a site' }); | ||
await publishing.getByLabel('Folder').setInputFiles(dir); | ||
// Published, the page loads its data again (who is looking, then their | ||
// invites), which must be done before its requests are counted. | ||
const reloaded = page.waitForResponse((r) => | ||
r.url().endsWith('/xrpc/fyi.opensocial.getActorInvites') | ||
); | ||
await publishing.getByRole('button', { name: 'Publish' }).click(); | ||
await expect(publishing).toBeHidden(); | ||
await reloaded; | ||
| ||
// Each request the browser sends the console, with its cookies, until | ||
// the one signing out. | ||
harness/e2e/pages.mjs+84−4
| @@ -226,9 +226,9 @@ export class App { | ||
} | ||
} | ||
| ||
/// A new P-256 key, as a did:key: what a steward holds as a recovery key. | ||
export const didKey = () => { | ||
const { publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' }); | ||
/// A new P-256 key: its private half, and its public half as a did:key. | ||
const p256 = () => { | ||
const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' }); | ||
const point = publicKey.export({ format: 'der', type: 'spki' }).subarray(-65); | ||
const compressed = Buffer.concat([Buffer.from([point[64] & 1 ? 3 : 2]), point.subarray(1, 33)]); | ||
const bytes = Buffer.concat([Buffer.from([0x80, 0x24]), compressed]); | ||
| @@ -239,7 +239,87 @@ export const didKey = () => { | ||
out = alphabet[Number(n % 58n)] + out; | ||
n /= 58n; | ||
} | ||
return `did:key:z${out}`; | ||
return { privateKey, did: `did:key:z${out}` }; | ||
}; | ||
| ||
/// A new P-256 key, as a did:key: what a steward holds as a recovery key. | ||
export const didKey = () => p256().did; | ||
| ||
/// `account`'s session at their own PDS, signed in with their password. | ||
const pdsSession = async (account) => { | ||
const res = await fetch(`${world.pds}/xrpc/com.atproto.server.createSession`, { | ||
method: 'POST', | ||
headers: { 'content-type': 'application/json' }, | ||
body: JSON.stringify({ identifier: account.handle, password: account.password }) | ||
}); | ||
if (!res.ok) throw new Error(`createSession: ${await res.text()}`); | ||
return (await res.json()).accessJwt; | ||
}; | ||
| ||
/// Makes `account`'s inbox at their PDS as their app does: a memberspace | ||
/// that keeps anyone's writes and names no members, so any group may | ||
/// write an invite there and only they read it. Its URI. | ||
export const makeInbox = async (account) => { | ||
const res = await fetch(`${world.pds}/xrpc/com.atproto.space.createSpace`, { | ||
method: 'POST', | ||
headers: { | ||
'content-type': 'application/json', | ||
authorization: `Bearer ${await pdsSession(account)}` | ||
}, | ||
body: JSON.stringify({ | ||
spaceType: 'fyi.opensocial.invites', | ||
skey: 'self', | ||
policy: { $type: 'com.atproto.memberspace.policy', publicWrite: true } | ||
}) | ||
}); | ||
if (!res.ok) throw new Error(`createSpace: ${await res.text()}`); | ||
return (await res.json()).space; | ||
}; | ||
| ||
/// The order of P-256, whose upper half a signature's `s` is kept out of. | ||
const ORDER = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n; | ||
| ||
/// The repos in the writer set of `account`'s `inbox`, as their PDS keeps | ||
/// it, read as their app syncs it: a credential for a key of its own, | ||
/// from their delegation token, and the request signed with that key. | ||
export const inboxWriters = async (account, inbox) => { | ||
const space = encodeURIComponent(inbox); | ||
const delegated = await fetch( | ||
`${world.pds}/xrpc/com.atproto.space.getDelegationToken?space=${space}`, | ||
{ headers: { authorization: `Bearer ${await pdsSession(account)}` } } | ||
); | ||
if (!delegated.ok) throw new Error(`getDelegationToken: ${await delegated.text()}`); | ||
const key = p256(); | ||
const issued = await fetch(`${world.pds}/xrpc/com.atproto.space.authorizeSpaceSync`, { | ||
method: 'POST', | ||
headers: { 'content-type': 'application/json' }, | ||
body: JSON.stringify({ | ||
space: inbox, | ||
credentialKey: key.did, | ||
delegationToken: (await delegated.json()).token | ||
}) | ||
}); | ||
if (!issued.ok) throw new Error(`authorizeSpaceSync: ${await issued.text()}`); | ||
const authorization = `Atproto-Space-Credential ${(await issued.json()).credential}`; | ||
const input = '("authorization" "atproto-space-audience");tag="atproto-space-credential"'; | ||
const base = `"authorization": ${authorization}\n"atproto-space-audience": ${account.did}\n"@signature-params": ${input}`; | ||
const signature = sign('sha256', Buffer.from(base), { | ||
key: key.privateKey, | ||
dsaEncoding: 'ieee-p1363' | ||
}); | ||
const s = BigInt(`0x${signature.subarray(32).toString('hex')}`); | ||
if (s > ORDER / 2n) | ||
signature.set(Buffer.from((ORDER - s).toString(16).padStart(64, '0'), 'hex'), 32); | ||
const res = await fetch(`${world.pds}/xrpc/com.atproto.space.listWriters?space=${space}`, { | ||
headers: { | ||
authorization, | ||
'atproto-space-audience': account.did, | ||
'signature-input': `sig=${input}`, | ||
signature: `sig=:${signature.toString('base64')}:` | ||
} | ||
}); | ||
if (!res.ok) throw new Error(`listWriters: ${await res.text()}`); | ||
return (await res.json()).repos.map((r) => r.repo); | ||
}; | ||
| ||
/// An MCP client on this machine, as an AI app signs in: it finds the | ||