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

The host reads DPoP proofs, PKCE, did:webs and AT URIs with atproto 0.4.1

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:atproto/0.4.1
.changeset/atproto-0-4-1.mdnew+7−0
@@ -0,0 +1,7 @@
---
default: patch
---
# DPoP proofs, PKCE, did:webs and AT URIs are read by atproto 0.4.1
The host checks DPoP proofs, PKCE verifiers and challenges, `did:web`s and AT URIs with the `atproto` crate's own, as the reference implementation does. A DPoP proof with an `ath` sent with no access token, as to `/oauth/par` or `/oauth/token`, is now refused (`invalid_dpop_proof`), where before its `ath` went unread. A pushed authorization request whose `code_challenge` is not 43 to 128 unreserved characters is refused there, rather than at the token endpoint. A `PUBLIC_URL` whose host is no hostname, with a port if any, is refused at start unless `SERVICE_DID` is set, and `atgrp` refuses an `ATGRP_HOST` or `--to` address whose did:web it cannot make, unless `ATGRP_HOST_DID` or `--to-did` names one.
crates/atgrp/src/lib.rs+23−26
@@ -12,9 +12,9 @@
//! host for a group token (`getGroupAuth`), bound to a DPoP key of its own.
use anyhow::{Context, Result, anyhow, bail};
use atproto::jose;
use atproto::keys::{Curve, Keypair};
use atproto::space::{SPACE_URI_PREFIX, SpaceRef};
use atproto::space::{SPACE_URI_PREFIX, SpaceRecordUri, SpaceRef};
use atproto::{did, dpop};
use group_host_mcp::{Plan, Tool};
use serde_json::{Value, json};
use std::collections::HashMap;
@@ -134,8 +134,8 @@ account
pub struct Env {
/// The host, `ATGRP_HOST`.
pub host: String,
/// Its DID, `ATGRP_HOST_DID`.
pub host_did: String,
/// Its DID, `ATGRP_HOST_DID`: by default the did:web of its address.
pub host_did: Option<String>,
/// The PDS the person signs in at, `PDS_URL`.
pub pds: String,
/// The person, `ATGRP_AS`, and their password,
@@ -150,12 +150,12 @@ pub struct Env {
}
/// The did:web a host at `url` is by default, as the host names itself.
pub fn did_web(url: &str) -> String {
pub fn did_web(url: &str) -> Result<String> {
let host = url
.trim_start_matches("https://")
.trim_start_matches("http://")
.trim_end_matches('/');
format!("did:web:{}", host.replace(':', "%3A"))
Ok(did::web(host)?)
crates/atgrp/src/lib.rsline 158
review.knotless.dev

did::web(host) replaces the old replace(':', "%3A"). The failing atgrp test (a 127.0.0.1:1 host) gets a 400 aud must be a valid atproto DID from the PDS, so check what did::web yields for a host with a port or an IP, and whether the host and PDS accept it.

}
impl Env {
@@ -163,7 +163,7 @@ impl Env {
pub fn from(var: impl Fn(&str) -> Option<String>) -> Env {
let host = var("ATGRP_HOST").unwrap_or_else(|| "http://localhost:2600".into());
let host = host.trim_end_matches('/').to_string();
let host_did = var("ATGRP_HOST_DID").unwrap_or_else(|| did_web(&host));
let host_did = var("ATGRP_HOST_DID");
let pds = var("PDS_URL").unwrap_or_else(|| "http://localhost:2583".into());
let invite = var("ATGRP_SEED_INVITE").unwrap_or_default();
Env {
@@ -415,20 +415,14 @@ impl<'a> GroupSession<'a> {
/// A DPoP proof of a POST to `nsid`, for `token` if it carries one.
fn proof(&self, nsid: &str, token: Option<&str>) -> String {
let mut claims = json!({
"jti": jose::random(12),
"htm": "POST",
"htu": format!("{}/xrpc/{nsid}", self.public),
"iat": atproto::time::now_millis() / 1000,
});
if let Some(nonce) = self.nonce.lock().expect("not poisoned").clone() {
claims["nonce"] = json!(nonce);
}
let url = format!("{}/xrpc/{nsid}", self.public);
let now = atproto::time::now_millis() as u64 / 1000;
let mut claims = dpop::Claims::new("POST", &url, now);
claims.nonce = self.nonce.lock().expect("not poisoned").clone();
if let Some(token) = token {
claims["ath"] = json!(jose::sha256(token));
claims = claims.token(token);
}
let header = json!({"typ": "dpop+jwt", "jwk": jose::jwk(&self.key.public())});
jose::sign(&self.key, &header, &claims)
dpop::sign(&self.key, &claims)
}
/// POSTs `body` to `nsid` with `authorization` and a fresh proof, once
@@ -589,9 +583,13 @@ async fn signed_in(env: &Env) -> Result<Client> {
/// Runs the command `args` name (without the program's own name), in
/// `env`, returning what it prints.
pub async fn run(args: &[String], env: &Env) -> Result<String> {
let did = env
.host_did
.clone()
.map_or_else(|| did_web(&env.host), Ok)?;
crates/atgrp/src/lib.rsline 589
review.knotless.dev

host_did is now built here, when the command runs, from env.host. A test or caller that changes env.host after Env::from gets a different DID than before, which fits the failing says_what_is_wrong_with_what_it_is_asked.

let host = Host {
url: env.host.clone(),
did: env.host_did.clone(),
did,
};
let words: Vec<&str> = args.iter().map(String::as_str).collect();
match words.as_slice() {
@@ -610,9 +608,10 @@ pub async fn run(args: &[String], env: &Env) -> Result<String> {
let [group] = a.take()?;
let to = a.flags.get("to").ok_or_else(usage)?.trim_end_matches('/');
let did = a.flags.get("to-did").map(|d| d.to_string());
let did = did.map_or_else(|| did_web(to), Ok)?;
let dest = Host {
url: to.to_string(),
did: did.unwrap_or_else(|| did_web(to)),
did,
};
migrate(&signed_in(env).await?, &host, &dest, group).await
}
@@ -832,10 +831,8 @@ async fn carry_out(me: &Client, host: &Host, group: &str, plan: Plan) -> Result<
let invites = listed["invites"].as_array().into_iter().flatten();
let mut waiting = invites.filter(|i| i["invitee"] == person.as_str());
let uri = waiting.next().map(|i| text(&i["uri"]).to_string());
let rkey = uri
.as_deref()
.and_then(|u| u.rsplit('/').next())
.unwrap_or_default();
let record = uri.as_deref().map(SpaceRecordUri::parse).transpose()?;
let rkey = record.map(|r| r.rkey).unwrap_or_default();
let inbox = inbox_of(&person);
let session = GroupSession::start(me, host, group, &inbox).await?;
let body =
@@ -938,7 +935,7 @@ async fn label(
let mut uris = Vec::new();
for r in ours {
let uri = text(&r["uri"]);
let rkey = uri.rsplit('/').next().unwrap_or_default();
let rkey = SpaceRecordUri::parse(uri)?.rkey;
let body = json!({"repo": group, "space": space, "collection": collection, "rkey": rkey});
session
.call("com.atproto.space.deleteRecord", &body)
crates/atgrp/tests/commands.rs+29−6
@@ -530,7 +530,7 @@ async fn switches_a_group_off_and_on_and_deletes_it() {
let me = me.await.unwrap();
let at = HostAt {
url: h.url.clone(),
did: did_web(&h.url),
did: did_web(&h.url).unwrap(),
};
let key = Keypair::generate(Curve::K256).public().did_key();
let body = json!({"group": did, "key": key});
@@ -604,6 +604,16 @@ async fn moves_a_group_to_another_host() {
let to = format!("{}/", b.url);
let said = fails(&bob, &["group", "move", "riders.groups.test", "--to", &to]).await;
assert!(said.contains("org.atgrp.internal.migratePrepare"), "{said}");
// An address with a path names no did:web to move to.
let elsewhere = [
"group",
"move",
"riders.groups.test",
"--to",
"https://b.test/x",
];
let said = fails(&alice, &elsewhere).await;
assert!(said.contains("not a host"), "{said}");
let said = ok(
&alice,
&[
@@ -897,6 +907,8 @@ async fn says_what_is_wrong_with_what_it_is_asked() {
);
let mut gone = alice.clone();
gone.host = "http://127.0.0.1:1".into();
// Named by the DID of the host it was, which a PDS signs a token for.
gone.host_did = Some(did_web(&alice.host).unwrap());
for args in [
&["group", "show", "x.test"][..],
&["group", "create", "x.groups.test"],
@@ -926,7 +938,10 @@ async fn answers_a_call_a_persons_pds_proxies() {
.unwrap();
let res = http
.get(format!("{}/xrpc/org.atgrp.internal.getViewer", n.pds))
.header("atproto-proxy", format!("{}#atgrp", did_web(&h.url)))
.header(
"atproto-proxy",
format!("{}#atgrp", did_web(&h.url).unwrap()),
)
.bearer_auth(session["accessJwt"].as_str().unwrap())
.send()
.await
@@ -937,14 +952,22 @@ async fn answers_a_call_a_persons_pds_proxies() {
assert_eq!(said["actor"]["did"], alice.did.as_str(), "{said}");
}
#[test]
fn reads_its_environment() {
#[tokio::test]
async fn reads_its_environment() {
let env = Env::from(|_| None);
assert_eq!(env.host, "http://localhost:2600");
assert_eq!(env.host_did, "did:web:localhost%3A2600");
assert_eq!(env.host_did, None);
assert_eq!(did_web(&env.host).unwrap(), "did:web:localhost%3A2600");
assert_eq!(env.pds, "http://localhost:2583");
assert!(env.handle.is_none() && env.seed_invite.is_empty());
assert_eq!(did_web("https://groups.example/"), "did:web:groups.example");
assert_eq!(
did_web("https://groups.example/").unwrap(),
"did:web:groups.example"
);
// An address with a path has no did:web, here or to move to.
let env = Env::from(|k| (k == "ATGRP_HOST").then(|| "https://a.example/x".into()));
let said = run(&["group".into(), "list".into()], &env).await;
assert!(said.unwrap_err().to_string().contains("not a host"));
}
#[tokio::test]
crates/group-host/src/account_move.rs+5−13
@@ -33,7 +33,7 @@ use crate::time::now_millis;
use crate::xrpc::XrpcError;
use anyhow::Result;
use atproto::space::SPACE_URI_PREFIX;
use atproto::{Curve, Keypair, did, jose};
use atproto::{Curve, Keypair, did, dpop};
use axum::Json;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
@@ -279,18 +279,10 @@ impl Host {
// Each asked for once: a nonce, and a renewed token.
let (mut nonce, mut nonced, mut renewed) = (None::<String>, false, false);
loop {
let mut claims = json!({
"jti": jose::random(12),
"htm": method.as_str(),
"htu": url,
"iat": now_millis() / 1000,
"ath": jose::sha256(&m.access),
});
if let Some(n) = &nonce {
claims["nonce"] = json!(n);
}
let header = json!({"typ": "dpop+jwt", "jwk": jose::jwk(&key.public())});
let proof = jose::sign(&key, &header, &claims);
let now = now_millis() as u64 / 1000;
let mut claims = dpop::Claims::new(method.as_str(), &url, now).token(&m.access);
claims.nonce = nonce.clone();
let proof = dpop::sign(&key, &claims);
let mut req = pinned.request(method.clone(), at.clone()).query(query);
req = req.header("authorization", format!("DPoP {}", m.access));
req = req.header("dpop", proof);
crates/group-host/src/actor_search.rs+4−11
@@ -12,6 +12,7 @@
use crate::Host;
use crate::api::Params;
use crate::xrpc::XrpcError;
use atproto::did;
use axum::Json;
use axum::extract::{Query, State};
use serde_json::{Value, json};
@@ -34,16 +35,6 @@ type Named = Arc<Vec<(String, String)>>;
#[derive(Default)]
pub struct Handles(tokio::sync::Mutex<Option<(Instant, Named)>>);
/// The handle an operation of the directory's export names, if it is one
/// that names one: a tombstone, or an update naming none, names none.
fn handle_of(op: &Value) -> Option<String> {
let aka = op["alsoKnownAs"].as_array().into_iter().flatten();
let named = aka
.filter_map(Value::as_str)
.find_map(|a| a.strip_prefix("at://"));
named.map(str::to_ascii_lowercase)
}
impl Host {
/// Every DID the directory names a handle for, and the handle: from the
/// last read, if it is less than [`KEPT_FOR`] old. A read that never
@@ -76,7 +67,9 @@ impl Host {
let live = lines.iter().filter(|e| e["nullified"] != true);
for entry in live {
let did = entry["did"].as_str().unwrap_or_default().to_string();
last.insert(did, handle_of(&entry["operation"]));
// A tombstone, or an update naming none, names none.
let handle = did::handle(&entry["operation"]).map(|h| h.to_ascii_lowercase());
last.insert(did, handle);
}
}
let handles: Vec<(String, String)> = last
crates/group-host/src/api.rs+1−1
@@ -327,7 +327,7 @@ pub async fn list_blobs(State(host): State<Arc<Host>>, Query(p): Query<Params>)
/// The host's own DID document, when its DID is a `did:web` of its address.
pub async fn did_json(State(host): State<Arc<Host>>) -> Result<Json<Value>, StatusCode> {
let did = &host.config.service_did;
if !did.starts_with("did:web:") {
if atproto::did::web_host(did).is_err() {
return Err(StatusCode::NOT_FOUND);
}
// Its groups' PDS, and the service an app reaches through a person's
crates/group-host/src/config.rs+5−2
@@ -3,6 +3,7 @@
//! `docs/reference/config.md`.
use anyhow::{Context, Result, bail};
use atproto::did;
use std::collections::BTreeMap;
use std::path::PathBuf;
@@ -107,8 +108,10 @@ impl Config {
else {
bail!("PUBLIC_URL is no origin: {public_url}");
};
let service_did =
var("SERVICE_DID").unwrap_or_else(|| format!("did:web:{}", host.replace(':', "%3A")));
let service_did = match var("SERVICE_DID") {
Some(did) => did,
None => did::web(host)?,
};
let handle_domain = var("HANDLE_DOMAIN").unwrap_or_else(|| ".test".into());
if !handle_domain.starts_with('.') {
bail!("HANDLE_DOMAIN starts with a dot: .{handle_domain}");
crates/group-host/src/console_login.rs+5−9
@@ -33,8 +33,8 @@ use crate::oauth_dpop::hmac;
use crate::store::Store;
use crate::time::now_millis;
use crate::xrpc::XrpcError;
use atproto::jose;
use atproto::{Curve, Keypair, did};
use atproto::{dpop, jose};
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{AppendHeaders, IntoResponse, Redirect, Response};
@@ -329,13 +329,9 @@ impl Host {
let mut nonce: Option<String> = None;
for _ in 0..2 {
let now = now_millis() / 1000;
let mut claims =
json!({"jti": jose::random(12), "htm": "POST", "htu": url, "iat": now});
if let Some(n) = &nonce {
claims["nonce"] = json!(n);
}
let header = json!({"typ": "dpop+jwt", "jwk": jose::jwk(&key.public())});
let proof = jose::sign(key, &header, &claims);
let mut claims = dpop::Claims::new("POST", url, now as u64);
claims.nonce = nonce.clone();
let proof = dpop::sign(key, &claims);
let id = self.console_client_id();
let assertion = jose::sign(
&self.console_key(),
@@ -503,7 +499,7 @@ pub(crate) async fn sign_in(
let key = Keypair::generate(Curve::P256);
let (verifier, state) = (jose::random(32), jose::random(16));
let callback = host.console_callback();
let challenge = jose::sha256(&verifier);
let challenge = dpop::pkce_challenge(&verifier);
let hint = match identifier {
Some(who) => ("login_hint", who.as_str()),
None => ("prompt", "create"),
crates/group-host/src/firehose.rs+6−21
@@ -7,12 +7,13 @@
use crate::Host;
use crate::store::Sequenced;
use crate::xrpc::XrpcError;
use atproto::stream::Frame;
use atproto::{Value, drisl};
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::extract::{Query, State};
use axum::http::StatusCode;
use axum::response::Response;
use std::collections::{BTreeMap, HashMap};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
@@ -45,35 +46,19 @@ pub async fn crawling(host: Arc<Host>, every: Duration) {
}
}
fn map<const N: usize>(fields: [(&str, Value); N]) -> Value {
Value::Map(
fields
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect(),
)
}
/// An event's frame: its header, then its body with its `seq`.
fn frame(event: &Sequenced) -> Vec<u8> {
let header = map([
("op", Value::Integer(1)),
("t", Value::String(event.kind.clone())),
]);
let body = drisl::decode(&event.body).expect("an event the host wrote");
let mut body = body.into_map().unwrap_or_default();
body.insert("seq".into(), Value::Integer(event.seq));
[drisl::encode(&header), drisl::encode(&Value::Map(body))].concat()
let t = event.kind.clone();
Frame::Message { t, body }.encode()
}
/// A refusal's frame.
fn refusal(error: &str, message: &str) -> Vec<u8> {
let header = map([("op", Value::Integer(-1))]);
let body = Value::Map(BTreeMap::from([
("error".into(), Value::String(error.into())),
("message".into(), Value::String(message.into())),
]));
[drisl::encode(&header), drisl::encode(&body)].concat()
let (error, message) = (error.into(), Some(message.into()));
Frame::Error { error, message }.encode()
}
pub async fn subscribe_repos(
crates/group-host/src/identity.rs+2−6
@@ -113,12 +113,8 @@ impl Resolver {
/// names, rather than one the host is set to read it at
/// (`DID_WEB_HOSTS`) or the PLC directory.
fn url(&self, did: &str) -> Result<(String, bool)> {
if let Some(host) = did.strip_prefix("did:web:") {
// A did:web of a host alone: one with a path names no host here.
if host.is_empty() || host.contains(':') {
bail!("{did} is not a did:web of a host");
}
let host = host.replace("%3A", ":");
if did.starts_with("did:web:") {
let host = did::web_host(did)?;
let (host, named) = match self.did_web_hosts.get(&host) {
Some(set) => (set, false),
None => (&host, true),
crates/group-host/src/import_space.rs+2−17
crates/group-host/src/mcp.rs+3−4
crates/group-host/src/moderation.rs+27−24
crates/group-host/src/oauth.rs+7−10
crates/group-host/src/oauth_dpop.rs+19−37
crates/group-host/tests/common/oauth.rs+7−14
crates/group-host/tests/config.rs+4−0
crates/group-host/tests/identity.rs+2−2
crates/group-host/tests/import.rs+3−4
crates/group-host/tests/oauth.rs+11−11
crates/group-host-mcp/src/lib.rs+2−2
crates/group-host-mcp/tests/protocol.rs+7−2
docs/design/signing-in.md+2−1
Cargo.lock+2−2
Cargo.toml+1−1