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

371 lines · 14083 bytes Raw Blame History
1//! Signed revision state moves (ADR 0003 sections 5.3 and 5.4, step B4; issue #89).
2//!
3//! Section 5.4: every operation records the actor and the capability chain used. A state
4//! move (WAL kind 9) therefore carries the mover's key and its strict Ed25519 signature over
5//! the move under [`DOMAIN_STATE_MOVE_SIGN_V1`], as an obsolescence marker does, and the
6//! leaf link of the chain it was made under. The chain is a list of link digests, so the
7//! leaf link is what ties the mover key to the chain: its digest must be the chain's last
8//! digest, its parent the digest before it (or [`ROOT_PARENT`] for a one-link chain), its
9//! repository the move's repository, and its audience the mover key. Replay checks all of
10//! this from the record alone, so a record written into the WAL without the private key of
11//! the chain's leaf never verifies. See `docs/B4_REVISION_STATES.md`.
12
13use crate::{CapabilityChain, CapabilityLink, ROOT_PARENT};
14use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
15use synapse_core::{
16 ChainPath, ChangesetId, RefusalCode, RepoId, RevisionState, SynapseError, SynapseResult,
17};
18
19/// Domain tag of the mover's Ed25519 signature over a revision state move.
20pub const DOMAIN_STATE_MOVE_SIGN_V1: &[u8] = b"SYNAPSE_STATE_MOVE_SIGN_V1\0";
21
22/// Why a signed state move does not verify.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
24pub enum StateMoveFault {
25 /// The mover key is not an Ed25519 key, or the signature does not verify strictly over
26 /// [`SignedStateMove::signable_bytes`].
27 SignatureInvalid,
28 /// The leaf link is not the leaf of the move's chain (its digest, parent, or repository
29 /// differ), or the mover key is not the leaf link's audience.
30 SignerNotChainLeaf,
31}
32
33impl StateMoveFault {
34 /// The refusal of a live request carrying this fault (`AuthSignatureInvalid`, as for an
35 /// envelope whose author is not the chain's leaf audience).
36 pub fn into_error(self) -> SynapseError {
37 let msg = match self {
38 Self::SignatureInvalid => "state move: mover signature does not verify",
39 Self::SignerNotChainLeaf => {
40 "state move: the mover key is not the audience of the chain's leaf link"
41 }
42 };
43 SynapseError::new(RefusalCode::AuthSignatureInvalid, msg)
44 }
45}
46
47/// A revision state move signed by its mover: revision `changeset_id` of `repo_id` moves to
48/// `to` under `chain`, signed at the mover's time `signed_at_ms` by `mover_key`, the
49/// audience of `leaf_link` (the chain's leaf link).
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct SignedStateMove {
52 pub repo_id: RepoId,
53 pub changeset_id: ChangesetId,
54 pub to: RevisionState,
55 pub chain: ChainPath,
56 pub signed_at_ms: u64,
57 pub leaf_link: CapabilityLink,
58 pub mover_key: [u8; 32],
59 pub signature: [u8; 64],
60}
61
62impl SignedStateMove {
63 /// `DOMAIN_STATE_MOVE_SIGN_V1 || u32 len | repo_id || changeset_id [32] || to u8 ||
64 /// chain (u8 count | link digest [32]*) || signed_at_ms u64`: what the mover signs.
65 pub fn statement_bytes(
66 repo_id: &RepoId,
67 changeset_id: ChangesetId,
68 to: RevisionState,
69 chain: &ChainPath,
70 signed_at_ms: u64,
71 ) -> Vec<u8> {
72 let repo = repo_id.as_str().as_bytes();
73 let mut buf = Vec::with_capacity(
74 DOMAIN_STATE_MOVE_SIGN_V1.len() + 4 + repo.len() + 32 + 1 + 1 + 32 * 16 + 8,
75 );
76 buf.extend_from_slice(DOMAIN_STATE_MOVE_SIGN_V1);
77 buf.extend_from_slice(&(repo.len() as u32).to_le_bytes());
78 buf.extend_from_slice(repo);
79 buf.extend_from_slice(&changeset_id.0);
80 buf.push(to.tag_byte());
81 chain.encode_into(&mut buf);
82 buf.extend_from_slice(&signed_at_ms.to_le_bytes());
83 buf
84 }
85
86 /// The mover's signature over [`Self::statement_bytes`].
87 pub fn sign_statement(
88 mover: &SigningKey,
89 repo_id: &RepoId,
90 changeset_id: ChangesetId,
91 to: RevisionState,
92 chain: &ChainPath,
93 signed_at_ms: u64,
94 ) -> [u8; 64] {
95 mover
96 .sign(&Self::statement_bytes(
97 repo_id,
98 changeset_id,
99 to,
100 chain,
101 signed_at_ms,
102 ))
103 .to_bytes()
104 }
105
106 /// Build and sign a move under the F1 chain `chain` (its link digests and its leaf link).
107 /// An empty chain is `AuthChainBroken`.
108 pub fn sign_new(
109 mover: &SigningKey,
110 repo_id: RepoId,
111 changeset_id: ChangesetId,
112 to: RevisionState,
113 chain: &CapabilityChain,
114 signed_at_ms: u64,
115 ) -> SynapseResult<Self> {
116 let leaf_link = chain.leaf().cloned().ok_or_else(|| {
117 SynapseError::new(RefusalCode::AuthChainBroken, "state move: empty chain")
118 })?;
119 let path = ChainPath::new(chain.link_digests().iter().map(|d| d.0).collect())?;
120 let signature =
121 Self::sign_statement(mover, &repo_id, changeset_id, to, &path, signed_at_ms);
122 Ok(Self {
123 repo_id,
124 changeset_id,
125 to,
126 chain: path,
127 signed_at_ms,
128 leaf_link,
129 mover_key: mover.verifying_key().to_bytes(),
130 signature,
131 })
132 }
133
134 /// [`Self::statement_bytes`] of this move.
135 pub fn signable_bytes(&self) -> Vec<u8> {
136 Self::statement_bytes(
137 &self.repo_id,
138 self.changeset_id,
139 self.to,
140 &self.chain,
141 self.signed_at_ms,
142 )
143 }
144
145 /// The signature verifies strictly under `mover_key`, and `mover_key` is the audience
146 /// of the chain's leaf link: `leaf_link` hashes to the chain's last digest, names the
147 /// digest before it as its parent (`ROOT_PARENT` for a one-link chain), and belongs to
148 /// the move's repository. A pure function of the move, so replay gives the same verdict
149 /// as the live store.
150 ///
151 /// **This binds the signer to the chain; it does not authorize the move.** It never
152 /// checks who issued `leaf_link`, nor its caveats, so anyone can mint a root link of
153 /// their own, or append a link of their own under someone else's chain, and sign a
154 /// move that verifies. Precondition for every caller: the chain must also be, or
155 /// dominate, the chain of the revision's first admission (`ChainPath::dominates`, as
156 /// the store's owner rule does). Dominance pins every digest of the chain, the leaf
157 /// included, to links that were really admitted. A descendant chain (`descends_from`)
158 /// is not enough: its extra links are unchecked.
159 pub fn verify(&self) -> Result<(), StateMoveFault> {
160 let key = VerifyingKey::from_bytes(&self.mover_key)
161 .map_err(|_| StateMoveFault::SignatureInvalid)?;
162 key.verify_strict(
163 &self.signable_bytes(),
164 &Signature::from_bytes(&self.signature),
165 )
166 .map_err(|_| StateMoveFault::SignatureInvalid)?;
167 let links = self.chain.links();
168 let (leaf, ancestors) = links
169 .split_last()
170 .ok_or(StateMoveFault::SignerNotChainLeaf)?;
171 let parent = ancestors.last().copied().unwrap_or(ROOT_PARENT.0);
172 let link = &self.leaf_link;
173 if link.digest().0 != *leaf
174 || link.parent.0 != parent
175 || link.repo_id != self.repo_id
176 || link.audience_key != self.mover_key
177 {
178 return Err(StateMoveFault::SignerNotChainLeaf);
179 }
180 Ok(())
181 }
182}
183
184#[cfg(test)]
185mod tests {
186 use super::*;
187 use crate::{
188 Capability, ChainQuotas, ChangeScope, LinkCaveats, LinkDigest, OperationSet, PathScope,
189 ReferenceScope,
190 };
191 use sha2::{Digest, Sha256};
192
193 /// Keys and nonces are SHA-256 of a label, never fixed byte values.
194 fn derived(label: &str) -> [u8; 32] {
195 Sha256::digest(label.as_bytes()).into()
196 }
197
198 fn key(label: &str) -> SigningKey {
199 SigningKey::from_bytes(&derived(label))
200 }
201
202 fn repo() -> RepoId {
203 RepoId::new("aien-spark/synapse").unwrap()
204 }
205
206 fn caveats() -> LinkCaveats {
207 LinkCaveats {
208 operations: OperationSet::from_capabilities(&[Capability::Read, Capability::Propose]),
209 paths: PathScope::whole_repository(),
210 references: ReferenceScope::from_kinds(&[]),
211 changes: ChangeScope::any(),
212 quotas: ChainQuotas {
213 max_ops_per_window: 100,
214 window_duration_ms: 60_000,
215 storage_bytes: 1 << 20,
216 footprint_paths: 64,
217 max_bytes_per_op: 1 << 20,
218 },
219 issued_at_ms: 0,
220 expires_at_ms: u64::MAX,
221 }
222 }
223
224 fn link(
225 issuer: &SigningKey,
226 parent: LinkDigest,
227 to: &SigningKey,
228 label: &str,
229 ) -> CapabilityLink {
230 CapabilityLink::issue(
231 issuer,
232 parent,
233 derived(label),
234 repo(),
235 to.verifying_key().to_bytes(),
236 caveats(),
237 )
238 }
239
240 /// Authority -> orchestrator -> worker.
241 fn chains() -> (SigningKey, SigningKey, CapabilityChain, CapabilityChain) {
242 let authority = key("state-move authority");
243 let orchestrator = key("state-move orchestrator");
244 let worker = key("state-move worker");
245 let root = link(
246 &authority,
247 ROOT_PARENT,
248 &orchestrator,
249 "state-move root link",
250 );
251 let child = link(
252 &orchestrator,
253 root.digest(),
254 &worker,
255 "state-move child link",
256 );
257 let co = CapabilityChain::new(vec![root]);
258 let cw = co.extended(child);
259 (orchestrator, worker, co, cw)
260 }
261
262 fn id() -> ChangesetId {
263 ChangesetId(derived("state-move changeset"))
264 }
265
266 #[test]
267 fn a_move_signed_by_the_chain_leaf_verifies_for_root_and_derived_chains() {
268 let (o, w, co, cw) = chains();
269 for (k, c) in [(&o, &co), (&w, &cw)] {
270 let m = SignedStateMove::sign_new(k, repo(), id(), RevisionState::Draft, c, 7).unwrap();
271 assert_eq!(m.verify(), Ok(()));
272 }
273 }
274
275 #[test]
276 fn a_bad_signature_or_a_signer_that_is_not_the_leaf_is_refused_typed() {
277 let (o, w, co, cw) = chains();
278 let good =
279 SignedStateMove::sign_new(&w, repo(), id(), RevisionState::Draft, &cw, 7).unwrap();
280
281 // Any change to a signed field breaks the signature.
282 let mut m = good.clone();
283 m.to = RevisionState::Proposed;
284 assert_eq!(m.verify(), Err(StateMoveFault::SignatureInvalid));
285 let mut m = good.clone();
286 m.signed_at_ms += 1;
287 assert_eq!(m.verify(), Err(StateMoveFault::SignatureInvalid));
288 let mut m = good.clone();
289 m.signature[0] ^= 1;
290 assert_eq!(m.verify(), Err(StateMoveFault::SignatureInvalid));
291 let mut m = good.clone();
292 m.mover_key = derived("state-move not the mover");
293 assert_eq!(m.verify(), Err(StateMoveFault::SignatureInvalid));
294
295 // A valid signature by the orchestrator over the worker's chain: the orchestrator is
296 // an ancestor, not the leaf, so it must sign under its own chain instead.
297 let m = SignedStateMove {
298 mover_key: o.verifying_key().to_bytes(),
299 signature: SignedStateMove::sign_statement(
300 &o,
301 &repo(),
302 id(),
303 RevisionState::Draft,
304 &good.chain,
305 7,
306 ),
307 ..good.clone()
308 };
309 assert_eq!(m.verify(), Err(StateMoveFault::SignerNotChainLeaf));
310
311 // A leaf link that is not the chain's leaf (the root link under the worker's chain).
312 let m = SignedStateMove {
313 leaf_link: co.leaf().unwrap().clone(),
314 ..good.clone()
315 };
316 assert_eq!(m.verify(), Err(StateMoveFault::SignerNotChainLeaf));
317
318 // A self-issued link whose audience is the signer, named as a one-link chain whose
319 // digest is that link: the parent is not the root, so it is not this chain's leaf
320 // unless it really is a root link. A forger can mint such a root link, but then the
321 // chain is its own and never dominates another owner's chain (section 5.3).
322 let forger = key("state-move forger");
323 let fake = link(
324 &forger,
325 LinkDigest(*good.chain.links().first().unwrap()),
326 &forger,
327 "fake",
328 );
329 let path = ChainPath::new(vec![good.chain.links()[0], fake.digest().0]).unwrap();
330 let m = SignedStateMove {
331 chain: path.clone(),
332 leaf_link: fake,
333 mover_key: forger.verifying_key().to_bytes(),
334 signature: SignedStateMove::sign_statement(
335 &forger,
336 &repo(),
337 id(),
338 RevisionState::Draft,
339 &path,
340 7,
341 ),
342 ..good.clone()
343 };
344 assert_eq!(
345 m.verify(),
346 Ok(()),
347 "the record alone binds key to chain digests"
348 );
349 assert_ne!(m.chain, good.chain, "but never to another chain's digests");
350 }
351
352 #[test]
353 fn a_leaf_link_of_another_repository_is_refused() {
354 let (_, w, _, cw) = chains();
355 let mut m =
356 SignedStateMove::sign_new(&w, repo(), id(), RevisionState::Draft, &cw, 7).unwrap();
357 m.repo_id = RepoId::new("aien-spark/other").unwrap();
358 m.signature = SignedStateMove::sign_statement(&w, &m.repo_id, id(), m.to, &m.chain, 7);
359 assert_eq!(m.verify(), Err(StateMoveFault::SignerNotChainLeaf));
360 }
361
362 #[test]
363 fn faults_map_to_auth_signature_invalid() {
364 for f in [
365 StateMoveFault::SignatureInvalid,
366 StateMoveFault::SignerNotChainLeaf,
367 ] {
368 assert_eq!(f.into_error().code, RefusalCode::AuthSignatureInvalid);
369 }
370 }
371}