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-radicle / src / identity.rs

642 lines · 25211 bytes Raw Blame History
1//! Repository identity document (ADR 0003 section 5.5 "Trust root", step E0).
2//!
3//! The document names who may change a repository's trust settings and which machines it
4//! trusts:
5//!
6//! * `delegates` and `threshold`: the keys whose signatures change the document, and how many
7//! distinct delegates must sign. This mirrors Radicle `refs/rad/id` delegates and threshold
8//! (ADR 0001 section 2.2 item 3 is unchanged; delegates can be machines);
9//! * `executors`: the registered executor machine keys whose evidence receipts may count
10//! (section 5.5 "Who may execute"; consumed by E1);
11//! * `server_key`: the server's own machine key, which signs derivation attestations
12//! (section 5.1 `DerivationAttestation`; consumed by B5).
13//!
14//! Every revision after genesis is an [`IdentityEdit`]: the full next document plus delegate
15//! signatures. An edit applies only if at least the *current* document's threshold of its
16//! *current* delegates signed it, as in Radicle. The next document carries the revision
17//! number and the digest of the document it replaces, so a signed edit cannot be replayed
18//! onto a later revision, applied out of order, or moved to another repository.
19//!
20//! [`IdentityLog`] records the `WalSeq` from which each revision is in effect, so a question
21//! such as "was this executor registered when that receipt was accepted" is answered from the
22//! document in effect at that `WalSeq`. A later edit never revokes a receipt already
23//! accepted; it refuses only receipts accepted from its own `WalSeq` on.
24//!
25//! Format (ADR 0003 principle P5): fixed-width, little-endian, length-prefixed binary, no
26//! Rust-specific serialization. See `docs/E0_IDENTITY_DOCUMENT.md` for the byte layout.
27
28use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
29use sha2::{Digest, Sha256};
30use std::collections::BTreeSet;
31use synapse_core::{
32 decode_did_key_ed25519, RefusalCode, RepoId, SynapseError, SynapseResult, WalSeq,
33};
34use synapse_evidence::{EvidenceReceipt, EvidenceReceiptId, ReceiptError};
35
36/// The only identity document record version this module reads or writes.
37pub const IDENTITY_DOCUMENT_VERSION_V1: u16 = 1;
38/// Domain tag that opens every encoded identity document.
39pub const DOMAIN_IDENTITY_DOCUMENT_V1: &[u8] = b"SYNAPSE_IDENTITY_DOCUMENT_V1\0";
40/// Domain tag for [`IdentityDocumentDigest`].
41pub const DOMAIN_IDENTITY_DOCUMENT_DIGEST_V1: &[u8] = b"SYNAPSE_IDENTITY_DOCUMENT_DIGEST_V1\0";
42/// Domain tag for a delegate's Ed25519 signature over an identity document digest.
43pub const DOMAIN_IDENTITY_EDIT_SIGN_V1: &[u8] = b"SYNAPSE_IDENTITY_EDIT_SIGN_V1\0";
44/// Domain tag that opens every encoded identity edit.
45pub const DOMAIN_IDENTITY_EDIT_V1: &[u8] = b"SYNAPSE_IDENTITY_EDIT_V1\0";
46/// Most delegates one document may list.
47pub const MAX_DELEGATES: usize = 256;
48/// Most registered executors one document may list.
49pub const MAX_EXECUTORS: usize = 4096;
50/// Most signatures one edit may carry.
51pub const MAX_EDIT_SIGNATURES: usize = MAX_DELEGATES;
52/// Longest repository identifier, in bytes, the decoder accepts.
53pub const MAX_REPO_ID_BYTES: usize = 4096;
54/// Largest encoded document the edit decoder accepts (every list and string at its cap).
55pub const MAX_DOCUMENT_BYTES: usize = DOMAIN_IDENTITY_DOCUMENT_V1.len()
56 + 2
57 + 4
58 + MAX_REPO_ID_BYTES
59 + 8
60 + 32
61 + 4
62 + 4
63 + MAX_DELEGATES * 32
64 + 4
65 + MAX_EXECUTORS * 32
66 + 32;
67
68/// Raw 32-byte Ed25519 public key.
69pub type Ed25519PublicKey = [u8; 32];
70
71/// Domain-separated SHA-256 digest of one encoded identity document. Never a `BlobDigest`,
72/// `ChangesetId`, or receipt identity.
73#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
74pub struct IdentityDocumentDigest(pub [u8; 32]);
75
76impl IdentityDocumentDigest {
77 /// The `prev` of a genesis document.
78 pub const ZERO: Self = Self([0u8; 32]);
79
80 pub fn to_hex(self) -> String {
81 hex::encode(self.0)
82 }
83}
84
85/// One revision of a repository's identity document.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct RepositoryIdentityDocument {
88 pub repo_id: RepoId,
89 /// 0 for genesis; each edit adds exactly 1.
90 pub revision: u64,
91 /// Digest of the document this one replaces; [`IdentityDocumentDigest::ZERO`] for genesis.
92 pub prev: IdentityDocumentDigest,
93 /// Distinct delegate signatures an edit of this document needs (1 to delegate count).
94 pub threshold: u32,
95 /// Strictly ascending, unique, at most [`MAX_DELEGATES`], at least one.
96 pub delegates: Vec<Ed25519PublicKey>,
97 /// Registered executor machine keys. Strictly ascending, unique, at most [`MAX_EXECUTORS`].
98 pub executors: Vec<Ed25519PublicKey>,
99 /// The server's machine key (signs derivation attestations).
100 pub server_key: Ed25519PublicKey,
101}
102
103fn invalid(message: impl Into<String>) -> SynapseError {
104 SynapseError::new(RefusalCode::RadicleIdentityInvalid, message)
105}
106
107/// A key is usable only if it decodes to a curve point that is not of small order.
108fn check_key(key: &Ed25519PublicKey, what: &str) -> SynapseResult<VerifyingKey> {
109 let vk = VerifyingKey::from_bytes(key)
110 .map_err(|_| invalid(format!("{what} is not an Ed25519 public key")))?;
111 if vk.is_weak() {
112 return Err(invalid(format!("{what} is a small-order Ed25519 key")));
113 }
114 Ok(vk)
115}
116
117fn check_key_list(keys: &[Ed25519PublicKey], cap: usize, what: &str) -> SynapseResult<()> {
118 if keys.len() > cap {
119 return Err(invalid(format!(
120 "{} {what} keys exceed the cap of {cap}",
121 keys.len()
122 )));
123 }
124 if keys.windows(2).any(|w| w[0] >= w[1]) {
125 return Err(invalid(format!(
126 "{what} keys must be strictly ascending and unique"
127 )));
128 }
129 for k in keys {
130 check_key(k, what)?;
131 }
132 Ok(())
133}
134
135impl RepositoryIdentityDocument {
136 /// Check every structural rule of record version 1.
137 pub fn validate(&self) -> SynapseResult<()> {
138 if self.repo_id.as_str().len() > MAX_REPO_ID_BYTES {
139 return Err(invalid("repository identifier exceeds its cap"));
140 }
141 if (self.revision == 0) != (self.prev == IdentityDocumentDigest::ZERO) {
142 return Err(invalid(
143 "revision 0, and only revision 0, has the zero prev digest",
144 ));
145 }
146 if self.delegates.is_empty() {
147 return Err(invalid("identity document must have at least one delegate"));
148 }
149 check_key_list(&self.delegates, MAX_DELEGATES, "delegate")?;
150 if self.threshold == 0 || self.threshold as usize > self.delegates.len() {
151 return Err(invalid(format!(
152 "invalid threshold {} for {} delegates",
153 self.threshold,
154 self.delegates.len()
155 )));
156 }
157 check_key_list(&self.executors, MAX_EXECUTORS, "executor")?;
158 check_key(&self.server_key, "server key")?;
159 Ok(())
160 }
161
162 /// The next revision's starting point: this document with `revision + 1` and `prev` set to
163 /// this document's digest. The caller then changes what the edit changes.
164 pub fn successor(&self) -> Self {
165 let mut next = self.clone();
166 next.revision = self.revision.saturating_add(1);
167 next.prev = self.digest();
168 next
169 }
170
171 /// Canonical record bytes (see `docs/E0_IDENTITY_DOCUMENT.md`).
172 pub fn encode(&self) -> Vec<u8> {
173 let repo = self.repo_id.as_str().as_bytes();
174 let mut buf = Vec::with_capacity(
175 DOMAIN_IDENTITY_DOCUMENT_V1.len()
176 + 90
177 + repo.len()
178 + 32 * (self.delegates.len() + self.executors.len()),
179 );
180 buf.extend_from_slice(DOMAIN_IDENTITY_DOCUMENT_V1);
181 buf.extend_from_slice(&IDENTITY_DOCUMENT_VERSION_V1.to_le_bytes());
182 buf.extend_from_slice(&(repo.len() as u32).to_le_bytes());
183 buf.extend_from_slice(repo);
184 buf.extend_from_slice(&self.revision.to_le_bytes());
185 buf.extend_from_slice(&self.prev.0);
186 buf.extend_from_slice(&self.threshold.to_le_bytes());
187 for list in [&self.delegates, &self.executors] {
188 buf.extend_from_slice(&(list.len() as u32).to_le_bytes());
189 for k in list {
190 buf.extend_from_slice(k);
191 }
192 }
193 buf.extend_from_slice(&self.server_key);
194 buf
195 }
196
197 /// Decode and validate one record. Refuses a wrong tag or version, a truncated record,
198 /// trailing bytes, a count above its cap (before allocating for it), and any document
199 /// [`validate`](Self::validate) refuses. Every refusal is `RadicleIdentityInvalid`.
200 pub fn decode(bytes: &[u8]) -> SynapseResult<Self> {
201 let mut r = Reader::new(bytes);
202 let doc = Self::read(&mut r)?;
203 r.finish()?;
204 Ok(doc)
205 }
206
207 fn read(r: &mut Reader<'_>) -> SynapseResult<Self> {
208 r.tag(DOMAIN_IDENTITY_DOCUMENT_V1, "identity document")?;
209 let version = r.u16()?;
210 if version != IDENTITY_DOCUMENT_VERSION_V1 {
211 return Err(invalid(format!(
212 "identity document version {version} is not supported"
213 )));
214 }
215 let repo_len = r.count(MAX_REPO_ID_BYTES, 1, "repo_id")?;
216 let repo =
217 std::str::from_utf8(r.take(repo_len)?).map_err(|_| invalid("repo_id is not UTF-8"))?;
218 let repo_id = RepoId::new(repo).map_err(|e| invalid(e.message))?;
219 let revision = r.u64()?;
220 let prev = IdentityDocumentDigest(r.array()?);
221 let threshold = r.u32()?;
222 let delegates = r.keys(MAX_DELEGATES, "delegates")?;
223 let executors = r.keys(MAX_EXECUTORS, "executors")?;
224 let server_key = r.array()?;
225 let doc = Self {
226 repo_id,
227 revision,
228 prev,
229 threshold,
230 delegates,
231 executors,
232 server_key,
233 };
234 doc.validate()?;
235 Ok(doc)
236 }
237
238 /// SHA-256 over the digest tag, the record length (u64 LE), and the record.
239 pub fn digest(&self) -> IdentityDocumentDigest {
240 let bytes = self.encode();
241 let mut h = Sha256::new();
242 h.update(DOMAIN_IDENTITY_DOCUMENT_DIGEST_V1);
243 h.update((bytes.len() as u64).to_le_bytes());
244 h.update(&bytes);
245 IdentityDocumentDigest(h.finalize().into())
246 }
247
248 /// Bytes a delegate signs to approve this document: the sign tag, then the digest.
249 pub fn signable_bytes(&self) -> Vec<u8> {
250 let mut buf = DOMAIN_IDENTITY_EDIT_SIGN_V1.to_vec();
251 buf.extend_from_slice(&self.digest().0);
252 buf
253 }
254
255 /// One delegate's signature approving this document.
256 pub fn sign(&self, delegate: &SigningKey) -> IdentitySignature {
257 IdentitySignature {
258 key: delegate.verifying_key().to_bytes(),
259 signature: delegate.sign(&self.signable_bytes()).to_bytes(),
260 }
261 }
262
263 pub fn is_delegate(&self, key: &Ed25519PublicKey) -> bool {
264 self.delegates.contains(key)
265 }
266
267 pub fn is_executor(&self, key: &Ed25519PublicKey) -> bool {
268 self.executors.contains(key)
269 }
270
271 /// Check that at least `threshold` distinct delegates of *this* document signed `message`
272 /// (strict Ed25519). Fails closed: a signer that is not a delegate is refused with
273 /// `RadicleIdentityInvalid`, a signature that does not verify with
274 /// `RadicleSignatureInvalid`, and too few distinct delegates with
275 /// `RadicleQuorumInsufficient`. A delegate signing twice counts once. Returns the distinct
276 /// signing delegates, ascending. `message` must carry its own domain tag.
277 pub fn verify_quorum(
278 &self,
279 message: &[u8],
280 signatures: &[IdentitySignature],
281 ) -> SynapseResult<Vec<Ed25519PublicKey>> {
282 if signatures.len() > MAX_EDIT_SIGNATURES {
283 return Err(invalid(format!(
284 "{} signatures exceed the cap of {MAX_EDIT_SIGNATURES}",
285 signatures.len()
286 )));
287 }
288 let mut signed = BTreeSet::new();
289 for s in signatures {
290 if !self.is_delegate(&s.key) {
291 return Err(invalid(format!(
292 "signer {} is not a delegate of identity revision {}",
293 hex::encode(s.key),
294 self.revision
295 )));
296 }
297 let vk = check_key(&s.key, "delegate")?;
298 vk.verify_strict(message, &Signature::from_bytes(&s.signature))
299 .map_err(|_| {
300 SynapseError::new(
301 RefusalCode::RadicleSignatureInvalid,
302 format!(
303 "Ed25519 signature of delegate {} does not verify",
304 hex::encode(s.key)
305 ),
306 )
307 })?;
308 signed.insert(s.key);
309 }
310 if signed.len() < self.threshold as usize {
311 return Err(SynapseError::new(
312 RefusalCode::RadicleQuorumInsufficient,
313 format!(
314 "{} of {} required distinct delegate signatures for identity revision {}",
315 signed.len(),
316 self.threshold,
317 self.revision
318 ),
319 ));
320 }
321 Ok(signed.into_iter().collect())
322 }
323}
324
325/// One delegate's Ed25519 signature.
326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
327pub struct IdentitySignature {
328 pub key: Ed25519PublicKey,
329 pub signature: [u8; 64],
330}
331
332/// A proposed next identity document with the delegate signatures over it.
333#[derive(Debug, Clone, PartialEq, Eq)]
334pub struct IdentityEdit {
335 pub document: RepositoryIdentityDocument,
336 pub signatures: Vec<IdentitySignature>,
337}
338
339impl IdentityEdit {
340 /// Sign `document` with each of `signers` (in the given order).
341 pub fn sign(document: RepositoryIdentityDocument, signers: &[&SigningKey]) -> Self {
342 let signatures = signers.iter().map(|k| document.sign(k)).collect();
343 Self {
344 document,
345 signatures,
346 }
347 }
348
349 /// Canonical record bytes: tag, version, length-prefixed document, signature count, then
350 /// each 32-byte key and 64-byte signature.
351 pub fn encode(&self) -> Vec<u8> {
352 let doc = self.document.encode();
353 let mut buf = Vec::with_capacity(
354 DOMAIN_IDENTITY_EDIT_V1.len() + 10 + doc.len() + 96 * self.signatures.len(),
355 );
356 buf.extend_from_slice(DOMAIN_IDENTITY_EDIT_V1);
357 buf.extend_from_slice(&IDENTITY_DOCUMENT_VERSION_V1.to_le_bytes());
358 buf.extend_from_slice(&(doc.len() as u32).to_le_bytes());
359 buf.extend_from_slice(&doc);
360 buf.extend_from_slice(&(self.signatures.len() as u32).to_le_bytes());
361 for s in &self.signatures {
362 buf.extend_from_slice(&s.key);
363 buf.extend_from_slice(&s.signature);
364 }
365 buf
366 }
367
368 /// Decode one edit record. Structural refusals are `RadicleIdentityInvalid`. Signatures
369 /// are not verified here; [`IdentityLog::apply`] verifies them against the current
370 /// document.
371 pub fn decode(bytes: &[u8]) -> SynapseResult<Self> {
372 let mut r = Reader::new(bytes);
373 r.tag(DOMAIN_IDENTITY_EDIT_V1, "identity edit")?;
374 let version = r.u16()?;
375 if version != IDENTITY_DOCUMENT_VERSION_V1 {
376 return Err(invalid(format!(
377 "identity edit version {version} is not supported"
378 )));
379 }
380 let doc_len = r.count(MAX_DOCUMENT_BYTES, 1, "document")?;
381 let document = RepositoryIdentityDocument::decode(r.take(doc_len)?)?;
382 let n = r.count(MAX_EDIT_SIGNATURES, 96, "signatures")?;
383 let mut signatures = Vec::with_capacity(n);
384 for _ in 0..n {
385 signatures.push(IdentitySignature {
386 key: r.array()?,
387 signature: r.array()?,
388 });
389 }
390 r.finish()?;
391 Ok(Self {
392 document,
393 signatures,
394 })
395 }
396}
397
398/// One applied identity document and the `WalSeq` from which it is in effect.
399#[derive(Debug, Clone, PartialEq, Eq)]
400pub struct IdentityLogEntry {
401 pub applied_at: WalSeq,
402 pub document: RepositoryIdentityDocument,
403}
404
405/// Why a receipt was refused at admission against the identity log.
406#[derive(Debug, Clone, PartialEq, Eq)]
407pub enum ReceiptRefusal {
408 /// The receipt failed its own verification (`EvidenceReceipt::verify`): structure,
409 /// executor key, or signature.
410 Receipt(ReceiptError),
411 /// No identity document was in effect at the `WalSeq`, or the executor key was not
412 /// registered in it (`RadicleIdentityInvalid`).
413 Identity(SynapseError),
414}
415
416/// The chain of applied identity documents of one repository, in `WalSeq` order. Entry 0 is
417/// genesis; entry `i` has revision `i` and chains to entry `i - 1` by digest.
418#[derive(Debug, Clone, PartialEq, Eq)]
419pub struct IdentityLog {
420 entries: Vec<IdentityLogEntry>,
421}
422
423impl IdentityLog {
424 /// Start a log from a genesis document (revision 0, zero `prev`) signed by at least its own
425 /// threshold of its own delegates, in effect from `at`.
426 pub fn genesis(edit: &IdentityEdit, at: WalSeq) -> SynapseResult<Self> {
427 let doc = &edit.document;
428 doc.validate()?;
429 if doc.revision != 0 {
430 return Err(invalid(format!(
431 "genesis identity document has revision {}",
432 doc.revision
433 )));
434 }
435 doc.verify_quorum(&doc.signable_bytes(), &edit.signatures)?;
436 Ok(Self {
437 entries: vec![IdentityLogEntry {
438 applied_at: at,
439 document: doc.clone(),
440 }],
441 })
442 }
443
444 /// Apply `edit` from `at` on. Refused unless `at` is after the current document's
445 /// `WalSeq`, the next document is valid, names the same repository, has the next revision
446 /// number and the current document's digest as `prev`, and at least the *current*
447 /// threshold of *current* delegates signed it. A refused edit changes nothing.
448 pub fn apply(&mut self, edit: &IdentityEdit, at: WalSeq) -> SynapseResult<()> {
449 let last = self.last();
450 let cur = &last.document;
451 if at <= last.applied_at {
452 return Err(invalid(format!(
453 "identity edit at {at} does not follow the current revision's {}",
454 last.applied_at
455 )));
456 }
457 let next = &edit.document;
458 next.validate()?;
459 if next.repo_id != cur.repo_id {
460 return Err(invalid(format!(
461 "identity edit for {} applied to {}",
462 next.repo_id, cur.repo_id
463 )));
464 }
465 if Some(next.revision) != cur.revision.checked_add(1) {
466 return Err(invalid(format!(
467 "identity edit revision {} does not follow current revision {}",
468 next.revision, cur.revision
469 )));
470 }
471 let cur_digest = cur.digest();
472 if next.prev != cur_digest {
473 return Err(invalid(format!(
474 "identity edit chains to {}, current document is {}",
475 next.prev.to_hex(),
476 cur_digest.to_hex()
477 )));
478 }
479 cur.verify_quorum(&next.signable_bytes(), &edit.signatures)?;
480 self.entries.push(IdentityLogEntry {
481 applied_at: at,
482 document: next.clone(),
483 });
484 Ok(())
485 }
486
487 fn last(&self) -> &IdentityLogEntry {
488 // Every constructor creates the genesis entry and nothing removes entries.
489 &self.entries[self.entries.len() - 1]
490 }
491
492 /// The document in effect now (the last applied).
493 pub fn current(&self) -> &RepositoryIdentityDocument {
494 &self.last().document
495 }
496
497 pub fn entries(&self) -> &[IdentityLogEntry] {
498 &self.entries
499 }
500
501 /// The document in effect at `at`: the last one applied at or before `at`. `None` before
502 /// genesis.
503 pub fn document_at(&self, at: WalSeq) -> Option<&RepositoryIdentityDocument> {
504 let n = self.entries.partition_point(|e| e.applied_at <= at);
505 n.checked_sub(1).map(|i| &self.entries[i].document)
506 }
507
508 /// Whether `key` was a registered executor in the document in effect at `at`.
509 pub fn executor_registered_at(&self, key: &Ed25519PublicKey, at: WalSeq) -> bool {
510 self.document_at(at).is_some_and(|d| d.is_executor(key))
511 }
512
513 /// The server machine key in the document in effect at `at`.
514 pub fn server_key_at(&self, at: WalSeq) -> Option<Ed25519PublicKey> {
515 self.document_at(at).map(|d| d.server_key)
516 }
517
518 /// Admit `receipt` as accepted at `accepted_at` only if it verifies and its executor key is
519 /// registered in the document in effect at `accepted_at`. Checking an earlier receipt at
520 /// its own acceptance `WalSeq` (replay) gives the same answer after any later edit. This
521 /// checks executor registration only; what a receipt counts toward (input root, policy,
522 /// independence) is E1.
523 pub fn admit_executor_receipt(
524 &self,
525 receipt: &EvidenceReceipt,
526 accepted_at: WalSeq,
527 ) -> Result<EvidenceReceiptId, ReceiptRefusal> {
528 let id = receipt.verify().map_err(ReceiptRefusal::Receipt)?;
529 let key =
530 decode_did_key_ed25519(&receipt.executor_did).map_err(ReceiptRefusal::Identity)?;
531 let doc = self.document_at(accepted_at).ok_or_else(|| {
532 ReceiptRefusal::Identity(invalid(format!(
533 "no identity document in effect at {accepted_at}"
534 )))
535 })?;
536 if !doc.is_executor(&key) {
537 return Err(ReceiptRefusal::Identity(invalid(format!(
538 "executor {} is not registered in identity revision {} in effect at {accepted_at}",
539 receipt.executor_did, doc.revision
540 ))));
541 }
542 Ok(id)
543 }
544}
545
546/// Bounded little-endian reader. Every read is checked against the remaining bytes.
547struct Reader<'a> {
548 bytes: &'a [u8],
549 pos: usize,
550}
551
552impl<'a> Reader<'a> {
553 fn new(bytes: &'a [u8]) -> Self {
554 Self { bytes, pos: 0 }
555 }
556
557 fn take(&mut self, n: usize) -> SynapseResult<&'a [u8]> {
558 let end = self
559 .pos
560 .checked_add(n)
561 .filter(|&e| e <= self.bytes.len())
562 .ok_or_else(|| invalid("identity record is truncated"))?;
563 let s = &self.bytes[self.pos..end];
564 self.pos = end;
565 Ok(s)
566 }
567
568 fn array<const N: usize>(&mut self) -> SynapseResult<[u8; N]> {
569 let mut a = [0u8; N];
570 a.copy_from_slice(self.take(N)?);
571 Ok(a)
572 }
573
574 fn u16(&mut self) -> SynapseResult<u16> {
575 Ok(u16::from_le_bytes(self.array()?))
576 }
577
578 fn u32(&mut self) -> SynapseResult<u32> {
579 Ok(u32::from_le_bytes(self.array()?))
580 }
581
582 fn u64(&mut self) -> SynapseResult<u64> {
583 Ok(u64::from_le_bytes(self.array()?))
584 }
585
586 fn tag(&mut self, tag: &[u8], what: &str) -> SynapseResult<()> {
587 if self.take(tag.len())? != tag {
588 return Err(invalid(format!("{what} record has the wrong domain tag")));
589 }
590 Ok(())
591 }
592
593 /// A u32 count, refused above `cap` or above what the remaining bytes can hold at
594 /// `item_bytes` each, before the caller allocates for it.
595 fn count(&mut self, cap: usize, item_bytes: usize, what: &str) -> SynapseResult<usize> {
596 let n = self.u32()? as usize;
597 if n > cap {
598 return Err(invalid(format!(
599 "{what} count {n} exceeds the cap of {cap}"
600 )));
601 }
602 if n.saturating_mul(item_bytes) > self.bytes.len() - self.pos {
603 return Err(invalid(format!("{what} count {n} exceeds the record")));
604 }
605 Ok(n)
606 }
607
608 fn keys(&mut self, cap: usize, what: &str) -> SynapseResult<Vec<Ed25519PublicKey>> {
609 let n = self.count(cap, 32, what)?;
610 let mut v = Vec::with_capacity(n);
611 for _ in 0..n {
612 v.push(self.array()?);
613 }
614 Ok(v)
615 }
616
617 fn finish(&self) -> SynapseResult<()> {
618 if self.pos != self.bytes.len() {
619 return Err(invalid("identity record has trailing bytes"));
620 }
621 Ok(())
622 }
623}
624
625/// The server key a derivation attestation must name is the `server_key` of the document in
626/// effect at the admission `WalSeq` (ADR 0003 step B5): a later rotation never invalidates a
627/// derivation admitted before it, and a key rotated out refuses every later one. The log holds
628/// one repository's documents (`apply` refuses an edit for another), so it answers only for
629/// that repository and names it as `OtherRepository` for any other.
630impl synapse_core::ServerKeyRegistry for IdentityLog {
631 fn registered_server_key(&self, repo: &RepoId, at: WalSeq) -> synapse_core::ServerKeyLookup {
632 use synapse_core::ServerKeyLookup;
633 let own = &self.current().repo_id;
634 if own != repo {
635 return ServerKeyLookup::OtherRepository(own.clone());
636 }
637 match self.server_key_at(at) {
638 Some(key) => ServerKeyLookup::Registered(key),
639 None => ServerKeyLookup::NoDocument,
640 }
641 }
642}