1use base64::Engine;
2use chrono::{DateTime, Utc};
3use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
4use hmac::{Hmac, KeyInit, Mac};
5use lean_ctx_protocol::DataClassification;
6use serde::{Deserialize, Serialize};
7use sha2::Sha256;
8use std::collections::HashSet;
9use std::net::IpAddr;
10
11use super::super::a2a_transport::TransportContentType;
12
13pub const RELAY_RECORD_VERSION: u8 = 1;
14pub const RELAY_PEER_TABLE_VERSION: u8 = 1;
15pub const RELAY_METADATA_KEY: &str = "leanctx.relay.v1";
16pub const RELAY_PEER_HEADER: &str = "x-leanctx-peer-id";
17pub const RELAY_MAX_HOPS: usize = 16;
18pub const RELAY_MAX_PEERS: usize = 32;
19pub const RELAY_MAX_RECORD_BYTES: usize = 32 * 1024;
20pub const RELAY_MAX_PAYLOAD_BYTES: usize = 2 * 1024 * 1024;
21pub const RELAY_MAX_DEADLINE_SECS: i64 = 24 * 60 * 60;
22pub const RELAY_MAX_RETRIES: u8 = 5;
23pub const RELAY_MAX_RETRY_DELAY_MS: u64 = 30_000;
24pub const RELAY_MAX_ID_BYTES: usize = 128;
25
26type HmacSha256 = Hmac<Sha256>;
27
28#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
29#[serde(deny_unknown_fields)]
30pub struct RelayHop {
31 pub agent_id: String,
32 pub received_at: DateTime<Utc>,
33 pub forwarded_at: Option<DateTime<Utc>>,
34 pub processing_ms: Option<u64>,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
38#[serde(deny_unknown_fields)]
39pub struct RelayChain {
40 pub hops: Vec<RelayHop>,
41 pub max_hops: usize,
42}
43
44impl RelayChain {
45 pub fn new(max_hops: usize) -> Self {
46 Self {
47 hops: Vec::new(),
48 max_hops,
49 }
50 }
51
52 pub fn add_hop(&mut self, hop: RelayHop) -> Result<(), RelayError> {
53 if self.max_hops == 0 || self.max_hops > RELAY_MAX_HOPS || self.hops.len() >= self.max_hops
54 {
55 return Err(RelayError::MaxHopsExceeded(self.max_hops));
56 }
57 if hop.agent_id.is_empty() || hop.agent_id.len() > RELAY_MAX_ID_BYTES {
58 return Err(RelayError::Malformed("relay hop identity".into()));
59 }
60 if self.contains_agent(&hop.agent_id) {
61 return Err(RelayError::CycleDetected(hop.agent_id));
62 }
63 if hop
64 .forwarded_at
65 .is_some_and(|forwarded| forwarded < hop.received_at)
66 {
67 return Err(RelayError::Malformed("relay hop timestamps".into()));
68 }
69 self.hops.push(hop);
70 Ok(())
71 }
72
73 pub fn add_peer_hop(
74 &mut self,
75 agent_id: impl Into<String>,
76 now: DateTime<Utc>,
77 ) -> Result<(), RelayError> {
78 self.add_hop(RelayHop {
79 agent_id: agent_id.into(),
80 received_at: now,
81 forwarded_at: Some(now),
82 processing_ms: Some(0),
83 })
84 }
85
86 pub fn depth(&self) -> usize {
87 self.hops.len()
88 }
89
90 pub fn total_latency_ms(&self) -> u64 {
91 self.hops
92 .iter()
93 .filter_map(|hop| hop.processing_ms)
94 .fold(0, u64::saturating_add)
95 }
96
97 pub fn contains_agent(&self, agent_id: &str) -> bool {
98 self.hops.iter().any(|hop| hop.agent_id == agent_id)
99 }
100
101 pub fn origin(&self) -> Option<&str> {
102 self.hops.first().map(|hop| hop.agent_id.as_str())
103 }
104
105 pub fn validate(&self) -> Result<(), RelayError> {
106 if self.max_hops == 0
107 || self.max_hops > RELAY_MAX_HOPS
108 || self.hops.is_empty()
109 || self.hops.len() > self.max_hops
110 {
111 return Err(RelayError::MaxHopsExceeded(self.max_hops));
112 }
113 let mut identities = HashSet::new();
114 for hop in &self.hops {
115 if hop.agent_id.is_empty() || hop.agent_id.len() > RELAY_MAX_ID_BYTES {
116 return Err(RelayError::Malformed("relay hop identity".into()));
117 }
118 if hop
119 .forwarded_at
120 .is_some_and(|forwarded| forwarded < hop.received_at)
121 || !identities.insert(&hop.agent_id)
122 {
123 return Err(RelayError::CycleDetected(hop.agent_id.clone()));
124 }
125 }
126 Ok(())
127 }
128}
129
130impl Default for RelayChain {
131 fn default() -> Self {
132 Self::new(5)
133 }
134}
135
136#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
137struct RelayOriginView<'a> {
138 schema_version: u8,
139 payload_sha256: &'a str,
140 delivery_id: &'a str,
141 origin: &'a str,
142 final_recipient: &'a str,
143 tenant_id: &'a str,
144 project_id: &'a str,
145 content_type: &'a TransportContentType,
146 classification: &'a DataClassification,
147 expires_at: DateTime<Utc>,
148 max_hops: usize,
149 origin_hop: &'a RelayHop,
150}
151
152#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
153#[serde(deny_unknown_fields)]
154pub struct RelayRecordV1 {
155 pub schema_version: u8,
156 pub payload_sha256: String,
157 pub delivery_id: String,
158 pub origin: String,
159 pub final_recipient: String,
160 pub current_peer: String,
161 pub next_peer: String,
162 pub tenant_id: String,
163 pub project_id: String,
164 pub content_type: TransportContentType,
165 pub classification: DataClassification,
166 pub expires_at: DateTime<Utc>,
167 pub relay_chain: RelayChain,
168 pub origin_signature: String,
169 pub hop_signature: String,
170}
171
172impl RelayRecordV1 {
173 #[allow(clippy::too_many_arguments)]
174 pub fn new_signed(
175 delivery_id: impl Into<String>,
176 origin: impl Into<String>,
177 final_recipient: impl Into<String>,
178 tenant_id: impl Into<String>,
179 project_id: impl Into<String>,
180 content_type: TransportContentType,
181 classification: DataClassification,
182 expires_at: DateTime<Utc>,
183 max_hops: usize,
184 now: DateTime<Utc>,
185 origin_key: &SigningKey,
186 channel_key: &str,
187 payload: &[u8],
188 ) -> Result<Self, RelayError> {
189 let origin = origin.into();
190 let mut relay_chain = RelayChain::new(max_hops);
191 relay_chain.add_peer_hop(origin.clone(), now)?;
192 let mut record = Self {
193 schema_version: RELAY_RECORD_VERSION,
194 payload_sha256: Self::payload_digest(payload),
195 delivery_id: delivery_id.into(),
196 origin: origin.clone(),
197 final_recipient: final_recipient.into(),
198 current_peer: origin,
199 next_peer: String::new(),
200 tenant_id: tenant_id.into(),
201 project_id: project_id.into(),
202 content_type,
203 classification,
204 expires_at,
205 relay_chain,
206 origin_signature: String::new(),
207 hop_signature: String::new(),
208 };
209 record.next_peer = record.final_recipient.clone();
210 record.validate_shape()?;
211 record.validate_deadline(now)?;
212 record.origin_signature = record.sign_origin(origin_key)?;
213 record.hop_signature = record.sign_hop(channel_key)?;
214 Ok(record)
215 }
216
217 pub fn validate_shape(&self) -> Result<(), RelayError> {
218 if self.payload_sha256.len() != 64
219 || !self
220 .payload_sha256
221 .bytes()
222 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
223 {
224 return Err(RelayError::Malformed("payload digest".into()));
225 }
226 if self.schema_version != RELAY_RECORD_VERSION {
227 return Err(RelayError::Malformed("relay record version".into()));
228 }
229 for (name, value) in [
230 ("delivery_id", self.delivery_id.as_str()),
231 ("origin", self.origin.as_str()),
232 ("final_recipient", self.final_recipient.as_str()),
233 ("current_peer", self.current_peer.as_str()),
234 ("next_peer", self.next_peer.as_str()),
235 ("tenant_id", self.tenant_id.as_str()),
236 ("project_id", self.project_id.as_str()),
237 ] {
238 if value.is_empty() || value.len() > RELAY_MAX_ID_BYTES {
239 return Err(RelayError::Malformed(name.into()));
240 }
241 }
242 if self.origin_signature.len() > RELAY_MAX_ID_BYTES * 2
243 || self.hop_signature.len() > RELAY_MAX_ID_BYTES * 2
244 {
245 return Err(RelayError::Malformed("relay signature".into()));
246 }
247 self.relay_chain.validate()?;
248 if self
249 .relay_chain
250 .hops
251 .last()
252 .map(|hop| hop.agent_id.as_str())
253 != Some(self.current_peer.as_str())
254 || self.relay_chain.origin() != Some(self.origin.as_str())
255 {
256 return Err(RelayError::Malformed("relay chain identity".into()));
257 }
258 Ok(())
259 }
260
261 fn validate_deadline(&self, now: DateTime<Utc>) -> Result<(), RelayError> {
262 if self.expires_at <= now {
263 return Err(RelayError::DeadlineExceeded);
264 }
265 if self.expires_at.signed_duration_since(now).num_seconds() > RELAY_MAX_DEADLINE_SECS {
266 return Err(RelayError::Malformed("relay deadline exceeds cap".into()));
267 }
268 Ok(())
269 }
270
271 pub fn validate_at(
272 &self,
273 now: DateTime<Utc>,
274 expected_current: &str,
275 expected_next: Option<&str>,
276 max_hops: usize,
277 ) -> Result<(), RelayError> {
278 self.validate_shape()?;
279 self.validate_deadline(now)?;
280 if self.current_peer != expected_current
281 || expected_next
282 .map(|peer| self.next_peer != peer)
283 .unwrap_or(false)
284 {
285 return Err(RelayError::RouteMismatch);
286 }
287 if self.relay_chain.max_hops > max_hops || self.relay_chain.depth() > max_hops {
288 return Err(RelayError::MaxHopsExceeded(max_hops));
289 }
290 if self.origin_signature.is_empty() || self.hop_signature.is_empty() {
291 return Err(RelayError::InvalidSignature);
292 }
293 Ok(())
294 }
295
296 fn origin_view(&self) -> Result<RelayOriginView<'_>, RelayError> {
297 Ok(RelayOriginView {
298 schema_version: self.schema_version,
299 payload_sha256: &self.payload_sha256,
300 delivery_id: &self.delivery_id,
301 origin: &self.origin,
302 final_recipient: &self.final_recipient,
303 tenant_id: &self.tenant_id,
304 project_id: &self.project_id,
305 content_type: &self.content_type,
306 classification: &self.classification,
307 expires_at: self.expires_at,
308 max_hops: self.relay_chain.max_hops,
309 origin_hop: self
310 .relay_chain
311 .hops
312 .first()
313 .ok_or_else(|| RelayError::Malformed("relay origin hop".into()))?,
314 })
315 }
316
317 fn origin_bytes(&self) -> Result<Vec<u8>, RelayError> {
318 serde_json::to_vec(&("leanctx.relay.origin.v1", self.origin_view()?))
319 .map_err(|e| RelayError::Malformed(e.to_string()))
320 }
321
322 pub(crate) fn origin_fingerprint(&self) -> Result<String, RelayError> {
323 Ok(Self::payload_digest(&self.origin_bytes()?))
324 }
325
326 fn payload_digest(payload: &[u8]) -> String {
327 use sha2::Digest;
328 hex::encode(Sha256::digest(payload))
329 }
330
331 pub fn verify_payload(&self, payload: &[u8]) -> Result<(), RelayError> {
332 if self.payload_sha256 != Self::payload_digest(payload) {
333 return Err(RelayError::InvalidSignature);
334 }
335 Ok(())
336 }
337
338 fn hop_bytes(&self) -> Result<Vec<u8>, RelayError> {
339 let mut unsigned = self.clone();
340 unsigned.hop_signature.clear();
341 serde_json::to_vec(&("leanctx.relay.hop.v1", unsigned))
342 .map_err(|e| RelayError::Malformed(e.to_string()))
343 }
344
345 fn sign(key: &str, bytes: &[u8]) -> Result<String, RelayError> {
346 if key.is_empty() {
347 return Err(RelayError::InvalidCredential);
348 }
349 let mut mac = HmacSha256::new_from_slice(key.as_bytes())
350 .map_err(|_| RelayError::InvalidCredential)?;
351 mac.update(bytes);
352 Ok(hex::encode(mac.finalize().into_bytes()))
353 }
354
355 fn sign_origin(&self, key: &SigningKey) -> Result<String, RelayError> {
356 Ok(hex::encode(key.sign(&self.origin_bytes()?).to_bytes()))
357 }
358
359 fn sign_hop(&self, key: &str) -> Result<String, RelayError> {
360 Self::sign(key, &self.hop_bytes()?)
361 }
362
363 pub fn verify_origin(&self, key: &str) -> Result<(), RelayError> {
364 let key = decode_origin_key(key)?;
365 if self.origin_signature.len() != 128 {
366 return Err(RelayError::InvalidSignature);
367 }
368 let bytes =
369 hex::decode(&self.origin_signature).map_err(|_| RelayError::InvalidSignature)?;
370 let signature = Signature::from_slice(&bytes).map_err(|_| RelayError::InvalidSignature)?;
371 key.verify_strict(&self.origin_bytes()?, &signature)
372 .map_err(|_| RelayError::InvalidSignature)
373 }
374
375 pub fn verify_hop(&self, key: &str) -> Result<(), RelayError> {
376 verify_signature(&self.hop_signature, &self.sign_hop(key)?)
377 }
378
379 pub fn route_from_origin(
381 &mut self,
382 next_peer: impl Into<String>,
383 now: DateTime<Utc>,
384 origin_public_key: &str,
385 channel_key: &str,
386 ) -> Result<(), RelayError> {
387 self.validate_at(now, &self.origin, None, self.relay_chain.max_hops)?;
388 self.verify_origin(origin_public_key)?;
389 if self.relay_chain.depth() != 1 {
390 return Err(RelayError::RouteMismatch);
391 }
392 let mut routed = self.clone();
393 routed.next_peer = next_peer.into();
394 if routed.relay_chain.contains_agent(&routed.next_peer) {
395 return Err(RelayError::CycleDetected(routed.next_peer));
396 }
397 routed.validate_shape()?;
398 routed.hop_signature = routed.sign_hop(channel_key)?;
399 *self = routed;
400 Ok(())
401 }
402
403 pub fn forward_from(
404 &mut self,
405 local_peer: impl Into<String>,
406 next_peer: impl Into<String>,
407 now: DateTime<Utc>,
408 hop_key: &str,
409 ) -> Result<(), RelayError> {
410 self.validate_at(
411 now,
412 &self.current_peer.clone(),
413 None,
414 self.relay_chain.max_hops,
415 )?;
416 let local_peer = local_peer.into();
417 if local_peer != self.next_peer {
418 return Err(RelayError::RouteMismatch);
419 }
420 let mut forwarded = self.clone();
421 forwarded
422 .relay_chain
423 .add_peer_hop(local_peer.clone(), now)?;
424 forwarded.current_peer = local_peer;
425 forwarded.next_peer = next_peer.into();
426 if forwarded.relay_chain.contains_agent(&forwarded.next_peer) {
427 return Err(RelayError::CycleDetected(forwarded.next_peer));
428 }
429 forwarded.validate_shape()?;
430 forwarded.hop_signature = forwarded.sign_hop(hop_key)?;
431 *self = forwarded;
432 Ok(())
433 }
434
435 pub fn encode_metadata(&self) -> Result<String, RelayError> {
436 self.validate_shape()?;
437 let bytes = serde_json::to_vec(self).map_err(|e| RelayError::Malformed(e.to_string()))?;
438 if bytes.len() > RELAY_MAX_RECORD_BYTES {
439 return Err(RelayError::Oversize);
440 }
441 Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes))
442 }
443
444 pub fn decode_metadata(value: &str) -> Result<Self, RelayError> {
445 if value.is_empty() || value.len() > RELAY_MAX_RECORD_BYTES * 2 {
446 return Err(RelayError::Oversize);
447 }
448 let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
449 .decode(value)
450 .map_err(|_| RelayError::Malformed("relay metadata encoding".into()))?;
451 if bytes.len() > RELAY_MAX_RECORD_BYTES {
452 return Err(RelayError::Oversize);
453 }
454 let record: Self = serde_json::from_slice(&bytes)
455 .map_err(|e| RelayError::Malformed(format!("relay metadata: {e}")))?;
456 record.validate_shape()?;
457 if record.encode_metadata()? != value {
458 return Err(RelayError::Malformed("non-canonical relay metadata".into()));
459 }
460 Ok(record)
461 }
462}
463
464fn verify_signature(actual: &str, expected: &str) -> Result<(), RelayError> {
465 let actual = hex::decode(actual).map_err(|_| RelayError::InvalidSignature)?;
466 let expected = hex::decode(expected).map_err(|_| RelayError::InvalidSignature)?;
467 if actual.len() != expected.len() || !constant_time_eq(&actual, &expected) {
468 return Err(RelayError::InvalidSignature);
469 }
470 Ok(())
471}
472
473fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
474 if left.len() != right.len() {
475 return false;
476 }
477 let mut difference = 0u8;
478 for (&left, &right) in left.iter().zip(right) {
479 difference |= left ^ right;
480 }
481 difference == 0
482}
483
484fn decode_origin_key(raw: &str) -> Result<VerifyingKey, RelayError> {
485 if raw.len() != 64 {
486 return Err(RelayError::InvalidCredential);
487 }
488 let bytes: [u8; 32] = hex::decode(raw)
489 .map_err(|_| RelayError::InvalidCredential)?
490 .try_into()
491 .map_err(|_| RelayError::InvalidCredential)?;
492 let key = VerifyingKey::from_bytes(&bytes).map_err(|_| RelayError::InvalidCredential)?;
493 if key.is_weak() {
494 return Err(RelayError::InvalidCredential);
495 }
496 Ok(key)
497}
498
499#[cfg(test)]
500pub(crate) fn test_origin_key(label: &str) -> SigningKey {
501 use sha2::Digest;
502 let seed: [u8; 32] = Sha256::digest(format!("test-only-relay-origin:{label}")).into();
504 SigningKey::from_bytes(&seed)
505}
506
507#[cfg(test)]
508pub(crate) fn test_origin_public_key(label: &str) -> String {
509 hex::encode(test_origin_key(label).verifying_key().to_bytes())
510}
511
512#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
513#[serde(deny_unknown_fields)]
514pub struct RelayPeerConfigV1 {
515 pub schema_version: u8,
516 pub peer_id: String,
517 pub endpoint_url: String,
518 pub bearer_token: String,
519 pub channel_key: String,
520 pub origin_public_key: String,
522 pub recipient_id: String,
523 pub allowed_tenant_ids: Vec<String>,
524 pub allowed_project_ids: Vec<String>,
525 pub allowed_content_types: Vec<TransportContentType>,
526 pub allowed_classifications: Vec<DataClassification>,
527 pub max_hops: usize,
528 pub max_payload_bytes: usize,
529 pub retry_count: u8,
530 pub retry_delay_ms: u64,
531}
532
533impl RelayPeerConfigV1 {
534 pub fn validate(&self, allow_loopback_http: bool) -> Result<(), RelayError> {
535 decode_origin_key(&self.origin_public_key)?;
536 if self.schema_version != RELAY_PEER_TABLE_VERSION
537 || self.peer_id.is_empty()
538 || self.peer_id == "legacy"
539 || self.peer_id.len() > RELAY_MAX_ID_BYTES
540 || self.recipient_id.is_empty()
541 || self.recipient_id.len() > RELAY_MAX_ID_BYTES
542 || self.bearer_token.is_empty()
543 || self.channel_key.is_empty()
544 || self.bearer_token == self.channel_key
545 {
546 return Err(RelayError::InvalidPeer(self.peer_id.clone()));
547 }
548 if self.allowed_tenant_ids.is_empty()
549 || self.allowed_project_ids.is_empty()
550 || self.allowed_content_types.is_empty()
551 || self.allowed_classifications.is_empty()
552 {
553 return Err(RelayError::ScopeViolation);
554 }
555 ensure_unique(&self.allowed_tenant_ids)?;
556 ensure_unique(&self.allowed_project_ids)?;
557 if self.max_hops == 0 || self.max_hops > RELAY_MAX_HOPS {
558 return Err(RelayError::MaxHopsExceeded(self.max_hops));
559 }
560 if self.max_payload_bytes == 0 || self.max_payload_bytes > RELAY_MAX_PAYLOAD_BYTES {
561 return Err(RelayError::Oversize);
562 }
563 if self.retry_count > RELAY_MAX_RETRIES || self.retry_delay_ms > RELAY_MAX_RETRY_DELAY_MS {
564 return Err(RelayError::RetryCap);
565 }
566 if self
567 .allowed_content_types
568 .iter()
569 .any(|kind| matches!(kind, TransportContentType::A2AMessage))
570 {
571 return Err(RelayError::ScopeViolation);
572 }
573 let url = reqwest::Url::parse(&self.endpoint_url)
574 .map_err(|_| RelayError::InvalidPeer(self.peer_id.clone()))?;
575 let loopback = url.host_str().map(is_loopback_host).unwrap_or(false);
576 if url.host_str().is_none()
577 || !url.username().is_empty()
578 || url.password().is_some()
579 || !(url.scheme() == "https"
580 || (allow_loopback_http && loopback && url.scheme() == "http"))
581 {
582 return Err(RelayError::InvalidPeer(self.peer_id.clone()));
583 }
584 Ok(())
585 }
586
587 pub fn allows(&self, record: &RelayRecordV1, payload_bytes: usize) -> bool {
588 payload_bytes <= self.max_payload_bytes
589 && self
590 .allowed_tenant_ids
591 .iter()
592 .any(|id| id == &record.tenant_id)
593 && self
594 .allowed_project_ids
595 .iter()
596 .any(|id| id == &record.project_id)
597 && self
598 .allowed_content_types
599 .iter()
600 .any(|kind| kind == &record.content_type)
601 && self
602 .allowed_classifications
603 .iter()
604 .any(|kind| kind == &record.classification)
605 && record.relay_chain.depth() <= self.max_hops
606 }
607}
608
609fn ensure_unique(values: &[String]) -> Result<(), RelayError> {
610 let mut seen = HashSet::new();
611 if values
612 .iter()
613 .any(|value| value.is_empty() || !seen.insert(value))
614 {
615 return Err(RelayError::ScopeViolation);
616 }
617 Ok(())
618}
619
620fn is_loopback_host(host: &str) -> bool {
621 host.eq_ignore_ascii_case("localhost")
622 || host
623 .parse::<IpAddr>()
624 .map(|ip| ip.is_loopback())
625 .unwrap_or(false)
626}
627
628#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
629#[serde(deny_unknown_fields)]
630pub struct RelayPeerTableV1 {
631 pub schema_version: u8,
632 pub peers: Vec<RelayPeerConfigV1>,
633}
634
635impl Default for RelayPeerTableV1 {
636 fn default() -> Self {
637 Self {
638 schema_version: RELAY_PEER_TABLE_VERSION,
639 peers: Vec::new(),
640 }
641 }
642}
643
644impl RelayPeerTableV1 {
645 pub fn validate(&self, allow_loopback_http: bool) -> Result<(), RelayError> {
646 if self.schema_version != RELAY_PEER_TABLE_VERSION || self.peers.len() > RELAY_MAX_PEERS {
647 return Err(RelayError::InvalidPeer("peer table".into()));
648 }
649 let mut ids = HashSet::new();
650 for peer in &self.peers {
651 peer.validate(allow_loopback_http)?;
652 if !ids.insert(&peer.peer_id) {
653 return Err(RelayError::InvalidPeer(peer.peer_id.clone()));
654 }
655 }
656 Ok(())
657 }
658
659 pub fn validate_for_tests(&self) -> Result<(), RelayError> {
660 self.validate(true)
661 }
662
663 pub fn from_json(value: &str, allow_loopback_http: bool) -> Result<Self, RelayError> {
664 let table: Self = serde_json::from_str(value)
665 .map_err(|e| RelayError::Malformed(format!("peer table: {e}")))?;
666 table.validate(allow_loopback_http)?;
667 Ok(table)
668 }
669
670 pub fn peer(&self, peer_id: &str) -> Option<&RelayPeerConfigV1> {
671 self.peers.iter().find(|peer| peer.peer_id == peer_id)
672 }
673
674 pub fn route_for_recipient(
675 &self,
676 recipient_id: &str,
677 ) -> Result<&RelayPeerConfigV1, RelayError> {
678 let mut routes = self
679 .peers
680 .iter()
681 .filter(|peer| peer.recipient_id == recipient_id);
682 let first = routes
683 .next()
684 .ok_or_else(|| RelayError::UnknownRoute(recipient_id.into()))?;
685 if routes.next().is_some() {
686 return Err(RelayError::AmbiguousRoute(recipient_id.into()));
687 }
688 Ok(first)
689 }
690
691 pub fn reject_shared_secret(&self) -> Result<(), RelayError> {
692 for (index, left) in self.peers.iter().enumerate() {
693 for right in self.peers.iter().skip(index + 1) {
694 if left.channel_key == right.channel_key || left.bearer_token == right.bearer_token
695 {
696 return Err(RelayError::InvalidCredential);
697 }
698 }
699 }
700 Ok(())
701 }
702}
703
704#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, thiserror::Error)]
705pub enum RelayError {
706 #[error("relay chain exceeded maximum of {0} hops")]
707 MaxHopsExceeded(usize),
708 #[error("relay cycle detected at agent {0}")]
709 CycleDetected(String),
710 #[error("malformed relay data: {0}")]
711 Malformed(String),
712 #[error("relay data exceeds its cap")]
713 Oversize,
714 #[error("relay deadline expired")]
715 DeadlineExceeded,
716 #[error("relay route mismatch")]
717 RouteMismatch,
718 #[error("relay scope or classification is not allowed")]
719 ScopeViolation,
720 #[error("unknown relay route: {0}")]
721 UnknownRoute(String),
722 #[error("ambiguous relay route: {0}")]
723 AmbiguousRoute(String),
724 #[error("invalid relay peer: {0}")]
725 InvalidPeer(String),
726 #[error("invalid relay signature")]
727 InvalidSignature,
728 #[error("invalid relay credential")]
729 InvalidCredential,
730 #[error("relay retry cap exceeded")]
731 RetryCap,
732}
733
734#[cfg(test)]
735mod tests {
736 use chrono::{Duration, TimeZone, Utc};
737 use lean_ctx_protocol::DataClassification;
738
739 use super::{
740 RelayChain, RelayError, RelayHop, RelayRecordV1, test_origin_key, test_origin_public_key,
741 };
742 use crate::core::a2a_transport::TransportContentType;
743
744 fn hop(agent_id: &str, processing_ms: Option<u64>) -> RelayHop {
745 RelayHop {
746 agent_id: agent_id.to_owned(),
747 received_at: Utc.timestamp_millis_opt(1_700_000_000_000).unwrap(),
748 forwarded_at: None,
749 processing_ms,
750 }
751 }
752
753 #[test]
754 fn unforwarded_hop_is_valid_but_time_reversal_is_rejected() {
755 let mut pending = hop("pending", None);
756 pending.forwarded_at = None;
757 let mut chain = RelayChain::default();
758 chain.add_hop(pending.clone()).unwrap();
759 chain.validate().unwrap();
760
761 pending.agent_id = "backwards".into();
762 pending.forwarded_at = Some(pending.received_at - Duration::seconds(1));
763 assert!(chain.add_hop(pending.clone()).is_err());
764 chain.hops.push(pending);
765 assert!(chain.validate().is_err());
766 }
767
768 #[test]
769 fn relay_peer_cannot_select_the_legacy_retry_namespace() {
770 let mut peer = super::RelayPeerConfigV1 {
771 schema_version: 1,
772 peer_id: "peer".into(),
773 endpoint_url: "https://peer.example".into(),
774 bearer_token: "bearer".into(),
775 channel_key: "channel-key".into(),
776 origin_public_key: test_origin_public_key("peer"),
777 recipient_id: "recipient".into(),
778 allowed_tenant_ids: vec!["tenant".into()],
779 allowed_project_ids: vec!["project".into()],
780 allowed_content_types: vec![TransportContentType::EvidenceBundle],
781 allowed_classifications: vec![DataClassification::Internal],
782 max_hops: 4,
783 max_payload_bytes: 1024,
784 retry_count: 0,
785 retry_delay_ms: 0,
786 };
787 peer.validate(false).unwrap();
788 peer.peer_id = "legacy".into();
789 assert_eq!(
790 peer.validate(false),
791 Err(RelayError::InvalidPeer("legacy".into()))
792 );
793 }
794
795 #[test]
796 fn adds_hop_and_reports_chain_metadata() {
797 let mut chain = RelayChain::new(3);
798 chain.add_hop(hop("origin-agent", Some(4))).unwrap();
799 assert_eq!(chain.depth(), 1);
800 assert!(chain.contains_agent("origin-agent"));
801 assert_eq!(chain.origin(), Some("origin-agent"));
802 }
803
804 #[test]
805 fn rejects_cycle() {
806 let mut chain = RelayChain::new(3);
807 chain.add_hop(hop("relay-agent", None)).unwrap();
808 let error = chain.add_hop(hop("relay-agent", Some(1))).unwrap_err();
809 assert_eq!(error, RelayError::CycleDetected("relay-agent".to_owned()));
810 }
811
812 #[test]
813 fn rejects_hop_beyond_maximum() {
814 let mut chain = RelayChain::new(1);
815 chain.add_hop(hop("origin-agent", None)).unwrap();
816 assert_eq!(
817 chain.add_hop(hop("next-agent", None)),
818 Err(RelayError::MaxHopsExceeded(1))
819 );
820 }
821
822 #[test]
823 fn sums_available_processing_latency() {
824 let mut chain = RelayChain::new(3);
825 chain.add_hop(hop("origin-agent", Some(12))).unwrap();
826 chain.add_hop(hop("relay-agent", None)).unwrap();
827 chain.add_hop(hop("recipient-agent", Some(8))).unwrap();
828 assert_eq!(chain.total_latency_ms(), 20);
829 }
830
831 #[test]
832 fn default_chain_allows_five_hops() {
833 let mut chain = RelayChain::default();
834 for index in 0..5 {
835 chain
836 .add_hop(hop(&format!("agent-{index}"), Some(u64::MAX)))
837 .unwrap();
838 }
839 assert_eq!(chain.depth(), 5);
840 assert_eq!(chain.total_latency_ms(), u64::MAX);
841 assert_eq!(
842 chain.add_hop(hop("sixth-agent", None)),
843 Err(RelayError::MaxHopsExceeded(5))
844 );
845 }
846
847 #[test]
848 fn signed_record_has_canonical_reserved_wire_value_and_forwarding_changes_route_only() {
849 let now = Utc.timestamp_opt(1_700_000_000, 0).unwrap();
850 let mut record = RelayRecordV1::new_signed(
851 "delivery-1",
852 "origin",
853 "recipient",
854 "tenant",
855 "project",
856 TransportContentType::A2ATask,
857 DataClassification::Internal,
858 now + Duration::hours(1),
859 4,
860 now,
861 &test_origin_key("origin"),
862 "origin-key",
863 b"task-payload",
864 )
865 .unwrap();
866 record
867 .route_from_origin(
868 "relay-a",
869 now,
870 &test_origin_public_key("origin"),
871 "inbound-key",
872 )
873 .unwrap();
874 assert!(
875 record
876 .verify_origin(&test_origin_public_key("origin"))
877 .is_ok()
878 );
879 assert!(record.verify_hop("inbound-key").is_ok());
880 let unchanged = record.encode_metadata().unwrap();
881 assert_eq!(
882 record.forward_from("unaddressed-peer", "recipient", now, "relay-key"),
883 Err(RelayError::RouteMismatch)
884 );
885 assert_eq!(record.encode_metadata().unwrap(), unchanged);
886 for invalid_next in ["", "origin", "relay-a"] {
887 assert!(
888 record
889 .forward_from("relay-a", invalid_next, now, "relay-key")
890 .is_err()
891 );
892 assert_eq!(record.encode_metadata().unwrap(), unchanged);
893 }
894 let encoded = record.encode_metadata().unwrap();
895 let mut forwarded = RelayRecordV1::decode_metadata(&encoded).unwrap();
896 forwarded
897 .forward_from(
898 "relay-a",
899 "recipient",
900 now + Duration::seconds(1),
901 "relay-key",
902 )
903 .unwrap();
904 assert_eq!(forwarded.delivery_id, "delivery-1");
905 assert!(
906 forwarded
907 .verify_origin(&test_origin_public_key("origin"))
908 .is_ok()
909 );
910 assert!(forwarded.verify_payload(b"task-payload").is_ok());
911 assert!(forwarded.verify_payload(b"substituted-payload").is_err());
912 let mut substituted = forwarded.clone();
913 substituted.payload_sha256 = RelayRecordV1::payload_digest(b"substituted-payload");
914 assert!(
915 substituted
916 .verify_origin(&test_origin_public_key("origin"))
917 .is_err()
918 );
919 substituted.origin_signature = substituted
922 .sign_origin(&test_origin_key("relay-a"))
923 .unwrap();
924 substituted.hop_signature = substituted.sign_hop("relay-key").unwrap();
925 assert!(substituted.verify_hop("relay-key").is_ok());
926 assert!(substituted.verify_payload(b"substituted-payload").is_ok());
927 assert_eq!(
928 substituted.verify_origin(&test_origin_public_key("origin")),
929 Err(RelayError::InvalidSignature)
930 );
931 assert!(forwarded.verify_hop("relay-key").is_ok());
932 assert!(RelayRecordV1::decode_metadata(&format!("{encoded} ")).is_err());
933 }
934
935 #[test]
936 fn relay_origin_public_keys_reject_wrong_length_non_hex_and_weak_points() {
937 for invalid in [
938 String::new(),
939 "a".repeat(62),
940 "a".repeat(66),
941 "z".repeat(64),
942 "0".repeat(64),
943 ] {
944 assert!(super::decode_origin_key(&invalid).is_err());
945 }
946 assert!(super::decode_origin_key(&test_origin_public_key("origin")).is_ok());
947 }
948}