chadtmiller.com/group-host
atmosphere group host
0
0
atproto: the data model, CIDs, TIDs, syntax and keys
crates/atproto/src/base32.rsnew+43−0
| @@ -0,0 +1,43 @@ | ||
//! Base32 without padding, in the two alphabets atproto uses: RFC 4648's, | ||
//! lower case, for CIDs (multibase `b`), and the sortable one TIDs are | ||
//! written in. | ||
| ||
/// RFC 4648's alphabet, lower case: a CID's multibase `b`. | ||
pub const LOWER: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567"; | ||
| ||
/// The sortable alphabet a TID is written in, so that text order is time order. | ||
pub const SORTABLE: &[u8; 32] = b"234567abcdefghijklmnopqrstuvwxyz"; | ||
| ||
pub fn encode(alphabet: &[u8; 32], bytes: &[u8]) -> String { | ||
let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8); | ||
let (mut buffer, mut bits) = (0u32, 0); | ||
for &b in bytes { | ||
buffer = (buffer << 8) | u32::from(b); | ||
bits += 8; | ||
while bits >= 5 { | ||
bits -= 5; | ||
out.push(alphabet[((buffer >> bits) & 31) as usize] as char); | ||
} | ||
} | ||
if bits > 0 { | ||
out.push(alphabet[((buffer << (5 - bits)) & 31) as usize] as char); | ||
} | ||
out | ||
} | ||
| ||
/// The bytes `text` holds, or `None` for a character outside `alphabet` | ||
/// or bits left over that are not zero. | ||
pub fn decode(alphabet: &[u8; 32], text: &str) -> Option<Vec<u8>> { | ||
let mut out = Vec::with_capacity(text.len() * 5 / 8); | ||
let (mut buffer, mut bits) = (0u32, 0); | ||
for c in text.bytes() { | ||
let value = alphabet.iter().position(|&a| a == c)? as u32; | ||
buffer = (buffer << 5) | value; | ||
bits += 5; | ||
if bits >= 8 { | ||
bits -= 8; | ||
out.push((buffer >> bits) as u8); | ||
} | ||
} | ||
(buffer & ((1 << bits) - 1) == 0).then_some(out) | ||
} | ||
crates/atproto/src/cid.rsnew+102−0
| @@ -0,0 +1,102 @@ | ||
//! CIDs, as atproto blesses them: version 1, SHA-256, and either DAG-CBOR | ||
//! (a record, a commit, a tree node) or raw (a blob). | ||
| ||
use crate::base32; | ||
use sha2::{Digest, Sha256}; | ||
use std::fmt; | ||
| ||
/// The codec of a record, a commit or an MST node. | ||
pub const DAG_CBOR: u8 = 0x71; | ||
/// The codec of a blob. | ||
pub const RAW: u8 = 0x55; | ||
const SHA256: u8 = 0x12; | ||
| ||
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] | ||
pub struct Cid { | ||
codec: u8, | ||
digest: [u8; 32], | ||
} | ||
| ||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
pub enum CidError { | ||
/// Not multibase `b`, or not base32 within it. | ||
Encoding, | ||
/// Not version 1, SHA-256, DAG-CBOR or raw. | ||
Unblessed, | ||
} | ||
| ||
impl fmt::Display for CidError { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
f.write_str(match self { | ||
CidError::Encoding => "a CID is base32, starting with b", | ||
CidError::Unblessed => "a CID is version 1 and SHA-256, of DAG-CBOR or raw", | ||
}) | ||
} | ||
} | ||
| ||
impl std::error::Error for CidError {} | ||
| ||
impl Cid { | ||
/// The CID of DRISL bytes: a record's, a commit's, a tree node's. | ||
pub fn of_cbor(bytes: &[u8]) -> Cid { | ||
Cid::of(DAG_CBOR, bytes) | ||
} | ||
| ||
/// The CID of a blob's bytes. | ||
pub fn of_raw(bytes: &[u8]) -> Cid { | ||
Cid::of(RAW, bytes) | ||
} | ||
| ||
fn of(codec: u8, bytes: &[u8]) -> Cid { | ||
Cid { | ||
codec, | ||
digest: Sha256::digest(bytes).into(), | ||
} | ||
} | ||
| ||
pub fn codec(&self) -> u8 { | ||
self.codec | ||
} | ||
| ||
pub fn digest(&self) -> &[u8; 32] { | ||
&self.digest | ||
} | ||
| ||
/// The CID as binary, as a CAR file and a DAG-CBOR link hold it. | ||
pub fn to_bytes(&self) -> Vec<u8> { | ||
[&[1, self.codec, SHA256, 32][..], &self.digest].concat() | ||
} | ||
| ||
pub fn from_bytes(bytes: &[u8]) -> Result<Cid, CidError> { | ||
match bytes { | ||
[1, codec @ (DAG_CBOR | RAW), SHA256, 32, digest @ ..] if digest.len() == 32 => { | ||
Ok(Cid { | ||
codec: *codec, | ||
digest: digest.try_into().expect("32 bytes"), | ||
}) | ||
} | ||
_ => Err(CidError::Unblessed), | ||
} | ||
} | ||
| ||
/// A CID as text: multibase `b`, base32 lower case. | ||
pub fn parse(text: &str) -> Result<Cid, CidError> { | ||
let bytes = text | ||
.strip_prefix('b') | ||
.and_then(|b32| base32::decode(base32::LOWER, b32)) | ||
.ok_or(CidError::Encoding)?; | ||
Cid::from_bytes(&bytes) | ||
} | ||
} | ||
| ||
impl fmt::Display for Cid { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
write!(f, "b{}", base32::encode(base32::LOWER, &self.to_bytes())) | ||
} | ||
} | ||
| ||
impl fmt::Debug for Cid { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
write!(f, "Cid({self})") | ||
} | ||
} | ||
crates/atproto/src/drisl.rsnew+354−0
| @@ -0,0 +1,354 @@ | ||
//! DRISL, atproto's deterministic CBOR (DAG-CBOR): the bytes a record, a | ||
//! commit and a tree node are hashed as. Written out in the one form it | ||
//! allows, and read back refusing any other, so that what reads is what | ||
//! was signed: the shortest lengths, map keys in order, no floats, no | ||
//! tags but links. | ||
//! | ||
//! Records arrive as JSON, in which a link is `{"$link": cid}` and bytes | ||
//! `{"$bytes": base64}`; [`Value::from_json`] and [`Value::to_json`] go | ||
//! between the two. | ||
| ||
use crate::cid::Cid; | ||
use base64::Engine; | ||
use base64::engine::general_purpose::STANDARD_NO_PAD; | ||
use std::collections::BTreeMap; | ||
use std::fmt; | ||
| ||
/// What a record can hold. | ||
#[derive(Clone, Debug, PartialEq)] | ||
pub enum Value { | ||
Null, | ||
Bool(bool), | ||
Integer(i64), | ||
String(String), | ||
Bytes(Vec<u8>), | ||
Link(Cid), | ||
Array(Vec<Value>), | ||
/// Keys in DRISL's order is the encoding's business; a map here is a map. | ||
Map(BTreeMap<String, Value>), | ||
} | ||
| ||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
pub struct DrislError(pub String); | ||
| ||
impl fmt::Display for DrislError { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
f.write_str(&self.0) | ||
} | ||
} | ||
| ||
impl std::error::Error for DrislError {} | ||
| ||
fn err<T>(what: impl Into<String>) -> Result<T, DrislError> { | ||
Err(DrislError(what.into())) | ||
} | ||
| ||
/// How deep values may nest, so that bytes from anyone cannot run the | ||
/// reader out of stack. | ||
pub const MAX_DEPTH: usize = 128; | ||
| ||
/// `value` in DRISL. | ||
pub fn encode(value: &Value) -> Vec<u8> { | ||
let mut out = Vec::new(); | ||
write(value, &mut out); | ||
out | ||
} | ||
| ||
/// The CID of `value`, as DRISL. | ||
pub fn cid(value: &Value) -> Cid { | ||
Cid::of_cbor(&encode(value)) | ||
} | ||
| ||
fn head(major: u8, n: u64, out: &mut Vec<u8>) { | ||
let m = major << 5; | ||
match n { | ||
0..=23 => out.push(m | n as u8), | ||
24..=0xff => out.extend([m | 24, n as u8]), | ||
0x100..=0xffff => { | ||
out.push(m | 25); | ||
out.extend((n as u16).to_be_bytes()); | ||
} | ||
0x1_0000..=0xffff_ffff => { | ||
out.push(m | 26); | ||
out.extend((n as u32).to_be_bytes()); | ||
} | ||
_ => { | ||
out.push(m | 27); | ||
out.extend(n.to_be_bytes()); | ||
} | ||
} | ||
} | ||
| ||
/// DRISL's order of map keys: shorter first, then bytewise. | ||
fn key_order(a: &str, b: &str) -> std::cmp::Ordering { | ||
a.len().cmp(&b.len()).then_with(|| a.cmp(b)) | ||
} | ||
| ||
fn write(value: &Value, out: &mut Vec<u8>) { | ||
match value { | ||
Value::Null => out.push(0xf6), | ||
Value::Bool(b) => out.push(if *b { 0xf5 } else { 0xf4 }), | ||
Value::Integer(i) if *i >= 0 => head(0, *i as u64, out), | ||
Value::Integer(i) => head(1, (-1 - *i) as u64, out), | ||
Value::String(s) => { | ||
head(3, s.len() as u64, out); | ||
out.extend(s.as_bytes()); | ||
} | ||
Value::Bytes(b) => { | ||
head(2, b.len() as u64, out); | ||
out.extend(b); | ||
} | ||
Value::Link(cid) => { | ||
head(6, 42, out); | ||
let bytes = cid.to_bytes(); | ||
head(2, bytes.len() as u64 + 1, out); | ||
out.push(0); | ||
out.extend(bytes); | ||
} | ||
Value::Array(items) => { | ||
head(4, items.len() as u64, out); | ||
items.iter().for_each(|v| write(v, out)); | ||
} | ||
Value::Map(map) => { | ||
head(5, map.len() as u64, out); | ||
let mut keys: Vec<&String> = map.keys().collect(); | ||
keys.sort_by(|a, b| key_order(a, b)); | ||
for k in keys { | ||
head(3, k.len() as u64, out); | ||
out.extend(k.as_bytes()); | ||
write(&map[k], out); | ||
} | ||
} | ||
} | ||
} | ||
| ||
/// The value `bytes` hold, all of them, refusing any form but DRISL's one. | ||
pub fn decode(bytes: &[u8]) -> Result<Value, DrislError> { | ||
let mut reader = Reader { bytes, at: 0 }; | ||
let value = reader.value(0)?; | ||
if reader.at != bytes.len() { | ||
return err("bytes after the value"); | ||
} | ||
Ok(value) | ||
} | ||
| ||
struct Reader<'a> { | ||
bytes: &'a [u8], | ||
at: usize, | ||
} | ||
| ||
impl Reader<'_> { | ||
fn take(&mut self, n: u64) -> Result<&[u8], DrislError> { | ||
let left = (self.bytes.len() - self.at) as u64; | ||
if n > left { | ||
return err("the bytes end in the middle of a value"); | ||
} | ||
let start = self.at; | ||
self.at += n as usize; | ||
Ok(&self.bytes[start..self.at]) | ||
} | ||
| ||
/// A head's major type and the number it carries, refusing a number | ||
/// written longer than it needs, and lengths left open. | ||
fn head(&mut self) -> Result<(u8, u8, u64), DrislError> { | ||
let first = self.take(1)?[0]; | ||
let (major, info) = (first >> 5, first & 31); | ||
let n = match info { | ||
0..=23 => u64::from(info), | ||
24 => u64::from(self.take(1)?[0]), | ||
25 => u64::from(u16::from_be_bytes(self.take(2)?.try_into().expect("2"))), | ||
26 => u64::from(u32::from_be_bytes(self.take(4)?.try_into().expect("4"))), | ||
27 => u64::from_be_bytes(self.take(8)?.try_into().expect("8")), | ||
_ => return err("an indefinite or reserved length"), | ||
}; | ||
let shortest = match info { | ||
24 => n >= 24, | ||
25 => n > 0xff, | ||
26 => n > 0xffff, | ||
27 => n > 0xffff_ffff, | ||
_ => true, | ||
}; | ||
if !shortest && major != 7 { | ||
return err("a number written longer than it needs"); | ||
} | ||
Ok((major, info, n)) | ||
} | ||
| ||
fn text(&mut self, n: u64) -> Result<String, DrislError> { | ||
let bytes = self.take(n)?.to_vec(); | ||
String::from_utf8(bytes).or_else(|_| err("text that is not UTF-8")) | ||
} | ||
| ||
fn value(&mut self, depth: usize) -> Result<Value, DrislError> { | ||
if depth > MAX_DEPTH { | ||
return err("values nested too deep"); | ||
} | ||
let (major, info, n) = self.head()?; | ||
Ok(match major { | ||
0 => Value::Integer(i64::try_from(n).or_else(|_| err("an integer past 64 bits"))?), | ||
1 => Value::Integer( | ||
i64::try_from(n) | ||
.map(|n| -1 - n) | ||
.or_else(|_| err("an integer past 64 bits"))?, | ||
), | ||
2 => Value::Bytes(self.take(n)?.to_vec()), | ||
3 => Value::String(self.text(n)?), | ||
4 => { | ||
let mut items = Vec::new(); | ||
for _ in 0..n { | ||
items.push(self.value(depth + 1)?); | ||
} | ||
Value::Array(items) | ||
} | ||
5 => { | ||
let mut map = BTreeMap::new(); | ||
let mut last: Option<String> = None; | ||
for _ in 0..n { | ||
let (major, _, len) = self.head()?; | ||
if major != 3 { | ||
return err("a map key that is not text"); | ||
} | ||
let key = self.text(len)?; | ||
if let Some(last) = &last | ||
&& key_order(last, &key) != std::cmp::Ordering::Less | ||
{ | ||
return err("map keys out of order, or repeated"); | ||
} | ||
let v = self.value(depth + 1)?; | ||
map.insert(key.clone(), v); | ||
last = Some(key); | ||
} | ||
Value::Map(map) | ||
} | ||
6 if n == 42 => { | ||
let (major, _, len) = self.head()?; | ||
let bytes = self.take(len)?; | ||
match (major, bytes) { | ||
(2, [0, cid @ ..]) => { | ||
Value::Link(Cid::from_bytes(cid).or_else(|e| err(format!("a link: {e}")))?) | ||
} | ||
_ => return err("a link that is not bytes starting with 0"), | ||
} | ||
} | ||
6 => return err(format!("tag {n}: only links (42) are allowed")), | ||
_ => match info { | ||
20 => Value::Bool(false), | ||
21 => Value::Bool(true), | ||
22 => Value::Null, | ||
25..=27 => return err("a float"), | ||
_ => return err(format!("simple value {info}")), | ||
}, | ||
}) | ||
} | ||
} | ||
| ||
impl Value { | ||
/// The value a record's JSON holds, as atproto writes it: an object | ||
/// of `$link` alone a link, of `$bytes` alone bytes, a number with a | ||
/// fraction refused. | ||
pub fn from_json(json: &serde_json::Value) -> Result<Value, DrislError> { | ||
use serde_json::Value as J; | ||
Ok(match json { | ||
J::Null => Value::Null, | ||
J::Bool(b) => Value::Bool(*b), | ||
J::Number(n) => match n.as_i64() { | ||
Some(i) => Value::Integer(i), | ||
// JSON cannot tell 123.0 from 123, so neither does a record. | ||
None => match n.as_f64() { | ||
Some(f) if f.fract() == 0.0 && f.abs() < 9_007_199_254_740_992.0 => { | ||
Value::Integer(f as i64) | ||
} | ||
_ => return err(format!("{n} is not an integer")), | ||
}, | ||
}, | ||
J::String(s) => Value::String(s.clone()), | ||
J::Array(items) => Value::Array( | ||
items | ||
.iter() | ||
.map(Value::from_json) | ||
.collect::<Result<_, _>>()?, | ||
), | ||
J::Object(map) => { | ||
if let Some(link) = map.get("$link") { | ||
let (Some(text), 1) = (link.as_str(), map.len()) else { | ||
return err("a $link is a CID's text, alone in its object"); | ||
}; | ||
return Cid::parse(text) | ||
.map(Value::Link) | ||
.or_else(|e| err(format!("$link: {e}"))); | ||
} | ||
if let Some(bytes) = map.get("$bytes") { | ||
let (Some(text), 1) = (bytes.as_str(), map.len()) else { | ||
return err("$bytes is base64 text, alone in its object"); | ||
}; | ||
let text = text.trim_end_matches('='); | ||
crates/atproto/src/drisl.rsline 284
| ||
return STANDARD_NO_PAD | ||
.decode(text) | ||
.map(Value::Bytes) | ||
.or_else(|_| err("$bytes is not base64")); | ||
} | ||
Value::Map( | ||
map.iter() | ||
.map(|(k, v)| Ok((k.clone(), Value::from_json(v)?))) | ||
.collect::<Result<_, DrislError>>()?, | ||
) | ||
} | ||
}) | ||
} | ||
| ||
/// The value as a record's JSON. | ||
pub fn to_json(&self) -> serde_json::Value { | ||
use serde_json::{Value as J, json}; | ||
match self { | ||
Value::Null => J::Null, | ||
Value::Bool(b) => J::Bool(*b), | ||
Value::Integer(i) => J::from(*i), | ||
Value::String(s) => J::String(s.clone()), | ||
Value::Bytes(b) => json!({ "$bytes": STANDARD_NO_PAD.encode(b) }), | ||
Value::Link(cid) => json!({ "$link": cid.to_string() }), | ||
Value::Array(items) => J::Array(items.iter().map(Value::to_json).collect()), | ||
Value::Map(map) => { | ||
J::Object(map.iter().map(|(k, v)| (k.clone(), v.to_json())).collect()) | ||
} | ||
} | ||
} | ||
} | ||
| ||
/// Whether `json` is a record as atproto's data model has one: an object, | ||
/// whose every `$type` is a name, and whose every blob says what it holds. | ||
/// What fails is said. | ||
pub fn check_record(json: &serde_json::Value) -> Result<(), DrislError> { | ||
if !json.is_object() { | ||
return err("a record is an object"); | ||
} | ||
Value::from_json(json)?; | ||
check_types(json) | ||
} | ||
| ||
fn check_types(json: &serde_json::Value) -> Result<(), DrislError> { | ||
use serde_json::Value as J; | ||
match json { | ||
J::Array(items) => items.iter().try_for_each(check_types), | ||
J::Object(map) => { | ||
match map.get("$type") { | ||
None => {} | ||
Some(J::String(t)) if t == "blob" && !is_blob(map) => { | ||
return err("a blob has a ref, a mimeType and a size"); | ||
} | ||
Some(J::String(t)) if !t.is_empty() => {} | ||
Some(_) => return err("a $type is a name"), | ||
} | ||
map.values().try_for_each(check_types) | ||
} | ||
_ => Ok(()), | ||
} | ||
} | ||
| ||
/// Whether an object whose `$type` is `blob` says what a blob does. | ||
fn is_blob(map: &serde_json::Map<String, serde_json::Value>) -> bool { | ||
map.get("ref").and_then(|r| r.get("$link")).is_some() | ||
&& map | ||
.get("mimeType") | ||
.is_some_and(serde_json::Value::is_string) | ||
&& map.get("size").is_some_and(serde_json::Value::is_i64) | ||
} | ||
crates/atproto/src/keys.rsnew+209−0
| @@ -0,0 +1,209 @@ | ||
//! The keys atproto signs with, secp256k1 (`ES256K`) and P-256 (`ES256`): | ||
//! a group's repo and rotation keys, the host's own, and the keys in a DID | ||
//! document, as multikeys and `did:key`s. Signatures are 64 bytes, `r` | ||
//! then `s`, with `s` in the low half: atproto refuses any other. | ||
| ||
use rand_core::OsRng; | ||
use std::fmt; | ||
| ||
const K256_CODEC: [u8; 2] = [0xe7, 0x01]; | ||
const P256_CODEC: [u8; 2] = [0x80, 0x24]; | ||
| ||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
pub struct KeyError(pub &'static str); | ||
| ||
impl fmt::Display for KeyError { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
f.write_str(self.0) | ||
} | ||
} | ||
| ||
impl std::error::Error for KeyError {} | ||
| ||
/// Which curve a key is on. | ||
#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
pub enum Curve { | ||
K256, | ||
P256, | ||
} | ||
| ||
impl Curve { | ||
/// Its JWT algorithm. | ||
pub fn alg(self) -> &'static str { | ||
match self { | ||
Curve::K256 => "ES256K", | ||
Curve::P256 => "ES256", | ||
} | ||
} | ||
} | ||
| ||
/// A key that signs. | ||
#[derive(Clone)] | ||
pub enum Keypair { | ||
K256(k256::ecdsa::SigningKey), | ||
P256(p256::ecdsa::SigningKey), | ||
} | ||
| ||
impl fmt::Debug for Keypair { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
write!(f, "Keypair({})", self.public().did_key()) | ||
} | ||
} | ||
| ||
impl Keypair { | ||
pub fn generate(curve: Curve) -> Keypair { | ||
match curve { | ||
Curve::K256 => Keypair::K256(k256::ecdsa::SigningKey::random(&mut OsRng)), | ||
Curve::P256 => Keypair::P256(p256::ecdsa::SigningKey::random(&mut OsRng)), | ||
} | ||
} | ||
| ||
/// The key whose secret is the 32 bytes `secret`. | ||
pub fn from_bytes(curve: Curve, secret: &[u8]) -> Result<Keypair, KeyError> { | ||
let bad = |_| KeyError("not a secret key on its curve"); | ||
Ok(match curve { | ||
Curve::K256 => Keypair::K256(k256::ecdsa::SigningKey::from_slice(secret).map_err(bad)?), | ||
Curve::P256 => Keypair::P256(p256::ecdsa::SigningKey::from_slice(secret).map_err(bad)?), | ||
}) | ||
} | ||
| ||
/// The 32 bytes of its secret, to keep. | ||
pub fn to_bytes(&self) -> [u8; 32] { | ||
match self { | ||
Keypair::K256(k) => k.to_bytes().into(), | ||
Keypair::P256(k) => k.to_bytes().into(), | ||
} | ||
} | ||
| ||
pub fn curve(&self) -> Curve { | ||
match self { | ||
Keypair::K256(_) => Curve::K256, | ||
Keypair::P256(_) => Curve::P256, | ||
} | ||
} | ||
| ||
pub fn public(&self) -> PublicKey { | ||
match self { | ||
Keypair::K256(k) => PublicKey::K256(*k.verifying_key()), | ||
Keypair::P256(k) => PublicKey::P256(*k.verifying_key()), | ||
} | ||
} | ||
| ||
/// `message` signed, hashed with SHA-256: `r` then `s`, low-S. | ||
pub fn sign(&self, message: &[u8]) -> [u8; 64] { | ||
use ecdsa::signature::Signer; | ||
match self { | ||
Keypair::K256(k) => { | ||
let sig: k256::ecdsa::Signature = k.sign(message); | ||
sig.normalize_s().unwrap_or(sig).to_bytes().into() | ||
} | ||
Keypair::P256(k) => { | ||
let sig: p256::ecdsa::Signature = k.sign(message); | ||
sig.normalize_s().unwrap_or(sig).to_bytes().into() | ||
} | ||
} | ||
} | ||
} | ||
| ||
/// A key that checks signatures: one a DID document or `did:key` names. | ||
#[derive(Clone, Debug, PartialEq, Eq)] | ||
pub enum PublicKey { | ||
K256(k256::ecdsa::VerifyingKey), | ||
P256(p256::ecdsa::VerifyingKey), | ||
} | ||
| ||
fn base58(text: &str) -> Result<Vec<u8>, KeyError> { | ||
let b58 = text | ||
.strip_prefix('z') | ||
.ok_or(KeyError("a multikey is base58btc, starting with z"))?; | ||
bs58::decode(b58) | ||
.into_vec() | ||
.map_err(|_| KeyError("bad base58 in a key")) | ||
} | ||
| ||
impl PublicKey { | ||
/// The key a multikey (multibase `z`, base58btc, with its multicodec) holds. | ||
pub fn from_multibase(text: &str) -> Result<PublicKey, KeyError> { | ||
let bytes = base58(text)?; | ||
let (codec, key) = bytes.split_at(2.min(bytes.len())); | ||
match <[u8; 2]>::try_from(codec) { | ||
Ok(K256_CODEC) => PublicKey::from_sec1(Curve::K256, key), | ||
Ok(P256_CODEC) => PublicKey::from_sec1(Curve::P256, key), | ||
_ => Err(KeyError("not a secp256k1 or P-256 multikey")), | ||
} | ||
} | ||
| ||
/// The key of a DID document's verification method: a `Multikey`, or | ||
/// one of the older types, whose multibase holds the bare key. | ||
pub fn from_method(kind: &str, multibase: &str) -> Result<PublicKey, KeyError> { | ||
match kind { | ||
"EcdsaSecp256k1VerificationKey2019" => { | ||
PublicKey::from_sec1(Curve::K256, &base58(multibase)?) | ||
} | ||
"EcdsaSecp256r1VerificationKey2019" => { | ||
PublicKey::from_sec1(Curve::P256, &base58(multibase)?) | ||
} | ||
_ => PublicKey::from_multibase(multibase), | ||
} | ||
} | ||
| ||
pub fn from_did_key(did: &str) -> Result<PublicKey, KeyError> { | ||
let multibase = did | ||
.strip_prefix("did:key:") | ||
.ok_or(KeyError("not a did:key"))?; | ||
PublicKey::from_multibase(multibase) | ||
} | ||
| ||
/// The key as SEC1 bytes, compressed or not. | ||
pub fn from_sec1(curve: Curve, bytes: &[u8]) -> Result<PublicKey, KeyError> { | ||
match curve { | ||
Curve::K256 => k256::ecdsa::VerifyingKey::from_sec1_bytes(bytes) | ||
.map(PublicKey::K256) | ||
.map_err(|_| KeyError("not a secp256k1 key")), | ||
Curve::P256 => p256::ecdsa::VerifyingKey::from_sec1_bytes(bytes) | ||
.map(PublicKey::P256) | ||
.map_err(|_| KeyError("not a P-256 key")), | ||
} | ||
} | ||
| ||
pub fn curve(&self) -> Curve { | ||
match self { | ||
PublicKey::K256(_) => Curve::K256, | ||
PublicKey::P256(_) => Curve::P256, | ||
} | ||
} | ||
| ||
/// The key as SEC1 bytes, compressed. | ||
pub fn to_sec1(&self) -> Vec<u8> { | ||
match self { | ||
PublicKey::K256(k) => k.to_encoded_point(true).as_bytes().to_vec(), | ||
PublicKey::P256(k) => k.to_encoded_point(true).as_bytes().to_vec(), | ||
} | ||
} | ||
| ||
/// The key as a multikey, as a DID document's `publicKeyMultibase`. | ||
pub fn to_multibase(&self) -> String { | ||
let codec = match self { | ||
PublicKey::K256(_) => K256_CODEC, | ||
PublicKey::P256(_) => P256_CODEC, | ||
}; | ||
let bytes = [&codec[..], &self.to_sec1()].concat(); | ||
format!("z{}", bs58::encode(bytes).into_string()) | ||
} | ||
| ||
pub fn did_key(&self) -> String { | ||
format!("did:key:{}", self.to_multibase()) | ||
} | ||
| ||
/// Whether `signature` is this key's of `message`: 64 bytes, `r` then | ||
/// `s`, low-S. A DER signature, or a high-S one, is refused. | ||
pub fn verify(&self, message: &[u8], signature: &[u8]) -> bool { | ||
use ecdsa::signature::Verifier; | ||
match self { | ||
PublicKey::K256(k) => k256::ecdsa::Signature::from_slice(signature) | ||
.is_ok_and(|s| s.normalize_s().is_none() && k.verify(message, &s).is_ok()), | ||
PublicKey::P256(k) => p256::ecdsa::Signature::from_slice(signature) | ||
.is_ok_and(|s| s.normalize_s().is_none() && k.verify(message, &s).is_ok()), | ||
} | ||
} | ||
} | ||
crates/atproto/src/lib.rs+13−2
| @@ -4,5 +4,16 @@ | ||
//! a repo's records hang from, CAR files, PLC operations, and the | ||
//! service-auth tokens one server hands another. | ||
//! | ||
//! Each part arrives with the pull that first needs it; see | ||
//! `docs/design/README.md` for the order. | ||
//! Each part is checked against atproto's interop test vectors, under | ||
//! `tests/interop`. The parts still to come are in `docs/design/README.md`. | ||
| ||
pub mod base32; | ||
pub mod cid; | ||
pub mod drisl; | ||
pub mod keys; | ||
pub mod syntax; | ||
pub mod tid; | ||
| ||
pub use cid::Cid; | ||
pub use drisl::Value; | ||
pub use keys::{Curve, Keypair, PublicKey}; | ||
crates/atproto/src/syntax.rsnew+74−0
| @@ -0,0 +1,74 @@ | ||
//! What atproto's identifiers may look like, as its specs give their | ||
//! syntax: DIDs, handles, NSIDs, record keys and TIDs. Each says only | ||
//! whether a string is well formed, not whether it names anything. | ||
| ||
/// A DID: `did:`, a lower-case method, and an identifier of letters, | ||
/// digits and `._:%-` not ending in `:` or `%`, 2 KiB at most. | ||
pub fn is_did(s: &str) -> bool { | ||
let Some(rest) = s.strip_prefix("did:") else { | ||
return false; | ||
}; | ||
let Some((method, id)) = rest.split_once(':') else { | ||
return false; | ||
}; | ||
s.len() <= 2048 | ||
&& !method.is_empty() | ||
&& method.bytes().all(|c| c.is_ascii_lowercase()) | ||
&& !id.is_empty() | ||
&& id | ||
.bytes() | ||
.all(|c| c.is_ascii_alphanumeric() || b"._:%-".contains(&c)) | ||
&& !id.ends_with([':', '%']) | ||
} | ||
| ||
/// A handle: two or more labels of letters, digits and inner hyphens, each | ||
/// 63 characters at most, the last not starting with a digit, 253 in all. | ||
pub fn is_handle(s: &str) -> bool { | ||
let labels: Vec<&str> = s.split('.').collect(); | ||
s.len() <= 253 | ||
&& labels.len() >= 2 | ||
&& labels.iter().all(|l| is_label(l)) | ||
&& !labels[labels.len() - 1].starts_with(|c: char| c.is_ascii_digit()) | ||
} | ||
| ||
fn is_label(l: &str) -> bool { | ||
(1..=63).contains(&l.len()) | ||
&& l.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-') | ||
&& !l.starts_with('-') | ||
&& !l.ends_with('-') | ||
} | ||
| ||
/// An NSID: a reversed domain of two or more labels, its first not | ||
/// starting with a digit, then a name of letters and digits not starting | ||
/// with one, 317 characters in all. The interop vectors hold a domain | ||
/// longer than a hostname's 253 as valid, so this does too. | ||
pub fn is_nsid(s: &str) -> bool { | ||
let Some((domain, name)) = s.rsplit_once('.') else { | ||
return false; | ||
}; | ||
let domain: Vec<&str> = domain.split('.').collect(); | ||
s.len() <= 317 | ||
&& domain.len() >= 2 | ||
&& domain.iter().all(|l| is_label(l)) | ||
&& !domain[0].starts_with(|c: char| c.is_ascii_digit()) | ||
&& (1..=63).contains(&name.len()) | ||
&& name.bytes().all(|c| c.is_ascii_alphanumeric()) | ||
&& !name.starts_with(|c: char| c.is_ascii_digit()) | ||
} | ||
| ||
/// A record key: 1 to 512 of letters, digits and `._:~-`, but not `.` or `..`. | ||
pub fn is_record_key(s: &str) -> bool { | ||
(1..=512).contains(&s.len()) | ||
&& s.bytes() | ||
.all(|c| c.is_ascii_alphanumeric() || b"._:~-".contains(&c)) | ||
&& s != "." | ||
&& s != ".." | ||
} | ||
| ||
/// A TID: 13 characters of sortable base32, the first holding no top bit. | ||
pub fn is_tid(s: &str) -> bool { | ||
let alphabet = crate::base32::SORTABLE; | ||
s.len() == 13 | ||
&& alphabet[..16].contains(&s.as_bytes()[0]) | ||
&& s.bytes().all(|c| alphabet.contains(&c)) | ||
} | ||
crates/atproto/src/tid.rsnew+63−0
| @@ -0,0 +1,63 @@ | ||
//! TIDs: the record keys and revisions atproto makes from the time, 13 | ||
//! characters of sortable base32 holding the microseconds since 1970 and a | ||
//! clock id, so that a later one sorts after. | ||
| ||
use crate::base32::SORTABLE; | ||
use std::sync::Mutex; | ||
use std::time::{SystemTime, UNIX_EPOCH}; | ||
| ||
/// The TID of `micros` since 1970 from clock `clock` (its low 10 bits). | ||
pub fn tid_from(micros: u64, clock: u64) -> String { | ||
// 63 bits, the top one clear, five to a character from the last. | ||
let mut v = ((micros & ((1 << 53) - 1)) << 10) | (clock & 1023); | ||
let mut out = [0; 13]; | ||
for c in out.iter_mut().rev() { | ||
*c = SORTABLE[(v & 31) as usize]; | ||
v >>= 5; | ||
} | ||
String::from_utf8(out.to_vec()).expect("ascii") | ||
} | ||
| ||
/// The microseconds a TID holds, or `None` for what is not one. | ||
pub fn micros(tid: &str) -> Option<u64> { | ||
if !crate::syntax::is_tid(tid) { | ||
return None; | ||
} | ||
let value = tid.bytes().fold(0u64, |v, c| { | ||
(v << 5) | SORTABLE.iter().position(|&a| a == c).expect("checked") as u64 | ||
}); | ||
Some(value >> 10) | ||
} | ||
| ||
/// Makes TIDs that only go forward, each after the last this clock made, | ||
/// even when the system's clock steps back. | ||
pub struct TidClock { | ||
clock: u64, | ||
last: Mutex<u64>, | ||
} | ||
| ||
impl TidClock { | ||
/// A clock whose TIDs carry `clock` as their clock id. | ||
pub fn new(clock: u64) -> TidClock { | ||
TidClock { | ||
clock, | ||
last: Mutex::new(0), | ||
} | ||
} | ||
| ||
/// The next TID, at now or just after the last one made. | ||
pub fn next(&self) -> String { | ||
let now = SystemTime::now() | ||
.duration_since(UNIX_EPOCH) | ||
.expect("after 1970") | ||
.as_micros() as u64; | ||
self.next_at(now) | ||
} | ||
| ||
/// The next TID, as [`TidClock::next`], at `now` microseconds. | ||
pub fn next_at(&self, now: u64) -> String { | ||
let mut last = self.last.lock().expect("not poisoned"); | ||
*last = now.max(*last + 1); | ||
tid_from(*last, self.clock) | ||
} | ||
} | ||
crates/atproto/tests/interop/crypto/signature-fixtures.jsonnew+68−0
| @@ -0,0 +1,68 @@ | ||
[ | ||
{ | ||
"comment": "valid P-256 key and signature, with low-S signature", | ||
"messageBase64": "oWVoZWxsb2V3b3JsZA", | ||
"algorithm": "ES256", | ||
"didDocSuite": "EcdsaSecp256r1VerificationKey2019", | ||
"publicKeyDid": "did:key:zDnaembgSGUhZULN2Caob4HLJPaxBh92N7rtH21TErzqf8HQo", | ||
"publicKeyMultibase": "zxdM8dSstjrpZaRUwBmDvjGXweKuEMVN95A9oJBFjkWMh", | ||
"signatureBase64": "2vZNsG3UKvvO/CDlrdvyZRISOFylinBh0Jupc6KcWoJWExHptCfduPleDbG3rko3YZnn9Lw0IjpixVmexJDegg", | ||
"validSignature": true, | ||
"tags": [] | ||
}, | ||
{ | ||
"comment": "valid K-256 key and signature, with low-S signature", | ||
"messageBase64": "oWVoZWxsb2V3b3JsZA", | ||
"algorithm": "ES256K", | ||
"didDocSuite": "EcdsaSecp256k1VerificationKey2019", | ||
"publicKeyDid": "did:key:zQ3shqwJEJyMBsBXCWyCBpUBMqxcon9oHB7mCvx4sSpMdLJwc", | ||
"publicKeyMultibase": "z25z9DTpsiYYJKGsWmSPJK2NFN8PcJtZig12K59UgW7q5t", | ||
"signatureBase64": "5WpdIuEUUfVUYaozsi8G0B3cWO09cgZbIIwg1t2YKdUn/FEznOndsz/qgiYb89zwxYCbB71f7yQK5Lr7NasfoA", | ||
"validSignature": true, | ||
"tags": [] | ||
}, | ||
{ | ||
"comment": "P-256 key and signature, with non-low-S signature which is invalid in atproto", | ||
"messageBase64": "oWVoZWxsb2V3b3JsZA", | ||
"algorithm": "ES256", | ||
"didDocSuite": "EcdsaSecp256r1VerificationKey2019", | ||
"publicKeyDid": "did:key:zDnaembgSGUhZULN2Caob4HLJPaxBh92N7rtH21TErzqf8HQo", | ||
"publicKeyMultibase": "zxdM8dSstjrpZaRUwBmDvjGXweKuEMVN95A9oJBFjkWMh", | ||
"signatureBase64": "2vZNsG3UKvvO/CDlrdvyZRISOFylinBh0Jupc6KcWoKp7O4VS9giSAah8k5IUbXIW00SuOrjfEqQ9HEkN9JGzw", | ||
"validSignature": false, | ||
"tags": ["high-s"] | ||
}, | ||
{ | ||
"comment": "K-256 key and signature, with non-low-S signature which is invalid in atproto", | ||
"messageBase64": "oWVoZWxsb2V3b3JsZA", | ||
"algorithm": "ES256K", | ||
"didDocSuite": "EcdsaSecp256k1VerificationKey2019", | ||
"publicKeyDid": "did:key:zQ3shqwJEJyMBsBXCWyCBpUBMqxcon9oHB7mCvx4sSpMdLJwc", | ||
"publicKeyMultibase": "z25z9DTpsiYYJKGsWmSPJK2NFN8PcJtZig12K59UgW7q5t", | ||
"signatureBase64": "5WpdIuEUUfVUYaozsi8G0B3cWO09cgZbIIwg1t2YKdXYA67MYxYiTMAVfdnkDCMN9S5B3vHosRe07aORmoshoQ", | ||
"validSignature": false, | ||
"tags": ["high-s"] | ||
}, | ||
{ | ||
"comment": "P-256 key and signature, with DER-encoded signature which is invalid in atproto", | ||
"messageBase64": "oWVoZWxsb2V3b3JsZA", | ||
"algorithm": "ES256", | ||
"didDocSuite": "EcdsaSecp256r1VerificationKey2019", | ||
"publicKeyDid": "did:key:zDnaeT6hL2RnTdUhAPLij1QBkhYZnmuKyM7puQLW1tkF4Zkt8", | ||
"publicKeyMultibase": "ze8N2PPxnu19hmBQ58t5P3E9Yj6CqakJmTVCaKvf9Byq2", | ||
"signatureBase64": "MEQCIFxYelWJ9lNcAVt+jK0y/T+DC/X4ohFZ+m8f9SEItkY1AiACX7eXz5sgtaRrz/SdPR8kprnbHMQVde0T2R8yOTBweA", | ||
"validSignature": false, | ||
"tags": ["der-encoded"] | ||
}, | ||
{ | ||
"comment": "K-256 key and signature, with DER-encoded signature which is invalid in atproto", | ||
"messageBase64": "oWVoZWxsb2V3b3JsZA", | ||
"algorithm": "ES256K", | ||
"didDocSuite": "EcdsaSecp256k1VerificationKey2019", | ||
"publicKeyDid": "did:key:zQ3shnriYMXc8wvkbJqfNWh5GXn2bVAeqTC92YuNbek4npqGF", | ||
"publicKeyMultibase": "z22uZXWP8fdHXi4jyx8cCDiBf9qQTsAe6VcycoMQPfcMQX", | ||
"signatureBase64": "MEUCIQCWumUqJqOCqInXF7AzhIRg2MhwRz2rWZcOEsOjPmNItgIgXJH7RnqfYY6M0eg33wU0sFYDlprwdOcpRn78Sz5ePgk", | ||
"validSignature": false, | ||
"tags": ["der-encoded"] | ||
} | ||
] | ||
crates/atproto/tests/interop/crypto/w3c_didkey_K256.jsonnew+22−0
| @@ -0,0 +1,22 @@ | ||
[ | ||
{ | ||
"privateKeyBytesHex": "9085d2bef69286a6cbb51623c8fa258629945cd55ca705cc4e66700396894e0c", | ||
"publicDidKey": "did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme" | ||
}, | ||
{ | ||
"privateKeyBytesHex": "f0f4df55a2b3ff13051ea814a8f24ad00f2e469af73c363ac7e9fb999a9072ed", | ||
"publicDidKey": "did:key:zQ3shtxV1FrJfhqE1dvxYRcCknWNjHc3c5X1y3ZSoPDi2aur2" | ||
}, | ||
{ | ||
"privateKeyBytesHex": "6b0b91287ae3348f8c2f2552d766f30e3604867e34adc37ccbb74a8e6b893e02", | ||
"publicDidKey": "did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N" | ||
}, | ||
{ | ||
"privateKeyBytesHex": "c0a6a7c560d37d7ba81ecee9543721ff48fea3e0fb827d42c1868226540fac15", | ||
"publicDidKey": "did:key:zQ3shadCps5JLAHcZiuX5YUtWHHL8ysBJqFLWvjZDKAWUBGzy" | ||
}, | ||
{ | ||
"privateKeyBytesHex": "175a232d440be1e0788f25488a73d9416c04b6f924bea6354bf05dd2f1a75133", | ||
"publicDidKey": "did:key:zQ3shptjE6JwdkeKN4fcpnYQY3m9Cet3NiHdAfpvSUZBFoKBj" | ||
} | ||
] | ||
crates/atproto/tests/interop/crypto/w3c_didkey_P256.jsonnew+6−0
| @@ -0,0 +1,6 @@ | ||
[ | ||
{ | ||
"privateKeyBytesBase58": "9p4VRzdmhsnq869vQjVCTrRry7u4TtfRxhvBFJTGU2Cp", | ||
"publicDidKey": "did:key:zDnaeTiq1PdzvZXUaMdezchcMJQpBdH2VN4pgrrEhMCCbmwSb" | ||
} | ||
] | ||