chadtmiller.com/group-host
atmosphere group host
0
0
Apps signed in as a group call other services through the host
.changeset/service-proxy.mdnew+9−0
| @@ -0,0 +1,9 @@ | ||
--- | ||
default: minor | ||
--- | ||
| ||
# An app signed in as a group calls other services through the host | ||
| ||
An app signed in as a group (with OAuth or an app password) calls other services as the group the way it would through any account's PDS: a call with `atproto-proxy: <did>#<service>` to a method the host doesn't serve is sent on to that service with service auth the group signs (`aud` the service's DID, `lxm` the method, a minute), and its answer streamed back. `com.atproto.server.getServiceAuth` gives an app such a token to send itself. A token's scope must hold the call (`rpc:<method>?aud=<did>#<service>`, a permission set that gives it, or `transition:generic`), or it fails `ScopeMissingError`, and its member must still hold `repo:*`. An app password's session calls anything but chat unless it may use chat. The host refuses methods that manage an account directly, itself as the service, and services not at a public address. | ||
| ||
Signing an app in now keeps `transition:generic` and `transition:chat.bsky` for members holding `repo:*`, and other apps' permission sets (`include:social.grain.authFull?aud=…`) as far as the member's roles grant their parts. A set is read as its app publishes it: its `_lexicon` TXT record, read from `DNS_OVER_HTTPS` (Cloudflare's unless set), names the repo holding it. | ||
crates/group-host/src/authorization.rs+23−11
| @@ -11,6 +11,7 @@ use crate::group_api::{group_of, signed_in}; | ||
use crate::mcp; | ||
use crate::oauth_scope::{concrete, set_of}; | ||
use crate::oauth_store::Request; | ||
use crate::permission_sets::Sets; | ||
use crate::rbac::{INTERNAL, NS}; | ||
use crate::time::now_millis; | ||
use crate::xrpc::XrpcError; | ||
| @@ -82,13 +83,20 @@ impl Host { | ||
} | ||
| ||
/// A group as the approval page shows it to `member`: what of its | ||
/// about record they may read, their roles, and what the app would get. | ||
pub(crate) fn offered(&self, group: &str, member: &str, requested: &[String]) -> Answer { | ||
/// about record they may read, their roles, and what the app would | ||
/// get, other apps' permission sets read as `sets` holds them. | ||
pub(crate) fn offered( | ||
&self, | ||
group: &str, | ||
member: &str, | ||
requested: &[String], | ||
sets: &Sets, | ||
) -> Answer { | ||
let handle = group_of(self, group)?; | ||
let roles = self.roles(group, member).map_err(XrpcError::internal)?; | ||
let granted = match roles.is_empty() { | ||
true => Vec::new(), | ||
false => self.narrow(group, &roles, requested)?, | ||
false => self.narrow(group, &roles, requested, sets)?, | ||
}; | ||
let withheld: Vec<String> = requested | ||
.iter() | ||
| @@ -127,12 +135,13 @@ impl Host { | ||
} | ||
} | ||
| ||
/// What each of this host's permission sets among `scopes` is called, | ||
/// and says it is for, once each. | ||
fn labels(scopes: &[&str]) -> Value { | ||
/// What each permission set among `scopes`, this host's or another app's | ||
/// in `sets`, is called, and says it is for, once each. | ||
fn labels(scopes: &[&str], sets: &Sets) -> Value { | ||
let mut out: Vec<Value> = Vec::new(); | ||
for (i, s) in scopes.iter().enumerate() { | ||
let set = set_of(s).filter(|_| !scopes[..i].contains(s)); | ||
let set = set_of(s).or_else(|| sets.get(*s)); | ||
let set = set.filter(|_| !scopes[..i].contains(s)); | ||
out.extend( | ||
set.map(|set| json!({"scope": s, "title": set["title"], "text": set["detail"]})), | ||
); | ||
| @@ -171,9 +180,10 @@ pub async fn get_authorization( | ||
Some(named) => vec![named], | ||
None => host.groups_of(&me)?, | ||
}; | ||
let sets = host.permission_sets(&requested).await; | ||
let mut offered = Vec::new(); | ||
for group in &groups { | ||
offered.push(host.offered(group, &me, &requested)?.0); | ||
offered.push(host.offered(group, &me, &requested, &sets)?.0); | ||
} | ||
// Each set asked for, and any within it a group would give in its | ||
// place. | ||
| @@ -188,7 +198,7 @@ pub async fn get_authorization( | ||
let mut out = json!({ | ||
"client": client, | ||
"requested": objects("scope", &requested), | ||
"labels": labels(&named), | ||
"labels": labels(&named, &sets), | ||
"groups": offered, | ||
}); | ||
if let Some(hint) = request.parameters.get("login_hint") { | ||
| @@ -225,8 +235,10 @@ pub async fn approve_authorization( | ||
if roles.is_empty() { | ||
return Err(forbidden("you hold no role in this group")); | ||
} | ||
let granted = host.narrow(group, &roles, &requested(&request))?; | ||
let scope = concrete(&granted, group); | ||
let requested = requested(&request); | ||
let sets = host.permission_sets(&requested).await; | ||
let granted = host.narrow(group, &roles, &requested, &sets)?; | ||
let scope = concrete(&granted, group, &sets); | ||
let approved = host.approve_request(&request, group, &me, &scope); | ||
let redirect = approved.map_err(XrpcError::internal)?.ok_or_else(expired)?; | ||
tracing::info!( | ||
crates/group-host/src/config.rs+13−0
| @@ -34,6 +34,10 @@ pub struct Config { | ||
/// `/.well-known/atproto-did`, or a service answering | ||
/// `com.atproto.identity.resolveHandle`, which reads its DNS record. | ||
pub handle_resolvers: Vec<String>, | ||
/// Where the host reads a DNS TXT record, `DNS_OVER_HTTPS`: a | ||
/// DNS-over-HTTPS service answering JSON (`application/dns-json`), | ||
/// for the `_lexicon` record of another app's permission set. | ||
pub dns_over_https: String, | ||
/// Who this host starts groups for, `GROUP_FOUNDERS`, comma-separated | ||
/// DIDs: anyone when it names none. | ||
pub group_founders: Vec<String>, | ||
| @@ -80,6 +84,10 @@ pub struct Config { | ||
/// The service that finds anyone on the network by what is typed. | ||
pub const TYPEAHEAD: &str = "https://typeahead.waow.tech/xrpc/tech.waow.typeahead.searchActors"; | ||
| ||
/// The DNS-over-HTTPS service the host reads TXT records from unless | ||
/// `DNS_OVER_HTTPS` names another. | ||
pub const DNS_OVER_HTTPS: &str = "https://cloudflare-dns.com/dns-query"; | ||
| ||
impl Config { | ||
/// The config `var` names, as `std::env::var` would read it; the | ||
/// environment's own with [`Config::from_env`]. | ||
| @@ -144,6 +152,10 @@ impl Config { | ||
]; | ||
} | ||
let crawlers = urls("PDS_CRAWLERS"); | ||
let dns_over_https = var("DNS_OVER_HTTPS").unwrap_or_else(|| DNS_OVER_HTTPS.into()); | ||
if reqwest::Url::parse(&dns_over_https).is_err() { | ||
bail!("DNS_OVER_HTTPS is no URL: {dns_over_https}"); | ||
} | ||
let blob_upload_limit = match var("BLOB_UPLOAD_LIMIT") { | ||
Some(l) => l | ||
.parse() | ||
| @@ -190,6 +202,7 @@ impl Config { | ||
did_web_scheme, | ||
did_web_hosts, | ||
handle_resolvers, | ||
dns_over_https, | ||
group_founders, | ||
crawlers, | ||
blob_upload_limit, | ||
crates/group-host/src/lib.rs+11−7
| @@ -48,8 +48,10 @@ pub mod oauth_resource; | ||
pub mod oauth_scope; | ||
pub mod oauth_store; | ||
pub mod observe; | ||
pub mod permission_sets; | ||
pub mod plc; | ||
pub mod provision; | ||
pub mod proxy; | ||
pub mod rbac; | ||
pub mod recovery; | ||
pub mod repo; | ||
| @@ -64,14 +66,12 @@ pub mod time; | ||
pub mod token_writes; | ||
pub mod xrpc; | ||
| ||
use axum::extract::Path; | ||
use axum::routing::{get, post}; | ||
use axum::{Json, Router}; | ||
use config::Config; | ||
use serde_json::{Value, json}; | ||
use std::sync::Arc; | ||
use tokio::net::TcpListener; | ||
use xrpc::XrpcError; | ||
| ||
/// What every request is answered with. | ||
pub struct Host { | ||
| @@ -95,6 +95,8 @@ pub struct Host { | ||
pub(crate) clients: oauth_clients::Clients, | ||
/// The handles the directory names, as last read for a search. | ||
pub(crate) handles: actor_search::Handles, | ||
/// Other apps' permission sets, as read. | ||
pub(crate) sets: permission_sets::Read, | ||
/// The lines it logged, kept for its operators. | ||
pub logs: Arc<logs::Logs>, | ||
/// How it is used, counted for its operators. | ||
| @@ -131,6 +133,7 @@ impl Host { | ||
index_wake: Default::default(), | ||
clients: Default::default(), | ||
handles: Default::default(), | ||
sets: Default::default(), | ||
logs: Arc::new(logs), | ||
stats, | ||
limits, | ||
| @@ -461,7 +464,6 @@ pub(crate) fn routes(host: Arc<Host>) -> Router { | ||
.route("/tls/ask", get(group_domain::tls_ask)) | ||
.route("/.well-known/did.json", get(api::did_json)) | ||
.route("/.well-known/atproto-did", get(api::atproto_did)) | ||
.route("/xrpc/{nsid}", get(not_implemented).post(not_implemented)) | ||
.layer(axum::middleware::from_fn(lexicons::check)) | ||
.layer(axum::middleware::from_fn_with_state( | ||
host.clone(), | ||
| @@ -630,6 +632,12 @@ fn token_routes() -> Router<Arc<Host>> { | ||
&x("org.atgrp.internal.getGroupAuth"), | ||
post(group_tokens::get_group_auth), | ||
) | ||
.route( | ||
&x("com.atproto.server.getServiceAuth"), | ||
get(proxy::get_service_auth), | ||
) | ||
// Any other method, proxied where `atproto-proxy` says. | ||
.route("/xrpc/{nsid}", get(proxy::proxy).post(proxy::proxy)) | ||
.layer(axum::middleware::from_fn(oauth::cors)) | ||
} | ||
| ||
| @@ -642,10 +650,6 @@ async fn health() -> Json<Value> { | ||
Json(json!({ "version": env!("CARGO_PKG_VERSION"), "commit": COMMIT })) | ||
} | ||
| ||
async fn not_implemented(Path(nsid): Path<String>) -> XrpcError { | ||
XrpcError::not_implemented(&nsid) | ||
} | ||
| ||
/// What `group-host` prints for a command it does not know. | ||
pub const USAGE: &str = "usage: group-host serve, as the environment says | ||
group-host move-host --from <old address> [--dry-run] | ||
crates/group-host/src/mcp.rs+1−1
| @@ -516,7 +516,7 @@ pub(crate) fn mcp_view(host: &Host, uri: &str, me: &str) -> Result<Value, XrpcEr | ||
let mut groups = Vec::new(); | ||
// It asks for no scope: it does what the member's roles allow. | ||
for group in host.groups_of(me)? { | ||
groups.push(host.offered(&group, me, &[])?.0); | ||
groups.push(host.offered(&group, me, &[], &Default::default())?.0); | ||
} | ||
Ok(json!({ | ||
"client": {"clientId": request.client_id, "name": request.client_name}, | ||
crates/group-host/src/oauth.rs+4−3
| @@ -107,7 +107,8 @@ fn failed(host: &Host, e: OAuthError) -> Response { | ||
res | ||
} | ||
| ||
/// Lets a page anywhere reach the authorization server, as an app in a | ||
/// Lets a page anywhere reach the authorization server, and the methods | ||
/// an app calls as a group, proxied ones among them, as an app in a | ||
/// browser does: its requests carry no cookies, so any origin may. | ||
pub async fn cors(req: HttpRequest, next: Next) -> Response { | ||
let mut res = if req.method() == Method::OPTIONS { | ||
| @@ -121,11 +122,11 @@ pub async fn cors(req: HttpRequest, next: Next) -> Response { | ||
(header::ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, OPTIONS"), | ||
( | ||
header::ACCESS_CONTROL_ALLOW_HEADERS, | ||
"content-type, dpop, authorization", | ||
"content-type, dpop, authorization, atproto-proxy, atproto-accept-labelers", | ||
), | ||
( | ||
header::ACCESS_CONTROL_EXPOSE_HEADERS, | ||
"dpop-nonce, www-authenticate, retry-after, ratelimit-limit, ratelimit-remaining, ratelimit-reset, ratelimit-policy", | ||
"dpop-nonce, www-authenticate, retry-after, ratelimit-limit, ratelimit-remaining, ratelimit-reset, ratelimit-policy, atproto-repo-rev, atproto-content-labelers", | ||
), | ||
(header::ACCESS_CONTROL_MAX_AGE, "600"), | ||
] { | ||
crates/group-host/src/oauth_scope.rs+46−14
| @@ -3,17 +3,19 @@ | ||
//! group, then made concrete, so the token never depends on how a scope | ||
//! is read later. | ||
//! | ||
//! No lexicon is resolved: the only permission sets a token keeps are | ||
//! this host's own for a group's session (`org.atgrp.authManageBasic`, | ||
//! `authManageMembers` and `authModerate`, and `authManageAdmin`, which | ||
//! holds all three), read from their lexicons here, each an upper bound: | ||
//! the parts of it the roles grant are kept. A space scope naming no | ||
//! collection keeps every one, which narrowing allowed only to roles that | ||
//! may write every one there. | ||
//! The permission sets a token keeps are this host's own for a group's | ||
//! session (`org.atgrp.authManageBasic`, `authManageMembers` and | ||
//! `authModerate`, and `authManageAdmin`, which holds all three), read | ||
//! from their lexicons here, and other apps' sets, read as they publish | ||
//! them (`permission_sets`): each an upper bound, of which the parts the | ||
//! roles grant are kept. A space scope naming no collection keeps every | ||
//! one, which narrowing allowed only to roles that may write every one | ||
//! there. | ||
| ||
use crate::Host; | ||
use crate::group::{members_space, meta_space}; | ||
use crate::lexicons::lexicons; | ||
use crate::permission_sets::{Sets, included}; | ||
use crate::rbac::{self, LABEL, NS, actions_for, label_writes, meta_writes, repo_collections_for}; | ||
use crate::scopes::{decoded, is_blob, repo_collections}; | ||
use crate::xrpc::XrpcError; | ||
| @@ -268,7 +270,13 @@ impl Host { | ||
/// - `atproto`, always; | ||
/// - one of this host's permission sets for a group's session | ||
/// ([`TIERS`]), as far as the roles grant it ([`parts`]); | ||
/// - another app's permission set (`include:…`), read as `sets` holds | ||
/// it, as far as the roles grant its parts: each collection as | ||
/// `repo:C` is, and each method as `rpc:M` is; the whole set when | ||
/// they grant every part, else the parts they grant; | ||
/// - `repo:C`, for roles whose grants hold `repo:C` or `repo:*`; | ||
/// - `transition:generic` and `transition:chat.bsky`, for roles with | ||
/// `repo:*`, as an app password's maker holds; | ||
/// - `rpc:M`, a method of another service, for roles with `repo:*`; | ||
/// or one of this host's own the proposal has a group session call | ||
/// ([`ASKS`], but the `internal` ones), for this host or any, for | ||
| @@ -291,6 +299,7 @@ impl Host { | ||
group: &str, | ||
roles: &[String], | ||
requested: &[String], | ||
sets: &Sets, | ||
) -> Result<Vec<String>, XrpcError> { | ||
let grants = self.role_grants(group).map_err(XrpcError::internal)?; | ||
let repo = repo_collections_for(&grants, roles); | ||
| @@ -307,6 +316,20 @@ impl Host { | ||
} else if let Some(set) = tier_of(s) { | ||
each.push(parts(set, &held, &rooms)); | ||
continue; | ||
} else if let Some(set) = sets.get(s) { | ||
let all = included(s, set); | ||
let granted = |p: &&String| { | ||
let c = repo_collections(p); | ||
everything || c.is_some_and(|c| c.iter().all(|c| repo.contains(c))) | ||
}; | ||
let kept: Vec<String> = all.iter().filter(granted).cloned().collect(); | ||
each.push(match !all.is_empty() && kept == all { | ||
true => vec![s.clone()], | ||
false => kept, | ||
}); | ||
continue; | ||
} else if s == "transition:generic" || s == "transition:chat.bsky" { | ||
everything | ||
} else if let Some(named) = repo_collections(s) { | ||
let each = !named.is_empty() && named.iter().all(|c| repo.contains(c)); | ||
everything || each | ||
| @@ -332,7 +355,14 @@ impl Host { | ||
each.push(keep.then(|| s.clone()).into_iter().collect()); | ||
} | ||
let writes = |s: &String| { | ||
let repo_of = |set: &Value| { | ||
included(s, set) | ||
.iter() | ||
.any(|p| repo_collections(p).is_some()) | ||
}; | ||
tier_of(s).is_some() | ||
|| s == "transition:generic" | ||
|| sets.get(s).is_some_and(repo_of) | ||
|| repo_collections(s).is_some() | ||
|| SpaceScope::parse(s).is_some_and(|w| !w.read_only) | ||
}; | ||
| @@ -502,15 +532,17 @@ fn any_kind(group: &str, want: &SpaceScope, rooms: &[Room]) -> Vec<String> { | ||
out | ||
} | ||
| ||
/// A granted scope as the token carries it: a permission set of ours as | ||
/// the scopes its lexicon lists, `authority=self` as the group, and a | ||
/// space scope naming no collection as naming every one. | ||
pub fn concrete(granted: &[String], group: &str) -> String { | ||
/// A granted scope as the token carries it: a permission set, ours or | ||
/// another app's (as `sets` holds it), as the scopes it lists, | ||
/// `authority=self` as the group, and a space scope naming no collection | ||
/// as naming every one. | ||
pub fn concrete(granted: &[String], group: &str, sets: &Sets) -> String { | ||
let mut out: Vec<String> = Vec::new(); | ||
for s in granted { | ||
let scopes = match set_of(s) { | ||
Some(set) => scopes_of(set), | ||
None => vec![s.clone()], | ||
let scopes = match (set_of(s), sets.get(s)) { | ||
(Some(set), _) => scopes_of(set), | ||
(None, Some(set)) => included(s, set), | ||
(None, None) => vec![s.clone()], | ||
}; | ||
for s in scopes { | ||
let mut s = s.replace("authority=self", &format!("authority={group}")); | ||
crates/group-host/src/permission_sets.rsnew+190−0
| @@ -0,0 +1,190 @@ | ||
//! Other apps' permission sets, as an app signing in as a group asks for | ||
//! one: `include:social.grain.authFull?aud=did:web:grain.social%23grain_appview`. | ||
//! Each is read as atproto publishes lexicons: the TXT record | ||
//! `_lexicon.<authority>` (the NSID's segments but the last, reversed) | ||
//! names a DID, from `DNS_OVER_HTTPS`, and that DID's repo, at its PDS, | ||
//! holds the set as the record `com.atproto.lexicon.schema/<nsid>`. A set | ||
//! read, or found missing, is kept ten minutes. | ||
//! | ||
//! What an include gives is what atproto's permissions give of one: each | ||
//! `repo` permission's collections and each `rpc` permission's methods, | ||
//! all within the set's own namespace (`social.grain.` of | ||
//! `social.grain.authFull`), an `rpc` one's audience the include's where | ||
//! it inherits it (`inheritAud`), and none that names an audience but | ||
//! `*`. The rest of a set, its `space` permissions among it, gives a | ||
//! group's session nothing. | ||
| ||
use crate::Host; | ||
use crate::rbac::NS; | ||
use crate::scopes::{decoded, named, query}; | ||
use atproto::did; | ||
use atproto::syntax::{is_did, is_nsid}; | ||
use reqwest::Url; | ||
use serde_json::{Value, json}; | ||
use std::collections::{BTreeMap, HashMap}; | ||
use std::sync::Mutex; | ||
| ||
/// How long a set read, or found missing, is kept. | ||
const KEEP_FOR: i64 = 10 * 60_000; | ||
/// How many sets are kept at once. | ||
const KEEP_AT_MOST: usize = 1000; | ||
/// The collection a lexicon is published in. | ||
const SCHEMA: &str = "com.atproto.lexicon.schema"; | ||
/// The DNS type of a TXT record. | ||
const TXT: u64 = 16; | ||
| ||
/// The sets an app asked for, each its lexicon's main def, by the | ||
/// `include:` scope that asked for it. | ||
pub type Sets = BTreeMap<String, Value>; | ||
| ||
/// The sets read, by NSID, and when: `None` for one that did not resolve. | ||
#[derive(Default)] | ||
pub struct Read(Mutex<HashMap<String, (i64, Option<Value>)>>); | ||
| ||
/// The NSID an `include:` scope names, and its audience, if it is one of | ||
/// another app's sets. | ||
pub fn include(scope: &str) -> Option<(String, Option<String>)> { | ||
let scope = decoded(scope); | ||
let nsid = named(&scope, "include")?; | ||
let aud = query(&scope, "aud").first().map(|a| a.to_string()); | ||
let ours = nsid.starts_with(&format!("{NS}.")); | ||
(is_nsid(nsid) && !ours).then(|| (nsid.to_string(), aud)) | ||
} | ||
| ||
/// Whether `nsid` is within the namespace of the set `set`: its NSID up | ||
/// to its last dot, and more. | ||
fn within(set: &str, nsid: &str) -> bool { | ||
let space = &set[..=set.rfind('.').expect("an NSID has dots")]; | ||
nsid.len() > space.len() && nsid.starts_with(space) | ||
} | ||
| ||
/// The strings of `value`, an array. | ||
fn strings(value: &Value) -> Vec<&str> { | ||
let items = value.as_array().map(Vec::as_slice).unwrap_or_default(); | ||
items.iter().filter_map(Value::as_str).collect() | ||
} | ||
| ||
/// The scopes the `include:` scope `scope` gives of `set`, its main def, | ||
/// as atproto reads one: a scope for each collection or method. | ||
pub fn included(scope: &str, set: &Value) -> Vec<String> { | ||
let (nsid, aud) = include(scope).expect("an include of another app's set"); | ||
let mut out = Vec::new(); | ||
for p in set["permissions"].as_array().into_iter().flatten() { | ||
let (resource, names) = match p["resource"].as_str() { | ||
Some("repo") => ("repo", strings(&p["collection"])), | ||
Some("rpc") => ("rpc", strings(&p["lxm"])), | ||
_ => continue, | ||
}; | ||
if names.is_empty() || !names.iter().all(|n| within(&nsid, n)) { | ||
continue; | ||
} | ||
let query = match (resource, p["aud"].as_str(), &aud) { | ||
("repo", ..) => strings(&p["action"]) | ||
.iter() | ||
.map(|a| format!("action={a}")) | ||
.collect::<Vec<_>>() | ||
.join("&"), | ||
(_, Some("*"), _) => "aud=*".into(), | ||
(_, None, Some(aud)) if p["inheritAud"] == true => { | ||
format!("aud={}", aud.replace('#', "%23")) | ||
} | ||
_ => continue, | ||
}; | ||
let at = |n: &&str| match query.is_empty() { | ||
true => format!("{resource}:{n}"), | ||
false => format!("{resource}:{n}?{query}"), | ||
}; | ||
out.extend(names.iter().map(at)); | ||
} | ||
out | ||
} | ||
| ||
/// The text of a TXT record's data as DNS-over-HTTPS's JSON gives it: | ||
/// its quoted strings, joined. | ||
fn txt(data: &str) -> String { | ||
data.split('"').skip(1).step_by(2).collect() | ||
} | ||
| ||
impl Read { | ||
fn get(&self, nsid: &str, now: i64) -> Option<Option<Value>> { | ||
let kept = self.0.lock().expect("not poisoned"); | ||
let (at, set) = kept.get(nsid).filter(|(at, _)| now - at < KEEP_FOR)?; | ||
tracing::debug!(nsid, at, "kept"); | ||
Some(set.clone()) | ||
} | ||
| ||
fn keep(&self, nsid: &str, now: i64, set: Option<Value>) { | ||
let mut kept = self.0.lock().expect("not poisoned"); | ||
// Full, all of them go. | ||
let full = kept.len() >= KEEP_AT_MOST; | ||
kept.retain(|_, _| !full); | ||
kept.insert(nsid.into(), (now, set)); | ||
} | ||
} | ||
| ||
impl Host { | ||
/// The sets of other apps `requested` asks for that resolve. | ||
pub async fn permission_sets(&self, requested: &[String]) -> Sets { | ||
let mut sets = Sets::new(); | ||
for scope in requested { | ||
let Some((nsid, _)) = include(scope) else { | ||
continue; | ||
}; | ||
if let Some(set) = self.permission_set(&nsid).await { | ||
sets.insert(scope.clone(), set); | ||
} | ||
} | ||
sets | ||
} | ||
| ||
/// The set `nsid`, kept or read now. | ||
async fn permission_set(&self, nsid: &str) -> Option<Value> { | ||
let now = crate::time::now_millis(); | ||
if let Some(kept) = self.sets.get(nsid, now) { | ||
return kept; | ||
} | ||
let set = self.read_set(nsid).await; | ||
tracing::info!(nsid, resolved = set.is_some(), "read a permission set"); | ||
self.sets.keep(nsid, now, set.clone()); | ||
set | ||
} | ||
| ||
/// The set `nsid`, read from its publisher's repo. | ||
async fn read_set(&self, nsid: &str) -> Option<Value> { | ||
let publisher = self.lexicon_did(nsid).await?; | ||
let doc = self.identity.document(&publisher).await.ok()?; | ||
let pds = did::pds(&doc)?; | ||
let at = format!("{pds}/xrpc/com.atproto.repo.getRecord"); | ||
let q = [ | ||
("repo", publisher.as_str()), | ||
("collection", SCHEMA), | ||
("rkey", nsid), | ||
]; | ||
let url = Url::parse_with_params(&at, q).ok()?; | ||
let record = self.public_json(url.as_str(), "a lexicon").await.ok()?; | ||
let main = &record["value"]["defs"]["main"]; | ||
let set = record["value"]["id"] == nsid && main["type"] == "permission-set"; | ||
set.then(|| main.clone()) | ||
} | ||
| ||
/// The DID the `_lexicon` TXT record of `nsid`'s authority names: one | ||
/// record alone may. | ||
async fn lexicon_did(&self, nsid: &str) -> Option<String> { | ||
let mut authority: Vec<&str> = nsid.split('.').collect(); | ||
authority.pop(); | ||
authority.reverse(); | ||
let name = format!("_lexicon.{}", authority.join(".")); | ||
let asked = self.http.get(&self.config.dns_over_https); | ||
let asked = asked.query(&[("name", name.as_str()), ("type", "TXT")]); | ||
let res = asked.header("accept", "application/dns-json").send().await; | ||
let answer: Value = res.ok()?.json().await.ok()?; | ||
let records = answer["Answer"].as_array()?.iter(); | ||
let texts = records | ||
.filter(|r| r["type"] == json!(TXT)) | ||
.map(|r| txt(r["data"].as_str().unwrap_or_default())); | ||
let mut dids: Vec<String> = texts | ||
.filter_map(|t| t.strip_prefix("did=").map(String::from)) | ||
.collect(); | ||
(dids.len() == 1 && is_did(&dids[0])).then(|| dids.remove(0)) | ||
} | ||
} | ||
crates/group-host/src/provision.rs+3−2
| @@ -97,7 +97,8 @@ pub async fn provision_group( | ||
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, &requested)?; | ||
let sets = host.permission_sets(&requested).await; | ||
let granted = host.narrow(&did, &roles, &requested, &sets)?; | ||
let (access, refresh, access_expires, expires_at) = new_tokens(&auth, now); | ||
let tokens = Tokens { | ||
access_hash: &jose::sha256(&access), | ||
| @@ -111,7 +112,7 @@ pub async fn provision_group( | ||
member: founder, | ||
client_id: client.id, | ||
client_auth: auth, | ||
scope: concrete(&granted, &did), | ||
scope: concrete(&granted, &did, &sets), | ||
dpop_jkt: proof.jkt, | ||
access_expires, | ||
expires_at, | ||
crates/group-host/src/proxy.rsnew+374−0
| @@ -0,0 +1,374 @@ | ||
//! Calling other services as a group, as an account's PDS lets its apps | ||
//! call theirs: a method the host doesn't answer itself, asked of it with | ||
//! `atproto-proxy: <did>#<service>`, is sent on to that service with | ||
//! service auth the group signs, and its answer streamed back; and | ||
//! `com.atproto.server.getServiceAuth` hands an app such a token to send | ||
//! itself. Both as the reference PDS does them, for a token or an app | ||
//! password's session acting as a group. | ||
//! | ||
//! A token's scope must hold the call (`Permissions::rpc`), and the | ||
//! member who signed the app in must still hold `repo:*`, as narrowing | ||
//! asked of them; an app password's session may call anything but chat | ||
//! and `createAccount`, unless it may use chat. The service is found in | ||
//! its DID's document, and reached only at a public address (or any, | ||
//! where the host is on http itself, for test networks), never at this | ||
//! host. The token sent names the service's DID alone as its audience, | ||
//! the method as `lxm`, and lapses in a minute. | ||
| ||
use crate::Host; | ||
use crate::api::{Params, invalid, param}; | ||
use crate::app_passwords::SOURCE as APP_PASSWORD; | ||
use crate::oauth_resource::{Acting, Refusal}; | ||
use crate::time::now_millis; | ||
use crate::xrpc::{XrpcError, read_body}; | ||
use atproto::did; | ||
use atproto::jose; | ||
use atproto::service_auth::{self, Claims}; | ||
use atproto::syntax::is_did; | ||
use axum::Json; | ||
use axum::body::Body; | ||
use axum::extract::{Path, Query, State}; | ||
use axum::http::{HeaderMap, Method, StatusCode, Uri}; | ||
use axum::response::{IntoResponse, Response}; | ||
use serde_json::{Value, json}; | ||
use std::sync::Arc; | ||
use std::time::Duration; | ||
| ||
/// How long a proxied call may take, its answer read whole. | ||
pub const PROXIED_FOR: Duration = Duration::from_secs(60); | ||
/// The most bytes of a service's failure read, for its error's name. | ||
const FAILURE_AT_MOST: usize = 64 * 1024; | ||
/// How long a token `getServiceAuth` gives may last, in seconds: an hour | ||
/// for one method, a minute for any. | ||
const HOUR: i64 = 3600; | ||
const MINUTE: i64 = 60; | ||
| ||
/// The methods reserved for managing an account directly, never proxied | ||
/// nor given service auth for, as the reference PDS reserves them; and | ||
/// every `com.atproto.admin.*` method. | ||
const PROTECTED: [&str; 15] = [ | ||
"com.atproto.identity.requestPlcOperationSignature", | ||
"com.atproto.identity.signPlcOperation", | ||
"com.atproto.identity.updateHandle", | ||
"com.atproto.server.activateAccount", | ||
"com.atproto.server.confirmEmail", | ||
"com.atproto.server.createAppPassword", | ||
"com.atproto.server.deactivateAccount", | ||
"com.atproto.server.getAccountInviteCodes", | ||
"com.atproto.server.getSession", | ||
"com.atproto.server.listAppPasswords", | ||
"com.atproto.server.requestAccountDelete", | ||
"com.atproto.server.requestEmailConfirmation", | ||
"com.atproto.server.requestEmailUpdate", | ||
"com.atproto.server.revokeAppPassword", | ||
"com.atproto.server.updateEmail", | ||
]; | ||
| ||
/// The request headers sent on, besides `x-atproto-*` and, for a | ||
/// procedure, its body's `content-type` and `content-encoding`. | ||
const SENT_ON: [&str; 3] = [ | ||
"accept-language", | ||
"atproto-accept-labelers", | ||
"x-bsky-topics", | ||
]; | ||
| ||
/// The answer's headers passed back: its content's, and these. | ||
const PASSED_BACK: [&str; 3] = [ | ||
"atproto-repo-rev", | ||
"atproto-content-labelers", | ||
"retry-after", | ||
]; | ||
const CONTENT: [&str; 4] = [ | ||
"content-length", | ||
"content-encoding", | ||
"content-type", | ||
"content-language", | ||
]; | ||
| ||
/// XRPC's names for a failure's status, where a service names none. | ||
const NAMES: [(u16, &str); 13] = [ | ||
(400, "InvalidRequest"), | ||
(401, "AuthenticationRequired"), | ||
(403, "Forbidden"), | ||
(404, "XRPCNotSupported"), | ||
(406, "NotAcceptable"), | ||
(413, "PayloadTooLarge"), | ||
(415, "UnsupportedMediaType"), | ||
(429, "RateLimitExceeded"), | ||
(500, "InternalServerError"), | ||
(501, "MethodNotImplemented"), | ||
(502, "UpstreamFailure"), | ||
(503, "NotEnoughResources"), | ||
(504, "UpstreamTimeout"), | ||
]; | ||
| ||
/// Whether `lxm` is never proxied nor given service auth for. | ||
pub fn protected(lxm: &str) -> bool { | ||
let lxm = lxm.to_lowercase(); | ||
lxm.starts_with("com.atproto.admin.") || PROTECTED.iter().any(|p| p.to_lowercase() == lxm) | ||
} | ||
| ||
/// Whether `lxm` needs an app password that may use chat. | ||
pub fn privileged(lxm: &str) -> bool { | ||
let lxm = lxm.to_lowercase(); | ||
lxm.starts_with("chat.bsky.") || lxm == "com.atproto.server.createaccount" | ||
} | ||
| ||
fn bad_method() -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_REQUEST, "InvalidToken", "Bad token method") | ||
} | ||
| ||
fn upstream(message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::BAD_GATEWAY, "UpstreamFailure", message) | ||
} | ||
| ||
/// A token whose scope doesn't hold calling `lxm` at `aud`, refused as | ||
/// the reference PDS refuses it, naming the scope it needs. | ||
pub fn scope_missing(lxm: &str, aud: &str) -> XrpcError { | ||
let scope = format!("rpc:{lxm}?aud={}", aud.replace('#', "%23")); | ||
let said = format!("Missing required scope \"{scope}\""); | ||
XrpcError::new(StatusCode::FORBIDDEN, "ScopeMissingError", said) | ||
} | ||
| ||
/// The DID and service id `atproto-proxy` names: `<did>#<service>`. | ||
pub fn proxy_target(header: &str) -> Result<(&str, &str), XrpcError> { | ||
let Some((did, service)) = header.split_once('#') else { | ||
return Err(invalid("no service id specified in proxy header")); | ||
}; | ||
if did.is_empty() { | ||
return Err(invalid("no did specified in proxy header")); | ||
} | ||
if service.is_empty() { | ||
return Err(invalid("no service id specified in proxy header")); | ||
} | ||
if service.contains('#') { | ||
return Err(invalid("invalid proxy header format")); | ||
} | ||
if header.contains(' ') { | ||
return Err(invalid("proxy header cannot contain spaces")); | ||
} | ||
Ok((did, service)) | ||
} | ||
| ||
impl Host { | ||
/// Whether `acting` may call `lxm` (`*`: any) at `aud` as its group: | ||
/// for an app password's session, a method it is privileged enough | ||
/// for, else `privileged` says why not; for a token, one its scope | ||
/// holds, its member still holding `repo:*`. | ||
fn may_call( | ||
&self, | ||
acting: &Acting, | ||
lxm: &str, | ||
aud: &str, | ||
privileged_refusal: impl FnOnce() -> XrpcError, | ||
) -> Result<(), XrpcError> { | ||
let g = &acting.grant; | ||
if g.source == APP_PASSWORD { | ||
let chat = g.scope.split(' ').any(|s| s == "transition:chat.bsky"); | ||
return match privileged(lxm) && !chat { | ||
true => Err(privileged_refusal()), | ||
false => Ok(()), | ||
}; | ||
} | ||
if !acting.permissions.rpc(lxm, aud) { | ||
return Err(scope_missing(lxm, aud)); | ||
} | ||
if !self.may_issue(&g.group, &g.member)? { | ||
let said = | ||
"the member who signed this app in may no longer call other services as the group"; | ||
return Err(XrpcError::new(StatusCode::FORBIDDEN, "Forbidden", said)); | ||
} | ||
Ok(()) | ||
} | ||
| ||
/// Where `did`'s `#service` is: from its document, never this host. | ||
async fn endpoint(&self, did: &str, service: &str) -> Result<String, XrpcError> { | ||
if did == self.config.service_did { | ||
return Err(invalid("a call is never proxied to this host itself")); | ||
} | ||
let doc = self.identity.document(did).await; | ||
let doc = doc.map_err(|_| invalid("could not resolve proxy did"))?; | ||
let found = did::service(&doc, &format!("#{service}")); | ||
let url = found.ok_or_else(|| invalid("could not resolve proxy did service url"))?; | ||
if url == self.config.public_url { | ||
return Err(invalid("a call is never proxied to this host itself")); | ||
} | ||
Ok(url) | ||
} | ||
| ||
/// Service auth from `group` for `lxm` at `aud`, lapsing at `exp` | ||
/// (seconds since 1970). | ||
fn service_jwt(&self, group: &str, aud: &str, lxm: Option<&str>, exp: i64) -> String { | ||
let account = self.store.account(group).ok().flatten(); | ||
let account = account.expect("a group with a grant is here"); | ||
let claims = Claims { | ||
iss: group.into(), | ||
aud: aud.into(), | ||
exp: exp as u64, | ||
iat: Some((now_millis() / 1000) as u64), | ||
lxm: lxm.map(String::from), | ||
jti: Some(jose::random(16)), | ||
}; | ||
service_auth::sign(&account.signing, &claims) | ||
} | ||
} | ||
| ||
/// A method the host doesn't answer, sent on where `atproto-proxy` says, | ||
/// as the group; without the header, refused as not implemented. | ||
pub async fn proxy( | ||
State(host): State<Arc<Host>>, | ||
Path(nsid): Path<String>, | ||
method: Method, | ||
uri: Uri, | ||
headers: HeaderMap, | ||
body: Body, | ||
) -> Result<Response, Refusal> { | ||
let Some(to) = headers.get("atproto-proxy") else { | ||
return Err(XrpcError::not_implemented(&nsid).into()); | ||
}; | ||
let to = to | ||
.to_str() | ||
.map_err(|_| invalid("invalid proxy header format"))?; | ||
if protected(&nsid) { | ||
return Err(bad_method().into()); | ||
} | ||
let acting = host.acting(&headers, method.as_str(), &format!("/xrpc/{nsid}"))?; | ||
let (did, service) = proxy_target(to)?; | ||
host.may_call(&acting, &nsid, to, bad_method)?; | ||
let endpoint = host.endpoint(did, service).await?; | ||
let exp = now_millis() / 1000 + MINUTE; | ||
let token = host.service_jwt(&acting.grant.group, did, Some(&nsid), exp); | ||
let input = match method == Method::POST { | ||
true => Some(read_body(body, host.config.blob_upload_limit, "PayloadTooLarge").await?), | ||
false => None, | ||
}; | ||
let path = uri.path_and_query().map_or(uri.path(), |p| p.as_str()); | ||
let pinned = host.pinned(&format!("{endpoint}{path}")).await; | ||
let (client, at) = pinned.map_err(upstream)?; | ||
let mut sent = client.request(method, at).timeout(PROXIED_FOR); | ||
let encoding = headers.get("accept-encoding").cloned(); | ||
sent = sent.header( | ||
"accept-encoding", | ||
encoding.unwrap_or("identity".parse().expect("a header")), | ||
); | ||
let content = ["content-type", "content-encoding"] | ||
.into_iter() | ||
.filter(|_| input.is_some()); | ||
for name in SENT_ON.into_iter().chain(content) { | ||
if let Some(v) = headers.get(name) { | ||
sent = sent.header(name, v); | ||
} | ||
} | ||
for (name, v) in headers | ||
.iter() | ||
.filter(|(n, _)| n.as_str().starts_with("x-atproto-")) | ||
{ | ||
sent = sent.header(name, v); | ||
} | ||
if let Some(input) = input { | ||
sent = sent.body(input); | ||
} | ||
let answered = sent.bearer_auth(token).send().await; | ||
let res = answered.map_err(|_| upstream("Upstream service unreachable"))?; | ||
let status = res.status().as_u16(); | ||
tracing::info!(method = nsid, service = to, status, "proxied"); | ||
Ok(answer(res).await) | ||
} | ||
| ||
/// A service's answer, as the caller is given it: a success streamed | ||
/// with its content's headers, a failure as XRPC's, its name and message | ||
/// the service's. | ||
async fn answer(res: reqwest::Response) -> Response { | ||
let status = res.status(); | ||
let mut out = Response::builder().status(status); | ||
let succeeded = status.as_u16() < 400; | ||
let names = PASSED_BACK | ||
.iter() | ||
.chain(CONTENT.iter().filter(|_| succeeded)); | ||
for name in names { | ||
if let Some(v) = res.headers().get(*name) { | ||
out = out.header(*name, v); | ||
} | ||
} | ||
if succeeded { | ||
let chunks = futures::stream::try_unfold(res, |mut r| async move { | ||
Ok::<_, reqwest::Error>(r.chunk().await?.map(|c| (c, r))) | ||
}); | ||
return out.body(Body::from_stream(chunks)).expect("a response"); | ||
} | ||
let said = crate::index_api::capped(res, FAILURE_AT_MOST).await; | ||
let said: Value = serde_json::from_slice(&said.unwrap_or_default()).unwrap_or_default(); | ||
let code = status.as_u16(); | ||
let named = NAMES | ||
.iter() | ||
.find(|(s, _)| *s == code) | ||
.map_or("Unknown", |(_, n)| n); | ||
let error = said["error"].as_str().unwrap_or(named); | ||
let message = said["message"].as_str().unwrap_or(error); | ||
let status = match code { | ||
500 => StatusCode::BAD_GATEWAY, | ||
_ => status, | ||
}; | ||
let body = Json(json!({ "error": error, "message": message })); | ||
let mut res = body.into_response(); | ||
*res.status_mut() = status; | ||
let built = out.body(Body::empty()).expect("a response"); | ||
res.headers_mut().extend(built.headers().clone()); | ||
res | ||
} | ||
| ||
/// A token the group signs for an app to call `aud` with, for `lxm` or | ||
/// any method, lapsing at `exp`: within an hour, or a minute for any | ||
/// method, and a minute from now unless asked. | ||
pub async fn get_service_auth( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Result<Json<Value>, Refusal> { | ||
let nsid = "com.atproto.server.getServiceAuth"; | ||
let acting = host.acting(&headers, "GET", &format!("/xrpc/{nsid}"))?; | ||
let aud = param(&p, "aud")?; | ||
let lxm = p.get("lxm").map(String::as_str); | ||
let insufficient = || { | ||
let lxm = lxm.unwrap_or_default(); | ||
invalid(format!( | ||
"insufficient access to request a service auth token for the following method: {lxm}" | ||
)) | ||
}; | ||
host.may_call(&acting, lxm.unwrap_or("*"), aud, insufficient)?; | ||
let (bare, service) = aud | ||
.split_once('#') | ||
.map_or((aud, None), |(d, s)| (d, Some(s))); | ||
if !is_did(bare) || service.is_some_and(|s| s.is_empty() || s.contains('#')) { | ||
let said = "aud must be a valid atproto DID or did#serviceId reference"; | ||
return Err(invalid(said).into()); | ||
} | ||
let now = now_millis() / 1000; | ||
let exp = match p.get("exp") { | ||
Some(e) => e | ||
.parse::<i64>() | ||
.map_err(|_| invalid("exp is a number of seconds"))?, | ||
None => now + MINUTE, | ||
}; | ||
let bad = |said: &str| XrpcError::new(StatusCode::BAD_REQUEST, "BadExpiration", said); | ||
if exp < now { | ||
return Err(bad("expiration is in past").into()); | ||
} | ||
if exp - now > HOUR { | ||
let said = "cannot request a token with an expiration more than an hour in the future"; | ||
return Err(bad(said).into()); | ||
} | ||
if lxm.is_none() && exp - now > MINUTE { | ||
let said = "cannot request a method-less token with an expiration more than a minute in the future"; | ||
return Err(bad(said).into()); | ||
} | ||
if let Some(lxm) = lxm.filter(|l| protected(l)) { | ||
let said = format!( | ||
"cannot request a service auth token for the following protected method: {lxm}" | ||
); | ||
return Err(invalid(said).into()); | ||
} | ||
let token = host.service_jwt(&acting.grant.group, aud, lxm, exp); | ||
tracing::info!(aud, lxm, "gave service auth"); | ||
Ok(Json(json!({ "token": token }))) | ||
} | ||
crates/group-host/src/rbac.rs+2−1
crates/group-host/src/scopes.rs+25−2
crates/group-host/tests/config.rs+7−0
crates/group-host/tests/oauth_scope.rs+62−15
crates/group-host/tests/proxy.rsnew+938−0
938 lines changed: not loaded until asked for.