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

The host asks no host a DID or handle names at a private address

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:host/identity-guard
.changeset/identity-guard.mdnew+7−0
@@ -0,0 +1,7 @@
---
default: patch
---
# The host asks no host a DID or handle names at a private address
A `did:web`'s document, a handle's `/.well-known/atproto-did`, the PDS a DID document names (told of a write in a space or of revoked credentials, or read for a space's repo or file) and a group's own domain, when the host checks that it reaches it, are now asked only over `https`, at public addresses, with no redirect followed. These are the rules the host already held client metadata, syncer endpoints and proxied services to. Before, anyone controlling a `did:web` or a handle could point the host at an address on its own network. A host whose `PUBLIC_URL` is `http`, a network of test servers, asks them over `http` too, at any address, as before. So `DID_WEB_SCHEME=http` now reaches a `did:web`'s own host only from such a host. The addresses `DID_WEB_HOSTS` sets are the host's own settings, and are read as they are set.
crates/group-host/src/authority.rs+11−15
@@ -18,8 +18,8 @@
//! or a day has passed, as pds.js's `outbox.js` does.
use crate::Host;
use crate::guard::pinned_client;
use crate::index_api::capped;
use crate::oauth_clients::pinned_client;
use crate::rbac::Policy;
use crate::repo::invalid;
use crate::space::NOTIFY_REPO_UPDATE;
@@ -31,7 +31,7 @@ use anyhow::{Context, Result};
use atproto::service_auth::{self, Claims};
use atproto::space::SpaceRef;
use atproto::space_auth::{self, space_host_aud};
use atproto::{Value, did, jose, syntax};
use atproto::{Value, jose, syntax};
use axum::http::StatusCode;
use futures::future::join_all;
use futures::{StreamExt, stream};
@@ -658,11 +658,11 @@ impl Host {
jtis: &[String],
) -> Result<()> {
let doc = self.identity.document(writer).await?;
let pds = did::pds(&doc).context("the writer's document names no PDS")?;
let claims = self.claims(authority, writer, NOTIFY_REVOKED);
let res = self
.http
.post(format!("{pds}/xrpc/{NOTIFY_REVOKED}"))
let pds = self.at_pds(&doc, NOTIFY_REVOKED).await;
let (client, at) = pds.map_err(anyhow::Error::msg)?;
let res = client
.post(at)
.bearer_auth(service_auth::sign(signing, &claims))
.json(&json!({ "space": space, "credentials": jtis }))
.send()
@@ -710,8 +710,10 @@ impl Host {
Some(doc) => Ok(doc),
None => self.identity.document(&space.authority).await,
};
// An authority not found, or naming no PDS yet, may be found later.
let Some(pds) = doc.ok().as_ref().and_then(did::pds) else {
// An authority not found, or naming no PDS yet, or none to be
// asked ([`crate::guard`]), may be found later.
let doc = doc.unwrap_or_default();
let Ok((client, at)) = self.at_pds(&doc, NOTIFY_REPO_UPDATE).await else {
return Delivery::Retry;
};
let aud = space_host_aud(&space.authority);
@@ -725,13 +727,7 @@ impl Host {
"repoRev": notice.rev,
"data": Value::Bytes(notice.data.clone()).to_json(),
});
let sent = self
.http
.post(format!("{pds}/xrpc/{NOTIFY_REPO_UPDATE}"))
.bearer_auth(token)
.json(&body)
.send()
.await;
let sent = client.post(at).bearer_auth(token).json(&body).send().await;
delivery(sent)
}
crates/group-host/src/group_domain.rs+14−11
@@ -66,19 +66,22 @@ impl Host {
}
/// Whether `domain` answers as this host: its `describeServer` naming
/// this host's DID. Asked at the domain over https, or at
/// `DOMAIN_CHECK_AT` with the domain as its `Host`.
/// this host's DID. Asked at `DOMAIN_CHECK_AT`, as it is set, with the
/// domain as its `Host`; or else at the domain itself, a group's to
/// name, over https as [`crate::guard`] holds such a host.
async fn reaches(&self, domain: &str) -> bool {
let base = match &self.config.domain_check_at {
Some(at) => at.clone(),
None => format!("https://{domain}"),
let path = "/xrpc/com.atproto.server.describeServer";
let asked = match &self.config.domain_check_at {
Some(at) => Ok(self.http.get(format!("{at}{path}"))),
None => {
let pinned = self.pinned(&format!("https://{domain}{path}")).await;
pinned.map(|(client, at)| client.get(at))
}
};
let url = format!("{base}/xrpc/com.atproto.server.describeServer");
let asked = self
.http
.get(url)
.header(header::HOST, domain)
.timeout(LOOKUP);
let Ok(asked) = asked else {
return false;
};
let asked = asked.header(header::HOST, domain).timeout(LOOKUP);
let Ok(answer) = asked.send().await else {
return false;
};
crates/group-host/src/guard.rsnew+93−0
@@ -0,0 +1,93 @@
//! What a host that others' data names may be asked. A DID document names
//! whatever PDS and services it likes, a `did:web` whatever host, a handle
//! whatever name, and a client's metadata or a syncer's registration
//! whatever URL, and anyone can make the host read one; so such a host is
//! asked only on https, at public addresses, its connections pinned to the
//! addresses checked, and no redirect is followed ([`pinned_client`]). A
//! host on http itself (`PUBLIC_URL`), as on a network of test servers,
//! asks one on http too, at any address.
//!
//! The PLC directory, the handle resolvers, `DID_WEB_HOSTS`,
//! `DOMAIN_CHECK_AT` and the other services the host is configured with
//! are its settings, not others' data, and are asked as they are set.
use crate::Host;
use atproto::did;
use reqwest::{Client, Url};
use serde_json::Value;
use std::net::{IpAddr, SocketAddr};
/// A client for requests to `url`, an https URL at a public address (or
/// http at any address, with `http_here`, as on a network of test servers
/// whose host is on http itself), and the URL. Its connections go to the
/// addresses checked, so a name that resolves elsewhere a moment later is
/// not followed there, and it follows no redirect.
pub async fn pinned_client(url: &str, http_here: bool) -> Result<(Client, Url), String> {
let at = Url::parse(url).map_err(|_| format!("{url} is not a URL"))?;
let scheme_ok = at.scheme() == "https" || (http_here && at.scheme() == "http");
if !scheme_ok || at.fragment().is_some() || !at.username().is_empty() {
return Err(format!("{url} is not an https URL"));
}
let host = at.host_str().unwrap_or_default().to_string();
let port = at.port_or_known_default().unwrap_or_default();
let found = tokio::net::lookup_host(format!("{host}:{port}")).await;
let addrs: Vec<SocketAddr> = found.map_err(|e| format!("{url}: {e}"))?.collect();
if !http_here && !addrs.iter().all(|a| public(a.ip())) {
return Err(format!("{url} is not at a public address"));
}
let pinned = crate::client_builder()
.redirect(reqwest::redirect::Policy::none())
.resolve_to_addrs(host.trim_matches(['[', ']']), &addrs)
.build()
.expect("a client builds");
Ok((pinned, at))
}
/// Whether `ip` is on the public internet: not loopback, private,
/// link-local (a cloud's metadata service among them), shared, reserved,
/// documentation or multicast. An IPv6 address is public only as global
/// unicast (`2000::/3`), less documentation's: an address that carries an
/// IPv4 one (NAT64, IPv4-compatible) is not, but as IPv4-mapped, where it
/// is that address.
pub fn public(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => {
let [a, b, ..] = v4.octets();
!(v4.is_loopback()
|| v4.is_private()
|| v4.is_link_local()
|| v4.is_broadcast()
|| v4.is_documentation()
|| v4.is_unspecified()
|| v4.is_multicast()
|| a == 0
|| a >= 240
|| (a == 100 && (64..128).contains(&b))
|| (a == 192 && b == 0)
|| (a == 198 && (18..20).contains(&b)))
}
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
Some(v4) => public(IpAddr::V4(v4)),
None => {
let [s, t, ..] = v6.segments();
(s & 0xe000) == 0x2000 && !(s == 0x2001 && t == 0xdb8)
}
},
}
}
impl Host {
/// A client for requests to `url`, as [`pinned_client`] makes one, and
/// the URL: http allowed while this host is on http itself.
pub(crate) async fn pinned(&self, url: &str) -> Result<(Client, Url), String> {
pinned_client(url, self.config.public_url.starts_with("http://")).await
}
/// A client for calling `nsid` at the PDS `doc`, a DID document, names,
/// as [`Host::pinned`] makes one, and the call's URL: none where it
/// names no PDS, or one not to be asked.
pub(crate) async fn at_pds(&self, doc: &Value, nsid: &str) -> Result<(Client, Url), String> {
let pds = did::pds(doc).ok_or("the document names no PDS")?;
self.pinned(&format!("{pds}/xrpc/{nsid}")).await
}
}
crates/group-host/src/identity.rs+54−20
@@ -1,8 +1,14 @@
//! Other accounts' DID documents, as the host reads them to check what
//! they sign and to find their servers: a `did:plc`'s from the PLC
//! directory, a `did:web`'s from its host, each kept a few minutes.
use anyhow::{Context, Result, bail};
//!
//! The hosts identity data names, a `did:web`'s and a handle's own, are
//! held to [`crate::guard`]; the PLC directory, the addresses
//! `DID_WEB_HOSTS` sets and the handle resolvers set are asked as they are
//! set.
use crate::guard::pinned_client;
use anyhow::{Context, Error, Result, bail};
use atproto::{PublicKey, did};
use serde_json::Value;
use std::collections::{BTreeMap, HashMap};
@@ -33,13 +39,17 @@ async fn body(mut res: reqwest::Response) -> Result<Vec<u8>> {
pub const KEPT_AT_MOST: usize = 10_000;
/// How long a lookup at a host a name alone points to may take: a
/// handle's `/.well-known/atproto-did` may be anyone's, and never answer.
/// `did:web`'s host, or a handle's `/.well-known/atproto-did`, may be
/// anyone's, and never answer.
pub const LOOKUP: Duration = Duration::from_secs(3);
pub struct Resolver {
plc_url: String,
did_web_scheme: String,
did_web_hosts: BTreeMap<String, String>,
/// Whether a host identity data names may be asked on http, at any
/// address, as on a network of test servers ([`crate::guard`]).
http_here: bool,
http: reqwest::Client,
kept: Mutex<HashMap<String, (Instant, Value)>>,
kept_for: Duration,
@@ -65,8 +75,9 @@ impl Resolver {
plc_url: plc_url.trim_end_matches('/').to_string(),
did_web_scheme: did_web_scheme.to_string(),
did_web_hosts: BTreeMap::new(),
// A document or handle is at a host the caller names: one that
// redirects is not followed elsewhere.
http_here: false,
// The PLC directory and the handle resolvers are as set: one
// that redirects is not followed elsewhere all the same.
http: crate::client_builder()
.redirect(reqwest::redirect::Policy::none())
.build()
@@ -82,21 +93,40 @@ impl Resolver {
self
}
/// Where `did`'s document is read.
fn url(&self, did: &str) -> Result<String> {
/// This resolver, for a host on http itself (`PUBLIC_URL`), as on a
/// network of test servers: asking the hosts identity data names on
/// http too, at any address ([`crate::guard`]).
pub fn http_here(mut self, here: bool) -> Resolver {
self.http_here = here;
self
}
/// What a host identity data names answers at `url`, asked as
/// [`crate::guard`] holds it.
async fn guarded(&self, url: &str) -> Result<reqwest::Response> {
let pinned = pinned_client(url, self.http_here).await;
let (client, at) = pinned.map_err(Error::msg)?;
Ok(client.get(at).timeout(LOOKUP).send().await?)
}
/// Where `did`'s document is read, and whether at a host the DID
/// 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", ":");
let host = self.did_web_hosts.get(&host).unwrap_or(&host);
Ok(format!(
"{}://{host}/.well-known/did.json",
self.did_web_scheme
))
let (host, named) = match self.did_web_hosts.get(&host) {
Some(set) => (set, false),
None => (&host, true),
};
let scheme = &self.did_web_scheme;
Ok((format!("{scheme}://{host}/.well-known/did.json"), named))
} else if did.starts_with("did:plc:") {
Ok(format!("{}/{did}", self.plc_url))
Ok((format!("{}/{did}", self.plc_url), false))
} else {
bail!("{did}: not a did:plc or a did:web");
}
@@ -104,7 +134,11 @@ impl Resolver {
/// `did`'s document, read now, and kept.
pub async fn document(&self, did: &str) -> Result<Value> {
let res = self.http.get(self.url(did)?).send().await?;
let (url, named) = self.url(did)?;
let res = match named {
true => self.guarded(&url).await?,
false => self.http.get(url).send().await?,
};
let res = res.error_for_status().context(format!("resolving {did}"))?;
let doc: Value = serde_json::from_slice(&body(res).await?)?;
if doc.get("id").and_then(Value::as_str) != Some(did) {
@@ -129,7 +163,7 @@ impl Resolver {
let named = match resolver.strip_prefix("well-known:") {
Some(scheme) => {
let url = format!("{scheme}://{handle}/.well-known/atproto-did");
text(self.http.get(url).timeout(LOOKUP).send().await).await
text(self.guarded(&url).await.ok()).await
}
None => {
let url = format!("{resolver}/xrpc/com.atproto.identity.resolveHandle");
@@ -138,7 +172,7 @@ impl Resolver {
.get(url)
.query(&[("handle", handle)])
.timeout(LOOKUP);
let body = json(asked.send().await).await;
let body = json(asked.send().await.ok()).await;
body.and_then(|b| b["did"].as_str().map(String::from))
}
};
@@ -181,11 +215,11 @@ impl Resolver {
/// A response's text, if it answered with one no longer than a document
/// may be.
async fn text(res: reqwest::Result<reqwest::Response>) -> Option<String> {
String::from_utf8(body(res.ok()?.error_for_status().ok()?).await.ok()?).ok()
async fn text(res: Option<reqwest::Response>) -> Option<String> {
String::from_utf8(body(res?.error_for_status().ok()?).await.ok()?).ok()
}
/// A response's JSON, as [`text`] reads it.
async fn json(res: reqwest::Result<reqwest::Response>) -> Option<Value> {
serde_json::from_slice(&body(res.ok()?.error_for_status().ok()?).await.ok()?).ok()
async fn json(res: Option<reqwest::Response>) -> Option<Value> {
serde_json::from_slice(&body(res?.error_for_status().ok()?).await.ok()?).ok()
}
crates/group-host/src/index.rs+9−5
@@ -42,6 +42,8 @@ struct Remote {
space: String,
did: String,
pds: String,
/// For asking `pds`, held to [`crate::guard`].
client: reqwest::Client,
kem: String,
/// `Atproto-Space-Credential <jwt>`, the group's to its own space.
authorization: String,
@@ -66,10 +68,10 @@ impl Vouched {
}
impl Remote {
async fn ask(&self, host: &Host, method: &str, params: &[(&str, &str)]) -> Result<Vouched> {
async fn ask(&self, method: &str, params: &[(&str, &str)]) -> Result<Vouched> {
let (share, secret) = encapsulate(&self.kem)?;
let mut req = host
.http
let mut req = self
.client
.get(format!("{}/xrpc/com.atproto.space.{method}", self.pds))
.query(&[("space", self.space.as_str()), ("repo", self.did.as_str())])
.query(params)
@@ -218,6 +220,7 @@ impl Host {
async fn remote(&self, space: &str, authority: &str, did: &str) -> Result<Remote> {
let doc = self.identity.document(did).await?;
let pds = did::pds(&doc).context("a writer's document names no PDS")?;
let (client, _) = self.pinned(&pds).await.map_err(anyhow::Error::msg)?;
let kem = did::kem_key(&doc).context("a writer with no #atproto_kem key")?;
let key = Keypair::generate(Curve::P256);
let signing = self
@@ -239,6 +242,7 @@ impl Host {
space: space.into(),
did: did.into(),
pds,
client,
kem: kem.did_key(),
authorization: format!("Atproto-Space-Credential {credential}"),
key,
@@ -257,7 +261,7 @@ impl Host {
if let Some(c) = &cursor {
params.push(("cursor", c));
}
let answer = remote.ask(self, "listRepoOps", &params).await?;
let answer = remote.ask("listRepoOps", &params).await?;
let page: Json = serde_json::from_slice(&answer.body)?;
for op in page["ops"].as_array().context("a page with no ops")? {
let (collection, rkey) = (
@@ -325,7 +329,7 @@ impl Host {
/// Reads the repo whole, from its STAR archive, checked against the
/// commit it opens with.
async fn read_whole(&self, remote: &Remote) -> Result<()> {
let answer = remote.ask(self, "getRepo", &[]).await?;
let answer = remote.ask("getRepo", &[]).await?;
let (commit, records) = read_repo_star(
&answer.body,
&remote.space,
crates/group-host/src/index_api.rs+6−6
@@ -14,7 +14,7 @@ use crate::time::iso;
use crate::xrpc::XrpcError;
use atproto::space::SpaceRef;
use atproto::space_auth::{self, Kind, Make, sign_request};
use atproto::{Cid, Curve, Keypair, did, drisl};
use atproto::{Cid, Curve, Keypair, drisl};
use axum::Json;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode, header};
@@ -237,7 +237,7 @@ impl Host {
return Some((blob.mime_type, bytes));
}
let doc = self.identity.document(repo).await.ok()?;
let pds = did::pds(&doc)?;
let (client, at) = self.at_pds(&doc, "com.atproto.space.getBlob").await.ok()?;
let key = Keypair::generate(Curve::P256);
let signing = self.store.account(group).ok()??.signing;
let kid = key.public().did_key();
@@ -250,10 +250,10 @@ impl Host {
let now = crate::time::now_millis() as u64 / 1000;
let credential = space_auth::create(Kind::Credential, &make, &signing, now).ok()?;
let authorization = format!("Atproto-Space-Credential {credential}");
let mut req = self
.http
.get(format!("{pds}/xrpc/com.atproto.space.getBlob"))
.query(&[("space", space), ("repo", repo), ("cid", &cid.to_string())]);
let mut req =
client
.get(at)
.query(&[("space", space), ("repo", repo), ("cid", &cid.to_string())]);
for (k, v) in sign_request(&key, &authorization, repo).ok()? {
req = req.header(k, v);
}
crates/group-host/src/lib.rs+3−1
@@ -28,6 +28,7 @@ pub mod group_lifecycle;
pub mod group_members;
pub mod group_spaces;
pub mod group_tokens;
pub mod guard;
pub mod identity;
pub mod import;
pub mod import_space;
@@ -118,7 +119,8 @@ impl Host {
let stats = stats::Stats::open(&config.data_dir.join("stats.sqlite"))?;
let plc = plc::Directory::new(&config.plc_url);
let identity = identity::Resolver::new(&config.plc_url, &config.did_web_scheme)
.reading_at(&config.did_web_hosts);
.reading_at(&config.did_web_hosts)
.http_here(config.public_url.starts_with("http://"));
// A clock id of its own, so two hosts' revisions never collide.
let clock = atproto::tid::TidClock::new(u64::from(secrets.signing.public().to_sec1()[1]));
let limits = limits::Limiter::new(config.rate_limits);
crates/group-host/src/oauth_clients.rs+0−70
@@ -12,7 +12,6 @@ use atproto::jose;
use reqwest::Url;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
pub const CLIENT_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
@@ -184,69 +183,6 @@ fn validate(id: &str, metadata: Value) -> Result<Value, OAuthError> {
}
}
/// A client for requests to `url`, an https URL at a public address (or
/// http at any address, with `http_here`, as on a network of test servers
/// whose host is on http itself), and the URL. Its connections go to the
/// addresses checked, so a name that resolves elsewhere a moment later is
/// not followed there, and it follows no redirect.
pub(crate) async fn pinned_client(
url: &str,
http_here: bool,
) -> Result<(reqwest::Client, Url), String> {
let at = Url::parse(url).map_err(|_| format!("{url} is not a URL"))?;
let scheme_ok = at.scheme() == "https" || (http_here && at.scheme() == "http");
if !scheme_ok || at.fragment().is_some() || !at.username().is_empty() {
return Err(format!("{url} is not an https URL"));
}
let host = at.host_str().unwrap_or_default().to_string();
let port = at.port_or_known_default().unwrap_or_default();
let found = tokio::net::lookup_host(format!("{host}:{port}")).await;
let addrs: Vec<SocketAddr> = found.map_err(|e| format!("{url}: {e}"))?.collect();
if !http_here && !addrs.iter().all(|a| public(a.ip())) {
return Err(format!("{url} is not at a public address"));
}
let pinned = crate::client_builder()
.redirect(reqwest::redirect::Policy::none())
.resolve_to_addrs(host.trim_matches(['[', ']']), &addrs)
.build()
.expect("a client builds");
Ok((pinned, at))
}
/// Whether `ip` is on the public internet: not loopback, private,
/// link-local (a cloud's metadata service among them), shared, reserved,
/// documentation or multicast.
pub fn public(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => {
let [a, b, ..] = v4.octets();
!(v4.is_loopback()
|| v4.is_private()
|| v4.is_link_local()
|| v4.is_broadcast()
|| v4.is_documentation()
|| v4.is_unspecified()
|| v4.is_multicast()
|| a == 0
|| a >= 240
|| (a == 100 && (64..128).contains(&b))
|| (a == 192 && b == 0)
|| (a == 198 && (18..20).contains(&b)))
}
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
Some(v4) => public(IpAddr::V4(v4)),
None => {
!(v6.is_loopback()
|| v6.is_unspecified()
|| v6.is_multicast()
|| v6.is_unique_local()
|| v6.is_unicast_link_local()
|| v6.segments()[0] == 0x2001 && v6.segments()[1] == 0xdb8)
}
},
}
}
/// Whether a later request authenticates as the first did: the same
/// method, and for a confidential client, the same key, by its thumbprint.
pub fn same_auth(first: &Value, now: &Value) -> bool {
@@ -304,12 +240,6 @@ impl Host {
})
}
/// A client for requests to `url`, as [`pinned_client`] makes one, and
/// the URL: http allowed while this host is on http itself.
pub(crate) async fn pinned(&self, url: &str) -> Result<(reqwest::Client, Url), String> {
pinned_client(url, self.config.public_url.starts_with("http://")).await
}
/// The JSON object at `url`, fetched by a [`Host::pinned`] client.
pub(crate) async fn public_json(&self, url: &str, what: &str) -> Result<Value, String> {
let unreadable = |why: String| format!("{what} at {url}: {why}");
crates/group-host/tests/authority.rs+2−1
@@ -1030,7 +1030,8 @@ fn waits_longer_between_tries_up_to_an_hour() {
#[tokio::test]
async fn owes_an_authority_word_of_a_write_until_it_lands() {
let h = start(&[], false).await;
// On http, as on a network of test servers: the PDS is on this machine.
let h = start(&[("PUBLIC_URL", "http://host.test")], false).await;
let group = h.host.create_account(RIDERS).await.unwrap();
let elsewhere = authority(&h, true, true).await;
let space = format!("at:space/{}/{KIND}/self", elsewhere.did);
crates/group-host/tests/domain.rs+18−0
crates/group-host/tests/identity.rs+158−24
crates/group-host/tests/index.rs+4−2
crates/group-host/tests/interop.rs+7−1
crates/group-host/tests/invites.rs+2−1
crates/group-host/tests/members.rs+3−1
crates/group-host/tests/oauth_clients.rs+0−32
crates/group-host/tests/spaces.rs+31−4
docs/design/groups.md+7−3
docs/design/spaces.md+11−2
docs/reference/config.md+3−3