car-a2a 0.51.0

Bridge between Common Agent Runtime and the Linux Foundation Agent2Agent (A2A) v1.0 protocol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! Only CAR talks to CAR over the network.
//!
//! The A2A listener ships open (`NoAuth`) — fine behind a reverse proxy, not
//! fine bound to a LAN interface, which is where peer discovery puts it. This
//! module is what makes binding a reachable port safe: every peer request is
//! signed by the caller's ed25519 identity, and the listener refuses any signer
//! it does not already trust.
//!
//! ## Why signatures rather than a shared secret
//!
//! A secret derived from the login would authenticate "someone on this account"
//! and nothing finer. A per-daemon keypair authenticates *which machine* is
//! calling, can be revoked one host at a time, and never has to travel. The
//! private key is generated on first use and never leaves the device; only the
//! public half is published.
//!
//! ## How a key becomes trusted
//!
//! Trust does not come from the network. A peer's public key is trusted when it
//! arrives over a channel that was already authenticated:
//!
//! - **Same login** — the key rides the E2E-encrypted oplog next to the host's
//!   endpoint, so only a device holding the login's key material could have put
//!   it there.
//! - **Manual promotion** — an operator adds the peer explicitly, the same
//!   decision `a2a.peers.add` already represents.
//!
//! An mDNS advertisement carries a public key too, but that is a *claim*, not a
//! credential: anyone on the network can broadcast one. It is shown so an
//! operator can compare fingerprints when promoting, never trusted on arrival.
//!
//! ## What is signed
//!
//! A canonical string over method, path, timestamp, nonce, and a SHA-256 of the
//! body. Covering the body means a proxy cannot alter a message in flight;
//! covering method and path means a signature captured from one request cannot
//! be replayed against another endpoint.
//!
//! Replay is bounded twice: a timestamp outside a narrow window is refused
//! outright, and a nonce already seen inside that window is refused too. Either
//! alone is insufficient — a window with no nonce check lets an attacker replay
//! freely inside it, and a nonce set with no window has to grow forever.
//!
//! ## What this is not
//!
//! Authentication and integrity, not confidentiality. A signed request over
//! plain HTTP is unforgeable but readable on the wire. Bodies that must stay
//! private need TLS in front, or payload encryption — the oplog already does
//! the latter for synced state.

use base64::Engine;
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use sha2::{Digest, Sha256};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::{Arc, Mutex};

/// Header carrying the caller's base64 ed25519 public key.
pub const H_KEY: &str = "x-car-peer-key";
/// Header carrying the signing timestamp, Unix milliseconds.
pub const H_TS: &str = "x-car-peer-ts";
/// Header carrying a per-request nonce.
pub const H_NONCE: &str = "x-car-peer-nonce";
/// Header carrying the base64 signature.
pub const H_SIG: &str = "x-car-peer-sig";

/// How far a request's timestamp may be from ours, in milliseconds.
///
/// Narrow enough that a captured request is useless almost immediately, wide
/// enough to survive ordinary clock skew between two machines that have never
/// synchronised with each other.
pub const CLOCK_SKEW_MS: u64 = 60_000;

const B64: base64::engine::general_purpose::GeneralPurpose =
    base64::engine::general_purpose::STANDARD_NO_PAD;

/// This daemon's signing identity.
pub struct PeerIdentity {
    signing: SigningKey,
}

impl PeerIdentity {
    /// Load the identity at `path`, generating one on first use.
    ///
    /// The file holds a private key, so it is created 0600 and its directory
    /// 0700. A key that leaked would let its holder impersonate this host to
    /// every peer that trusts it.
    pub fn load_or_generate(path: &Path) -> Result<Self, String> {
        if let Ok(raw) = std::fs::read(path) {
            if raw.len() == 32 {
                let mut b = [0u8; 32];
                b.copy_from_slice(&raw);
                return Ok(Self {
                    signing: SigningKey::from_bytes(&b),
                });
            }
            // A wrong-sized file is corruption, not a key. Refuse rather than
            // silently minting a new identity: every peer trusting the old key
            // would stop recognising this host, and the operator would see an
            // unexplained authentication failure instead of a clear error.
            return Err(format!(
                "{} is not a 32-byte ed25519 key ({} bytes); refusing to replace it",
                path.display(),
                raw.len()
            ));
        }
        let signing = SigningKey::generate(&mut rand_core::OsRng);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| format!("create key dir: {e}"))?;
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700));
            }
        }
        std::fs::write(path, signing.to_bytes()).map_err(|e| format!("write key: {e}"))?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
        }
        Ok(Self { signing })
    }

    /// Build from raw key bytes. Test seam.
    pub fn from_bytes(b: [u8; 32]) -> Self {
        Self {
            signing: SigningKey::from_bytes(&b),
        }
    }

    /// This host's public key, base64. Safe to publish.
    pub fn public_key(&self) -> String {
        B64.encode(self.signing.verifying_key().to_bytes())
    }

    /// A short fingerprint for an operator comparing keys by eye.
    pub fn fingerprint(&self) -> String {
        fingerprint_of(&self.public_key())
    }

    /// Headers authenticating one request.
    pub fn sign(
        &self,
        method: &str,
        path: &str,
        body: &[u8],
        now_ms: u64,
    ) -> Vec<(String, String)> {
        let nonce = B64.encode(uuid_bytes());
        let canonical = canonical_string(method, path, now_ms, &nonce, body);
        let sig = self.signing.sign(canonical.as_bytes());
        vec![
            (H_KEY.to_string(), self.public_key()),
            (H_TS.to_string(), now_ms.to_string()),
            (H_NONCE.to_string(), nonce),
            (H_SIG.to_string(), B64.encode(sig.to_bytes())),
        ]
    }
}

