chadtmiller.com/group-host
atmosphere group host
0
0
Apps sign in to a group with OAuth, approved by a member in the console
crates/atproto/src/jose.rsnew+151−0
| @@ -0,0 +1,151 @@ | ||
//! JOSE as atproto OAuth uses it: public keys as JWKs, their RFC 7638 | ||
//! thumbprints (a DPoP key's `jkt`), and compact JWTs signed with ES256 or | ||
//! ES256K, the two curves atproto keys are on. What jose, which the | ||
//! reference OAuth provider uses, makes of the same keys is in | ||
//! `tests/reference/jose.json`. | ||
| ||
use crate::keys::{Curve, Keypair, PublicKey}; | ||
use base64::Engine; | ||
use base64::engine::general_purpose::URL_SAFE_NO_PAD; | ||
use serde_json::{Value, json}; | ||
use sha2::{Digest, Sha256}; | ||
use std::fmt; | ||
| ||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
pub struct JoseError(pub String); | ||
| ||
impl fmt::Display for JoseError { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
f.write_str(&self.0) | ||
} | ||
} | ||
| ||
impl std::error::Error for JoseError {} | ||
| ||
fn err<T>(what: impl Into<String>) -> Result<T, JoseError> { | ||
Err(JoseError(what.into())) | ||
} | ||
| ||
/// `bytes`, base64url without padding. | ||
pub fn b64(bytes: impl AsRef<[u8]>) -> String { | ||
URL_SAFE_NO_PAD.encode(bytes) | ||
} | ||
| ||
/// SHA-256 of `text`, base64url: a PKCE challenge, a DPoP proof's `ath`. | ||
pub fn sha256(text: &str) -> String { | ||
b64(Sha256::digest(text.as_bytes())) | ||
} | ||
| ||
/// `bytes` random bytes, base64url: a token, a nonce, a `jti`. | ||
pub fn random(bytes: usize) -> String { | ||
let mut buf = vec![0; bytes]; | ||
rand_core::RngCore::fill_bytes(&mut rand_core::OsRng, &mut buf); | ||
b64(buf) | ||
} | ||
| ||
fn crv(curve: Curve) -> &'static str { | ||
match curve { | ||
Curve::K256 => "secp256k1", | ||
Curve::P256 => "P-256", | ||
} | ||
} | ||
| ||
/// `key` as a public JWK. | ||
pub fn jwk(key: &PublicKey) -> Value { | ||
let point = match key { | ||
PublicKey::K256(k) => k.to_encoded_point(false).as_bytes().to_vec(), | ||
PublicKey::P256(k) => k.to_encoded_point(false).as_bytes().to_vec(), | ||
}; | ||
json!({ | ||
"kty": "EC", | ||
"crv": crv(key.curve()), | ||
"x": b64(&point[1..33]), | ||
"y": b64(&point[33..]), | ||
}) | ||
} | ||
| ||
/// The public key a JWK holds: an EC key on P-256 or secp256k1, never one | ||
/// with its private part. | ||
pub fn from_jwk(jwk: &Value) -> Result<PublicKey, JoseError> { | ||
if jwk.get("d").is_some() { | ||
return err("a JWK with its private key"); | ||
} | ||
if jwk["kty"] != "EC" { | ||
return err("a JWK that is not an EC key"); | ||
} | ||
let curve = match jwk["crv"].as_str() { | ||
Some("P-256") => Curve::P256, | ||
Some("secp256k1") => Curve::K256, | ||
other => return err(format!("a JWK on the curve {other:?}")), | ||
}; | ||
let coordinate = |name: &str| { | ||
let text = jwk[name].as_str().unwrap_or_default(); | ||
URL_SAFE_NO_PAD | ||
.decode(text) | ||
.ok() | ||
.filter(|c| c.len() == 32) | ||
.ok_or_else(|| JoseError(format!("a JWK whose {name} is not 32 bytes"))) | ||
}; | ||
let point = [&[4u8][..], &coordinate("x")?, &coordinate("y")?].concat(); | ||
PublicKey::from_sec1(curve, &point).map_err(|e| JoseError(e.0.into())) | ||
} | ||
| ||
/// A JWK's RFC 7638 thumbprint, SHA-256: its required members, in order, | ||
/// as JSON with no spaces. | ||
pub fn thumbprint(key: &PublicKey) -> String { | ||
let jwk = jwk(key); | ||
let canonical = format!( | ||
r#"{{"crv":"{}","kty":"EC","x":"{}","y":"{}"}}"#, | ||
jwk["crv"].as_str().unwrap_or_default(), | ||
jwk["x"].as_str().unwrap_or_default(), | ||
jwk["y"].as_str().unwrap_or_default(), | ||
); | ||
b64(Sha256::digest(canonical.as_bytes())) | ||
} | ||
| ||
/// `claims` signed with `key` as a compact JWT, under `header` with the | ||
/// key's `alg` added. | ||
pub fn sign(key: &Keypair, header: &Value, claims: &Value) -> String { | ||
let mut header = header.clone(); | ||
header["alg"] = key.curve().alg().into(); | ||
let body = format!("{}.{}", b64(header.to_string()), b64(claims.to_string())); | ||
format!("{body}.{}", b64(key.sign(body.as_bytes()))) | ||
} | ||
| ||
/// A compact JWT's header and claims, unchecked: to find whose key to | ||
/// check it with. | ||
pub fn parts(token: &str) -> Result<(Value, Value), JoseError> { | ||
let pieces: Vec<&str> = token.split('.').collect(); | ||
let [header, claims, _] = pieces[..] else { | ||
return err("not a compact JWT"); | ||
}; | ||
let decode = |part: &str, what: &str| { | ||
let bytes = URL_SAFE_NO_PAD.decode(part); | ||
let json = bytes | ||
.ok() | ||
.and_then(|b| serde_json::from_slice::<Value>(&b).ok()); | ||
json.filter(Value::is_object) | ||
.ok_or_else(|| JoseError(format!("bad JSON in a JWT {what}"))) | ||
}; | ||
Ok((decode(header, "header")?, decode(claims, "payload")?)) | ||
} | ||
| ||
/// A JWT's header and claims, once it is signed by `key` with the key's | ||
/// `alg`. Its claims' times are the caller's to check. Either `s` is | ||
/// taken, as jose signs with either. | ||
pub fn verify(token: &str, key: &PublicKey) -> Result<(Value, Value), JoseError> { | ||
let (header, claims) = parts(token)?; | ||
let alg = key.curve().alg(); | ||
if header["alg"] != alg { | ||
return err(format!( | ||
"a JWT signed with {} where {alg} was expected", | ||
header["alg"] | ||
)); | ||
} | ||
let (signed, sig) = token.rsplit_once('.').unwrap_or_default(); | ||
let sig = URL_SAFE_NO_PAD.decode(sig).unwrap_or_default(); | ||
if !key.verify_either_s(signed.as_bytes(), &sig) { | ||
return err("bad signature"); | ||
} | ||
Ok((header, claims)) | ||
} | ||
crates/atproto/src/lib.rs+4−2
| @@ -1,8 +1,9 @@ | ||
//! The atproto a group host needs, written for it rather than taken from a | ||
//! framework, as knotless writes its own: DRISL (DAG-CBOR) and CIDs, the | ||
//! keys a repo and a PLC operation are signed with, the Merkle search tree | ||
//! a repo's records hang from, CAR files, PLC operations, and the | ||
//! service-auth tokens one server hands another. | ||
//! a repo's records hang from, CAR files, PLC operations, the | ||
//! service-auth tokens one server hands another, and the JWKs and JWTs | ||
//! of OAuth's DPoP proofs and client assertions. | ||
//! | ||
//! Each part is checked against atproto's interop test vectors, under | ||
//! `tests/interop`. The parts still to come are in `docs/design/README.md`. | ||
| @@ -13,6 +14,7 @@ pub mod cid; | ||
pub mod commit; | ||
pub mod did; | ||
pub mod drisl; | ||
pub mod jose; | ||
pub mod keys; | ||
pub mod mst; | ||
pub mod plc; | ||
crates/atproto/tests/reference/jose.jsonnew+40−0
| @@ -0,0 +1,40 @@ | ||
{ | ||
"generatedFrom": "jose 5.10.0", | ||
"keys": [ | ||
{ | ||
"crv": "P-256", | ||
"alg": "ES256", | ||
"secret": "1111111111111111111111111111111111111111111111111111111111111111", | ||
"jwk": { | ||
"kty": "EC", | ||
"x": "AhfmF_C2RDkoJ4-WmZ5pojpPLBUr321s32bluAKC1O0", | ||
"y": "GUp968uXcS0t2jyoWqh2Wlb0X8dYWZZS8ol8ZTBuV5Q", | ||
"crv": "P-256" | ||
}, | ||
"thumbprint": "OEurnbzOGbRad4qOD9lNK8VYMQGvg5cmLnVKeydAqL4", | ||
"jwt": "eyJhbGciOiJFUzI1NiIsInR5cCI6ImRwb3Arand0IiwiandrIjp7Imt0eSI6IkVDIiwieCI6IkFoZm1GX0MyUkRrb0o0LVdtWjVwb2pwUExCVXIzMjFzMzJibHVBS0MxTzAiLCJ5IjoiR1VwOTY4dVhjUzB0Mmp5b1dxaDJXbGIwWDhkWVdaWlM4b2w4WlRCdVY1USIsImNydiI6IlAtMjU2In19.eyJodG0iOiJQT1NUIiwiaHR1IjoiaHR0cHM6Ly9ob3N0LnRlc3Qvb2F1dGgvdG9rZW4iLCJqdGkiOiJvbmUiLCJpYXQiOjE3OTM3MzYzMDB9.EHR_ND19U_feGktyQVNdcP-UFpj0iwuwCaI_kq0hMY1iDBG179kyyYtsCNV9lzRYURmnpu-5uB4LPO6aGq4WZQ" | ||
}, | ||
{ | ||
"crv": "secp256k1", | ||
"alg": "ES256K", | ||
"secret": "a1b2c3d4e5f60718293a4b5c6d7e8f90112233445566778899aabbccddeeff01", | ||
"jwk": { | ||
"kty": "EC", | ||
"x": "rGCGVkwOABZvgtf_M7hT2j2l5W3mImwKSN3f9bu4Sr4", | ||
"y": "Pg1cSFNKQJUJsXt4oBKZdy3M66Y-qegHxfsqulzNnDg", | ||
"crv": "secp256k1" | ||
}, | ||
"thumbprint": "Ym23HMODSUu1h6hO29_iBkHavyM35ttqeUm6GC4FYBM", | ||
"jwt": "eyJhbGciOiJFUzI1NksiLCJ0eXAiOiJkcG9wK2p3dCIsImp3ayI6eyJrdHkiOiJFQyIsIngiOiJyR0NHVmt3T0FCWnZndGZfTTdoVDJqMmw1VzNtSW13S1NOM2Y5YnU0U3I0IiwieSI6IlBnMWNTRk5LUUpVSnNYdDRvQktaZHkzTTY2WS1xZWdIeGZzcXVsek5uRGciLCJjcnYiOiJzZWNwMjU2azEifX0.eyJodG0iOiJQT1NUIiwiaHR1IjoiaHR0cHM6Ly9ob3N0LnRlc3Qvb2F1dGgvdG9rZW4iLCJqdGkiOiJvbmUiLCJpYXQiOjE3OTM3MzYzMDB9.whUE0sRtWfLlHXOCw0lluy6hFVkz0iKF1toi-lJ1AJhv2PLyrvzezSqzOq_0U12WYfzgdTqM6bX60xVSdqepEw" | ||
} | ||
], | ||
"rfc9449": { | ||
"jwk": { | ||
"kty": "EC", | ||
"x": "l8tFrhx-34tV3hRICRDY9zCkDlpBhF42UQUfWVAWBFs", | ||
"y": "9VE4jf_Ok_o64zbTTlcuNJajHmt6v9TDVrU0CdvGRDA", | ||
"crv": "P-256" | ||
}, | ||
"thumbprint": "0ZcOCORZNYy-DWpqq30jZyJGHTN0d2HglBV3uiguA4I" | ||
} | ||
} | ||
crates/atproto/tests/reference/jose.mjsnew+38−0
| @@ -0,0 +1,38 @@ | ||
// Records what jose (panva's, which @atproto/oauth-provider checks DPoP | ||
// proofs and client assertions with) makes of fixed keys, into jose.json | ||
// beside this: each key's public JWK and RFC 7638 thumbprint, and a JWT it | ||
// signs. ECDSA signatures are random, so the JWTs differ each run. | ||
// | ||
// node jose.mjs <jose's directory, 5.x for ES256K> > jose.json | ||
import { createECDH, createPrivateKey } from 'node:crypto' | ||
const jose = await import(process.argv[2] + '/dist/node/esm/index.js') | ||
| ||
const keys = { | ||
'P-256': ['ES256', '1111111111111111111111111111111111111111111111111111111111111111'], | ||
secp256k1: ['ES256K', 'a1b2c3d4e5f60718293a4b5c6d7e8f90112233445566778899aabbccddeeff01'], | ||
} | ||
| ||
// A private key from its scalar: ECDH finds its public point. | ||
function privateKey(crv, hex) { | ||
const ecdh = createECDH(crv === 'P-256' ? 'prime256v1' : 'secp256k1') | ||
ecdh.setPrivateKey(Buffer.from(hex, 'hex')) | ||
const point = ecdh.getPublicKey() | ||
const b64 = (b) => Buffer.from(b).toString('base64url') | ||
const jwk = { kty: 'EC', crv, d: b64(Buffer.from(hex, 'hex')), x: b64(point.subarray(1, 33)), y: b64(point.subarray(33)) } | ||
return createPrivateKey({ key: jwk, format: 'jwk' }) | ||
} | ||
| ||
const out = { generatedFrom: `jose ${process.argv[2].match(/jose@([^/]+)/)?.[1]}`, keys: [] } | ||
for (const [crv, [alg, hex]] of Object.entries(keys)) { | ||
const key = privateKey(crv, hex) | ||
const { d: _, ...jwk } = key.export({ format: 'jwk' }) | ||
const jwt = await new jose.SignJWT({ htm: 'POST', htu: 'https://host.test/oauth/token', jti: 'one' }) | ||
.setProtectedHeader({ alg, typ: 'dpop+jwt', jwk }) | ||
.setIssuedAt(1793736300) | ||
.sign(key) | ||
out.keys.push({ crv, alg, secret: hex, jwk, thumbprint: await jose.calculateJwkThumbprint(jwk, 'sha256'), jwt }) | ||
} | ||
// RFC 9449's own example key (§ 6.1), with the thumbprint it gives. | ||
const rfc = { kty: 'EC', x: 'l8tFrhx-34tV3hRICRDY9zCkDlpBhF42UQUfWVAWBFs', y: '9VE4jf_Ok_o64zbTTlcuNJajHmt6v9TDVrU0CdvGRDA', crv: 'P-256' } | ||
out.rfc9449 = { jwk: rfc, thumbprint: await jose.calculateJwkThumbprint(rfc, 'sha256') } | ||
console.log(JSON.stringify(out, null, 2)) | ||
crates/atproto/tests/reference/README.md+5−0
| @@ -15,3 +15,8 @@ LtHash set hash, a space repo's commit, its MAC and MAC header and its STAR | ||
archive, a record's MAC, a KEM decapsulation and its want-MAC header, and | ||
an HTTP signature, which the credentials' pull reads. | ||
| ||
| ||
`jose.json` is from `jose.mjs`, run against jose 5.10.0 (panva's, which | ||
@atproto/oauth-provider checks DPoP proofs and client assertions with): | ||
fixed P-256 and secp256k1 keys' public JWKs and RFC 7638 thumbprints, a | ||
DPoP proof each signs, and RFC 9449's own example key and thumbprint. | ||
crates/atproto/tests/jose.rsnew+111−0
| @@ -0,0 +1,111 @@ | ||
//! JWKs, thumbprints and JWTs, against what jose makes of the same keys | ||
//! (tests/reference/jose.json) and RFC 9449's example. | ||
| ||
use atproto::jose::{self, from_jwk, jwk, parts, random, sha256, sign, thumbprint, verify}; | ||
use atproto::keys::{Curve, Keypair}; | ||
use serde_json::{Value, json}; | ||
| ||
fn vectors() -> Value { | ||
let path = format!("{}/tests/reference/jose.json", env!("CARGO_MANIFEST_DIR")); | ||
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() | ||
} | ||
| ||
fn unhex(text: &str) -> Vec<u8> { | ||
(0..text.len()) | ||
.step_by(2) | ||
.map(|i| u8::from_str_radix(&text[i..i + 2], 16).unwrap()) | ||
.collect() | ||
} | ||
| ||
#[test] | ||
fn makes_the_jwk_and_thumbprint_jose_makes() { | ||
for v in vectors()["keys"].as_array().unwrap() { | ||
let curve = if v["alg"] == "ES256" { | ||
Curve::P256 | ||
} else { | ||
Curve::K256 | ||
}; | ||
let key = Keypair::from_bytes(curve, &unhex(v["secret"].as_str().unwrap())).unwrap(); | ||
assert_eq!(jwk(&key.public()), v["jwk"], "{}", v["crv"]); | ||
assert_eq!(thumbprint(&key.public()), v["thumbprint"], "{}", v["crv"]); | ||
assert_eq!(from_jwk(&v["jwk"]).unwrap(), key.public()); | ||
} | ||
} | ||
| ||
#[test] | ||
fn takes_the_thumbprint_rfc_9449_gives() { | ||
let rfc = &vectors()["rfc9449"]; | ||
let key = from_jwk(&rfc["jwk"]).unwrap(); | ||
assert_eq!(thumbprint(&key), rfc["thumbprint"]); | ||
} | ||
| ||
#[test] | ||
fn checks_the_proofs_jose_signed() { | ||
for v in vectors()["keys"].as_array().unwrap() { | ||
let token = v["jwt"].as_str().unwrap(); | ||
let (header, _) = parts(token).unwrap(); | ||
let key = from_jwk(&header["jwk"]).unwrap(); | ||
let (header, claims) = verify(token, &key).unwrap(); | ||
assert_eq!(header["typ"], "dpop+jwt"); | ||
assert_eq!(claims["htu"], "https://host.test/oauth/token"); | ||
} | ||
} | ||
| ||
#[test] | ||
fn signs_what_it_checks() { | ||
for curve in [Curve::P256, Curve::K256] { | ||
let key = Keypair::generate(curve); | ||
let token = sign(&key, &json!({"typ": "dpop+jwt"}), &json!({"jti": "a"})); | ||
let (header, claims) = verify(&token, &key.public()).unwrap(); | ||
assert_eq!(header["alg"], curve.alg()); | ||
assert_eq!(claims["jti"], "a"); | ||
} | ||
} | ||
| ||
#[test] | ||
fn refuses_another_key_or_alg() { | ||
let key = Keypair::generate(Curve::P256); | ||
let token = sign(&key, &json!({}), &json!({})); | ||
let other = Keypair::generate(Curve::P256).public(); | ||
assert_eq!( | ||
verify(&token, &other).unwrap_err().to_string(), | ||
"bad signature" | ||
); | ||
let k256 = Keypair::generate(Curve::K256).public(); | ||
let said = verify(&token, &k256).unwrap_err().to_string(); | ||
assert!(said.contains("where ES256K was expected"), "{said}"); | ||
} | ||
| ||
#[test] | ||
fn refuses_what_is_not_a_jwt() { | ||
for token in ["a.b", "a.b.c.d", "!!.e30.x", "e30.WzFd.x"] { | ||
assert!(parts(token).is_err(), "{token}"); | ||
} | ||
} | ||
| ||
#[test] | ||
fn refuses_a_jwk_it_cannot_use() { | ||
let good = vectors()["keys"][0]["jwk"].clone(); | ||
let with = |k: &str, v: Value| { | ||
let mut j = good.clone(); | ||
j[k] = v; | ||
from_jwk(&j).unwrap_err().0 | ||
}; | ||
assert!(with("d", json!("secret")).contains("private")); | ||
assert!(with("kty", json!("RSA")).contains("not an EC key")); | ||
assert!(with("crv", json!("P-384")).contains("curve")); | ||
assert!(with("x", json!("short")).contains("x is not 32 bytes")); | ||
// A point not on the curve. | ||
assert!(with("y", json!(jose::b64([7u8; 32]))).contains("P-256")); | ||
} | ||
| ||
#[test] | ||
fn hashes_and_draws_as_oauth_wants() { | ||
// RFC 7636's example verifier and its S256 challenge. | ||
assert_eq!( | ||
sha256("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"), | ||
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" | ||
); | ||
assert_eq!(random(32).len(), 43); | ||
assert_ne!(random(16), random(16)); | ||
} | ||
crates/group-host/src/authorization.rsnew+233−0
| @@ -0,0 +1,233 @@ | ||
//! Signing an app in as a group, from the member's side: the console's | ||
//! approval page reads the request, the member picks the group, and | ||
//! approves or declines. The member is whoever signed the service auth, | ||
//! their own PDS vouching for them, so who signed an app in is never a | ||
//! guess, and the grant is theirs: it ends when they are put out. | ||
//! | ||
//! As the prototype's `methods/authorization.ts`. | ||
| ||
use crate::Host; | ||
use crate::api::{Params, invalid, param}; | ||
use crate::group::meta_space; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::oauth_scope::{concrete, configure}; | ||
use crate::oauth_store::Request; | ||
use crate::rbac::{Access, NS}; | ||
use crate::time::now_millis; | ||
use crate::xrpc::XrpcError; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, StatusCode}; | ||
use serde_json::{Value, json}; | ||
use std::sync::Arc; | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
| ||
fn expired() -> XrpcError { | ||
XrpcError::new( | ||
StatusCode::BAD_REQUEST, | ||
"ExpiredRequest", | ||
"this sign-in request has expired; go back to the app and try again", | ||
) | ||
} | ||
| ||
fn forbidden(message: impl Into<String>) -> XrpcError { | ||
XrpcError::new(StatusCode::FORBIDDEN, "Forbidden", message) | ||
} | ||
| ||
fn pending(host: &Host, request_uri: &str) -> Result<Request, XrpcError> { | ||
let found = host | ||
.pending_request(request_uri) | ||
.map_err(XrpcError::internal)?; | ||
found.ok_or_else(expired) | ||
} | ||
| ||
fn requested(request: &Request) -> Vec<String> { | ||
let scope = request.parameters["scope"].as_str().unwrap_or_default(); | ||
scope.split(' ').map(String::from).collect() | ||
} | ||
| ||
fn objects(field: &str, items: &[String]) -> Value { | ||
items.iter().map(|i| json!({ field: i })).collect() | ||
} | ||
| ||
impl Host { | ||
/// The group an app named in its `login_hint`, by handle or DID, if | ||
/// it is one here and switched on. | ||
fn named_group(&self, request: &Request) -> Result<Option<String>, XrpcError> { | ||
let Some(hint) = request.parameters["login_hint"].as_str() else { | ||
return Ok(None); | ||
}; | ||
let hint = hint.trim_start_matches("at://").trim_start_matches('@'); | ||
let account = self.store.account(&hint.to_lowercase()); | ||
let did = account.map_err(XrpcError::internal)?.map(|a| a.did); | ||
let did = did.filter(|d| group_of(self, d).is_ok() && self.active(d).is_ok()); | ||
Ok(did) | ||
} | ||
| ||
/// The groups here, switched on, where `member` holds a role. | ||
fn groups_of(&self, member: &str) -> Result<Vec<String>, XrpcError> { | ||
let accounts = self.store.accounts(None, u32::MAX); | ||
let mut groups = Vec::new(); | ||
for (did, _) in accounts.map_err(XrpcError::internal)? { | ||
let roles = self.roles(&did, member).map_err(XrpcError::internal)?; | ||
if group_of(self, &did).is_ok() && self.active(&did).is_ok() && !roles.is_empty() { | ||
groups.push(did); | ||
} | ||
} | ||
Ok(groups) | ||
} | ||
| ||
/// A group as the approval page shows it to `member`: what of its | ||
/// profile they may read, their roles, and what the app would get. | ||
fn offered(&self, group: &str, member: &str, requested: &[String]) -> 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, member, requested)?, | ||
}; | ||
let withheld: Vec<String> = requested | ||
.iter() | ||
.filter(|s| !granted.contains(s)) | ||
.cloned() | ||
.collect(); | ||
let mut view = json!({ | ||
"did": group, | ||
"handle": handle, | ||
"roles": objects("role", &roles), | ||
"granted": objects("scope", &granted), | ||
"withheld": objects("scope", &withheld), | ||
}); | ||
let (meta, access) = (meta_space(group), format!("{NS}.access")); | ||
let access = self.group_record(group, &meta, &access, "self"); | ||
let access = access.map_err(XrpcError::internal)?.unwrap_or_default(); | ||
if Access::of(&access).can_read(&roles, member) { | ||
let profile = self.group_record(group, &meta, &format!("{NS}.profile"), "self"); | ||
let profile = profile.map_err(XrpcError::internal)?.unwrap_or_default(); | ||
if let Some(name) = profile.get("displayName") { | ||
view["displayName"] = name.clone(); | ||
} | ||
if let Some(cid) = profile["avatar"]["ref"]["$link"].as_str() { | ||
// Read as any file in the space is, by whoever may. | ||
let url = reqwest::Url::parse_with_params( | ||
&format!("{}/xrpc/{NS}.getSpaceBlob", self.config.public_url), | ||
&[ | ||
("group", group), | ||
("space", &meta), | ||
("repo", group), | ||
("cid", cid), | ||
], | ||
); | ||
view["avatar"] = json!(url.expect("the public URL is a URL").as_str()); | ||
} | ||
} | ||
Ok(Json(view)) | ||
} | ||
} | ||
| ||
/// What the configure permission set says it is for. | ||
fn labels(requested: &[String]) -> Value { | ||
let lexicon: Value = serde_json::from_str(include_str!( | ||
"../../../lexicons/fyi/opensocial/configure.json" | ||
)) | ||
.expect("the configure lexicon is JSON"); | ||
let text = &lexicon["defs"]["main"]["detail"]; | ||
let ours = requested.iter().filter(|s| **s == configure()); | ||
ours.map(|s| json!({"scope": s, "text": text})).collect() | ||
} | ||
| ||
/// An app's pending request to sign in as a group, as the caller would | ||
/// approve it: the app, and the groups they may sign it in as, each with | ||
/// what their roles there would let it do. | ||
pub async fn get_authorization( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
headers: HeaderMap, | ||
) -> Answer { | ||
let me = signed_in(&host, &headers, &format!("{NS}.getAuthorization")).await?; | ||
let request = pending(&host, param(&p, "requestUri")?)?; | ||
let requested = requested(&request); | ||
let metadata = host.client(&request.client_id, now_millis()).await; | ||
let metadata = metadata.map(|c| c.metadata).unwrap_or_default(); | ||
let mut client = json!({"clientId": request.client_id}); | ||
for (k, from) in [ | ||
("name", "client_name"), | ||
("uri", "client_uri"), | ||
("logo", "logo_uri"), | ||
] { | ||
if let Some(v) = metadata[from].as_str() { | ||
client[k] = json!(v); | ||
} | ||
} | ||
let groups = match host.named_group(&request)? { | ||
Some(named) => vec![named], | ||
None => host.groups_of(&me)?, | ||
}; | ||
let mut offered = Vec::new(); | ||
for group in &groups { | ||
offered.push(host.offered(group, &me, &requested)?.0); | ||
} | ||
let mut out = json!({ | ||
"client": client, | ||
"requested": objects("scope", &requested), | ||
"labels": labels(&requested), | ||
"groups": offered, | ||
}); | ||
if let Some(hint) = request.parameters.get("login_hint") { | ||
out["loginHint"] = hint.clone(); | ||
} | ||
Ok(Json(out)) | ||
} | ||
| ||
/// Approves an app's pending request to sign in as a group: it gets what | ||
/// the caller's roles there allow, and the grant is theirs. | ||
pub async fn approve_authorization( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let me = signed_in(&host, &headers, &format!("{NS}.approveAuthorization")).await?; | ||
let uri = body["requestUri"].as_str(); | ||
let request = pending(&host, uri.ok_or_else(|| invalid("requestUri is required"))?)?; | ||
let group = body["group"].as_str(); | ||
let group = group.ok_or_else(|| invalid("group is required"))?; | ||
group_of(&host, group)?; | ||
host.active(group)?; | ||
let named = host.named_group(&request)?; | ||
if named.is_some_and(|n| n != group) { | ||
return Err(forbidden("the app asked to sign in as another group")); | ||
} | ||
// A group has no password: without a role there is nothing to act with. | ||
let roles = host.roles(group, &me).map_err(XrpcError::internal)?; | ||
if roles.is_empty() { | ||
return Err(forbidden("you hold no role in this group")); | ||
} | ||
let granted = host.narrow(group, &roles, &me, &requested(&request))?; | ||
let scope = concrete(&granted, group); | ||
let approved = host.approve_request(&request, group, &me, &scope); | ||
let redirect = approved.map_err(XrpcError::internal)?.ok_or_else(expired)?; | ||
tracing::info!( | ||
member = me, | ||
client = request.client_id, | ||
group, | ||
scope, | ||
"approved" | ||
); | ||
Ok(Json(json!({ "redirectUrl": redirect }))) | ||
} | ||
| ||
/// Declines an app's pending request: the browser goes back to it with | ||
/// access_denied. | ||
pub async fn decline_authorization( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
signed_in(&host, &headers, &format!("{NS}.declineAuthorization")).await?; | ||
let uri = body["requestUri"].as_str(); | ||
let request = pending(&host, uri.ok_or_else(|| invalid("requestUri is required"))?)?; | ||
let declined = host.decline_request(&request); | ||
let redirect = declined.map_err(XrpcError::internal)?.ok_or_else(expired)?; | ||
Ok(Json(json!({ "redirectUrl": redirect }))) | ||
} | ||
crates/group-host/src/config.rs+10−0
| @@ -36,6 +36,10 @@ pub struct Config { | ||
pub crawlers: Vec<String>, | ||
/// The most bytes one blob may be, `BLOB_UPLOAD_LIMIT`. | ||
pub blob_upload_limit: u64, | ||
/// Where the console is, `CONSOLE_URL`, with no trailing slash: where | ||
/// 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, | ||
} | ||
| ||
impl Config { | ||
| @@ -92,6 +96,11 @@ impl Config { | ||
.with_context(|| format!("BLOB_UPLOAD_LIMIT is no number of bytes: {l}"))?, | ||
None => 50 * 1024 * 1024, | ||
}; | ||
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() { | ||
bail!("CONSOLE_URL is no URL: {console_url}"); | ||
} | ||
Ok(Config { | ||
port, | ||
public_url, | ||
| @@ -104,6 +113,7 @@ impl Config { | ||
group_founders, | ||
crawlers, | ||
blob_upload_limit, | ||
console_url, | ||
}) | ||
} | ||
| ||
crates/group-host/src/group_members.rs+3−0
| @@ -437,6 +437,9 @@ impl Host { | ||
// it may be asked again. | ||
let revoked = self.revoke_credentials(group, member).await; | ||
revoked.map_err(XrpcError::internal)?; | ||
// And the apps they signed in as the group. | ||
let ended = self.store.revoke_member_grants(group, member); | ||
ended.map_err(XrpcError::internal)?; | ||
let gone = Write::Delete { | ||
collection: format!("{NS}.membership"), | ||
rkey: did_rkey(member), | ||
crates/group-host/src/lib.rs+40−0
| @@ -6,6 +6,7 @@ | ||
pub mod api; | ||
pub mod authority; | ||
pub mod authority_api; | ||
pub mod authorization; | ||
pub mod blobs; | ||
pub mod config; | ||
pub mod firehose; | ||
| @@ -22,6 +23,11 @@ pub mod identity; | ||
pub mod index; | ||
pub mod index_api; | ||
pub mod lifecycle; | ||
pub mod oauth; | ||
pub mod oauth_clients; | ||
pub mod oauth_dpop; | ||
pub mod oauth_scope; | ||
pub mod oauth_store; | ||
pub mod plc; | ||
pub mod rbac; | ||
pub mod repo; | ||
| @@ -61,6 +67,8 @@ pub struct Host { | ||
/// The spaces the index is to read, and its wake. | ||
indexing: std::sync::Mutex<std::collections::BTreeSet<String>>, | ||
index_wake: tokio::sync::Notify, | ||
/// The OAuth clients' metadata, as read. | ||
pub(crate) clients: oauth_clients::Clients, | ||
} | ||
| ||
impl Host { | ||
| @@ -86,6 +94,7 @@ impl Host { | ||
http: client(), | ||
indexing: Default::default(), | ||
index_wake: Default::default(), | ||
clients: Default::default(), | ||
}) | ||
} | ||
} | ||
| @@ -302,12 +311,43 @@ pub fn router(host: Arc<Host>) -> Router { | ||
"/xrpc/com.atproto.managedspace.checkUserAccess", | ||
get(group_invites::check_user_access), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.getAuthorization", | ||
get(authorization::get_authorization), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.approveAuthorization", | ||
post(authorization::approve_authorization), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.declineAuthorization", | ||
post(authorization::decline_authorization), | ||
) | ||
.route("/oauth/authorize", get(oauth::authorize)) | ||
.merge(oauth_routes()) | ||
.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)) | ||
.with_state(host) | ||
} | ||
| ||
/// The OAuth endpoints an app reaches from a browser, open to any origin. | ||
fn oauth_routes() -> Router<Arc<Host>> { | ||
Router::new() | ||
.route( | ||
"/.well-known/oauth-authorization-server", | ||
get(oauth::server_metadata), | ||
) | ||
.route( | ||
"/.well-known/oauth-protected-resource", | ||
get(oauth::resource_metadata), | ||
) | ||
.route("/oauth/par", post(oauth::par)) | ||
.route("/oauth/token", post(oauth::token)) | ||
.route("/oauth/revoke", post(oauth::revoke)) | ||
.layer(axum::middleware::from_fn(oauth::cors)) | ||
} | ||
| ||
/// That the host is up, and which build it is. | ||
async fn health() -> Json<Value> { | ||
Json(json!({ "version": env!("CARGO_PKG_VERSION") })) | ||
crates/group-host/src/oauth.rsnew+549−0
549 lines changed: not loaded until asked for.
crates/group-host/src/oauth_clients.rsnew+373−0
crates/group-host/src/oauth_dpop.rsnew+117−0
crates/group-host/src/oauth_scope.rsnew+385−0
crates/group-host/src/oauth_store.rsnew+226−0
crates/group-host/src/store.rs+31−1
crates/group-host/tests/common/mod.rs+15−0
crates/group-host/tests/common/oauth.rsnew+243−0
crates/group-host/tests/authorization.rsnew+371−0
crates/group-host/tests/config.rs+7−0
crates/group-host/tests/oauth.rsnew+495−0
495 lines changed: not loaded until asked for.
crates/group-host/tests/oauth_clients.rsnew+635−0
635 lines changed: not loaded until asked for.
crates/group-host/tests/oauth_scope.rsnew+416−0
416 lines changed: not loaded until asked for.