interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-auth / src / lib.rs

1114 lines · 38333 bytes Raw Blame History
1//! Capability-scoped Ed25519 authentication, replay protection, quota enforcement,
2//! and tamper-evident hash-chained security audit logging (`synapse-auth`, Gate 2a).
3
4use ed25519_dalek::{Signature, Signer, SigningKey};
5use serde::{Deserialize, Serialize};
6use sha2::{Digest, Sha256};
7use std::collections::{BTreeMap, BTreeSet};
8use synapse_core::{
9 decode_did_key_ed25519, encode_did_key_ed25519, RefusalCode, RepoId, SynapseError,
10 SynapseResult,
11};
12
13mod chain;
14mod digest;
15mod key_cache;
16mod state_move;
17pub use chain::*;
18pub use digest::payload_digest;
19pub use key_cache::KEY_CACHE_CAPACITY;
20pub use state_move::*;
21
22/// Current capability grant schema version.
23pub const CAPABILITY_GRANT_VERSION: u16 = 1;
24
25/// Domain tag for signing `AgentCapabilityGrant`.
26pub const DOMAIN_CAPABILITY_GRANT_V1: &[u8] = b"SYNAPSE_CAPABILITY_GRANT_V1\0";
27
28/// Domain tag for signing `AuthenticatedRequest`.
29pub const DOMAIN_AUTH_REQUEST_V1: &[u8] = b"SYNAPSE_AUTH_REQUEST_V1\0";
30
31/// Domain tag for hash-chaining `AuditEntry`.
32pub const DOMAIN_AUDIT_ENTRY_V1: &[u8] = b"SYNAPSE_AUDIT_ENTRY_V1\0";
33
34/// Fine-grained capabilities enforced across Synapse boundaries.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
36pub enum Capability {
37 /// Inspect changesets, virtual trees, diffs, history, provenance, conflicts, status, and watch cursors.
38 Read,
39 /// Submit new changeset proposals (`submit`).
40 Propose,
41 /// Attach machine evaluation and benchmark receipts (`attach_evaluation`).
42 Evaluate,
43 /// Record review verdicts on changesets authored by other agents (`record_review`).
44 Review,
45 /// Project changesets to Git/GitHub or request canonical promotion (`project_git`, `promote_canonical`).
46 Publish,
47 /// Restore an earlier operation view (ADR 0003 section 5.4); undoing another actor's
48 /// operations also needs a delegation chain that dominates that actor's (step B2).
49 Undo,
50}
51
52impl Capability {
53 pub fn tag_byte(self) -> u8 {
54 match self {
55 Self::Read => 1,
56 Self::Propose => 2,
57 Self::Evaluate => 3,
58 Self::Review => 4,
59 Self::Publish => 5,
60 Self::Undo => 6,
61 }
62 }
63
64 pub fn is_mutating(self) -> bool {
65 !matches!(self, Self::Read)
66 }
67}
68
69/// Boundary at which a policy check is enforced and audited.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
71pub enum BoundaryKind {
72 Api,
73 Store,
74 Worker,
75 Export,
76}
77
78/// Repository-scoped capability grant signed by a trusted repository authority Ed25519 key.
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80pub struct AgentCapabilityGrant {
81 pub version: u16,
82 pub grant_id: [u8; 32],
83 pub repo_id: RepoId,
84 pub issuer_did: String,
85 pub agent_did: String,
86 pub capabilities: Vec<Capability>,
87 pub max_bytes_per_op: u64,
88 pub max_ops_per_window: u32,
89 pub window_duration_ms: u64,
90 pub issued_at_ms: u64,
91 pub expires_at_ms: u64,
92 pub signature: Vec<u8>,
93}
94
95impl AgentCapabilityGrant {
96 /// Create and sign a new `AgentCapabilityGrant` using the repository authority's `SigningKey`.
97 #[allow(clippy::too_many_arguments)]
98 pub fn issue(
99 authority_key: &SigningKey,
100 grant_id: [u8; 32],
101 repo_id: RepoId,
102 agent_did: String,
103 mut capabilities: Vec<Capability>,
104 max_bytes_per_op: u64,
105 max_ops_per_window: u32,
106 window_duration_ms: u64,
107 issued_at_ms: u64,
108 expires_at_ms: u64,
109 ) -> Self {
110 capabilities.sort();
111 capabilities.dedup();
112 let issuer_did = encode_did_key_ed25519(&authority_key.verifying_key().to_bytes());
113 let mut grant = Self {
114 version: CAPABILITY_GRANT_VERSION,
115 grant_id,
116 repo_id,
117 issuer_did,
118 agent_did,
119 capabilities,
120 max_bytes_per_op,
121 max_ops_per_window,
122 window_duration_ms,
123 issued_at_ms,
124 expires_at_ms,
125 signature: Vec::new(),
126 };
127 let signable = grant.canonical_signable_bytes();
128 grant.signature = authority_key.sign(&signable).to_bytes().to_vec();
129 grant
130 }
131
132 /// Deterministically encode unsigned grant fields for Ed25519 authority signing.
133 pub fn canonical_signable_bytes(&self) -> Vec<u8> {
134 let mut buf = Vec::with_capacity(256);
135 buf.extend_from_slice(DOMAIN_CAPABILITY_GRANT_V1);
136 buf.extend_from_slice(&self.version.to_le_bytes());
137 buf.extend_from_slice(&self.grant_id);
138 put_str(&mut buf, self.repo_id.as_str());
139 put_str(&mut buf, &self.issuer_did);
140 put_str(&mut buf, &self.agent_did);
141 buf.extend_from_slice(&(self.capabilities.len() as u32).to_le_bytes());
142 for cap in &self.capabilities {
143 buf.push(cap.tag_byte());
144 }
145 buf.extend_from_slice(&self.max_bytes_per_op.to_le_bytes());
146 buf.extend_from_slice(&self.max_ops_per_window.to_le_bytes());
147 buf.extend_from_slice(&self.window_duration_ms.to_le_bytes());
148 buf.extend_from_slice(&self.issued_at_ms.to_le_bytes());
149 buf.extend_from_slice(&self.expires_at_ms.to_le_bytes());
150 buf
151 }
152
153 /// Verify the authority's Ed25519 signature over the grant.
154 pub fn verify_authority_signature(&self) -> SynapseResult<()> {
155 if self.version != CAPABILITY_GRANT_VERSION {
156 return Err(SynapseError::new(
157 RefusalCode::EnvelopeVersionUnsupported,
158 format!("unsupported capability grant version {}", self.version),
159 ));
160 }
161 let pubkey_bytes = decode_did_key_ed25519(&self.issuer_did)?;
162 let verifying_key = key_cache::verifying_key(&pubkey_bytes).map_err(|_| {
163 SynapseError::new(
164 RefusalCode::DidKeyInvalid,
165 "invalid authority Ed25519 public key",
166 )
167 })?;
168 let sig_arr: [u8; 64] = self.signature.as_slice().try_into().map_err(|_| {
169 SynapseError::new(
170 RefusalCode::AuthGrantSignatureInvalid,
171 "grant signature must be 64 bytes",
172 )
173 })?;
174 let sig = Signature::from_bytes(&sig_arr);
175 verifying_key
176 .verify_strict(&self.canonical_signable_bytes(), &sig)
177 .map_err(|_| {
178 SynapseError::new(
179 RefusalCode::AuthGrantSignatureInvalid,
180 "grant signature verification failed",
181 )
182 })
183 }
184}
185
186/// Signed request envelope binding an `AgentCapabilityGrant`, a single-use `request_nonce`,
187/// the target `RepoId`, the required `Capability`, and the payload digest.
188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
189pub struct AuthenticatedRequest<T> {
190 pub grant: AgentCapabilityGrant,
191 pub target_repo_id: RepoId,
192 pub required_capability: Capability,
193 pub request_nonce: [u8; 32],
194 pub timestamp_ms: u64,
195 pub payload_bytes_len: u64,
196 pub payload_sha256: [u8; 32],
197 pub payload: T,
198 pub agent_signature: Vec<u8>,
199}
200
201impl<T: Serialize> AuthenticatedRequest<T> {
202 #[allow(clippy::too_many_arguments)]
203 /// Construct and sign an `AuthenticatedRequest` with the agent's Ed25519 `SigningKey`.
204 pub fn sign_new(
205 agent_key: &SigningKey,
206 grant: AgentCapabilityGrant,
207 target_repo_id: RepoId,
208 required_capability: Capability,
209 request_nonce: [u8; 32],
210 timestamp_ms: u64,
211 declared_payload_bytes_len: u64,
212 payload: T,
213 ) -> SynapseResult<Self> {
214 let (payload_sha256, serialized_len) = payload_digest(&payload)?;
215 let effective_len = declared_payload_bytes_len.max(serialized_len);
216
217 let mut req = Self {
218 grant,
219 target_repo_id,
220 required_capability,
221 request_nonce,
222 timestamp_ms,
223 payload_bytes_len: effective_len,
224 payload_sha256,
225 payload,
226 agent_signature: Vec::new(),
227 };
228 let signable = req.canonical_signable_bytes();
229 req.agent_signature = agent_key.sign(&signable).to_bytes().to_vec();
230 Ok(req)
231 }
232
233 /// Deterministically encode request metadata + payload digest for agent Ed25519 signing.
234 pub fn canonical_signable_bytes(&self) -> Vec<u8> {
235 let mut buf = Vec::with_capacity(256);
236 buf.extend_from_slice(DOMAIN_AUTH_REQUEST_V1);
237 buf.extend_from_slice(&self.grant.grant_id);
238 put_str(&mut buf, self.target_repo_id.as_str());
239 buf.push(self.required_capability.tag_byte());
240 buf.extend_from_slice(&self.request_nonce);
241 buf.extend_from_slice(&self.timestamp_ms.to_le_bytes());
242 buf.extend_from_slice(&self.payload_bytes_len.to_le_bytes());
243 buf.extend_from_slice(&self.payload_sha256);
244 buf
245 }
246}
247
248/// Outcome recorded in the security `AuditLog`.
249#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
250pub enum AuditOutcome {
251 Admitted,
252 Refused { code: RefusalCode, reason: String },
253}
254
255/// Hash-chained security audit entry.
256#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
257pub struct AuditEntry {
258 pub audit_seq: u64,
259 pub timestamp_ms: u64,
260 pub boundary: BoundaryKind,
261 pub repo_id: RepoId,
262 pub actor_did: String,
263 pub capability: Capability,
264 pub operation: String,
265 pub outcome: AuditOutcome,
266 pub prev_entry_sha256: [u8; 32],
267 pub entry_sha256: [u8; 32],
268}
269
270impl AuditEntry {
271 pub fn compute_sha256(&self) -> [u8; 32] {
272 let mut hasher = Sha256::new();
273 hasher.update(DOMAIN_AUDIT_ENTRY_V1);
274 hasher.update(self.audit_seq.to_le_bytes());
275 hasher.update(self.timestamp_ms.to_le_bytes());
276 hasher.update([self.boundary as u8]);
277 hasher.update(self.repo_id.as_str().as_bytes());
278 hasher.update(b"\0");
279 hasher.update(self.actor_did.as_bytes());
280 hasher.update(b"\0");
281 hasher.update([self.capability.tag_byte()]);
282 hasher.update(self.operation.as_bytes());
283 hasher.update(b"\0");
284 match &self.outcome {
285 AuditOutcome::Admitted => hasher.update([1u8]),
286 AuditOutcome::Refused { code, reason } => {
287 hasher.update([0u8]);
288 hasher.update(format!("{code:?}").as_bytes());
289 hasher.update(b"\0");
290 hasher.update(reason.as_bytes());
291 }
292 }
293 hasher.update(self.prev_entry_sha256);
294 hasher.finalize().into()
295 }
296}
297
298/// Maximum retained audit decisions. Exhaustion stops authorization rather than dropping
299/// evidence; the caller must persist the complete log and restart with a fresh enforcer.
300pub const MAX_AUDIT_ENTRIES: usize = 4_096;
301/// Maximum retained bytes per attacker-controlled audit string. Oversized values retain a
302/// SHA-256 commitment and original length rather than occupying an unbounded log entry.
303const MAX_AUDIT_FIELD_BYTES: usize = 1_024;
304
305fn bounded_audit_field(value: String) -> String {
306 if value.len() <= MAX_AUDIT_FIELD_BYTES {
307 value
308 } else {
309 format!(
310 "[oversize {} bytes sha256={}]",
311 value.len(),
312 hex::encode(Sha256::digest(value.as_bytes()))
313 )
314 }
315}
316
317/// Tamper-evident hash-chained security audit log.
318#[derive(Debug, Clone, Default, Serialize)]
319pub struct AuditLog {
320 entries: Vec<AuditEntry>,
321 last_sha256: [u8; 32],
322}
323
324impl AuditLog {
325 pub fn new() -> Self {
326 Self::default()
327 }
328
329 pub fn entries(&self) -> &[AuditEntry] {
330 &self.entries
331 }
332
333 #[cfg(test)]
334 pub fn entries_mut_for_testing(&mut self) -> &mut Vec<AuditEntry> {
335 &mut self.entries
336 }
337 /// Reserve space before any authorization state (nonce or quota) is changed.
338 pub fn ensure_capacity(&self) -> SynapseResult<()> {
339 if self.entries.len() >= MAX_AUDIT_ENTRIES {
340 return Err(SynapseError::new(
341 RefusalCode::BackpressureOverCapacity,
342 "audit log full; no authorization decision was made",
343 ));
344 }
345 Ok(())
346 }
347
348 #[allow(clippy::too_many_arguments)]
349 pub fn record(
350 &mut self,
351 timestamp_ms: u64,
352 boundary: BoundaryKind,
353 repo_id: RepoId,
354 actor_did: String,
355 capability: Capability,
356 operation: impl Into<String>,
357 outcome: AuditOutcome,
358 ) -> SynapseResult<&AuditEntry> {
359 self.ensure_capacity()?;
360 let audit_seq = (self.entries.len() as u64) + 1;
361 let outcome = match outcome {
362 AuditOutcome::Refused { code, reason } => AuditOutcome::Refused {
363 code,
364 reason: bounded_audit_field(reason),
365 },
366 admitted => admitted,
367 };
368 let mut entry = AuditEntry {
369 audit_seq,
370 timestamp_ms,
371 boundary,
372 repo_id,
373 actor_did: bounded_audit_field(actor_did),
374 capability,
375 operation: bounded_audit_field(operation.into()),
376 outcome,
377 prev_entry_sha256: self.last_sha256,
378 entry_sha256: [0u8; 32],
379 };
380 entry.entry_sha256 = entry.compute_sha256();
381 self.last_sha256 = entry.entry_sha256;
382 self.entries.push(entry);
383 Ok(self.entries.last().expect("just pushed"))
384 }
385
386 /// Verify the entire hash chain and sequence continuity of the audit log.
387 pub fn verify_chain(&self) -> SynapseResult<[u8; 32]> {
388 let mut prev = [0u8; 32];
389 for (idx, entry) in self.entries.iter().enumerate() {
390 let expected_seq = (idx as u64) + 1;
391 if entry.audit_seq != expected_seq {
392 return Err(SynapseError::new(
393 RefusalCode::AuditChainCorrupt,
394 format!(
395 "audit sequence gap: expected {}, got {}",
396 expected_seq, entry.audit_seq
397 ),
398 ));
399 }
400 if entry.prev_entry_sha256 != prev {
401 return Err(SynapseError::new(
402 RefusalCode::AuditChainCorrupt,
403 format!(
404 "audit prev_entry_sha256 mismatch at seq {}",
405 entry.audit_seq
406 ),
407 ));
408 }
409 let computed = entry.compute_sha256();
410 if entry.entry_sha256 != computed {
411 return Err(SynapseError::new(
412 RefusalCode::AuditChainCorrupt,
413 format!("audit entry_sha256 tampered at seq {}", entry.audit_seq),
414 ));
415 }
416 prev = computed;
417 }
418 Ok(prev)
419 }
420}
421
422/// Policy enforcer verifying capability grants, Ed25519 request signatures, replay nonces,
423/// cross-repository isolation, and rate/size quotas across all Synapse boundaries.
424pub struct PolicyEnforcer {
425 trusted_authorities: BTreeMap<RepoId, BTreeSet<String>>,
426 consumed_nonces: BTreeSet<(RepoId, String, [u8; 32])>,
427 rate_windows: BTreeMap<(RepoId, String), Vec<u64>>,
428 audit_log: AuditLog,
429 chains: ChainRegistry,
430}
431
432impl Default for PolicyEnforcer {
433 fn default() -> Self {
434 Self::new()
435 }
436}
437
438impl PolicyEnforcer {
439 pub fn new() -> Self {
440 Self {
441 trusted_authorities: BTreeMap::new(),
442 consumed_nonces: BTreeSet::new(),
443 rate_windows: BTreeMap::new(),
444 audit_log: AuditLog::new(),
445 chains: ChainRegistry::default(),
446 }
447 }
448
449 /// Register a trusted repository authority `did:key:z6Mk...` for `repo_id`.
450 pub fn register_repo_authority(&mut self, repo_id: RepoId, authority_did: impl Into<String>) {
451 self.trusted_authorities
452 .entry(repo_id)
453 .or_default()
454 .insert(authority_did.into());
455 }
456
457 /// Return a reference to the tamper-evident security audit log.
458 pub fn audit_log(&self) -> &AuditLog {
459 &self.audit_log
460 }
461
462 /// Return a mutable reference to the audit log (for persistence or tamper-detection tests).
463 pub fn audit_log_mut(&mut self) -> &mut AuditLog {
464 &mut self.audit_log
465 }
466
467 /// Verify and authorize an `AuthenticatedRequest<T>` at `boundary` and `now_ms`,
468 /// recording either `Admitted` or `Refused` in the hash-chained `AuditLog`.
469 pub fn authorize<T: Serialize>(
470 &mut self,
471 boundary: BoundaryKind,
472 operation: &str,
473 expected_repo_id: &RepoId,
474 expected_capability: Capability,
475 req: &AuthenticatedRequest<T>,
476 now_ms: u64,
477 ) -> SynapseResult<()> {
478 self.audit_log.ensure_capacity()?;
479 let result = self.check_request_inner(expected_repo_id, expected_capability, req, now_ms);
480 match &result {
481 Ok(()) => {
482 self.audit_log.record(
483 now_ms,
484 boundary,
485 expected_repo_id.clone(),
486 req.grant.agent_did.clone(),
487 expected_capability,
488 operation,
489 AuditOutcome::Admitted,
490 )?;
491 }
492 Err(err) => {
493 self.audit_log.record(
494 now_ms,
495 boundary,
496 expected_repo_id.clone(),
497 req.grant.agent_did.clone(),
498 expected_capability,
499 operation,
500 AuditOutcome::Refused {
501 code: err.code,
502 reason: err.message.clone(),
503 },
504 )?;
505 }
506 }
507 result
508 }
509
510 fn check_request_inner<T: Serialize>(
511 &mut self,
512 expected_repo_id: &RepoId,
513 expected_capability: Capability,
514 req: &AuthenticatedRequest<T>,
515 now_ms: u64,
516 ) -> SynapseResult<()> {
517 // 1. Cross-repository check on both request target and grant scope
518 if &req.target_repo_id != expected_repo_id || &req.grant.repo_id != expected_repo_id {
519 return Err(SynapseError::new(
520 RefusalCode::AuthCrossRepoDenied,
521 format!(
522 "cross-repo access denied: grant repo {} vs target repo {}",
523 req.grant.repo_id, expected_repo_id
524 ),
525 ));
526 }
527
528 // 2. Verify grant issuer is a trusted authority for `expected_repo_id`
529 let trusted = self
530 .trusted_authorities
531 .get(expected_repo_id)
532 .is_some_and(|set| set.contains(&req.grant.issuer_did));
533 if !trusted {
534 return Err(SynapseError::new(
535 RefusalCode::AuthGrantSignatureInvalid,
536 format!(
537 "issuer {} is not a trusted authority for {}",
538 req.grant.issuer_did, expected_repo_id
539 ),
540 ));
541 }
542
543 // 3. Cryptographically verify the authority signature on the capability grant
544 req.grant.verify_authority_signature()?;
545
546 // 4. Verify grant time validity (`issued_at_ms <= now_ms <= expires_at_ms`)
547 if now_ms > req.grant.expires_at_ms || now_ms < req.grant.issued_at_ms {
548 return Err(SynapseError::new(
549 RefusalCode::AuthGrantExpired,
550 format!(
551 "capability grant expired or not yet valid (now={now_ms}, window={}..={})",
552 req.grant.issued_at_ms, req.grant.expires_at_ms
553 ),
554 ));
555 }
556
557 // 5. Verify required capability is present in both request and grant
558 if req.required_capability != expected_capability
559 || !req.grant.capabilities.contains(&expected_capability)
560 {
561 return Err(SynapseError::new(
562 RefusalCode::AuthCapabilityDenied,
563 format!(
564 "agent {} lacks required capability {:?}",
565 req.grant.agent_did, expected_capability
566 ),
567 ));
568 }
569
570 // 6. Verify payload digest and agent's Ed25519 signature over the request
571 let (actual_payload_sha256, serialized_payload_len) = payload_digest(&req.payload)?;
572 if actual_payload_sha256 != req.payload_sha256 {
573 return Err(SynapseError::new(
574 RefusalCode::AuthSignatureInvalid,
575 "request payload_sha256 does not match serialized payload",
576 ));
577 }
578
579 let agent_pubkey_bytes = decode_did_key_ed25519(&req.grant.agent_did)?;
580 let agent_verifying_key = key_cache::verifying_key(&agent_pubkey_bytes).map_err(|_| {
581 SynapseError::new(RefusalCode::DidKeyInvalid, "invalid agent Ed25519 key")
582 })?;
583 let sig_arr: [u8; 64] = req.agent_signature.as_slice().try_into().map_err(|_| {
584 SynapseError::new(
585 RefusalCode::AuthSignatureInvalid,
586 "agent request signature must be 64 bytes",
587 )
588 })?;
589 let sig = Signature::from_bytes(&sig_arr);
590 agent_verifying_key
591 .verify_strict(&req.canonical_signable_bytes(), &sig)
592 .map_err(|_| {
593 SynapseError::new(
594 RefusalCode::AuthSignatureInvalid,
595 "agent Ed25519 request signature verification failed",
596 )
597 })?;
598
599 // 7. Enforce payload byte quota
600 let effective_bytes = req.payload_bytes_len.max(serialized_payload_len);
601 if effective_bytes > req.grant.max_bytes_per_op {
602 return Err(SynapseError::new(
603 RefusalCode::QuotaPayloadTooLarge,
604 format!(
605 "request payload size {} exceeds grant max_bytes_per_op {}",
606 effective_bytes, req.grant.max_bytes_per_op
607 ),
608 ));
609 }
610
611 // 8. Enforce sliding-window rate limit per `(repo_id, agent_did)`
612 let window_key = (expected_repo_id.clone(), req.grant.agent_did.clone());
613 let window_start = now_ms.saturating_sub(req.grant.window_duration_ms);
614 let timestamps = self.rate_windows.entry(window_key).or_default();
615 timestamps.retain(|&ts| ts >= window_start);
616 if timestamps.len() as u32 >= req.grant.max_ops_per_window {
617 return Err(SynapseError::new(
618 RefusalCode::QuotaRateLimitExceeded,
619 format!(
620 "agent {} exceeded rate limit ({} ops per {} ms)",
621 req.grant.agent_did, req.grant.max_ops_per_window, req.grant.window_duration_ms
622 ),
623 ));
624 }
625
626 // 9. Enforce single-use nonce anti-replay for all mutating operations
627 if expected_capability.is_mutating() {
628 let nonce_key = (
629 expected_repo_id.clone(),
630 req.grant.agent_did.clone(),
631 req.request_nonce,
632 );
633 if !self.consumed_nonces.insert(nonce_key) {
634 return Err(SynapseError::new(
635 RefusalCode::AuthReplayDetected,
636 "replayed mutation request_nonce refused",
637 ));
638 }
639 }
640
641 timestamps.push(now_ms);
642 Ok(())
643 }
644}
645
646fn put_str(buf: &mut Vec<u8>, s: &str) {
647 buf.extend_from_slice(&(s.len() as u32).to_le_bytes());
648 buf.extend_from_slice(s.as_bytes());
649}
650
651#[cfg(test)]
652mod tests {
653 use super::*;
654
655 #[test]
656 fn unauthenticated_refusals_cannot_grow_audit_without_bound() {
657 let mut log = AuditLog::new();
658 let repo = RepoId::new("example/repo").unwrap();
659 for _ in 0..MAX_AUDIT_ENTRIES {
660 log.record(
661 1,
662 BoundaryKind::Api,
663 repo.clone(),
664 "untrusted".into(),
665 Capability::Propose,
666 "wire_submit",
667 AuditOutcome::Refused {
668 code: RefusalCode::AuthChainBroken,
669 reason: "untrusted chain".into(),
670 },
671 )
672 .unwrap();
673 }
674 let head = log.verify_chain().unwrap();
675 assert_eq!(
676 log.record(
677 1,
678 BoundaryKind::Api,
679 repo,
680 "untrusted".into(),
681 Capability::Propose,
682 "wire_submit",
683 AuditOutcome::Admitted
684 )
685 .unwrap_err()
686 .code,
687 RefusalCode::BackpressureOverCapacity
688 );
689 assert_eq!(log.entries().len(), MAX_AUDIT_ENTRIES);
690 assert_eq!(log.verify_chain().unwrap(), head);
691 }
692
693 #[test]
694 fn oversized_untrusted_audit_fields_keep_explicit_digest_not_payload() {
695 let mut log = AuditLog::new();
696 let value = "x".repeat(MAX_AUDIT_FIELD_BYTES + 1);
697 let entry = log
698 .record(
699 1,
700 BoundaryKind::Api,
701 RepoId::new("example/repo").unwrap(),
702 value.clone(),
703 Capability::Propose,
704 "wire_submit",
705 AuditOutcome::Refused {
706 code: RefusalCode::AuthChainBroken,
707 reason: value.clone(),
708 },
709 )
710 .unwrap();
711 let digest = hex::encode(Sha256::digest(value.as_bytes()));
712 assert!(entry.actor_did.contains(&digest));
713 assert!(
714 matches!(&entry.outcome, AuditOutcome::Refused { reason, .. }
715 if reason.contains(&digest) && reason.len() < MAX_AUDIT_FIELD_BYTES)
716 );
717 assert!(log.verify_chain().is_ok());
718 }
719
720 #[test]
721 fn full_audit_refuses_before_consuming_nonce_or_rate_quota() {
722 let authority = SigningKey::from_bytes(&[31; 32]);
723 let agent = SigningKey::from_bytes(&[32; 32]);
724 let repo = RepoId::new("example/repo").unwrap();
725 let grant = AgentCapabilityGrant::issue(
726 &authority,
727 [7; 32],
728 repo.clone(),
729 encode_did_key_ed25519(&agent.verifying_key().to_bytes()),
730 vec![Capability::Propose],
731 1024,
732 1,
733 60_000,
734 0,
735 100_000,
736 );
737 let req = AuthenticatedRequest::sign_new(
738 &agent,
739 grant,
740 repo.clone(),
741 Capability::Propose,
742 [8; 32],
743 2_000,
744 0,
745 "proposal",
746 )
747 .unwrap();
748 let mut auth = PolicyEnforcer::new();
749 auth.register_repo_authority(
750 repo.clone(),
751 encode_did_key_ed25519(&authority.verifying_key().to_bytes()),
752 );
753 for _ in 0..MAX_AUDIT_ENTRIES {
754 auth.audit_log
755 .record(
756 1,
757 BoundaryKind::Api,
758 repo.clone(),
759 "untrusted".into(),
760 Capability::Propose,
761 "wire_submit",
762 AuditOutcome::Refused {
763 code: RefusalCode::AuthChainBroken,
764 reason: "invalid".into(),
765 },
766 )
767 .unwrap();
768 }
769 let head = auth.audit_log.verify_chain().unwrap();
770 assert_eq!(
771 auth.authorize(
772 BoundaryKind::Api,
773 "submit",
774 &repo,
775 Capability::Propose,
776 &req,
777 2_000,
778 )
779 .unwrap_err()
780 .code,
781 RefusalCode::BackpressureOverCapacity
782 );
783 assert!(auth.consumed_nonces.is_empty());
784 assert!(auth.rate_windows.is_empty());
785 assert_eq!(auth.audit_log.verify_chain().unwrap(), head);
786 }
787
788 #[test]
789 fn test_capability_matrix_adversarial_refusals_and_audit_chain() {
790 let authority_key = SigningKey::from_bytes(&[1u8; 32]);
791 let authority_did = encode_did_key_ed25519(&authority_key.verifying_key().to_bytes());
792
793 let proposer_key = SigningKey::from_bytes(&[2u8; 32]);
794 let proposer_did = encode_did_key_ed25519(&proposer_key.verifying_key().to_bytes());
795
796 let attacker_key = SigningKey::from_bytes(&[99u8; 32]);
797
798 let repo_a = RepoId::new("aien-spark/synapse").unwrap();
799 let repo_b = RepoId::new("aien-spark/aien-sovereign-core").unwrap();
800
801 let mut enforcer = PolicyEnforcer::new();
802 enforcer.register_repo_authority(repo_a.clone(), authority_did);
803
804 let grant = AgentCapabilityGrant::issue(
805 &authority_key,
806 [0x10; 32],
807 repo_a.clone(),
808 proposer_did.clone(),
809 vec![Capability::Read, Capability::Propose],
810 1024, // max 1024 bytes per op
811 2, // max 2 ops per 10s window
812 10_000,
813 1_000,
814 5_000,
815 );
816
817 // 1. Valid Propose request succeeds
818 let req1 = AuthenticatedRequest::sign_new(
819 &proposer_key,
820 grant.clone(),
821 repo_a.clone(),
822 Capability::Propose,
823 [1u8; 32],
824 2_000,
825 128,
826 "changeset-1",
827 )
828 .unwrap();
829 enforcer
830 .authorize(
831 BoundaryKind::Api,
832 "submit",
833 &repo_a,
834 Capability::Propose,
835 &req1,
836 2_000,
837 )
838 .expect("valid Propose must be admitted");
839
840 // 2. Replay of the exact same mutation request (same request_nonce) is refused
841 let replay_err = enforcer
842 .authorize(
843 BoundaryKind::Api,
844 "submit",
845 &repo_a,
846 Capability::Propose,
847 &req1,
848 2_001,
849 )
850 .unwrap_err();
851 assert_eq!(replay_err.code, RefusalCode::AuthReplayDetected);
852
853 // 3. Forged agent signature (signed by attacker_key claiming proposer's grant) is refused
854 let forged_req = AuthenticatedRequest::sign_new(
855 &attacker_key,
856 grant.clone(),
857 repo_a.clone(),
858 Capability::Propose,
859 [2u8; 32],
860 2_002,
861 128,
862 "forged-changeset",
863 )
864 .unwrap();
865 let forged_err = enforcer
866 .authorize(
867 BoundaryKind::Api,
868 "submit",
869 &repo_a,
870 Capability::Propose,
871 &forged_req,
872 2_002,
873 )
874 .unwrap_err();
875 assert_eq!(forged_err.code, RefusalCode::AuthSignatureInvalid);
876
877 // 4. Cross-repository token reuse (grant for repo_a used against repo_b) is refused
878 let cross_err = enforcer
879 .authorize(
880 BoundaryKind::Store,
881 "submit",
882 &repo_b,
883 Capability::Propose,
884 &req1,
885 2_003,
886 )
887 .unwrap_err();
888 assert_eq!(cross_err.code, RefusalCode::AuthCrossRepoDenied);
889
890 // 5. Insufficient capability (proposer attempting Publish) is refused
891 let publish_req = AuthenticatedRequest::sign_new(
892 &proposer_key,
893 grant.clone(),
894 repo_a.clone(),
895 Capability::Publish,
896 [3u8; 32],
897 2_004,
898 128,
899 "promote-main",
900 )
901 .unwrap();
902 let cap_err = enforcer
903 .authorize(
904 BoundaryKind::Export,
905 "promote_canonical",
906 &repo_a,
907 Capability::Publish,
908 &publish_req,
909 2_004,
910 )
911 .unwrap_err();
912 assert_eq!(cap_err.code, RefusalCode::AuthCapabilityDenied);
913
914 // 6. Expired grant (now_ms = 6_000 > expires_at_ms = 5_000) is refused
915 let expired_err = enforcer
916 .authorize(
917 BoundaryKind::Api,
918 "submit",
919 &repo_a,
920 Capability::Propose,
921 &req1,
922 6_000,
923 )
924 .unwrap_err();
925 assert_eq!(expired_err.code, RefusalCode::AuthGrantExpired);
926
927 // 7. Payload byte quota exceeded (2048 > 1024) is refused
928 let oversize_req = AuthenticatedRequest::sign_new(
929 &proposer_key,
930 grant.clone(),
931 repo_a.clone(),
932 Capability::Propose,
933 [4u8; 32],
934 2_100,
935 2_048,
936 "oversize",
937 )
938 .unwrap();
939 let quota_err = enforcer
940 .authorize(
941 BoundaryKind::Api,
942 "submit",
943 &repo_a,
944 Capability::Propose,
945 &oversize_req,
946 2_100,
947 )
948 .unwrap_err();
949 assert_eq!(quota_err.code, RefusalCode::QuotaPayloadTooLarge);
950
951 // 8. Rate-limit exhaustion (2nd valid op succeeds, 3rd within 10s window is refused)
952 let req2 = AuthenticatedRequest::sign_new(
953 &proposer_key,
954 grant.clone(),
955 repo_a.clone(),
956 Capability::Read,
957 [5u8; 32],
958 2_200,
959 64,
960 "read-tree",
961 )
962 .unwrap();
963 enforcer
964 .authorize(
965 BoundaryKind::Api,
966 "tree",
967 &repo_a,
968 Capability::Read,
969 &req2,
970 2_200,
971 )
972 .unwrap();
973
974 let rate_err = enforcer
975 .authorize(
976 BoundaryKind::Api,
977 "tree",
978 &repo_a,
979 Capability::Read,
980 &req2,
981 2_300,
982 )
983 .unwrap_err();
984 assert_eq!(rate_err.code, RefusalCode::QuotaRateLimitExceeded);
985
986 // 9. Verify the hash-chained security audit log is intact across all 9 checks
987 assert_eq!(enforcer.audit_log().entries().len(), 9);
988 assert!(enforcer.audit_log().verify_chain().is_ok());
989
990 // 10. Tampering with any historical audit entry breaks the SHA-256 chain
991 enforcer.audit_log_mut().entries_mut_for_testing()[2].operation =
992 "tampered_operation".to_string();
993 let audit_err = enforcer.audit_log().verify_chain().unwrap_err();
994 assert_eq!(audit_err.code, RefusalCode::AuditChainCorrupt);
995 }
996
997 /// Ed25519 group order L, little-endian.
998 const ED25519_L: [u8; 32] = [
999 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde,
1000 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10,
1001 ];
1002
1003 /// Identity point encoding: a small-order public key. Under non-strict verify,
1004 /// signature (R = identity, S = 0) is accepted for every message.
1005 fn small_order_key_bytes() -> [u8; 32] {
1006 let mut b = [0u8; 32];
1007 b[0] = 1;
1008 b
1009 }
1010
1011 fn weak_signature() -> Vec<u8> {
1012 let mut sig = vec![0u8; 64];
1013 sig[0] = 1;
1014 sig
1015 }
1016
1017 fn repo() -> RepoId {
1018 RepoId::new("aien-spark/synapse").unwrap()
1019 }
1020
1021 #[test]
1022 fn small_order_issuer_key_grant_is_refused() {
1023 let key = SigningKey::from_bytes(&[1u8; 32]);
1024 let mut grant = AgentCapabilityGrant::issue(
1025 &key,
1026 [0x10; 32],
1027 repo(),
1028 encode_did_key_ed25519(&[2u8; 32]),
1029 vec![Capability::Read],
1030 1024,
1031 2,
1032 10_000,
1033 1_000,
1034 5_000,
1035 );
1036 grant.issuer_did = encode_did_key_ed25519(&small_order_key_bytes());
1037 grant.signature = weak_signature();
1038 let err = grant.verify_authority_signature().unwrap_err();
1039 assert_eq!(err.code, RefusalCode::AuthGrantSignatureInvalid);
1040 }
1041
1042 #[test]
1043 fn small_order_agent_key_request_is_refused() {
1044 let authority_key = SigningKey::from_bytes(&[1u8; 32]);
1045 let authority_did = encode_did_key_ed25519(&authority_key.verifying_key().to_bytes());
1046 let weak_did = encode_did_key_ed25519(&small_order_key_bytes());
1047 let mut enforcer = PolicyEnforcer::new();
1048 enforcer.register_repo_authority(repo(), authority_did);
1049 let grant = AgentCapabilityGrant::issue(
1050 &authority_key,
1051 [0x11; 32],
1052 repo(),
1053 weak_did,
1054 vec![Capability::Propose],
1055 1024,
1056 2,
1057 10_000,
1058 1_000,
1059 5_000,
1060 );
1061 let mut req = AuthenticatedRequest::sign_new(
1062 &SigningKey::from_bytes(&[2u8; 32]),
1063 grant,
1064 repo(),
1065 Capability::Propose,
1066 [4u8; 32],
1067 2_000,
1068 128,
1069 "weak-key",
1070 )
1071 .unwrap();
1072 req.agent_signature = weak_signature();
1073 let err = enforcer
1074 .authorize(
1075 BoundaryKind::Api,
1076 "submit",
1077 &repo(),
1078 Capability::Propose,
1079 &req,
1080 2_000,
1081 )
1082 .unwrap_err();
1083 assert_eq!(err.code, RefusalCode::AuthSignatureInvalid);
1084 }
1085
1086 #[test]
1087 fn non_canonical_malleable_signatures_are_refused() {
1088 let key = SigningKey::from_bytes(&[1u8; 32]);
1089 let mut grant = AgentCapabilityGrant::issue(
1090 &key,
1091 [0x12; 32],
1092 repo(),
1093 encode_did_key_ed25519(&[2u8; 32]),
1094 vec![Capability::Read],
1095 1024,
1096 2,
1097 10_000,
1098 1_000,
1099 5_000,
1100 );
1101 grant
1102 .verify_authority_signature()
1103 .expect("valid grant passes");
1104 // Malleate: S' = S + L encodes the same scalar non-canonically.
1105 let mut carry = 0u16;
1106 for (i, l) in ED25519_L.iter().enumerate() {
1107 let v = grant.signature[32 + i] as u16 + *l as u16 + carry;
1108 grant.signature[32 + i] = v as u8;
1109 carry = v >> 8;
1110 }
1111 let err = grant.verify_authority_signature().unwrap_err();
1112 assert_eq!(err.code, RefusalCode::AuthGrantSignatureInvalid);
1113 }
1114}