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 / chain.rs

1197 lines · 43400 bytes Raw Blame History
1//! Attenuated capability chains (ADR 0003 section 5.8, section 9 step F1).
2//!
3//! The repository authority issues a root link; any holder can sign a narrower link to another
4//! key. Every link signs its parent's digest, the `repo_id`, its audience key, and its caveats
5//! (operations, path prefixes, reference kinds, change scope, partitioned quotas, validity
6//! window) under a domain-separated Ed25519 signature. Granting a link and revoking it are
7//! operations at a `WalSeq`; the server accepts a chain only if every link was granted at or
8//! before the request's `WalSeq`, is unrevoked at it, is unexpired, and narrows its parent.
9//!
10//! Every signed and persisted form here is the fixed-width, little-endian, length-prefixed binary
11//! encoding of `docs/F1_CAPABILITY_CHAINS.md` (ADR 0003 principle P5); there is no serde form.
12
13use crate::{AuditOutcome, BoundaryKind, Capability, PolicyEnforcer};
14use ed25519_dalek::{Signature, Signer, SigningKey};
15use sha2::{Digest, Sha256};
16use std::collections::BTreeMap;
17use synapse_core::{
18 encode_did_key_ed25519, validate_repo_relative_path, ChangeId, RefusalCode, RepoId,
19 SynapseError, SynapseResult, WalSeq,
20};
21
22/// Capability link format version.
23pub const CAPABILITY_LINK_VERSION: u16 = 1;
24/// Capability chain format version.
25pub const CAPABILITY_CHAIN_VERSION: u16 = 1;
26/// Domain tag for the Ed25519 signature over a link body.
27pub const DOMAIN_CAPABILITY_LINK_SIGN_V1: &[u8] = b"SYNAPSE_CAPABILITY_LINK_SIGN_V1\0";
28/// Domain tag for a link digest (the identity a child link signs as its parent).
29pub const DOMAIN_CAPABILITY_LINK_ID_V1: &[u8] = b"SYNAPSE_CAPABILITY_LINK_ID_V1\0";
30/// Domain tag for the presenting agent's Ed25519 signature over a chained request.
31pub const DOMAIN_CHAIN_REQUEST_V1: &[u8] = b"SYNAPSE_CHAIN_REQUEST_V1\0";
32/// Domain tag for the digest of a chained request's payload bytes.
33pub const DOMAIN_CHAIN_PAYLOAD_V1: &[u8] = b"SYNAPSE_CHAIN_PAYLOAD_V1\0";
34/// Most links in one chain (root included).
35pub const MAX_CHAIN_DEPTH: usize = 16;
36/// Most path prefixes in one link's path scope.
37pub const MAX_PATH_PREFIXES: usize = 256;
38/// Most `ChangeId`s in one link's change scope.
39pub const MAX_CHANGE_IDS: usize = 1024;
40/// Longest path prefix (the `validate_repo_relative_path` bound).
41pub const MAX_PATH_BYTES: usize = 2048;
42/// Longest repository id (the `RepoId::new` bound).
43pub const MAX_REPO_ID_BYTES: usize = 128;
44/// Parent digest of a root link.
45pub const ROOT_PARENT: LinkDigest = LinkDigest([0u8; 32]);
46
47const KNOWN_OPERATION_BITS: u8 = 0b0011_1111;
48const KNOWN_REFERENCE_BITS: u8 = 0b0000_0011;
49
50fn malformed(msg: impl Into<String>) -> SynapseError {
51 SynapseError::new(RefusalCode::AuthChainMalformed, msg)
52}
53
54/// Domain-separated SHA-256 identity of one encoded capability link.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
56pub struct LinkDigest(pub [u8; 32]);
57
58/// Set of operations a link allows, one bit per `Capability` (bit `tag_byte - 1`).
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub struct OperationSet(u8);
61
62impl OperationSet {
63 pub fn from_capabilities(caps: &[Capability]) -> Self {
64 Self(
65 caps.iter()
66 .fold(0u8, |acc, c| acc | (1u8 << (c.tag_byte() - 1))),
67 )
68 }
69
70 pub fn from_bits(bits: u8) -> SynapseResult<Self> {
71 if bits & !KNOWN_OPERATION_BITS != 0 {
72 return Err(malformed(format!("unknown operation bits {bits:#04x}")));
73 }
74 Ok(Self(bits))
75 }
76
77 pub fn bits(self) -> u8 {
78 self.0
79 }
80
81 pub fn contains(self, cap: Capability) -> bool {
82 self.0 & (1u8 << (cap.tag_byte() - 1)) != 0
83 }
84
85 pub fn is_subset_of(self, parent: Self) -> bool {
86 self.0 & !parent.0 == 0
87 }
88}
89
90/// Kind of reference a request touches (ADR 0003 section 5.8: own drafts only; canonical only
91/// through the promotion queue).
92#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
93pub enum ReferenceKind {
94 /// References owned by the holder's chain (drafts, workspaces).
95 OwnDrafts,
96 /// The canonical reference, moved only by the promotion queue (step E2).
97 CanonicalViaPromotionQueue,
98}
99
100impl ReferenceKind {
101 pub fn tag_byte(self) -> u8 {
102 match self {
103 Self::OwnDrafts => 1,
104 Self::CanonicalViaPromotionQueue => 2,
105 }
106 }
107}
108
109/// Set of reference kinds a link allows, one bit per `ReferenceKind` (bit `tag_byte - 1`).
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
111pub struct ReferenceScope(u8);
112
113impl ReferenceScope {
114 pub fn from_kinds(kinds: &[ReferenceKind]) -> Self {
115 Self(
116 kinds
117 .iter()
118 .fold(0u8, |acc, k| acc | (1u8 << (k.tag_byte() - 1))),
119 )
120 }
121
122 pub fn from_bits(bits: u8) -> SynapseResult<Self> {
123 if bits & !KNOWN_REFERENCE_BITS != 0 {
124 return Err(malformed(format!("unknown reference bits {bits:#04x}")));
125 }
126 Ok(Self(bits))
127 }
128
129 pub fn bits(self) -> u8 {
130 self.0
131 }
132
133 pub fn contains(self, kind: ReferenceKind) -> bool {
134 self.0 & (1u8 << (kind.tag_byte() - 1)) != 0
135 }
136
137 pub fn is_subset_of(self, parent: Self) -> bool {
138 self.0 & !parent.0 == 0
139 }
140}
141
142/// Path prefixes a link allows, in canonical form: strictly ascending bytes, no prefix covered
143/// by another, and the empty prefix (the whole repository) only on its own. A prefix covers a
144/// path when it is empty, equal to the path, or followed in the path by `/` (segment boundary).
145#[derive(Debug, Clone, PartialEq, Eq, Hash)]
146pub struct PathScope {
147 prefixes: Vec<String>,
148}
149
150fn prefix_covers(prefix: &str, path: &str) -> bool {
151 prefix.is_empty()
152 || path == prefix
153 || (path.len() > prefix.len()
154 && path.starts_with(prefix)
155 && path.as_bytes()[prefix.len()] == b'/')
156}
157
158impl PathScope {
159 /// The whole repository (the single empty prefix).
160 pub fn whole_repository() -> Self {
161 Self {
162 prefixes: vec![String::new()],
163 }
164 }
165
166 /// Build a canonical scope from any prefixes: each must be empty or a valid
167 /// repository-relative path; the result is sorted with covered prefixes removed.
168 pub fn new(prefixes: Vec<String>) -> SynapseResult<Self> {
169 if prefixes.len() > MAX_PATH_PREFIXES {
170 return Err(SynapseError::new(
171 RefusalCode::PathInvalid,
172 format!("path scope has more than {MAX_PATH_PREFIXES} prefixes"),
173 ));
174 }
175 for p in &prefixes {
176 if !p.is_empty() {
177 validate_repo_relative_path(p)?;
178 }
179 }
180 if prefixes.iter().any(String::is_empty) {
181 return Ok(Self::whole_repository());
182 }
183 let mut sorted = prefixes;
184 sorted.sort();
185 sorted.dedup();
186 let mut kept: Vec<String> = Vec::with_capacity(sorted.len());
187 for p in sorted {
188 if !kept.iter().any(|k| prefix_covers(k, &p)) {
189 kept.retain(|k| !prefix_covers(&p, k));
190 kept.push(p);
191 }
192 }
193 kept.sort();
194 Ok(Self { prefixes: kept })
195 }
196
197 pub fn prefixes(&self) -> &[String] {
198 &self.prefixes
199 }
200
201 pub fn covers_path(&self, path: &str) -> bool {
202 self.prefixes.iter().any(|p| prefix_covers(p, path))
203 }
204
205 /// True when every path this scope covers is covered by `parent`.
206 pub fn is_within(&self, parent: &PathScope) -> bool {
207 self.prefixes.iter().all(|c| parent.covers_path(c))
208 }
209
210 fn is_canonical(prefixes: &[String]) -> bool {
211 if prefixes.iter().any(String::is_empty) {
212 return prefixes.len() == 1;
213 }
214 prefixes.windows(2).all(|w| w[0] < w[1])
215 && prefixes.iter().enumerate().all(|(i, p)| {
216 prefixes
217 .iter()
218 .enumerate()
219 .all(|(j, q)| i == j || !prefix_covers(q, p))
220 })
221 }
222}
223
224/// `ChangeId`s a link's holder may join (ADR 0003 sections 5.1 and 5.8): any, or exactly the
225/// listed ones (strictly ascending; an empty list allows none).
226#[derive(Debug, Clone, PartialEq, Eq, Hash)]
227pub struct ChangeScope {
228 only: Option<Vec<ChangeId>>,
229}
230
231impl ChangeScope {
232 pub fn any() -> Self {
233 Self { only: None }
234 }
235
236 pub fn only(mut ids: Vec<ChangeId>) -> SynapseResult<Self> {
237 ids.sort();
238 ids.dedup();
239 if ids.len() > MAX_CHANGE_IDS {
240 return Err(malformed(format!(
241 "change scope has more than {MAX_CHANGE_IDS} ids"
242 )));
243 }
244 Ok(Self { only: Some(ids) })
245 }
246
247 /// `None` for any `ChangeId`, else the allowed ids.
248 pub fn ids(&self) -> Option<&[ChangeId]> {
249 self.only.as_deref()
250 }
251
252 pub fn contains(&self, id: ChangeId) -> bool {
253 match &self.only {
254 None => true,
255 Some(ids) => ids.binary_search(&id).is_ok(),
256 }
257 }
258
259 pub fn is_within(&self, parent: &ChangeScope) -> bool {
260 match (&self.only, &parent.only) {
261 (_, None) => true,
262 (None, Some(_)) => false,
263 (Some(child), Some(_)) => child.iter().all(|id| parent.contains(*id)),
264 }
265 }
266}
267
268/// Quotas of one link. Request rate, storage, and footprint are partitioned: the children of
269/// one link together never exceed it, and the link itself keeps only what it has not handed
270/// down. `window_duration_ms` is inherited unchanged; `max_bytes_per_op` is a per-request cap
271/// that may only narrow (it is not a pool and is not partitioned).
272#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
273pub struct ChainQuotas {
274 pub max_ops_per_window: u32,
275 pub window_duration_ms: u64,
276 pub storage_bytes: u64,
277 /// Footprint breadth: declared prefixes weighted by the tracked paths beneath them (step F2).
278 pub footprint_paths: u64,
279 pub max_bytes_per_op: u64,
280}
281
282/// Caveats of one link: what its holder may do.
283#[derive(Debug, Clone, PartialEq, Eq, Hash)]
284pub struct LinkCaveats {
285 pub operations: OperationSet,
286 pub paths: PathScope,
287 pub references: ReferenceScope,
288 pub changes: ChangeScope,
289 pub quotas: ChainQuotas,
290 pub issued_at_ms: u64,
291 pub expires_at_ms: u64,
292}
293
294impl LinkCaveats {
295 /// The first dimension in which `self` is wider than `parent`, or `None` if it narrows.
296 pub fn escalation_against(&self, parent: &LinkCaveats) -> Option<&'static str> {
297 if !self.operations.is_subset_of(parent.operations) {
298 return Some("operations");
299 }
300 if !self.paths.is_within(&parent.paths) {
301 return Some("paths");
302 }
303 if !self.references.is_subset_of(parent.references) {
304 return Some("references");
305 }
306 if !self.changes.is_within(&parent.changes) {
307 return Some("change scope");
308 }
309 let (c, p) = (&self.quotas, &parent.quotas);
310 if c.window_duration_ms != p.window_duration_ms
311 || c.max_ops_per_window > p.max_ops_per_window
312 || c.storage_bytes > p.storage_bytes
313 || c.footprint_paths > p.footprint_paths
314 || c.max_bytes_per_op > p.max_bytes_per_op
315 {
316 return Some("quotas");
317 }
318 if self.issued_at_ms < parent.issued_at_ms || self.expires_at_ms > parent.expires_at_ms {
319 return Some("expiry");
320 }
321 None
322 }
323}
324
325/// One signed link of a capability chain.
326#[derive(Debug, Clone, PartialEq, Eq)]
327pub struct CapabilityLink {
328 pub version: u16,
329 pub nonce: [u8; 32],
330 pub parent: LinkDigest,
331 pub repo_id: RepoId,
332 pub issuer_key: [u8; 32],
333 pub audience_key: [u8; 32],
334 pub caveats: LinkCaveats,
335 pub signature: [u8; 64],
336}
337
338impl CapabilityLink {
339 /// Sign a link with `signer`. A root link has `parent == ROOT_PARENT` and is signed by a
340 /// repository authority; a derived link names its parent's digest and is signed by the
341 /// parent's audience. Narrowing is checked by the server, not here.
342 pub fn issue(
343 signer: &SigningKey,
344 parent: LinkDigest,
345 nonce: [u8; 32],
346 repo_id: RepoId,
347 audience_key: [u8; 32],
348 caveats: LinkCaveats,
349 ) -> Self {
350 let mut link = Self {
351 version: CAPABILITY_LINK_VERSION,
352 nonce,
353 parent,
354 repo_id,
355 issuer_key: signer.verifying_key().to_bytes(),
356 audience_key,
357 caveats,
358 signature: [0u8; 64],
359 };
360 link.signature = signer.sign(&link.signable_bytes()).to_bytes();
361 link
362 }
363
364 pub fn issuer_did(&self) -> String {
365 encode_did_key_ed25519(&self.issuer_key)
366 }
367
368 pub fn audience_did(&self) -> String {
369 encode_did_key_ed25519(&self.audience_key)
370 }
371
372 fn encode_body(&self, buf: &mut Vec<u8>) {
373 let c = &self.caveats;
374 buf.extend_from_slice(&self.version.to_le_bytes());
375 buf.extend_from_slice(&self.nonce);
376 buf.extend_from_slice(&self.parent.0);
377 put_str(buf, self.repo_id.as_str());
378 buf.extend_from_slice(&self.issuer_key);
379 buf.extend_from_slice(&self.audience_key);
380 buf.push(c.operations.bits());
381 buf.push(c.references.bits());
382 buf.extend_from_slice(&(c.paths.prefixes.len() as u32).to_le_bytes());
383 for p in &c.paths.prefixes {
384 put_str(buf, p);
385 }
386 match &c.changes.only {
387 None => buf.push(0),
388 Some(ids) => {
389 buf.push(1);
390 buf.extend_from_slice(&(ids.len() as u32).to_le_bytes());
391 for id in ids {
392 buf.extend_from_slice(&id.0);
393 }
394 }
395 }
396 let q = &c.quotas;
397 buf.extend_from_slice(&q.max_ops_per_window.to_le_bytes());
398 buf.extend_from_slice(&q.window_duration_ms.to_le_bytes());
399 buf.extend_from_slice(&q.storage_bytes.to_le_bytes());
400 buf.extend_from_slice(&q.footprint_paths.to_le_bytes());
401 buf.extend_from_slice(&q.max_bytes_per_op.to_le_bytes());
402 buf.extend_from_slice(&c.issued_at_ms.to_le_bytes());
403 buf.extend_from_slice(&c.expires_at_ms.to_le_bytes());
404 }
405
406 /// `DOMAIN_CAPABILITY_LINK_SIGN_V1 || body`: what the issuer signs.
407 pub fn signable_bytes(&self) -> Vec<u8> {
408 let mut buf = Vec::with_capacity(512);
409 buf.extend_from_slice(DOMAIN_CAPABILITY_LINK_SIGN_V1);
410 self.encode_body(&mut buf);
411 buf
412 }
413
414 /// Canonical binary encoding: `body || signature`.
415 pub fn encode(&self) -> Vec<u8> {
416 let mut buf = Vec::with_capacity(512);
417 self.encode_body(&mut buf);
418 buf.extend_from_slice(&self.signature);
419 buf
420 }
421
422 /// `SHA-256(DOMAIN_CAPABILITY_LINK_ID_V1 || encode())`.
423 pub fn digest(&self) -> LinkDigest {
424 let mut h = Sha256::new();
425 h.update(DOMAIN_CAPABILITY_LINK_ID_V1);
426 h.update(self.encode());
427 LinkDigest(h.finalize().into())
428 }
429
430 /// Decode exactly one canonical link; anything else is `AuthChainMalformed`.
431 pub fn decode(bytes: &[u8]) -> SynapseResult<Self> {
432 let mut r = Reader::new(bytes);
433 let link = Self::decode_from(&mut r)?;
434 r.finish()?;
435 Ok(link)
436 }
437
438 fn decode_from(r: &mut Reader<'_>) -> SynapseResult<Self> {
439 let version = r.u16()?;
440 if version != CAPABILITY_LINK_VERSION {
441 return Err(malformed(format!(
442 "unsupported capability link version {version}"
443 )));
444 }
445 let nonce = r.arr32()?;
446 let parent = LinkDigest(r.arr32()?);
447 let repo_raw = r.string(MAX_REPO_ID_BYTES)?;
448 let repo_id = RepoId::new(repo_raw).map_err(|e| malformed(e.message))?;
449 let issuer_key = r.arr32()?;
450 let audience_key = r.arr32()?;
451 let operations = OperationSet::from_bits(r.u8()?)?;
452 let references = ReferenceScope::from_bits(r.u8()?)?;
453 let path_count = r.count(MAX_PATH_PREFIXES, 4)?;
454 let mut prefixes = Vec::with_capacity(path_count);
455 for _ in 0..path_count {
456 let p = r.string(MAX_PATH_BYTES)?;
457 if !p.is_empty() {
458 validate_repo_relative_path(&p).map_err(|e| malformed(e.message))?;
459 }
460 prefixes.push(p);
461 }
462 if !PathScope::is_canonical(&prefixes) {
463 return Err(malformed("path scope is not in canonical form"));
464 }
465 let changes = match r.u8()? {
466 0 => ChangeScope::any(),
467 1 => {
468 let n = r.count(MAX_CHANGE_IDS, 16)?;
469 let mut ids = Vec::with_capacity(n);
470 for _ in 0..n {
471 let mut id = [0u8; 16];
472 id.copy_from_slice(r.take(16)?);
473 ids.push(ChangeId(id));
474 }
475 if !ids.windows(2).all(|w| w[0] < w[1]) {
476 return Err(malformed("change scope ids are not strictly ascending"));
477 }
478 ChangeScope { only: Some(ids) }
479 }
480 other => return Err(malformed(format!("unknown change scope tag {other}"))),
481 };
482 let quotas = ChainQuotas {
483 max_ops_per_window: r.u32()?,
484 window_duration_ms: r.u64()?,
485 storage_bytes: r.u64()?,
486 footprint_paths: r.u64()?,
487 max_bytes_per_op: r.u64()?,
488 };
489 let issued_at_ms = r.u64()?;
490 let expires_at_ms = r.u64()?;
491 let mut signature = [0u8; 64];
492 signature.copy_from_slice(r.take(64)?);
493 Ok(Self {
494 version,
495 nonce,
496 parent,
497 repo_id,
498 issuer_key,
499 audience_key,
500 caveats: LinkCaveats {
501 operations,
502 paths: PathScope { prefixes },
503 references,
504 changes,
505 quotas,
506 issued_at_ms,
507 expires_at_ms,
508 },
509 signature,
510 })
511 }
512
513 /// Verify the issuer's Ed25519 signature over `signable_bytes()`.
514 pub fn verify_signature(&self) -> SynapseResult<()> {
515 let invalid = |msg: &str| SynapseError::new(RefusalCode::AuthGrantSignatureInvalid, msg);
516 let key = crate::key_cache::verifying_key(&self.issuer_key)
517 .map_err(|_| invalid("link issuer key is not a valid Ed25519 key"))?;
518 key.verify_strict(
519 &self.signable_bytes(),
520 &Signature::from_bytes(&self.signature),
521 )
522 .map_err(|_| invalid("link signature verification failed"))
523 }
524}
525
526/// A capability chain, root first.
527#[derive(Debug, Clone, PartialEq, Eq)]
528pub struct CapabilityChain {
529 pub links: Vec<CapabilityLink>,
530}
531
532impl CapabilityChain {
533 pub fn new(links: Vec<CapabilityLink>) -> Self {
534 Self { links }
535 }
536
537 /// The chain with `link` appended (the parent chain plus a newly issued child).
538 pub fn extended(&self, link: CapabilityLink) -> Self {
539 let mut links = self.links.clone();
540 links.push(link);
541 Self { links }
542 }
543
544 pub fn leaf(&self) -> Option<&CapabilityLink> {
545 self.links.last()
546 }
547
548 pub fn link_digests(&self) -> Vec<LinkDigest> {
549 self.links.iter().map(CapabilityLink::digest).collect()
550 }
551
552 /// `version u16 | count u8 | (len u32 | link)*`.
553 pub fn encode(&self) -> Vec<u8> {
554 let mut buf = Vec::with_capacity(512 * self.links.len() + 3);
555 buf.extend_from_slice(&CAPABILITY_CHAIN_VERSION.to_le_bytes());
556 buf.push(self.links.len() as u8);
557 for link in &self.links {
558 let bytes = link.encode();
559 buf.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
560 buf.extend_from_slice(&bytes);
561 }
562 buf
563 }
564
565 /// Decode exactly one canonical chain of 1..=`MAX_CHAIN_DEPTH` links.
566 pub fn decode(bytes: &[u8]) -> SynapseResult<Self> {
567 let mut r = Reader::new(bytes);
568 let version = r.u16()?;
569 if version != CAPABILITY_CHAIN_VERSION {
570 return Err(malformed(format!(
571 "unsupported capability chain version {version}"
572 )));
573 }
574 let count = r.u8()? as usize;
575 if count == 0 || count > MAX_CHAIN_DEPTH {
576 return Err(malformed(format!(
577 "chain length {count} outside 1..={MAX_CHAIN_DEPTH}"
578 )));
579 }
580 let mut links = Vec::with_capacity(count);
581 for _ in 0..count {
582 let len = r.u32()? as usize;
583 let mut inner = Reader::new(r.take(len)?);
584 links.push(CapabilityLink::decode_from(&mut inner)?);
585 inner.finish()?;
586 }
587 r.finish()?;
588 Ok(Self { links })
589 }
590}
591
592/// What a chained request touches, checked against the leaf link's scopes.
593#[derive(Debug, Clone, PartialEq, Eq, Default)]
594pub struct RequestScope {
595 /// Repository-relative paths the request reads or writes.
596 pub paths: Vec<String>,
597 /// Reference kind the request reads or moves, if any.
598 pub reference: Option<ReferenceKind>,
599 /// `ChangeId` the request joins through change scope, if any (when change scope is needed
600 /// is decided by step B1).
601 pub join_change: Option<ChangeId>,
602}
603
604impl RequestScope {
605 fn encode_into(&self, buf: &mut Vec<u8>) {
606 buf.extend_from_slice(&(self.paths.len() as u32).to_le_bytes());
607 for p in &self.paths {
608 put_str(buf, p);
609 }
610 buf.push(self.reference.map_or(0, ReferenceKind::tag_byte));
611 match self.join_change {
612 None => buf.push(0),
613 Some(id) => {
614 buf.push(1);
615 buf.extend_from_slice(&id.0);
616 }
617 }
618 }
619}
620
621/// A request presented with a capability chain and signed by the leaf link's audience.
622#[derive(Debug, Clone, PartialEq, Eq)]
623pub struct ChainedRequest {
624 pub chain: CapabilityChain,
625 pub target_repo_id: RepoId,
626 pub agent_key: [u8; 32],
627 pub required_capability: Capability,
628 pub scope: RequestScope,
629 pub request_nonce: [u8; 32],
630 pub timestamp_ms: u64,
631 pub payload: Vec<u8>,
632 pub agent_signature: [u8; 64],
633}
634
635impl ChainedRequest {
636 #[allow(clippy::too_many_arguments)]
637 pub fn sign_new(
638 agent_key: &SigningKey,
639 chain: CapabilityChain,
640 target_repo_id: RepoId,
641 required_capability: Capability,
642 scope: RequestScope,
643 request_nonce: [u8; 32],
644 timestamp_ms: u64,
645 payload: Vec<u8>,
646 ) -> Self {
647 let mut req = Self {
648 chain,
649 target_repo_id,
650 agent_key: agent_key.verifying_key().to_bytes(),
651 required_capability,
652 scope,
653 request_nonce,
654 timestamp_ms,
655 payload,
656 agent_signature: [0u8; 64],
657 };
658 req.agent_signature = agent_key.sign(&req.canonical_signable_bytes()).to_bytes();
659 req
660 }
661
662 pub fn agent_did(&self) -> String {
663 encode_did_key_ed25519(&self.agent_key)
664 }
665
666 /// `SHA-256(DOMAIN_CHAIN_PAYLOAD_V1 || payload)`.
667 pub fn payload_sha256(&self) -> [u8; 32] {
668 let mut h = Sha256::new();
669 h.update(DOMAIN_CHAIN_PAYLOAD_V1);
670 h.update(&self.payload);
671 h.finalize().into()
672 }
673
674 /// `DOMAIN_CHAIN_REQUEST_V1 || leaf digest || repo || agent key || capability || scope ||
675 /// nonce || timestamp || payload length || payload digest`.
676 pub fn canonical_signable_bytes(&self) -> Vec<u8> {
677 let mut buf = Vec::with_capacity(256);
678 buf.extend_from_slice(DOMAIN_CHAIN_REQUEST_V1);
679 let leaf = self
680 .chain
681 .leaf()
682 .map_or(ROOT_PARENT, CapabilityLink::digest);
683 buf.extend_from_slice(&leaf.0);
684 put_str(&mut buf, self.target_repo_id.as_str());
685 buf.extend_from_slice(&self.agent_key);
686 buf.push(self.required_capability.tag_byte());
687 self.scope.encode_into(&mut buf);
688 buf.extend_from_slice(&self.request_nonce);
689 buf.extend_from_slice(&self.timestamp_ms.to_le_bytes());
690 buf.extend_from_slice(&(self.payload.len() as u64).to_le_bytes());
691 buf.extend_from_slice(&self.payload_sha256());
692 buf
693 }
694}
695
696#[derive(Debug, Clone)]
697struct GrantedLink {
698 granted_at: WalSeq,
699 revoked_at: Option<WalSeq>,
700 quotas: ChainQuotas,
701}
702
703/// Sums of the partitioned quotas handed down to a link's granted children.
704#[derive(Debug, Clone, Copy, Default)]
705struct Allocated {
706 ops: u64,
707 storage: u64,
708 footprint: u64,
709}
710
711/// Server-side record of granted and revoked links, quota partitions, and per-link rate windows.
712#[derive(Debug, Default)]
713pub(crate) struct ChainRegistry {
714 granted: BTreeMap<LinkDigest, GrantedLink>,
715 allocated: BTreeMap<LinkDigest, Allocated>,
716 rate_windows: BTreeMap<LinkDigest, Vec<u64>>,
717}
718
719impl PolicyEnforcer {
720 /// Stateless checks plus trusted root: linkage, repository, signatures, audience, narrowing,
721 /// and validity window of every link. Returns the link digests, root first.
722 fn verify_chain_links(
723 &self,
724 chain: &CapabilityChain,
725 expected_repo_id: &RepoId,
726 now_ms: u64,
727 ) -> SynapseResult<Vec<LinkDigest>> {
728 let n = chain.links.len();
729 if n == 0 || n > MAX_CHAIN_DEPTH {
730 return Err(SynapseError::new(
731 RefusalCode::AuthChainBroken,
732 format!("chain length {n} outside 1..={MAX_CHAIN_DEPTH}"),
733 ));
734 }
735 let mut digests: Vec<LinkDigest> = Vec::with_capacity(n);
736 for (i, link) in chain.links.iter().enumerate() {
737 if link.version != CAPABILITY_LINK_VERSION {
738 return Err(malformed(format!(
739 "link {i}: unsupported version {}",
740 link.version
741 )));
742 }
743 if &link.repo_id != expected_repo_id {
744 return Err(SynapseError::new(
745 RefusalCode::AuthCrossRepoDenied,
746 format!(
747 "link {i} is bound to repository {} not {expected_repo_id}",
748 link.repo_id
749 ),
750 ));
751 }
752 link.verify_signature()
753 .map_err(|e| SynapseError::new(e.code, format!("link {i}: {}", e.message)))?;
754 if i == 0 {
755 if link.parent != ROOT_PARENT {
756 return Err(SynapseError::new(
757 RefusalCode::AuthChainBroken,
758 "first link is not a root link",
759 ));
760 }
761 let trusted = self
762 .trusted_authorities
763 .get(expected_repo_id)
764 .is_some_and(|set| set.contains(&link.issuer_did()));
765 if !trusted {
766 return Err(SynapseError::new(
767 RefusalCode::AuthGrantSignatureInvalid,
768 format!(
769 "root issuer {} is not a trusted authority for {expected_repo_id}",
770 link.issuer_did()
771 ),
772 ));
773 }
774 } else {
775 let parent = &chain.links[i - 1];
776 if link.parent != digests[i - 1] {
777 return Err(SynapseError::new(
778 RefusalCode::AuthChainBroken,
779 format!("link {i} does not name link {} as its parent", i - 1),
780 ));
781 }
782 if link.issuer_key != parent.audience_key {
783 return Err(SynapseError::new(
784 RefusalCode::AuthAudienceMismatch,
785 format!(
786 "link {i} issuer {} is not the audience {} of its parent",
787 link.issuer_did(),
788 parent.audience_did()
789 ),
790 ));
791 }
792 if let Some(dim) = link.caveats.escalation_against(&parent.caveats) {
793 return Err(SynapseError::new(
794 RefusalCode::AuthScopeEscalation,
795 format!("link {i} is wider than its parent in {dim}"),
796 ));
797 }
798 }
799 if now_ms < link.caveats.issued_at_ms || now_ms > link.caveats.expires_at_ms {
800 return Err(SynapseError::new(
801 RefusalCode::AuthGrantExpired,
802 format!(
803 "link {i} expired or not yet valid (now={now_ms}, window={}..={})",
804 link.caveats.issued_at_ms, link.caveats.expires_at_ms
805 ),
806 ));
807 }
808 digests.push(link.digest());
809 }
810 Ok(digests)
811 }
812
813 /// Every listed link must be granted at or before `seq` and not revoked at `seq`.
814 fn check_granted_at(&self, digests: &[LinkDigest], seq: WalSeq) -> SynapseResult<()> {
815 for (i, d) in digests.iter().enumerate() {
816 let Some(rec) = self.chains.granted.get(d) else {
817 return Err(SynapseError::new(
818 RefusalCode::AuthChainBroken,
819 format!("link {i} was never granted"),
820 ));
821 };
822 if rec.revoked_at.is_some_and(|r| r <= seq) {
823 return Err(SynapseError::new(
824 RefusalCode::AuthGrantRevoked,
825 format!("link {i} is revoked at {seq}"),
826 ));
827 }
828 if rec.granted_at > seq {
829 return Err(SynapseError::new(
830 RefusalCode::AuthChainBroken,
831 format!(
832 "link {i} is granted only at {}, after {seq}",
833 rec.granted_at
834 ),
835 ));
836 }
837 }
838 Ok(())
839 }
840
841 /// Grant the leaf link of `chain` at `seq` (granting is an operation in the log). Every
842 /// earlier link must already be granted and unrevoked at `seq`; the leaf must narrow its
843 /// parent and fit in what the parent has not yet handed to other children. Granting a link
844 /// that is already granted returns its digest without charging its quotas again.
845 pub fn grant_link(
846 &mut self,
847 chain: &CapabilityChain,
848 seq: WalSeq,
849 now_ms: u64,
850 ) -> SynapseResult<LinkDigest> {
851 let leaf = chain.leaf().ok_or_else(|| {
852 SynapseError::new(RefusalCode::AuthChainBroken, "empty capability chain")
853 })?;
854 let repo_id = leaf.repo_id.clone();
855 let digests = self.verify_chain_links(chain, &repo_id, now_ms)?;
856 let (leaf_digest, ancestors) = digests.split_last().expect("non-empty chain");
857 self.check_granted_at(ancestors, seq)?;
858 if let Some(rec) = self.chains.granted.get(leaf_digest) {
859 if rec.revoked_at.is_some() {
860 return Err(SynapseError::new(
861 RefusalCode::AuthGrantRevoked,
862 "link is revoked; a revoked link cannot be granted again",
863 ));
864 }
865 return Ok(*leaf_digest);
866 }
867 let quotas = leaf.caveats.quotas;
868 if let Some(parent_digest) = ancestors.last() {
869 let parent_quotas = self.chains.granted[parent_digest].quotas;
870 let used = self
871 .chains
872 .allocated
873 .get(parent_digest)
874 .copied()
875 .unwrap_or_default();
876 let next_ops = used.ops.checked_add(u64::from(quotas.max_ops_per_window));
877 let next_storage = used.storage.checked_add(quotas.storage_bytes);
878 let next_footprint = used.footprint.checked_add(quotas.footprint_paths);
879 let over = if next_ops.is_none_or(|v| v > u64::from(parent_quotas.max_ops_per_window)) {
880 Some("request rate")
881 } else if next_storage.is_none_or(|v| v > parent_quotas.storage_bytes) {
882 Some("storage")
883 } else if next_footprint.is_none_or(|v| v > parent_quotas.footprint_paths) {
884 Some("footprint")
885 } else {
886 None
887 };
888 if let Some(dim) = over {
889 return Err(SynapseError::new(
890 RefusalCode::QuotaPartitionExceeded,
891 format!("children of the parent link would together exceed its {dim} quota"),
892 ));
893 }
894 self.chains.allocated.insert(
895 *parent_digest,
896 Allocated {
897 ops: next_ops.expect("checked above"),
898 storage: next_storage.expect("checked above"),
899 footprint: next_footprint.expect("checked above"),
900 },
901 );
902 }
903 self.chains.granted.insert(
904 *leaf_digest,
905 GrantedLink {
906 granted_at: seq,
907 revoked_at: None,
908 quotas,
909 },
910 );
911 Ok(*leaf_digest)
912 }
913
914 /// Revoke a granted link at `seq`. Revocation cannot be undone: a later revocation never
915 /// moves an earlier one, and there is no operation that clears it. Every chain through the
916 /// link is refused for requests at `seq` or later.
917 pub fn revoke_link(&mut self, link: LinkDigest, seq: WalSeq) -> SynapseResult<()> {
918 let rec = self.chains.granted.get_mut(&link).ok_or_else(|| {
919 SynapseError::new(
920 RefusalCode::AuthChainBroken,
921 "cannot revoke a link never granted",
922 )
923 })?;
924 rec.revoked_at = Some(rec.revoked_at.map_or(seq, |r| r.min(seq)));
925 Ok(())
926 }
927
928 /// The part of a granted link's partitioned quotas (rate, storage, footprint) not handed
929 /// down to its children; `None` if the link was never granted.
930 pub fn unallocated_quota(&self, link: &LinkDigest) -> Option<ChainQuotas> {
931 let rec = self.chains.granted.get(link)?;
932 let used = self.chains.allocated.get(link).copied().unwrap_or_default();
933 let mut q = rec.quotas;
934 q.max_ops_per_window = q
935 .max_ops_per_window
936 .saturating_sub(u32::try_from(used.ops).unwrap_or(u32::MAX));
937 q.storage_bytes = q.storage_bytes.saturating_sub(used.storage);
938 q.footprint_paths = q.footprint_paths.saturating_sub(used.footprint);
939 Some(q)
940 }
941
942 /// Verify and authorize a `ChainedRequest` whose `WalSeq` is `request_seq`, recording
943 /// `Admitted` or `Refused` in the hash-chained audit log.
944 #[allow(clippy::too_many_arguments)]
945 pub fn authorize_chain(
946 &mut self,
947 boundary: BoundaryKind,
948 operation: &str,
949 expected_repo_id: &RepoId,
950 expected_capability: Capability,
951 req: &ChainedRequest,
952 request_seq: WalSeq,
953 now_ms: u64,
954 ) -> SynapseResult<()> {
955 self.audit_log.ensure_capacity()?;
956 let result = self.check_chained_request(
957 expected_repo_id,
958 expected_capability,
959 req,
960 request_seq,
961 now_ms,
962 );
963 let outcome = match &result {
964 Ok(()) => AuditOutcome::Admitted,
965 Err(err) => AuditOutcome::Refused {
966 code: err.code,
967 reason: err.message.clone(),
968 },
969 };
970 self.audit_log.record(
971 now_ms,
972 boundary,
973 expected_repo_id.clone(),
974 req.agent_did(),
975 expected_capability,
976 operation,
977 outcome,
978 )?;
979 result
980 }
981
982 fn check_chained_request(
983 &mut self,
984 expected_repo_id: &RepoId,
985 expected_capability: Capability,
986 req: &ChainedRequest,
987 request_seq: WalSeq,
988 now_ms: u64,
989 ) -> SynapseResult<()> {
990 if &req.target_repo_id != expected_repo_id {
991 return Err(SynapseError::new(
992 RefusalCode::AuthCrossRepoDenied,
993 format!(
994 "request targets {} not {expected_repo_id}",
995 req.target_repo_id
996 ),
997 ));
998 }
999 let digests = self.verify_chain_links(&req.chain, expected_repo_id, now_ms)?;
1000 self.check_granted_at(&digests, request_seq)?;
1001 let leaf = req.chain.leaf().expect("verified non-empty chain");
1002 let leaf_digest = *digests.last().expect("verified non-empty chain");
1003
1004 if req.agent_key != leaf.audience_key {
1005 return Err(SynapseError::new(
1006 RefusalCode::AuthAudienceMismatch,
1007 format!(
1008 "request presented by {} but the leaf link's audience is {}",
1009 req.agent_did(),
1010 leaf.audience_did()
1011 ),
1012 ));
1013 }
1014 let agent_key = crate::key_cache::verifying_key(&req.agent_key).map_err(|_| {
1015 SynapseError::new(RefusalCode::DidKeyInvalid, "invalid agent Ed25519 key")
1016 })?;
1017 agent_key
1018 .verify_strict(
1019 &req.canonical_signable_bytes(),
1020 &Signature::from_bytes(&req.agent_signature),
1021 )
1022 .map_err(|_| {
1023 SynapseError::new(
1024 RefusalCode::AuthSignatureInvalid,
1025 "agent Ed25519 chained request signature verification failed",
1026 )
1027 })?;
1028
1029 let caveats = &leaf.caveats;
1030 if req.required_capability != expected_capability
1031 || !caveats.operations.contains(expected_capability)
1032 {
1033 return Err(SynapseError::new(
1034 RefusalCode::AuthCapabilityDenied,
1035 format!(
1036 "chain of {} lacks required capability {expected_capability:?}",
1037 req.agent_did()
1038 ),
1039 ));
1040 }
1041 for path in &req.scope.paths {
1042 validate_repo_relative_path(path)?;
1043 if !caveats.paths.covers_path(path) {
1044 return Err(SynapseError::new(
1045 RefusalCode::AuthPathOutOfScope,
1046 format!("path {path} is outside the chain's path scope"),
1047 ));
1048 }
1049 }
1050 if let Some(kind) = req.scope.reference {
1051 if !caveats.references.contains(kind) {
1052 return Err(SynapseError::new(
1053 RefusalCode::AuthReferenceOutOfScope,
1054 format!("reference kind {kind:?} is outside the chain's reference scope"),
1055 ));
1056 }
1057 }
1058 if let Some(id) = req.scope.join_change {
1059 if !caveats.changes.contains(id) {
1060 return Err(SynapseError::new(
1061 RefusalCode::AuthChangeOutOfScope,
1062 format!("{id:?} is outside the chain's change scope"),
1063 ));
1064 }
1065 }
1066 let payload_len = req.payload.len() as u64;
1067 if payload_len > caveats.quotas.max_bytes_per_op {
1068 return Err(SynapseError::new(
1069 RefusalCode::QuotaPayloadTooLarge,
1070 format!(
1071 "request payload size {payload_len} exceeds the chain's max_bytes_per_op {}",
1072 caveats.quotas.max_bytes_per_op
1073 ),
1074 ));
1075 }
1076
1077 // Partitioned rate: the leaf may use only the part it has not handed to children.
1078 let own = self
1079 .unallocated_quota(&leaf_digest)
1080 .expect("granted leaf has a quota record");
1081 let window_start = now_ms.saturating_sub(own.window_duration_ms);
1082 let timestamps = self.chains.rate_windows.entry(leaf_digest).or_default();
1083 timestamps.retain(|&ts| ts >= window_start);
1084 if timestamps.len() as u64 >= u64::from(own.max_ops_per_window) {
1085 return Err(SynapseError::new(
1086 RefusalCode::QuotaRateLimitExceeded,
1087 format!(
1088 "link exceeded its unallocated rate ({} ops per {} ms)",
1089 own.max_ops_per_window, own.window_duration_ms
1090 ),
1091 ));
1092 }
1093
1094 if expected_capability.is_mutating() {
1095 let nonce_key = (expected_repo_id.clone(), req.agent_did(), req.request_nonce);
1096 if !self.consumed_nonces.insert(nonce_key) {
1097 return Err(SynapseError::new(
1098 RefusalCode::AuthReplayDetected,
1099 "replayed mutation request_nonce refused",
1100 ));
1101 }
1102 }
1103 self.chains
1104 .rate_windows
1105 .entry(leaf_digest)
1106 .or_default()
1107 .push(now_ms);
1108 Ok(())
1109 }
1110}
1111
1112fn put_str(buf: &mut Vec<u8>, s: &str) {
1113 buf.extend_from_slice(&(s.len() as u32).to_le_bytes());
1114 buf.extend_from_slice(s.as_bytes());
1115}
1116
1117/// Bounds-checked little-endian reader; every failure is `AuthChainMalformed`.
1118struct Reader<'a> {
1119 buf: &'a [u8],
1120 pos: usize,
1121}
1122
1123impl<'a> Reader<'a> {
1124 fn new(buf: &'a [u8]) -> Self {
1125 Self { buf, pos: 0 }
1126 }
1127
1128 fn take(&mut self, n: usize) -> SynapseResult<&'a [u8]> {
1129 let remaining = self.buf.len() - self.pos;
1130 if n > remaining {
1131 return Err(malformed(format!(
1132 "truncated: need {n} bytes at offset {}, {remaining} remain",
1133 self.pos
1134 )));
1135 }
1136 let out = &self.buf[self.pos..self.pos + n];
1137 self.pos += n;
1138 Ok(out)
1139 }
1140
1141 fn u8(&mut self) -> SynapseResult<u8> {
1142 Ok(self.take(1)?[0])
1143 }
1144
1145 fn u16(&mut self) -> SynapseResult<u16> {
1146 Ok(u16::from_le_bytes(
1147 self.take(2)?.try_into().expect("2 bytes"),
1148 ))
1149 }
1150
1151 fn u32(&mut self) -> SynapseResult<u32> {
1152 Ok(u32::from_le_bytes(
1153 self.take(4)?.try_into().expect("4 bytes"),
1154 ))
1155 }
1156
1157 fn u64(&mut self) -> SynapseResult<u64> {
1158 Ok(u64::from_le_bytes(
1159 self.take(8)?.try_into().expect("8 bytes"),
1160 ))
1161 }
1162
1163 fn arr32(&mut self) -> SynapseResult<[u8; 32]> {
1164 Ok(self.take(32)?.try_into().expect("32 bytes"))
1165 }
1166
1167 /// A `u32` count, refused above `cap` or above what `min_item_bytes` per item could fit.
1168 fn count(&mut self, cap: usize, min_item_bytes: usize) -> SynapseResult<usize> {
1169 let n = self.u32()? as usize;
1170 let remaining = self.buf.len() - self.pos;
1171 if n > cap || n.saturating_mul(min_item_bytes) > remaining {
1172 return Err(malformed(format!(
1173 "count {n} above cap {cap} or the {remaining} bytes that remain"
1174 )));
1175 }
1176 Ok(n)
1177 }
1178
1179 fn string(&mut self, cap: usize) -> SynapseResult<String> {
1180 let len = self.u32()? as usize;
1181 if len > cap {
1182 return Err(malformed(format!("string length {len} above cap {cap}")));
1183 }
1184 let bytes = self.take(len)?;
1185 String::from_utf8(bytes.to_vec()).map_err(|_| malformed("string is not UTF-8"))
1186 }
1187
1188 fn finish(&self) -> SynapseResult<()> {
1189 if self.pos != self.buf.len() {
1190 return Err(malformed(format!(
1191 "{} trailing bytes",
1192 self.buf.len() - self.pos
1193 )));
1194 }
1195 Ok(())
1196 }
1197}