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

Apps make groups for people and leave with a session on them

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/provision
crates/group-host/src/config.rs+6−0
@@ -40,6 +40,10 @@ pub struct Config {
/// a member approves an app signing in as their group. The public URL
/// unless set, as when the console is served beside the host.
pub console_url: String,
/// The OAuth clients this host makes groups for with
/// `provisionGroup`, `PROVISIONING_CLIENTS`, comma-separated client
/// ids, `*` for any: none unless set.
pub provisioning_clients: Vec<String>,
}
impl Config {
@@ -96,6 +100,7 @@ impl Config {
.with_context(|| format!("BLOB_UPLOAD_LIMIT is no number of bytes: {l}"))?,
None => 50 * 1024 * 1024,
};
let provisioning_clients = list("PROVISIONING_CLIENTS");
let console_url = var("CONSOLE_URL").unwrap_or_else(|| public_url.clone());
let console_url = console_url.trim_end_matches('/').to_string();
if reqwest::Url::parse(&console_url).is_err() {
@@ -114,6 +119,7 @@ impl Config {
crawlers,
blob_upload_limit,
console_url,
provisioning_clients,
})
}
crates/group-host/src/group_api.rs+15−11
@@ -58,6 +58,20 @@ fn strings(body: &Value, key: &str, field: &str) -> Option<Vec<String>> {
body.get(key).map(|_| listed(body, key, field))
}
/// The group a `createGroup` body asks for, `founder`'s.
pub(crate) fn new_group(body: &Value, founder: String) -> Result<NewGroup, XrpcError> {
let text = |k: &str| body[k].as_str().map(String::from);
Ok(NewGroup {
handle: text("handle").ok_or_else(|| invalid("handle is required"))?,
founder,
stewards: strings(body, "stewards", "did").unwrap_or_default(),
display_name: text("displayName").ok_or_else(|| invalid("displayName is required"))?,
description: text("description"),
join_policy: text("joinPolicy"),
meta_readable_by: strings(body, "metaReadableBy", "role"),
})
}
/// Starts a group, the caller its founder and first admin.
pub async fn create_group(
State(host): State<Arc<Host>>,
@@ -65,17 +79,7 @@ pub async fn create_group(
Json(body): Json<Value>,
) -> Answer {
let founder = signed_in(&host, &headers, &format!("{NS}.createGroup")).await?;
let text = |k: &str| body[k].as_str().map(String::from);
let new = NewGroup {
handle: text("handle").ok_or_else(|| invalid("handle is required"))?,
founder,
stewards: strings(&body, "stewards", "did").unwrap_or_default(),
display_name: text("displayName").ok_or_else(|| invalid("displayName is required"))?,
description: text("description"),
join_policy: text("joinPolicy"),
meta_readable_by: strings(&body, "metaReadableBy", "role"),
};
let Made { did, meta, members } = host.create_group(&new).await?;
let Made { did, meta, members } = host.create_group(&new_group(&body, founder)?).await?;
Ok(Json(json!({"did": did, "meta": meta, "members": members})))
}
crates/group-host/src/lib.rs+5−0
@@ -32,6 +32,7 @@ pub mod oauth_resource;
pub mod oauth_scope;
pub mod oauth_store;
pub mod plc;
pub mod provision;
pub mod rbac;
pub mod repo;
pub mod scopes;
@@ -431,6 +432,10 @@ fn token_routes() -> Router<Arc<Host>> {
&x("com.atproto.server.deleteSession"),
post(app_passwords::delete_session),
)
.route(
&x("fyi.opensocial.provisionGroup"),
post(provision::provision_group),
)
.route(
&x("fyi.opensocial.getGroupAuth"),
post(group_tokens::get_group_auth),
crates/group-host/src/oauth.rs+47−22
@@ -420,12 +420,12 @@ async fn exchange(host: &Host, headers: &HeaderMap, form: OAuthForm) -> Result<V
let form = form_of(form)?;
let now = now_millis();
let (client, auth, jkt) = client_and_key(host, headers, &form, "/oauth/token", now).await?;
let (access, refresh) = (jose::random(32), jose::random(32));
let (access, refresh, access_expires, expires_at) = new_tokens(&auth, now);
let tokens = Tokens {
access_hash: &jose::sha256(&access),
access_expires: now + ACCESS_TTL,
access_expires,
refresh_hash: &jose::sha256(&refresh),
expires_at: lasts(&auth, now),
expires_at,
};
let grant = match form.get("grant_type").map(String::as_str) {
Some("authorization_code") => {
@@ -477,23 +477,7 @@ async fn exchange(host: &Host, headers: &HeaderMap, form: OAuthForm) -> Result<V
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,
client = grant.client_id,
"signed in"
);
host.issue_grant(&grant, &tokens)?;
grant
}
Some("refresh_token") => {
@@ -534,14 +518,55 @@ async fn exchange(host: &Host, headers: &HeaderMap, form: OAuthForm) -> Result<V
));
}
};
Ok(json!({
Ok(token_response(&access, &refresh, &grant))
}
/// A token response, as `/oauth/token` answers one.
pub(crate) fn token_response(access: &str, refresh: &str, grant: &Grant) -> Value {
json!({
"access_token": access,
"token_type": "DPoP",
"expires_in": ACCESS_TTL / 1000,
"refresh_token": refresh,
"scope": grant.scope,
"sub": grant.group,
}))
})
}
/// New tokens for a grant made `now` with client authentication `auth`:
/// the tokens, and their hashes and lapses to keep.
pub(crate) fn new_tokens(auth: &Value, now: i64) -> (String, String, i64, i64) {
(
jose::random(32),
jose::random(32),
now + ACCESS_TTL,
lasts(auth, now),
)
}
impl Host {
/// Keeps a new grant with its first tokens, and logs its sign-in.
pub(crate) fn issue_grant(&self, grant: &Grant, tokens: &Tokens) -> Result<(), OAuthError> {
self.store
.issue(grant, tokens)
.map_err(OAuthError::internal)?;
let signed_in = format!("signed in {}", grant.client_id);
let logged = self.record(
&grant.group,
&grant.member,
Some(&grant.client_id),
&signed_in,
);
logged.map_err(OAuthError::internal)?;
tracing::info!(
group = grant.group,
member = grant.member,
client = grant.client_id,
source = grant.source,
"signed in"
);
Ok(())
}
}
/// Ends the grant an access or refresh token is of, as RFC 7009 lets a
crates/group-host/src/provision.rsnew+134−0
@@ -0,0 +1,134 @@
//! An app makes a group for someone and leaves with its own session on it.
//!
//! Two parties sign in. The person asking does, as for any of the host's
//! methods, with service auth from their own PDS, and becomes the group's
//! founder. The app does, as at the token endpoint: its client id and, if
//! confidential, its assertion in the body, and a DPoP proof. It must be
//! one this host makes groups for (`PROVISIONING_CLIENTS`). Everything is
//! checked before the group is made. Its session is then issued as a code
//! exchange issues one, narrowed to the founder's roles as an approval is,
//! so from then on it is an ordinary grant: refreshed at `/oauth/token`,
//! listed among the group's, revoked there.
//!
//! As the prototype's `methods/provision.ts`.
use crate::Host;
use crate::api::invalid;
use crate::group::Made;
use crate::group_api::{new_group, signed_in};
use crate::oauth::{OAuthError, new_tokens, token_response};
use crate::oauth_resource::Refusal;
use crate::oauth_scope::concrete;
use crate::oauth_store::{Grant, Tokens};
use crate::rbac::NS;
use crate::time::now_millis;
use crate::xrpc::XrpcError;
use atproto::jose;
use axum::Json;
use axum::extract::State;
use axum::http::{HeaderMap, StatusCode};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;
/// What a grant made this way is, as the group's grants list it.
pub const SOURCE: &str = "provisionGroup";
/// An OAuth failure, as this method's own: its code and why.
fn refused(e: OAuthError) -> XrpcError {
XrpcError::new(e.status, e.error, e.description)
}
fn bad(error: &'static str, message: impl Into<String>) -> XrpcError {
XrpcError::new(StatusCode::BAD_REQUEST, error, message)
}
/// Makes a group for the caller, its founder, and a session on it for the
/// app that asked.
pub async fn provision_group(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Result<Json<Value>, Refusal> {
let nsid = format!("{NS}.provisionGroup");
let founder = signed_in(&host, &headers, &nsid).await?;
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 client_id = body["clientId"]
.as_str()
.ok_or_else(|| invalid("clientId is required"))?;
let client = host.client(client_id, now).await.map_err(refused)?;
let mut form = HashMap::new();
for (field, key) in [
("clientAssertionType", "client_assertion_type"),
("clientAssertion", "client_assertion"),
] {
if let Some(v) = body[field].as_str() {
form.insert(key.to_string(), v.to_string());
}
}
let auth = host
.authenticate_client(&client, &form, now)
.await
.map_err(refused)?;
let trusted = &host.config.provisioning_clients;
if !trusted.iter().any(|t| t == "*" || *t == client.id) {
let said = format!("{} is not an app this host makes groups for", client.id);
return Err(bad("UntrustedApp", said).into());
}
// What the app could be granted anywhere: what its metadata declares.
let declared = client.metadata["scope"].as_str().unwrap_or_default();
let asked = body["scope"].as_str().unwrap_or_default();
let requested: Vec<String> = asked
.split(' ')
.filter(|s| !s.is_empty())
.map(String::from)
.collect();
let undeclared: Vec<&str> = requested
.iter()
.filter(|s| !declared.split(' ').any(|d| d == s.as_str()))
.map(String::as_str)
.collect();
if !requested.iter().any(|s| s == "atproto") || !undeclared.is_empty() {
let said = match undeclared.is_empty() {
true => "the scope must include atproto".to_string(),
false => format!("not in the app's client metadata: {}", undeclared.join(" ")),
};
return Err(bad("InvalidScope", said).into());
}
let new = new_group(&body, founder.clone())?;
let Made { did, meta, members } = host.create_group(&new).await?;
let roles = host.roles(&did, &founder).map_err(XrpcError::internal)?;
let granted = host.narrow(&did, &roles, &founder, &requested)?;
let (access, refresh, access_expires, expires_at) = new_tokens(&auth, now);
let tokens = Tokens {
access_hash: &jose::sha256(&access),
access_expires,
refresh_hash: &jose::sha256(&refresh),
expires_at,
};
let grant = Grant {
id: format!("tok-{}", jose::random(16)),
group: did.clone(),
member: founder,
client_id: client.id,
client_auth: auth,
scope: concrete(&granted, &did),
dpop_jkt: proof.jkt,
access_expires,
expires_at,
created_at: now,
source: SOURCE.into(),
used_at: None,
};
host.issue_grant(&grant, &tokens).map_err(refused)?;
Ok(Json(json!({
"did": did,
"meta": meta,
"members": members,
"session": token_response(&access, &refresh, &grant),
})))
}
crates/group-host/tests/config.rs+10−1
@@ -26,6 +26,7 @@ fn defaults_serve_localhost() {
["well-known:https", "https://public.api.bsky.app"]
);
assert_eq!(c.console_url, "http://localhost:2600");
assert!(c.provisioning_clients.is_empty());
}
#[test]
@@ -53,8 +54,16 @@ fn the_environment_names_the_host() {
assert_eq!(c.group_founders, ["did:plc:a", "did:plc:b"]);
assert_eq!(c.service_did, "did:web:other.example");
assert_eq!(c.did_web_scheme, "http");
let c = config(&[("CONSOLE_URL", "https://console.example.com/")]).unwrap();
let c = config(&[
("CONSOLE_URL", "https://console.example.com/"),
("PROVISIONING_CLIENTS", "https://app.example/client.json, *"),
])
.unwrap();
assert_eq!(c.console_url, "https://console.example.com");
assert_eq!(
c.provisioning_clients,
["https://app.example/client.json", "*"]
);
}
#[test]
crates/group-host/tests/provision.rsnew+187−0
@@ -0,0 +1,187 @@
//! An app makes a group for someone and leaves with its own session on it.
mod common;
use common::groups::*;
use common::oauth::*;
use common::spaces::*;
use common::{Running, start};
use serde_json::{Value as Json, json};
const PROVISION: &str = "fyi.opensocial.provisionGroup";
const SCOPE: &str = "atproto repo:app.bsky.feed.post";
/// Asks `app` to provision as `who` with `body`, once more with the nonce
/// if asked.
async fn provision(h: &Running, app: &App, who: Option<&Authority>, body: &Json) -> Said {
let send = || {
let mut req = h
.http
.post(format!("{}/xrpc/{PROVISION}", h.url))
.json(body)
.header(
"dpop",
app.proof_with(h, "POST", &format!("/xrpc/{PROVISION}"), |_| {}),
);
if let Some(who) = who {
let (k, v) = auth(h, who, PROVISION);
req = req.header(k, v);
}
req
};
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 asking(app: &App, extra: Json) -> Json {
let mut body =
json!({"handle": RIDERS, "displayName": "Riders", "scope": SCOPE, "clientId": app.id});
body.as_object_mut()
.unwrap()
.extend(extra.as_object().unwrap().clone());
body
}
#[tokio::test]
async fn makes_a_group_and_a_session_on_it_for_the_app() {
let h = start(&[("PROVISIONING_CLIENTS", "*")], false).await;
let [alice, ..] = people(&h).await;
let app = App::loopback(SCOPE);
let said = provision(
&h,
&app,
Some(&alice),
&asking(&app, json!({"joinPolicy": "invite"})),
)
.await;
assert_eq!(said.status, 200, "{}", said.body);
let did = said.body["did"].as_str().unwrap().to_string();
assert!(
said.body["meta"]
.as_str()
.unwrap()
.ends_with("/space/fyi.opensocial.meta/self")
);
assert!(
said.body["members"]
.as_str()
.unwrap()
.ends_with("/space/fyi.opensocial.members/self")
);
let session = &said.body["session"];
assert_eq!(session["token_type"], "DPoP");
assert_eq!(session["sub"], did.as_str());
assert_eq!(session["scope"], SCOPE);
// Alice founded it.
let roles = h.host.roles(&did, &alice.did).unwrap();
assert!(roles.contains(&"admin".to_string()), "{roles:?}");
// The session writes as the group, refreshes, and is listed as Alice's.
let token = session["access_token"].as_str().unwrap();
let body = json!({"repo": did, "collection": "app.bsky.feed.post", "record": {"$type": "app.bsky.feed.post", "text": "hi", "createdAt": "2026-11-03T00:00:00Z"}});
let made = app
.call(&h, "com.atproto.repo.createRecord", token, Some(&body))
.await;
assert_eq!(made.status, 200, "{}", made.body);
let refreshed = app
.refresh(&h, session["refresh_token"].as_str().unwrap())
.await;
assert_eq!(refreshed.status, 200, "{}", refreshed.body);
let lxm = format!("{NS}.listGroupTokens");
let (_, grants) = get(&h, &lxm, &format!("group={did}"), &[auth(&h, &alice, &lxm)]).await;
let sessions = grants["sessions"].as_array().unwrap();
assert_eq!(sessions.len(), 1);
assert_eq!(sessions[0]["source"], "provisionGroup");
assert_eq!(sessions[0]["member"], alice.did.as_str());
assert_eq!(sessions[0]["clientId"], app.id.as_str());
}
#[tokio::test]
async fn refuses_before_it_makes_anything() {
let h = start(
&[("PROVISIONING_CLIENTS", "https://trusted.test/client.json")],
false,
)
.await;
let [alice, ..] = people(&h).await;
let app = App::loopback(SCOPE);
let ask = async |body: Json| provision(&h, &app, Some(&alice), &body).await;
let refused = [
(ask(asking(&app, json!({}))).await, (400, "UntrustedApp")),
(
ask(asking(&app, json!({"clientId": "nonsense"}))).await,
(400, "invalid_client_metadata"),
),
(
ask(asking(
&app,
json!({"clientAssertion": "x", "clientAssertionType": "y"}),
))
.await,
(400, "invalid_client"),
),
(
ask(json!({"handle": RIDERS, "displayName": "Riders", "scope": SCOPE})).await,
(400, "InvalidRequest"),
),
];
for (said, error) in refused {
assert_eq!(said.error(), error, "{}", said.body);
}
// Without service auth, or a proof.
let said = provision(&h, &app, None, &asking(&app, json!({}))).await;
assert_eq!(said.error(), (401, "AuthMissing"));
let (k, v) = auth(&h, &alice, PROVISION);
let bare = h
.http
.post(format!("{}/xrpc/{PROVISION}", h.url))
.json(&asking(&app, json!({})))
.header(k, v);
assert_eq!(app.said(bare).await.error(), (401, "invalid_dpop_proof"));
// Nothing was made.
assert!(h.host.store.account(RIDERS).unwrap().is_none());
}
#[tokio::test]
async fn gives_the_app_what_it_declares_and_the_founder_may() {
let h = start(&[("PROVISIONING_CLIENTS", "*")], false).await;
let [alice, bob, _] = people(&h).await;
let app = App::loopback(&format!("{SCOPE} rpc:fyi.opensocial.ejectMember?aud=*"));
for (scope, refused) in [
("repo:app.bsky.feed.post", "the scope must include atproto"),
(
"atproto repo:app.bsky.feed.like",
"not in the app's client metadata: repo:app.bsky.feed.like",
),
] {
let said = provision(
&h,
&app,
Some(&alice),
&asking(&app, json!({"scope": scope})),
)
.await;
assert_eq!(said.error(), (400, "InvalidScope"));
assert_eq!(said.body["message"], refused);
}
// A method of this host's is the founder's own to call, never the app's.
let scope = format!("{SCOPE} rpc:fyi.opensocial.ejectMember?aud=*");
let said = provision(
&h,
&app,
Some(&alice),
&asking(&app, json!({"scope": scope})),
)
.await;
assert_eq!(said.body["session"]["scope"], SCOPE);
// A handle taken is refused as createGroup refuses it.
let said = provision(&h, &app, Some(&bob), &asking(&app, json!({}))).await;
assert_eq!(said.status, 400, "{}", said.body);
}
docs/design/README.md+2−2
@@ -101,8 +101,8 @@ says otherwise.
within their scope and the member's roles (`oauth_resource.rs`,
`scopes.rs`, `token_writes.rs`; done); group tokens, and the grants
that act as a group with their log (`group_tokens.rs`; done); app
passwords and their sessions (`app_passwords.rs`; done); then
provisioning: `auth.ts`, `pds/auth.ts`, `pds/oauth/*`,
passwords and their sessions (`app_passwords.rs`; done); and
provisioning (`provision.rs`; done): `auth.ts`, `pds/auth.ts`, `pds/oauth/*`,
`methods/{authorization,groupAuth,appPasswords,connectedApps,provision}.ts`.
The console signs its people in at their own PDS here, as a
confidential client, and keeps the session on the server, as knotless
docs/design/signing-in.md+15−1
@@ -175,10 +175,24 @@ sign-in and refresh, the host asks, and once they could not (they lost
the role, or left), every app password of theirs is forgotten and every
session from one signed out.
## Provisioning
An app makes a group for someone and leaves with its own session on it
(`provision.rs`, `provisionGroup`). Two parties sign in: the person, with
service auth from their own PDS, who becomes the founder; and the app, as
at the token endpoint, its client id (and its assertion, if confidential)
in the body and a DPoP proof in the header. It must be one the host makes
groups for (`PROVISIONING_CLIENTS`), and its scope must hold `atproto`
and nothing its metadata does not declare. All of that is checked before
the group is made. The session is issued as a code exchange issues one,
narrowed to the founder's roles as an approval is, and recorded as the
founder's: from then on an ordinary grant, refreshed at `/oauth/token`,
listed among the group's, revoked there.
## Who acts as the group
Every grant names the member who gave it, its app, how it was given
(`oauth`, `getGroupAuth` or `appPassword`), its scope, and when it was last used, to the
(`oauth`, `getGroupAuth`, `appPassword` or `provisionGroup`), its scope, and when it was last used, to the
minute. `listGroupTokens` shows a group's configurers every grant that
still lasts, and its log: each sign-in, each token taken, each record a
grant wrote, and each grant ended, the latest twenty. `revokeGroupToken`
docs/reference/config.md+1−0
@@ -16,6 +16,7 @@ and refuses to start on a value that does not read, saying which.
| `GROUP_FOUNDERS` | who the host starts groups for, comma-separated DIDs | anyone |
| `BLOB_UPLOAD_LIMIT` | the most bytes one blob may be | 52428800 (50 MiB) |
| `CONSOLE_URL` | where the console is: the host sends the browser of an app signing in as a group to its `/authorize`, for a member to approve | `PUBLIC_URL` |
| `PROVISIONING_CLIENTS` | the apps the host makes groups for with `provisionGroup`, comma-separated OAuth client ids; `*` for any | none |
| `PDS_CRAWLERS` | relays told of news with `requestCrawl`, comma-separated: at most every 20 minutes, and the first time after a start | none |
| `RUST_LOG` | what it logs, as `tracing-subscriber`'s filter reads it; lines are JSON | `info` |