fn uuid_bytes() -> [u8; 16] {
    *uuid::Uuid::new_v4().as_bytes()
}

/// Short, human-comparable form of a public key.
pub fn fingerprint_of(public_key_b64: &str) -> String {
    let digest = Sha256::digest(public_key_b64.as_bytes());
    digest[..4]
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect::<Vec<_>>()
        .join(":")
}

/// The exact bytes both sides sign over.
///
/// Newline-separated with a hashed body: the body may be large or non-UTF-8, and
/// hashing keeps the signed string bounded while still committing to every byte.
fn canonical_string(method: &str, path: &str, ts_ms: u64, nonce: &str, body: &[u8]) -> String {
    let body_hash = Sha256::digest(body);
    format!(
        "{}\n{}\n{}\n{}\n{}",
        method.to_ascii_uppercase(),
        path,
        ts_ms,
        nonce,
        B64.encode(body_hash)
    )
}

/// Why a peer request was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PeerAuthError {
    /// One of the four headers was absent.
    MissingHeaders,
    /// The key or signature was not decodable as ed25519 material.
    Malformed(String),
    /// The signature did not verify for the presented key.
    BadSignature,
    /// The timestamp is outside [`CLOCK_SKEW_MS`].
    StaleTimestamp,
    /// This nonce was already used inside the window.
    Replay,
    /// The signature is valid, but this key is not a peer we trust.
    ///
    /// Distinct from [`PeerAuthError::BadSignature`] on purpose: this is the
    /// expected outcome for a stranger on the network, and an operator
    /// diagnosing a peering problem needs to tell "wrong key" apart from "not
    /// yet trusted".
    UntrustedKey { fingerprint: String },
}

impl PeerAuthError {
    pub fn message(&self) -> String {
        match self {
            PeerAuthError::MissingHeaders => {
                "peer authentication headers are missing; only CAR peers may call this surface"
                    .into()
            }
            PeerAuthError::Malformed(w) => format!("malformed peer credential: {w}"),
            PeerAuthError::BadSignature => "peer signature did not verify".into(),
            PeerAuthError::StaleTimestamp => {
                format!("peer request timestamp is outside the {CLOCK_SKEW_MS}ms window")
            }
            PeerAuthError::Replay => "peer request nonce was already used".into(),
            PeerAuthError::UntrustedKey { fingerprint } => format!(
                "peer key {fingerprint} is not trusted by this host; add it with a2a.peers.add \
                 after comparing the fingerprint"
            ),
        }
    }
}

/// The set of peer keys this host accepts, plus replay state.
#[derive(Clone)]
pub struct PeerTrust {
    trusted: Arc<Mutex<HashSet<String>>>,
    seen: Arc<Mutex<HashMap<String, u64>>>,
}

impl Default for PeerTrust {
    fn default() -> Self {
        Self::new()
    }
}

