Skip to main content

atomic_integration_proxy/
agent_id.rs

1//! Agent identifiers: the one place that parses them (issue #54, decision 9).
2//!
3//! The proxy's account is an Atomic agent. Its id carries its own public key,
4//! so verifying a signature needs no lookup. Accepted input forms:
5//!
6//! - `atomic:agent:<key>`, the canonical scheme since atomic-server#1585;
7//! - `did:ad:agent:<key>`, the legacy alias atomic-server accepts forever.
8//!
9//! `<key>` is base64 in either alphabet (standard or URL-safe), padded or not,
10//! as Atomic's own `decode_base64` accepts it. Only Ed25519 (a 32-byte key)
11//! exists today; a new algorithm is added here, in [`parse`], and nowhere
12//! else.
13//!
14//! Every id is converted to one canonical string before it is stored or
15//! compared: `atomic:agent:` followed by the key in unpadded base64url, the
16//! encoding Atomic's `encode_base64` emits. Two spellings of the same key are
17//! the same agent; the proxy only ever outputs the canonical form.
18use base64::{
19    engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
20    Engine as _,
21};
22use ed25519_dalek::{Signature, VerifyingKey};
23
24pub const ATOMIC_AGENT_PREFIX: &str = "atomic:agent:";
25pub const DID_AD_AGENT_PREFIX: &str = "did:ad:agent:";
26
27/// A parsed, verifiable agent id.
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub struct AgentId {
30    canonical: String,
31    key: AgentKey,
32}
33
34#[derive(Clone, Debug, PartialEq, Eq)]
35enum AgentKey {
36    Ed25519(VerifyingKey),
37}
38
39impl AgentId {
40    /// The canonical `atomic:agent:<base64url key>` form.
41    pub fn as_str(&self) -> &str {
42        &self.canonical
43    }
44
45    /// Verifies `signature` (base64, either alphabet) over `message`.
46    /// Strict: rejects small-order keys and non-canonical signatures.
47    pub fn verify(&self, message: &[u8], signature: &str) -> bool {
48        match &self.key {
49            AgentKey::Ed25519(key) => {
50                let Some(bytes) =
51                    decode_base64(signature).and_then(|bytes| <[u8; 64]>::try_from(bytes).ok())
52                else {
53                    return false;
54                };
55                key.verify_strict(message, &Signature::from_bytes(&bytes))
56                    .is_ok()
57            }
58        }
59    }
60}
61
62impl std::fmt::Display for AgentId {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        f.write_str(&self.canonical)
65    }
66}
67
68/// Decodes base64 the way Atomic Data does (`lib/src/agents.rs`
69/// `decode_base64`): URL-safe or standard alphabet, padded or not.
70pub fn decode_base64(value: &str) -> Option<Vec<u8>> {
71    let trimmed = value.trim_end_matches('=');
72    if trimmed.len() + 2 < value.len() {
73        return None;
74    }
75    let standard: String = trimmed
76        .chars()
77        .map(|c| match c {
78            '-' => '+',
79            '_' => '/',
80            other => other,
81        })
82        .collect();
83    let pad = (4 - standard.len() % 4) % 4;
84    STANDARD
85        .decode(format!("{standard}{}", "=".repeat(pad)))
86        .ok()
87}
88
89/// Parses any accepted spelling of an agent id. `None` for anything else:
90/// an HTTP agent URL, another identifier kind, a malformed or non-Ed25519
91/// key.
92pub fn parse(id: &str) -> Option<AgentId> {
93    let encoded = id
94        .strip_prefix(ATOMIC_AGENT_PREFIX)
95        .or_else(|| id.strip_prefix(DID_AD_AGENT_PREFIX))?;
96    from_public_key(encoded)
97}
98
99/// The agent whose key is `public_key` (base64, either alphabet), as sent in
100/// Atomic's `x-atomic-public-key` header.
101pub fn from_public_key(public_key: &str) -> Option<AgentId> {
102    if public_key.is_empty() || public_key.len() > 128 {
103        return None;
104    }
105    let bytes: [u8; 32] = decode_base64(public_key)?.try_into().ok()?;
106    let key = VerifyingKey::from_bytes(&bytes).ok()?;
107    if key.is_weak() {
108        return None;
109    }
110    Some(AgentId {
111        canonical: format!("{ATOMIC_AGENT_PREFIX}{}", URL_SAFE_NO_PAD.encode(bytes)),
112        key: AgentKey::Ed25519(key),
113    })
114}
115
116/// Test-only signer: what an Atomic agent does on its side.
117#[cfg(test)]
118pub mod test_signer {
119    use super::*;
120    use ed25519_dalek::{Signer, SigningKey};
121
122    pub struct Agent(pub SigningKey);
123
124    impl Agent {
125        pub fn new(seed: u8) -> Self {
126            Self(SigningKey::from_bytes(&[seed; 32]))
127        }
128        pub fn public_key(&self) -> String {
129            URL_SAFE_NO_PAD.encode(self.0.verifying_key().as_bytes())
130        }
131        pub fn id(&self) -> String {
132            format!("{ATOMIC_AGENT_PREFIX}{}", self.public_key())
133        }
134        pub fn legacy_id(&self) -> String {
135            format!(
136                "{DID_AD_AGENT_PREFIX}{}",
137                STANDARD.encode(self.0.verifying_key().as_bytes())
138            )
139        }
140        pub fn sign(&self, message: &[u8]) -> String {
141            STANDARD.encode(self.0.sign(message).to_bytes())
142        }
143        /// A v2 request signature as atomic-server's signer encodes it:
144        /// `get_authentication_headers_v2` (`lib/src/client/helpers.rs`)
145        /// signs through `commit::sign_message` (`lib/src/commit.rs`), which
146        /// encodes with `agents::encode_base64` (`lib/src/agents.rs`):
147        /// URL-safe base64, unpadded. Pinned by its golden vectors
148        /// (`signature::tests`).
149        pub fn sign_v2(&self, message: &[u8]) -> String {
150            URL_SAFE_NO_PAD.encode(self.0.sign(message).to_bytes())
151        }
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::test_signer::Agent;
158    use super::*;
159
160    #[test]
161    fn every_accepted_spelling_canonicalizes_to_one_atomic_agent_id() {
162        let agent = Agent::new(7);
163        let key = agent.0.verifying_key();
164        let canonical = format!("atomic:agent:{}", URL_SAFE_NO_PAD.encode(key.as_bytes()));
165        for spelling in [
166            format!("atomic:agent:{}", URL_SAFE_NO_PAD.encode(key.as_bytes())),
167            format!("atomic:agent:{}", STANDARD.encode(key.as_bytes())),
168            format!(
169                "atomic:agent:{}",
170                STANDARD.encode(key.as_bytes()).trim_end_matches('=')
171            ),
172            format!("did:ad:agent:{}", URL_SAFE_NO_PAD.encode(key.as_bytes())),
173            format!("did:ad:agent:{}", STANDARD.encode(key.as_bytes())),
174            format!("did:ad:agent:{}=", URL_SAFE_NO_PAD.encode(key.as_bytes())),
175        ] {
176            let parsed = parse(&spelling).unwrap_or_else(|| panic!("{spelling}"));
177            assert_eq!(parsed.as_str(), canonical, "{spelling}");
178            assert_eq!(parsed, parse(&canonical).unwrap());
179        }
180        assert_eq!(
181            from_public_key(&STANDARD.encode(key.as_bytes()))
182                .unwrap()
183                .as_str(),
184            canonical
185        );
186    }
187
188    #[test]
189    fn a_key_that_needs_both_alphabets_to_differ_still_canonicalizes() {
190        // Find a key whose standard encoding contains '+' or '/', so the two
191        // alphabets really spell it differently.
192        let agent = (0u8..=255)
193            .map(Agent::new)
194            .find(|agent| {
195                let standard = STANDARD.encode(agent.0.verifying_key().as_bytes());
196                standard.contains('+') || standard.contains('/')
197            })
198            .expect("some seed has a '+' or '/' in its standard encoding");
199        let standard = STANDARD.encode(agent.0.verifying_key().as_bytes());
200        let parsed = parse(&format!("did:ad:agent:{standard}")).unwrap();
201        assert_eq!(parsed.as_str(), agent.id());
202        assert!(!parsed.as_str().contains('+') && !parsed.as_str().contains('/'));
203    }
204
205    #[test]
206    fn identifiers_without_an_ed25519_key_are_rejected() {
207        for id in [
208            "",
209            "atomic:agent:",
210            "did:ad:agent:",
211            "did:ad:agent:test",
212            "atomic:agent:pubkey123",
213            "atomic:agent:AAAA",
214            "https://example.com/agents/abc",
215            "atomic:commit:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
216            "atomic:node:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
217            // 32 zero bytes: a small-order (weak) Ed25519 point.
218            "atomic:agent:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
219            // A valid key with excessive padding.
220            &format!("{}===", Agent::new(1).id()),
221            // Surrounding whitespace is not stripped.
222            &format!(" {}", Agent::new(1).id()),
223            &format!("ATOMIC:AGENT:{}", Agent::new(1).public_key()),
224        ] {
225            assert!(parse(id).is_none(), "{id:?}");
226        }
227    }
228
229    #[test]
230    fn signatures_verify_only_for_their_own_key_and_message() {
231        let agent = Agent::new(3);
232        let other = Agent::new(4);
233        let parsed = parse(&agent.id()).unwrap();
234        let signature = agent.sign(b"message");
235        assert!(parsed.verify(b"message", &signature));
236        // Either alphabet for the signature itself.
237        let url_safe = URL_SAFE_NO_PAD.encode(STANDARD.decode(&signature).unwrap());
238        assert!(parsed.verify(b"message", &url_safe));
239        assert!(!parsed.verify(b"message2", &signature));
240        assert!(!parse(&other.id()).unwrap().verify(b"message", &signature));
241        assert!(!parsed.verify(b"message", "not-a-signature"));
242        assert!(!parsed.verify(b"message", ""));
243    }
244}