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

atproto: PLC operations, DID documents and service-auth tokens

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:atproto/identity
crates/atproto/src/did.rsnew+92−0
@@ -0,0 +1,92 @@
//! DID documents, read as knotless reads them: the services and keys an
//! account's document names, each found by the end of its id, as a
//! document may write `#atproto` or `did:…#atproto`.
use crate::keys::{KeyError, PublicKey};
use serde_json::{Value, json};
/// The endpoint of the service whose id ends in `id`, as `#atproto_pds`,
/// with no trailing slash.
pub fn service(doc: &Value, id: &str) -> Option<String> {
doc.get("service")?
.as_array()?
.iter()
.find(|s| {
s.get("id")
.and_then(Value::as_str)
.is_some_and(|i| i.ends_with(id))
})?
.get("serviceEndpoint")?
.as_str()
.map(|s| s.trim_end_matches('/').to_string())
}
/// The account's PDS.
pub fn pds(doc: &Value) -> Option<String> {
service(doc, "#atproto_pds")
}
/// The key of the verification method whose id ends in `id`.
pub fn method_key(doc: &Value, id: &str) -> Result<PublicKey, KeyError> {
let method = doc
.get("verificationMethod")
.and_then(Value::as_array)
.and_then(|methods| {
methods.iter().find(|m| {
m.get("id")
.and_then(Value::as_str)
.is_some_and(|i| i.ends_with(id))
})
})
.ok_or(KeyError("the document names no such key"))?;
let kind = method
.get("type")
.and_then(Value::as_str)
.unwrap_or_default();
let multibase = method.get("publicKeyMultibase").and_then(Value::as_str);
PublicKey::from_method(
kind,
multibase.ok_or(KeyError("a key with no publicKeyMultibase"))?,
)
}
/// The key the account's repo, and its service tokens, are signed with.
pub fn signing_key(doc: &Value) -> Result<PublicKey, KeyError> {
method_key(doc, "#atproto")
}
/// The key a space's syncing service agrees a secret with (the space
/// alpha's `#atproto_kem`).
pub fn kem_key(doc: &Value) -> Result<PublicKey, KeyError> {
method_key(doc, "#atproto_kem")
}
/// The handle the document claims, its first `at://`. Whether the handle
/// claims the DID back is for whoever resolves it.
pub fn handle(doc: &Value) -> Option<String> {
doc.get("alsoKnownAs")?
.as_array()?
.iter()
.find_map(|a| a.as_str()?.strip_prefix("at://"))
.map(String::from)
}
/// The document of a service's own `did:web`, `did`, at `endpoint`, with
/// `key` its signing key, and its services, each an id (`#…`), a type and
/// an endpoint.
pub fn service_document(did: &str, key: &PublicKey, services: &[(&str, &str, &str)]) -> Value {
json!({
"@context": ["https://www.w3.org/ns/did/v1", "https://w3id.org/security/multikey/v1"],
"id": did,
"verificationMethod": [{
"id": format!("{did}#atproto"),
"type": "Multikey",
"controller": did,
"publicKeyMultibase": key.to_multibase(),
}],
"service": services
.iter()
.map(|(id, kind, endpoint)| json!({"id": id, "type": kind, "serviceEndpoint": endpoint}))
.collect::<Vec<_>>(),
})
}
crates/atproto/src/lib.rs+3−0
@@ -11,9 +11,12 @@ pub mod base32;
pub mod car;
pub mod cid;
pub mod commit;
pub mod did;
pub mod drisl;
pub mod keys;
pub mod mst;
pub mod plc;
pub mod service_auth;
pub mod syntax;
pub mod tid;
crates/atproto/src/plc.rsnew+275−0
@@ -0,0 +1,275 @@
//! PLC operations: how a `did:plc` is made, and how its document changes.
//! Each operation names the keys that may sign the next (its rotation
//! keys), the key the account's repo is signed with, its handle and its
//! PDS, and is signed by one of the rotation keys of the operation before
//! it. The DID is a hash of the first.
use crate::base32;
use crate::cid::Cid;
use crate::drisl::{self, Value};
use crate::keys::{Keypair, PublicKey};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlcError(pub String);
impl fmt::Display for PlcError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for PlcError {}
fn err<T>(what: impl Into<String>) -> Result<T, PlcError> {
Err(PlcError(what.into()))
}
/// A service an account's document names, such as its PDS.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Service {
/// Its type, as `AtprotoPersonalDataServer`.
pub kind: String,
pub endpoint: String,
}
/// What a `did:plc` document says, as one operation sets it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Op {
/// The `did:key`s that may sign the next operation, the first ranked
/// highest.
pub rotation_keys: Vec<String>,
/// Keys by name, as `atproto`, the repo's signing key, each a `did:key`.
pub verification_methods: BTreeMap<String, String>,
/// As `at://<handle>`.
pub also_known_as: Vec<String>,
/// Services by name, as `atproto_pds`.
pub services: BTreeMap<String, Service>,
}
impl Op {
/// An account at `handle` whose repo is signed with `signing` and
/// held at `pds`, its operations signed with `rotation_keys`.
pub fn atproto(signing: &str, rotation_keys: &[String], handle: &str, pds: &str) -> Op {
Op {
rotation_keys: rotation_keys.to_vec(),
verification_methods: BTreeMap::from([("atproto".into(), signing.into())]),
also_known_as: vec![format!("at://{handle}")],
services: BTreeMap::from([(
"atproto_pds".into(),
Service {
kind: "AtprotoPersonalDataServer".into(),
endpoint: pds.into(),
},
)]),
}
}
/// The handle the document names, its first `at://`.
pub fn handle(&self) -> Option<&str> {
self.also_known_as
.iter()
.find_map(|a| a.strip_prefix("at://"))
}
/// This operation after `prev` (none for the first), signed with
/// `key`, which must be one of the rotation keys before it.
pub fn sign(self, prev: Option<Cid>, key: &Keypair) -> Signed {
let mut signed = Signed::Update {
op: self,
prev,
sig: Vec::new(),
};
let sig = key.sign(&drisl::encode(&signed.unsigned())).to_vec();
if let Signed::Update { sig: s, .. } = &mut signed {
*s = sig;
}
signed
}
}
/// An operation as it is published.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Signed {
Update {
op: Op,
prev: Option<Cid>,
sig: Vec<u8>,
},
/// The end of the DID: nothing after it.
Tombstone { prev: Cid, sig: Vec<u8> },
}
/// The tombstone after `prev`, signed with `key`.
pub fn tombstone(prev: Cid, key: &Keypair) -> Signed {
let mut signed = Signed::Tombstone {
prev,
sig: Vec::new(),
};
let sig = key.sign(&drisl::encode(&signed.unsigned())).to_vec();
if let Signed::Tombstone { sig: s, .. } = &mut signed {
*s = sig;
}
signed
}
fn strings(items: &[String]) -> Value {
Value::Array(items.iter().map(|s| Value::String(s.clone())).collect())
}
impl Signed {
/// The operation without its signature: what is signed.
fn unsigned(&self) -> Value {
Value::Map(self.fields())
}
fn fields(&self) -> BTreeMap<String, Value> {
let s = |t: &str| Value::String(t.into());
// A CID is text in an operation, not a DRISL link: the directory
// signs and hashes it so.
let link = |c: &Option<Cid>| c.map_or(Value::Null, |c| Value::String(c.to_string()));
match self {
Signed::Update { op, prev, .. } => BTreeMap::from([
("type".into(), s("plc_operation")),
("rotationKeys".into(), strings(&op.rotation_keys)),
(
"verificationMethods".into(),
Value::Map(
op.verification_methods
.iter()
.map(|(k, v)| (k.clone(), s(v)))
.collect(),
),
),
("alsoKnownAs".into(), strings(&op.also_known_as)),
(
"services".into(),
Value::Map(
op.services
.iter()
.map(|(k, v)| {
let service = BTreeMap::from([
("type".into(), s(&v.kind)),
("endpoint".into(), s(&v.endpoint)),
]);
(k.clone(), Value::Map(service))
})
.collect(),
),
),
("prev".into(), link(prev)),
]),
Signed::Tombstone { prev, .. } => BTreeMap::from([
("type".into(), s("plc_tombstone")),
("prev".into(), link(&Some(*prev))),
]),
}
}
fn sig(&self) -> &[u8] {
match self {
Signed::Update { sig, .. } | Signed::Tombstone { sig, .. } => sig,
}
}
/// The operation with its signature, as DRISL.
fn value(&self) -> Value {
let mut map = self.fields();
map.insert(
"sig".into(),
Value::String(URL_SAFE_NO_PAD.encode(self.sig())),
);
Value::Map(map)
}
/// The CID of the signed operation: what the next one's `prev` names.
pub fn cid(&self) -> Cid {
drisl::cid(&self.value())
}
/// The DID this operation makes, as the first of its DID's.
pub fn did(&self) -> String {
let hash = Sha256::digest(drisl::encode(&self.value()));
let text = base32::encode(base32::LOWER, &hash);
format!("did:plc:{}", &text[..24])
}
pub fn prev(&self) -> Option<Cid> {
match self {
Signed::Update { prev, .. } => *prev,
Signed::Tombstone { prev, .. } => Some(*prev),
}
}
/// Which of `rotation_keys` (`did:key`s) signed it, by its place there.
pub fn signed_by(&self, rotation_keys: &[String]) -> Option<usize> {
let unsigned = drisl::encode(&self.unsigned());
rotation_keys.iter().position(|k| {
PublicKey::from_did_key(k).is_ok_and(|key| key.verify(&unsigned, self.sig()))
})
}
/// The operation as the PLC directory takes it.
pub fn to_json(&self) -> serde_json::Value {
self.value().to_json()
}
/// An operation as the PLC directory gives it.
pub fn from_json(json: &serde_json::Value) -> Result<Signed, PlcError> {
use serde_json::Value as J;
let text = |k: &str| json.get(k).and_then(J::as_str);
let Some(sig) = text("sig").and_then(|s| URL_SAFE_NO_PAD.decode(s).ok()) else {
return err("an operation's sig is base64url");
};
let prev = match json.get("prev") {
Some(J::String(p)) => Some(Cid::parse(p).or_else(|e| err(format!("prev: {e}")))?),
_ => None,
};
let list = |k: &str| -> Result<Vec<String>, PlcError> {
let items = json.get(k).and_then(J::as_array);
let items = items.map(|a| a.iter().map(|v| v.as_str().map(String::from)).collect());
items
.flatten()
.ok_or_else(|| PlcError(format!("{k} is a list of text")))
};
let map = |k: &str| json.get(k).and_then(J::as_object);
match text("type") {
Some("plc_tombstone") => match prev {
Some(prev) => Ok(Signed::Tombstone { prev, sig }),
None => err("a tombstone names the operation it ends"),
},
Some("plc_operation") => {
let methods = map("verificationMethods").map(|m| {
m.iter()
.map(|(k, v)| Some((k.clone(), v.as_str()?.to_string())))
.collect::<Option<BTreeMap<_, _>>>()
});
let services = map("services").map(|m| {
m.iter()
.map(|(k, v)| {
let kind = v.get("type")?.as_str()?.to_string();
let endpoint = v.get("endpoint")?.as_str()?.to_string();
Some((k.clone(), Service { kind, endpoint }))
})
.collect::<Option<BTreeMap<_, _>>>()
});
let (Some(Some(verification_methods)), Some(Some(services))) = (methods, services)
else {
return err("an operation's keys and services are maps of text");
};
let op = Op {
rotation_keys: list("rotationKeys")?,
verification_methods,
also_known_as: list("alsoKnownAs")?,
services,
};
Ok(Signed::Update { op, prev, sig })
}
_ => err("not a plc_operation or plc_tombstone"),
}
}
}
crates/atproto/src/service_auth.rsnew+143−0
@@ -0,0 +1,143 @@
//! Service auth: the short-lived JWT one server hands another to say who
//! is asking (`iss`), of whom (`aud`), and for which method (`lxm`),
//! signed with the asker's signing key. As the reference PDS writes them,
//! and as knotless checks them.
use crate::keys::{Keypair, PublicKey};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde_json::{Value, json};
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthError(pub String);
impl fmt::Display for AuthError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for AuthError {}
fn err<T>(what: impl Into<String>) -> Result<T, AuthError> {
Err(AuthError(what.into()))
}
/// What a token says.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Claims {
/// Who asks: a DID, with a service's `#fragment` if a service asks.
pub iss: String,
/// Whom it is for: a DID, or a DID and its service's `#fragment`.
pub aud: String,
/// When it lapses, in seconds since 1970.
pub exp: u64,
pub iat: Option<u64>,
/// The method it may call.
pub lxm: Option<String>,
pub jti: Option<String>,
}
impl Claims {
fn json(&self) -> Value {
let mut claims = json!({"iss": self.iss, "aud": self.aud, "exp": self.exp});
for (k, v) in [
("iat", self.iat.map(Value::from)),
("lxm", self.lxm.clone().map(Value::from)),
("jti", self.jti.clone().map(Value::from)),
] {
if let Some(v) = v {
claims[k] = v;
}
}
claims
}
/// The account asking: `iss` without a service's `#fragment`.
pub fn account(&self) -> &str {
self.iss.split('#').next().unwrap_or_default()
}
}
/// `claims` signed with `key`, as a compact JWT.
pub fn sign(key: &Keypair, claims: &Claims) -> String {
let header = json!({"typ": "JWT", "alg": key.curve().alg()});
let body = format!(
"{}.{}",
URL_SAFE_NO_PAD.encode(header.to_string()),
URL_SAFE_NO_PAD.encode(claims.json().to_string())
);
format!(
"{body}.{}",
URL_SAFE_NO_PAD.encode(key.sign(body.as_bytes()))
)
}
/// A token's header and claims, unchecked: to find whose key to check
/// it with.
pub fn parts(token: &str) -> Result<(Value, Claims), AuthError> {
let mut parts = token.split('.');
let mut decode = |what: &str| -> Result<Value, AuthError> {
let part = parts.next().unwrap_or_default();
let bytes = URL_SAFE_NO_PAD
.decode(part)
.or_else(|_| err(format!("bad base64 in a JWT {what}")))?;
serde_json::from_slice(&bytes).or_else(|_| err(format!("bad JSON in a JWT {what}")))
};
let (header, claims) = (decode("header")?, decode("payload")?);
let text = |k: &str| claims.get(k).and_then(Value::as_str).map(String::from);
let (Some(iss), Some(aud), Some(exp)) = (
text("iss"),
text("aud"),
claims.get("exp").and_then(Value::as_u64),
) else {
return err("a JWT without iss, aud and exp");
};
let iat = claims.get("iat").and_then(Value::as_u64);
Ok((
header,
Claims {
iss,
aud,
exp,
iat,
lxm: text("lxm"),
jti: text("jti"),
},
))
}
/// The claims of `token`, once its signature is `key`'s, its `alg` the
/// key's, and it has not lapsed by `now` (seconds since 1970).
pub fn verify(token: &str, key: &PublicKey, now: u64) -> Result<Claims, AuthError> {
let (header, claims) = parts(token)?;
if header.get("alg").and_then(Value::as_str) != Some(key.curve().alg()) {
return err(format!(
"a JWT signed with {} where {} was expected",
header["alg"],
key.curve().alg()
));
}
// `parts` read a header and payload, so there is a dot to split at.
let (signed, sig) = token.rsplit_once('.').unwrap_or((token, ""));
let sig = URL_SAFE_NO_PAD.decode(sig).unwrap_or_default();
if !key.verify(signed.as_bytes(), &sig) {
return err("bad signature");
}
if claims.exp <= now {
return err("an expired JWT");
}
Ok(claims)
}
/// Whether `claims` are for `aud` and `lxm`, answering who asks.
pub fn check<'a>(claims: &'a Claims, aud: &str, lxm: &str) -> Result<&'a str, AuthError> {
if claims.aud != aud {
return err(format!("a token for {}, not {aud}", claims.aud));
}
if claims.lxm.as_deref() != Some(lxm) {
return err(format!("a token for {:?}, not {lxm}", claims.lxm));
}
Ok(claims.account())
}
crates/atproto/tests/reference/identity.jsonnew+209−0
@@ -0,0 +1,209 @@
{
"keys": {
"rotation": "a1b2c3d4e5f60718293a4b5c6d7e8f90112233445566778899aabbccddeeff01",
"signing": "0f1e2d3c4b5a69788796a5b4c3d2e1f00112233445566778899aabbccddeeff0",
"p256Rotation": "1111111111111111111111111111111111111111111111111111111111111111"
},
"plc": [
{
"name": "k256 rotation",
"did": "did:plc:72hi64h42xani53ud76pudoq",
"genesis": {
"type": "plc_operation",
"verificationMethods": {
"atproto": "did:key:zQ3shQozXcnz15G51JC3Gm4qugNhwTcSg8fTg4YRr6XmHkSVe"
},
"rotationKeys": [
"did:key:zQ3shZ1gFKSNgByRCSLFZr5ZDmv9NybGo7CANHgynHf8erpUm"
],
"alsoKnownAs": [
"at://riders.groups.example.com"
],
"services": {
"atproto_pds": {
"type": "AtprotoPersonalDataServer",
"endpoint": "https://groups.example.com"
}
},
"prev": null,
"sig": "cRql1fq_raTriUyC8HA6fM_MOswflZvcBMR9ZDB0V7ImbwoP6ZZ9p9US8lz3UqA7yOx27JZESsXk6X9YWx7NjA"
},
"genesisCid": "bafyreih6r2hxb7gvydkho5a77t5a3uaybtft7guai2eediy3uax3cpzgyi",
"updateHandle": {
"type": "plc_operation",
"verificationMethods": {
"atproto": "did:key:zQ3shQozXcnz15G51JC3Gm4qugNhwTcSg8fTg4YRr6XmHkSVe"
},
"rotationKeys": [
"did:key:zQ3shZ1gFKSNgByRCSLFZr5ZDmv9NybGo7CANHgynHf8erpUm"
],
"alsoKnownAs": [
"at://riders.example.org"
],
"services": {
"atproto_pds": {
"type": "AtprotoPersonalDataServer",
"endpoint": "https://groups.example.com"
}
},
"prev": "bafyreih6r2hxb7gvydkho5a77t5a3uaybtft7guai2eediy3uax3cpzgyi",
"sig": "Fenc4sTCQpaPCme_kiYxgKmaR6x81WkleuPzatRl2AhPLBAPlWyEQkMHqcbEC3znkY5RT9cBo_UAtJcl1yxv1w"
},
"updatePds": {
"type": "plc_operation",
"verificationMethods": {
"atproto": "did:key:zQ3shQozXcnz15G51JC3Gm4qugNhwTcSg8fTg4YRr6XmHkSVe"
},
"rotationKeys": [
"did:key:zQ3shZ1gFKSNgByRCSLFZr5ZDmv9NybGo7CANHgynHf8erpUm"
],
"alsoKnownAs": [
"at://riders.example.org"
],
"services": {
"atproto_pds": {
"type": "AtprotoPersonalDataServer",
"endpoint": "https://other.example.com"
}
},
"prev": "bafyreihbzmfzd6azxizw4eoq2dlddbknvfhrnga2d3nqtqskhxqxkpxp2u",
"sig": "ep-peC8OEA1I7c1j3tA_K8yGaBY4OxRgG1mLdvWf4j0mj3tmpVIqz006DLwbnVIeGY_9j9trFstyhdrPbL-tQg"
},
"tombstone": {
"type": "plc_tombstone",
"prev": "bafyreih3b6a4l23km3vkt7xqsnotcf3dwx3vs4uo7sjnx3s5xr3sei2sey",
"sig": "Hedu8V2O4zHRb8GaSMQu44u8qJ_RrmYZLIGNUWjxNCotcneIC_POR88zdwMhJnAGYNNdkjOmhW5k1q_M7jZ5_A"
},
"document": {
"@context": [
"https://www.w3.org/ns/did/v1",
"https://w3id.org/security/suites/secp256k1-2019/v1"
],
"id": "did:plc:72hi64h42xani53ud76pudoq",
"alsoKnownAs": [
"at://riders.groups.example.com"
],
"verificationMethod": [
{
"id": "#atproto",
"type": "EcdsaSecp256k1VerificationKey2019",
"controller": "did:plc:72hi64h42xani53ud76pudoq",
"publicKeyMultibase": "zNV22yK93yTWeWjFZvBAsrKEjrxCZWpybUEpZ8vWPkpcmtVnw4r5Ma3tiHz6ijbYSm2HH3RKrj1inPTp4AR5tcE2h"
}
],
"service": [
{
"id": "#atproto_pds",
"type": "AtprotoPersonalDataServer",
"serviceEndpoint": "https://groups.example.com"
}
]
}
},
{
"name": "p256 rotation, a second key",
"did": "did:plc:lljzktf3kl772n33xdstllj7",
"genesis": {
"type": "plc_operation",
"verificationMethods": {
"atproto": "did:key:zQ3shQozXcnz15G51JC3Gm4qugNhwTcSg8fTg4YRr6XmHkSVe"
},
"rotationKeys": [
"did:key:zDnaeQa8zprPhHA7Yuxcgc2Uh6XNQgaKjmFZE4EaA9fk5svmJ",
"did:key:zQ3shZ1gFKSNgByRCSLFZr5ZDmv9NybGo7CANHgynHf8erpUm"
],
"alsoKnownAs": [
"at://riders.groups.example.com"
],
"services": {
"atproto_pds": {
"type": "AtprotoPersonalDataServer",
"endpoint": "https://groups.example.com"
}
},
"prev": null,
"sig": "FMekhOt9IsnnB6JVSrlNRMKDvCikXY-wYQW0YheM9ytRWJGrP5su6NQ4Txah8gkLxkzEhPR4Uko4DKxlvdIWUw"
},
"genesisCid": "bafyreic22okuzo2s776to65y4u222pz6noqrluhxm3hxrwsmalo2u2urle",
"updateHandle": {
"type": "plc_operation",
"verificationMethods": {
"atproto": "did:key:zQ3shQozXcnz15G51JC3Gm4qugNhwTcSg8fTg4YRr6XmHkSVe"
},
"rotationKeys": [
"did:key:zDnaeQa8zprPhHA7Yuxcgc2Uh6XNQgaKjmFZE4EaA9fk5svmJ",
"did:key:zQ3shZ1gFKSNgByRCSLFZr5ZDmv9NybGo7CANHgynHf8erpUm"
],
"alsoKnownAs": [
"at://riders.example.org"
],
"services": {
"atproto_pds": {
"type": "AtprotoPersonalDataServer",
"endpoint": "https://groups.example.com"
}
},
"prev": "bafyreic22okuzo2s776to65y4u222pz6noqrluhxm3hxrwsmalo2u2urle",
"sig": "3DeNoKqbOqNZXLXLmTnS8HsCIBqKtmeERqJPUucI8MA4hBZ6UsqQfFYHTgQSyhbweKy9GcKfpxoliypFZA-Tzw"
},
"updatePds": {
"type": "plc_operation",
"verificationMethods": {
"atproto": "did:key:zQ3shQozXcnz15G51JC3Gm4qugNhwTcSg8fTg4YRr6XmHkSVe"
},
"rotationKeys": [
"did:key:zDnaeQa8zprPhHA7Yuxcgc2Uh6XNQgaKjmFZE4EaA9fk5svmJ",
"did:key:zQ3shZ1gFKSNgByRCSLFZr5ZDmv9NybGo7CANHgynHf8erpUm"
],
"alsoKnownAs": [
"at://riders.example.org"
],
"services": {
"atproto_pds": {
"type": "AtprotoPersonalDataServer",
"endpoint": "https://other.example.com"
}
},
"prev": "bafyreidouofaj3mad33qxzajxbbd7qc5zdcvyue2jfjdass2b5igp2sw5i",
"sig": "7dN_sYQt5By4NrZYeAEQnllKby1khPE6jcDER5mJux5i6HTacq4ki9Kc385A1QfL0Q_Zt1QBa31ycvusuStnSw"
},
"tombstone": {
"type": "plc_tombstone",
"prev": "bafyreiacz7l4shchkhqiqqkljh5c333kxci4owwrrgkad4t3r6aygxlx4e",
"sig": "KN45Pfo4abkXranAT60undn0LX6tfPVLHbgP_CfqKa5SlStJ11NuIDZI0VbyDEwho_J8Hn8MHuKdG7obq3B9dQ"
},
"document": {
"@context": [
"https://www.w3.org/ns/did/v1",
"https://w3id.org/security/suites/secp256k1-2019/v1"
],
"id": "did:plc:lljzktf3kl772n33xdstllj7",
"alsoKnownAs": [
"at://riders.groups.example.com"
],
"verificationMethod": [
{
"id": "#atproto",
"type": "EcdsaSecp256k1VerificationKey2019",
"controller": "did:plc:lljzktf3kl772n33xdstllj7",
"publicKeyMultibase": "zNV22yK93yTWeWjFZvBAsrKEjrxCZWpybUEpZ8vWPkpcmtVnw4r5Ma3tiHz6ijbYSm2HH3RKrj1inPTp4AR5tcE2h"
}
],
"service": [
{
"id": "#atproto_pds",
"type": "AtprotoPersonalDataServer",
"serviceEndpoint": "https://groups.example.com"
}
]
}
}
],
"serviceJwt": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJpYXQiOjE3OTM3MzYzMDAsImlzcyI6ImRpZDpwbGM6NzJoaTY0aDQyeGFuaTUzdWQ3NnB1ZG9xIiwiYXVkIjoiZGlkOndlYjpncm91cHMuZXhhbXBsZS5jb20iLCJleHAiOjQxMDI0NDQ4MDAsImx4bSI6ImZ5aS5vcGVuc29jaWFsLmdldEdyb3VwIiwianRpIjoiYmRjYjZlM2RjNmIyNDg0Y2E5Njk4YzMxMGRiMzRiZDUifQ.OutfD4RtMjuvmBUeztuFkYvlbsADNQLIl6NoD_BDCtEV9S_-HCM0AWI9bzLoDUmz-fC8-Q6RhzmEgcj_4fbnMA",
"iss": "did:plc:72hi64h42xani53ud76pudoq",
"aud": "did:web:groups.example.com",
"lxm": "fyi.opensocial.getGroup",
"signingDidKey": "did:key:zQ3shQozXcnz15G51JC3Gm4qugNhwTcSg8fTg4YRr6XmHkSVe"
}
}
crates/atproto/tests/reference/identity.mjsnew+60−0
@@ -0,0 +1,60 @@
// Records what the reference implementations make of fixed keys, into
// identity.json beside this: PLC operations and DIDs (@did-plc/lib), DID
// documents, and a service-auth JWT (@atproto/xrpc-server). Its signatures
// are RFC 6979's, the same each run, but for the JWT's random jti.
//
// node identity.mjs <a package depending on @did-plc/lib, @atproto/crypto,
// @atproto/common and @atproto/xrpc-server> > identity.json
import { createRequire } from 'node:module'
const r = createRequire(process.argv[2] + '/package.json')
const plc = r('@did-plc/lib')
const crypto = r('@atproto/crypto')
const { createServiceJwt } = r('@atproto/xrpc-server')
const hex = (h) => Uint8Array.from(Buffer.from(h, 'hex'))
const ROTATION = 'a1b2c3d4e5f60718293a4b5c6d7e8f90112233445566778899aabbccddeeff01'
const SIGNING = '0f1e2d3c4b5a69788796a5b4c3d2e1f00112233445566778899aabbccddeeff0'
const P256_ROTATION = '1111111111111111111111111111111111111111111111111111111111111111'
const rotation = await crypto.Secp256k1Keypair.import(hex(ROTATION))
const signing = await crypto.Secp256k1Keypair.import(hex(SIGNING))
const p256 = await crypto.P256Keypair.import(hex(P256_ROTATION))
const out = { keys: { rotation: ROTATION, signing: SIGNING, p256Rotation: P256_ROTATION }, plc: [] }
for (const [name, key, extra] of [
['k256 rotation', rotation, []],
['p256 rotation, a second key', p256, [rotation.did()]],
]) {
const created = await plc.createOp({
signingKey: signing.did(),
handle: 'riders.groups.example.com',
pds: 'https://groups.example.com',
rotationKeys: [key.did(), ...extra],
signer: key,
})
const handle = await plc.updateHandleOp(created.op, key, 'riders.example.org')
const pds = await plc.updatePdsOp(handle, key, 'https://other.example.com')
const { cidForCbor } = r('@atproto/common')
const tomb = await plc.tombstoneOp(await cidForCbor(pds), key)
const data = await plc.assureValidCreationOp(created.did, created.op)
out.plc.push({
name,
did: created.did,
genesis: created.op,
genesisCid: (await cidForCbor(created.op)).toString(),
updateHandle: handle,
updatePds: pds,
tombstone: tomb,
document: plc.formatDidDoc({ did: created.did, ...data }),
})
}
const jwt = await createServiceJwt({
iss: out.plc[0].did,
aud: 'did:web:groups.example.com',
lxm: 'fyi.opensocial.getGroup',
keypair: signing,
exp: 4102444800, // 2100-01-01
})
out.serviceJwt = { token: jwt, iss: out.plc[0].did, aud: 'did:web:groups.example.com', lxm: 'fyi.opensocial.getGroup', signingDidKey: signing.did() }
console.log(JSON.stringify(out, null, 2))
crates/atproto/tests/reference/knotless.jsonnew+7−0
@@ -0,0 +1,7 @@
{
"aud": "did:web:groups.example.com",
"didKey": "did:key:zDnaezAvTCS153h4H9zmhpfJm5TPxRGBdgyCk2Fx8CDeo2kqm",
"iss": "did:plc:abc",
"lxm": "fyi.opensocial.getGroup",
"token": "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJkaWQ6d2ViOmdyb3Vwcy5leGFtcGxlLmNvbSIsImV4cCI6NDEwMjQ0NDgwMCwiaWF0IjoxNzkzNzM2MzAwLCJpc3MiOiJkaWQ6cGxjOmFiYyIsImx4bSI6ImZ5aS5vcGVuc29jaWFsLmdldEdyb3VwIn0.oVnY1mHwppydmgywIPk6JOl6lHARGXb-Em6nKRiqIZ8oqlzEA2NoqgEmdbBzI2u4PR2jrNYFFpjqIO54tI1Skg"
}
crates/atproto/tests/reference/README.mdnew+10−0
@@ -0,0 +1,10 @@
# Reference vectors
What atproto's reference implementations make of fixed keys, for the parts
the interop vectors leave out. `identity.json` is from `identity.mjs`, run
against @did-plc/lib 0.0.4 and the space alpha's @atproto/crypto and
@atproto/xrpc-server (0.0.0-spaces-alpha-20261022141228): PLC operations
and the DIDs they make, the DID document the directory serves, and a
service-auth JWT. `knotless.json` is a service-auth JWT knotless's own
client signs (`knotless::crypto::P256Key::sign_jwt`), checked here as
knotless checks one.
crates/atproto/tests/did.rsnew+66−0
@@ -0,0 +1,66 @@
//! DID documents, as the PLC directory serves them
//! (tests/reference/identity.json), and the host's own.
use atproto::did::{handle, kem_key, method_key, pds, service, service_document, signing_key};
use atproto::keys::{Curve, Keypair, PublicKey};
use serde_json::{Value, json};
fn reference() -> Value {
let path = format!(
"{}/tests/reference/identity.json",
env!("CARGO_MANIFEST_DIR")
);
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}
#[test]
fn reads_a_directory_document() {
let r = reference();
let doc = &r["plc"][0]["document"];
let signing = r["plc"][0]["genesis"]["verificationMethods"]["atproto"]
.as_str()
.unwrap();
assert_eq!(
signing_key(doc).unwrap(),
PublicKey::from_did_key(signing).unwrap()
);
assert_eq!(pds(doc).as_deref(), Some("https://groups.example.com"));
assert_eq!(handle(doc).as_deref(), Some("riders.groups.example.com"));
assert_eq!(
kem_key(doc).unwrap_err().to_string(),
"the document names no such key"
);
}
#[test]
fn makes_and_reads_a_service_document() {
let key = Keypair::generate(Curve::K256).public();
let did = "did:web:groups.example.com";
let doc = service_document(
did,
&key,
&[(
"#atproto_pds",
"AtprotoPersonalDataServer",
"https://groups.example.com/",
)],
);
assert_eq!(signing_key(&doc).unwrap(), key);
assert_eq!(pds(&doc).as_deref(), Some("https://groups.example.com"));
assert_eq!(service(&doc, "#atproto_labeler"), None);
assert_eq!(handle(&doc), None);
assert_eq!(doc["verificationMethod"][0]["id"], format!("{did}#atproto"));
}
#[test]
fn refuses_a_key_it_cannot_read() {
let doc = json!({"verificationMethod": [{"id": "#atproto", "type": "Multikey"}]});
assert_eq!(
signing_key(&doc).unwrap_err().to_string(),
"a key with no publicKeyMultibase"
);
let kem = Keypair::generate(Curve::P256).public();
let doc = json!({"verificationMethod": [{"id": "did:plc:x#atproto_kem", "type": "Multikey", "publicKeyMultibase": kem.to_multibase()}]});
assert_eq!(kem_key(&doc).unwrap(), kem);
assert!(method_key(&json!({}), "#atproto").is_err());
}
crates/atproto/tests/plc.rsnew+145−0
@@ -0,0 +1,145 @@
//! PLC operations, against what @did-plc/lib makes of the same keys
//! (tests/reference/identity.json): the same bytes, signatures and DIDs.
use atproto::keys::{Curve, Keypair};
use atproto::plc::{Op, Service, Signed, tombstone};
use serde_json::{Value, json};
fn reference() -> Value {
let path = format!(
"{}/tests/reference/identity.json",
env!("CARGO_MANIFEST_DIR")
);
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}
fn key(curve: Curve, hex: &Value) -> Keypair {
let h = hex.as_str().unwrap();
let bytes: Vec<u8> = (0..h.len())
.step_by(2)
.map(|i| u8::from_str_radix(&h[i..i + 2], 16).unwrap())
.collect();
Keypair::from_bytes(curve, &bytes).unwrap()
}
#[test]
fn operations_as_the_reference_makes_them() {
let r = reference();
let rotation = key(Curve::K256, &r["keys"]["rotation"]);
let signing = key(Curve::K256, &r["keys"]["signing"]);
let p256 = key(Curve::P256, &r["keys"]["p256Rotation"]);
for (v, signer, keys) in [
(&r["plc"][0], &rotation, vec![rotation.public().did_key()]),
(
&r["plc"][1],
&p256,
vec![p256.public().did_key(), rotation.public().did_key()],
),
] {
let op = Op::atproto(
&signing.public().did_key(),
&keys,
"riders.groups.example.com",
"https://groups.example.com",
);
let genesis = op.clone().sign(None, signer);
assert_eq!(genesis.to_json(), v["genesis"], "{}", v["name"]);
assert_eq!(genesis.did(), v["did"].as_str().unwrap());
assert_eq!(genesis.cid().to_string(), v["genesisCid"].as_str().unwrap());
assert_eq!(genesis.prev(), None);
assert_eq!(genesis.signed_by(&keys), Some(0));
let mut handle = op.clone();
handle.also_known_as = vec!["at://riders.example.org".into()];
assert_eq!(handle.handle(), Some("riders.example.org"));
let handle = handle.sign(Some(genesis.cid()), signer);
assert_eq!(handle.to_json(), v["updateHandle"]);
let mut pds = op.clone();
pds.also_known_as = vec!["at://riders.example.org".into()];
pds.services.insert(
"atproto_pds".into(),
Service {
kind: "AtprotoPersonalDataServer".into(),
endpoint: "https://other.example.com".into(),
},
);
let pds = pds.sign(Some(handle.cid()), signer);
assert_eq!(pds.to_json(), v["updatePds"]);
let end = tombstone(pds.cid(), signer);
assert_eq!(end.to_json(), v["tombstone"]);
assert_eq!(end.prev(), Some(pds.cid()));
assert_eq!(end.signed_by(&keys), Some(0));
for (json, ours) in [
(&v["genesis"], &genesis),
(&v["updatePds"], &pds),
(&v["tombstone"], &end),
] {
assert_eq!(&Signed::from_json(json).unwrap(), ours);
}
}
}
#[test]
fn says_which_key_signed() {
let r = reference();
let rotation = key(Curve::K256, &r["keys"]["rotation"]);
let other = Keypair::generate(Curve::P256);
let genesis = Signed::from_json(&r["plc"][0]["genesis"]).unwrap();
let keys = [
other.public().did_key(),
"did:key:z1".into(),
rotation.public().did_key(),
];
assert_eq!(genesis.signed_by(&keys), Some(2));
assert_eq!(genesis.signed_by(&keys[..2]), None);
assert_eq!(genesis.signed_by(&[]), None);
}
#[test]
fn refuses_what_is_no_operation() {
let r = reference();
let g = &r["plc"][0]["genesis"];
let with = |k: &str, v: Value| {
let mut j = g.clone();
j[k] = v;
Signed::from_json(&j).unwrap_err().to_string()
};
assert_eq!(with("sig", json!("!")), "an operation's sig is base64url");
assert_eq!(
with("prev", json!("x")),
"prev: a CID is base32, starting with b"
);
assert_eq!(
with("rotationKeys", json!([1])),
"rotationKeys is a list of text"
);
assert_eq!(
with("alsoKnownAs", json!("x")),
"alsoKnownAs is a list of text"
);
assert_eq!(
with("verificationMethods", json!({"atproto": 1})),
"an operation's keys and services are maps of text"
);
assert_eq!(
with("services", json!({"atproto_pds": {"type": 1}})),
"an operation's keys and services are maps of text"
);
assert_eq!(
with("services", json!([])),
"an operation's keys and services are maps of text"
);
assert_eq!(
with("type", json!("create")),
"not a plc_operation or plc_tombstone"
);
let mut t = r["plc"][0]["tombstone"].clone();
t["prev"] = Value::Null;
assert_eq!(
Signed::from_json(&t).unwrap_err().to_string(),
"a tombstone names the operation it ends"
);
}
crates/atproto/tests/service_auth.rsnew+128−0
crates/atproto/Cargo.toml+1−4
docs/design/README.md+5−1