impl PeerTrust {
    pub fn new() -> Self {
        Self {
            trusted: Arc::new(Mutex::new(HashSet::new())),
            seen: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Replace the trusted set.
    ///
    /// Wholesale replacement rather than incremental adds: the set is derived
    /// from the oplog and the peer registry, so a key removed there must stop
    /// being accepted here, and an add-only API would silently keep revoked
    /// peers working.
    pub fn set_trusted(&self, keys: impl IntoIterator<Item = String>) {
        let mut t = self.trusted.lock().unwrap_or_else(|e| e.into_inner());
        *t = keys.into_iter().collect();
    }

    pub fn trusted_count(&self) -> usize {
        self.trusted.lock().unwrap_or_else(|e| e.into_inner()).len()
    }

    pub fn is_trusted(&self, public_key_b64: &str) -> bool {
        self.trusted
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .contains(public_key_b64)
    }

    /// Verify one request. `now_ms` is injected so the window is testable.
    pub fn verify(
        &self,
        headers: &PeerHeaders,
        method: &str,
        path: &str,
        body: &[u8],
        now_ms: u64,
    ) -> Result<String, PeerAuthError> {
        let key_bytes = B64
            .decode(&headers.key)
            .map_err(|e| PeerAuthError::Malformed(format!("key: {e}")))?;
        let key_arr: [u8; 32] = key_bytes
            .try_into()
            .map_err(|_| PeerAuthError::Malformed("key is not 32 bytes".into()))?;
        let verifying = VerifyingKey::from_bytes(&key_arr)
            .map_err(|e| PeerAuthError::Malformed(format!("key: {e}")))?;

        let ts: u64 = headers
            .ts
            .parse()
            .map_err(|_| PeerAuthError::Malformed("timestamp is not a number".into()))?;
        if now_ms.abs_diff(ts) > CLOCK_SKEW_MS {
            return Err(PeerAuthError::StaleTimestamp);
        }

        let sig_bytes = B64
            .decode(&headers.sig)
            .map_err(|e| PeerAuthError::Malformed(format!("signature: {e}")))?;
        let sig_arr: [u8; 64] = sig_bytes
            .try_into()
            .map_err(|_| PeerAuthError::Malformed("signature is not 64 bytes".into()))?;
        let signature = Signature::from_bytes(&sig_arr);

        let canonical = canonical_string(method, path, ts, &headers.nonce, body);
        verifying
            .verify(canonical.as_bytes(), &signature)
            .map_err(|_| PeerAuthError::BadSignature)?;

        // Trust is checked AFTER the signature so an attacker cannot use the
        // error to probe which keys this host trusts without holding the
        // matching private key.
        if !self.is_trusted(&headers.key) {
            return Err(PeerAuthError::UntrustedKey {
                fingerprint: fingerprint_of(&headers.key),
            });
        }

        // Replay last: only a request that is otherwise entirely valid is worth
        // spending a nonce slot on, so a flood of junk cannot grow the cache.
        {
            let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
            seen.retain(|_, t| now_ms.saturating_sub(*t) <= CLOCK_SKEW_MS);
            if seen.contains_key(&headers.nonce) {
                return Err(PeerAuthError::Replay);
            }
            seen.insert(headers.nonce.clone(), now_ms);
        }

        Ok(headers.key.clone())
    }
}

/// The four credential headers, already extracted from a request.
#[derive(Debug, Clone)]
pub struct PeerHeaders {
    pub key: String,
    pub ts: String,
    pub nonce: String,
    pub sig: String,
}

impl PeerHeaders {
    /// Pull the credential out of a header map, or `None` when absent.
    pub fn from_map(get: impl Fn(&str) -> Option<String>) -> Option<Self> {
        Some(Self {
            key: get(H_KEY)?,
            ts: get(H_TS)?,
            nonce: get(H_NONCE)?,
            sig: get(H_SIG)?,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ident(seed: u8) -> PeerIdentity {
        PeerIdentity::from_bytes([seed; 32])
    }

    fn headers(v: Vec<(String, String)>) -> PeerHeaders {
        let map: HashMap<String, String> = v.into_iter().collect();
        PeerHeaders::from_map(|k| map.get(k).cloned()).expect("all four headers")
    }

    #[test]
    fn a_trusted_peers_signature_is_accepted() {
        let me = ident(1);
        let trust = PeerTrust::new();
        trust.set_trusted([me.public_key()]);
        let h = headers(me.sign("POST", "/a2a", b"hello", 1_000));
        assert_eq!(
            trust.verify(&h, "POST", "/a2a", b"hello", 1_000).unwrap(),
            me.public_key()
        );
    }

    #[test]
    fn a_stranger_with_a_valid_signature_is_still_refused() {
        // The whole point: anyone can generate a keypair and sign correctly.
        // Only a key this host already trusts gets in.
        let stranger = ident(9);
        let trust = PeerTrust::new();
        trust.set_trusted([ident(1).public_key()]);
        let h = headers(stranger.sign("POST", "/a2a", b"hello", 1_000));
        assert!(matches!(
            trust.verify(&h, "POST", "/a2a", b"hello", 1_000),
            Err(PeerAuthError::UntrustedKey { .. })
        ));
    }

    #[test]
    fn a_tampered_body_breaks_the_signature() {
        let me = ident(1);
        let trust = PeerTrust::new();
        trust.set_trusted([me.public_key()]);
        let h = headers(me.sign("POST", "/a2a", b"original", 1_000));
        assert_eq!(
            trust.verify(&h, "POST", "/a2a", b"tampered", 1_000),
            Err(PeerAuthError::BadSignature)
        );
    }

    #[test]
    fn a_signature_cannot_be_replayed_against_another_path_or_method() {
        let me = ident(1);
        let trust = PeerTrust::new();
        trust.set_trusted([me.public_key()]);
        let h = headers(me.sign("POST", "/a2a", b"x", 1_000));
        assert_eq!(
            trust.verify(&h, "POST", "/admin", b"x", 1_000),
            Err(PeerAuthError::BadSignature)
        );
        assert_eq!(
            trust.verify(&h, "DELETE", "/a2a", b"x", 1_000),
            Err(PeerAuthError::BadSignature)
        );
    }

    #[test]
    fn a_stale_request_is_refused() {
        let me = ident(1);
        let trust = PeerTrust::new();
        trust.set_trusted([me.public_key()]);
        let h = headers(me.sign("POST", "/a2a", b"x", 1_000));
        let much_later = 1_000 + CLOCK_SKEW_MS + 1;
        assert_eq!(
            trust.verify(&h, "POST", "/a2a", b"x", much_later),
            Err(PeerAuthError::StaleTimestamp)
        );
        // Skew in the other direction is refused too: a future-dated request
        // would otherwise stay valid for twice the window.
        let h2 = headers(me.sign("POST", "/a2a", b"x", much_later));
        assert_eq!(
            trust.verify(&h2, "POST", "/a2a", b"x", 1_000),
            Err(PeerAuthError::StaleTimestamp)
        );
    }

    #[test]
    fn a_captured_request_cannot_be_replayed_inside_the_window() {
        let me = ident(1);
        let trust = PeerTrust::new();
        trust.set_trusted([me.public_key()]);
        let h = headers(me.sign("POST", "/a2a", b"x", 1_000));
        assert!(trust.verify(&h, "POST", "/a2a", b"x", 1_000).is_ok());
        // Byte-identical replay, still inside the clock window.
        assert_eq!(
            trust.verify(&h, "POST", "/a2a", b"x", 1_500),
            Err(PeerAuthError::Replay)
        );
    }

    #[test]
    fn revoking_a_key_stops_it_immediately() {
        let me = ident(1);
        let trust = PeerTrust::new();
        trust.set_trusted([me.public_key()]);
        assert!(trust
            .verify(
                &headers(me.sign("POST", "/a2a", b"x", 1_000)),
                "POST",
                "/a2a",
                b"x",
                1_000
            )
            .is_ok());
        // Wholesale replacement is what makes revocation real.
        trust.set_trusted(Vec::<String>::new());
        assert!(matches!(
            trust.verify(
                &headers(me.sign("POST", "/a2a", b"y", 2_000)),
                "POST",
                "/a2a",
                b"y",
                2_000
            ),
            Err(PeerAuthError::UntrustedKey { .. })
        ));
    }

    #[test]
    fn missing_credentials_are_refused_rather_than_defaulting_open() {
        let empty: HashMap<String, String> = HashMap::new();
        assert!(PeerHeaders::from_map(|k| empty.get(k).cloned()).is_none());
    }

    #[test]
    fn a_corrupt_key_file_is_not_silently_replaced() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("peer-identity.key");
        std::fs::write(&path, b"not-a-key").unwrap();
        // Minting a fresh identity here would silently break every peer that
        // trusted the old one, presenting as an unexplained auth failure.
        assert!(PeerIdentity::load_or_generate(&path).is_err());
    }

    #[test]
    fn an_identity_persists_across_loads() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("peer-identity.key");
        let a = PeerIdentity::load_or_generate(&path).unwrap();
        let b = PeerIdentity::load_or_generate(&path).unwrap();
        assert_eq!(a.public_key(), b.public_key());
        assert_eq!(a.fingerprint(), b.fingerprint());
    }

    #[test]
    fn fingerprints_are_short_stable_and_key_specific() {
        let a = ident(1).fingerprint();
        assert_eq!(a, ident(1).fingerprint());
        assert_ne!(a, ident(2).fingerprint());
        assert_eq!(a.len(), 11, "four hex bytes joined by colons");
    }
}