synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-core / src / key_cache / tests.rs
| 1 | //! Issue #93, envelope path: `ChangesetEnvelope::validate` decodes each author key once per |
| 2 | //! thread, stays bounded, and gives the same verdict and refusal code as the uncached check |
| 3 | //! (`VerifyingKey::from_bytes` then `verify`) for every bad key, cold and warm. |
| 4 | //! |
| 5 | //! Keys and idempotency keys are derived from labels and counters (SHA-256), never written as |
| 6 | //! literals. Each `#[test]` runs on its own thread, so it starts with an empty cache; the |
| 7 | //! assertions still use before/after deltas. |
| 8 | |
| 9 | use super::{cached_verifying_key, key_cache_stats, KEY_CACHE_CAPACITY}; |
| 10 | use crate::{ |
| 11 | encode_did_key_ed25519, BlobDigest, ChangesetEnvelope, EvidenceAttachment, FileMode, GitOid, |
| 12 | IdempotencyKey, MutationOp, PathMutation, RefusalCode, RepoId, SynapseResult, |
| 13 | SYNAPSE_ENVELOPE_VERSION, |
| 14 | }; |
| 15 | use ed25519_dalek::{Signature, SigningKey, Verifier, VerifyingKey}; |
| 16 | use sha2::{Digest, Sha256}; |
| 17 | |
| 18 | fn derived(label: &str, n: u64) -> [u8; 32] { |
| 19 | let mut h = Sha256::new(); |
| 20 | h.update(b"SYNAPSE_CORE_KEY_CACHE_TEST_V1\0"); |
| 21 | h.update(label.as_bytes()); |
| 22 | h.update(n.to_le_bytes()); |
| 23 | h.finalize().into() |
| 24 | } |
| 25 | |
| 26 | fn key(label: &str, n: u64) -> SigningKey { |
| 27 | SigningKey::from_bytes(&derived(label, n)) |
| 28 | } |
| 29 | |
| 30 | /// 32 derived bytes that are not the encoding of a curve point (`from_bytes` refuses them). |
| 31 | fn invalid_point(label: &str) -> [u8; 32] { |
| 32 | (0u64..) |
| 33 | .map(|n| derived(label, n)) |
| 34 | .find(|b| VerifyingKey::from_bytes(b).is_err()) |
| 35 | .expect("an undecodable encoding exists") |
| 36 | } |
| 37 | |
| 38 | /// The identity point: decodes, but has small order. |
| 39 | fn small_order_point() -> [u8; 32] { |
| 40 | let mut b = [0u8; 32]; |
| 41 | b[0] = 1; |
| 42 | b |
| 43 | } |
| 44 | |
| 45 | fn envelope(n: u64) -> ChangesetEnvelope { |
| 46 | let payload = derived("payload", n); |
| 47 | ChangesetEnvelope { |
| 48 | version: SYNAPSE_ENVELOPE_VERSION, |
| 49 | repo_id: RepoId::new("aien-spark/synapse").unwrap(), |
| 50 | base_git_oid: GitOid::compute_blob(&payload), |
| 51 | parent_changesets: vec![], |
| 52 | author_did: String::new(), |
| 53 | idempotency_key: IdempotencyKey(derived("idem", n)), |
| 54 | created_at_ms: 1_789_800_000_000 + n, |
| 55 | intent_summary: "key cache test".to_string(), |
| 56 | mutations: vec![PathMutation { |
| 57 | path: "src/lib.rs".to_string(), |
| 58 | op: MutationOp::Upsert { |
| 59 | mode: FileMode::Regular644, |
| 60 | blob_digest: BlobDigest::compute(&payload), |
| 61 | size_bytes: payload.len() as u64, |
| 62 | }, |
| 63 | }], |
| 64 | evidence_receipts: vec![EvidenceAttachment { |
| 65 | gate_name: "cargo-test".to_string(), |
| 66 | passed: true, |
| 67 | artifact_digest: derived("artifact", n), |
| 68 | summary: "ok".to_string(), |
| 69 | }], |
| 70 | signature: vec![], |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | fn signed(k: &SigningKey, n: u64) -> ChangesetEnvelope { |
| 75 | let mut env = envelope(n); |
| 76 | env.sign(k); |
| 77 | env |
| 78 | } |
| 79 | |
| 80 | /// The pre-cache check, written out: decode with `from_bytes` on every call, then `verify`. |
| 81 | /// Used as the reference the cached path must agree with. |
| 82 | fn uncached_signature_verdict(env: &ChangesetEnvelope) -> SynapseResult<()> { |
| 83 | let bytes = crate::decode_did_key_ed25519(&env.author_did)?; |
| 84 | let vk = VerifyingKey::from_bytes(&bytes).map_err(|_| { |
| 85 | crate::SynapseError::new(RefusalCode::DidKeyInvalid, "invalid Ed25519 public key") |
| 86 | })?; |
| 87 | let sig: [u8; 64] = env.signature.as_slice().try_into().map_err(|_| { |
| 88 | crate::SynapseError::new( |
| 89 | RefusalCode::AuthSignatureInvalid, |
| 90 | "signature must be 64 bytes", |
| 91 | ) |
| 92 | })?; |
| 93 | vk.verify( |
| 94 | &env.canonical_signable_bytes(), |
| 95 | &Signature::from_bytes(&sig), |
| 96 | ) |
| 97 | .map_err(|_| crate::SynapseError::new(RefusalCode::AuthSignatureInvalid, "verify failed")) |
| 98 | } |
| 99 | |
| 100 | fn code(r: SynapseResult<impl Sized>) -> Option<RefusalCode> { |
| 101 | r.err().map(|e| e.code) |
| 102 | } |
| 103 | |
| 104 | #[test] |
| 105 | fn envelope_author_key_decodes_once_across_repeated_validates() { |
| 106 | let author = key("author", 0); |
| 107 | let (_, before) = key_cache_stats(); |
| 108 | for n in 0..32 { |
| 109 | signed(&author, n).validate().expect("valid envelope"); |
| 110 | } |
| 111 | let (len, after) = key_cache_stats(); |
| 112 | assert_eq!( |
| 113 | after - before, |
| 114 | 1, |
| 115 | "one decode for 32 validates by one author" |
| 116 | ); |
| 117 | assert_eq!(len, 1); |
| 118 | } |
| 119 | |
| 120 | #[test] |
| 121 | fn envelope_refusal_codes_for_bad_keys_are_unchanged_cold_and_warm() { |
| 122 | let author = key("author", 1); |
| 123 | let good = signed(&author, 0); |
| 124 | |
| 125 | let mut undecodable = good.clone(); |
| 126 | undecodable.author_did = encode_did_key_ed25519(&invalid_point("undecodable")); |
| 127 | |
| 128 | let mut no_z = good.clone(); |
| 129 | no_z.author_did = good.author_did.replacen("z", "y", 1); |
| 130 | |
| 131 | let mut wrong_codec = good.clone(); |
| 132 | wrong_codec.author_did = format!("did:key:z{}", "1".repeat(46)); |
| 133 | |
| 134 | let mut forged = good.clone(); |
| 135 | forged.signature = signed(&key("impostor", 0), 0).signature; |
| 136 | |
| 137 | let mut tampered = good.clone(); |
| 138 | tampered.intent_summary = "tampered".to_string(); |
| 139 | |
| 140 | let mut short_sig = good.clone(); |
| 141 | short_sig.signature.truncate(63); |
| 142 | |
| 143 | // Small-order author key with the (R = identity, S = 0) signature. The envelope check uses |
| 144 | // non-strict `verify` (unchanged by this issue); the cached path must give the same verdict. |
| 145 | let mut small_order = good.clone(); |
| 146 | small_order.author_did = encode_did_key_ed25519(&small_order_point()); |
| 147 | small_order.signature = { |
| 148 | let mut s = vec![0u8; 64]; |
| 149 | s[0] = 1; |
| 150 | s |
| 151 | }; |
| 152 | |
| 153 | let cases = [ |
| 154 | ("undecodable", undecodable, Some(RefusalCode::DidKeyInvalid)), |
| 155 | ("no z", no_z, Some(RefusalCode::DidKeyInvalid)), |
| 156 | ( |
| 157 | "wrong multicodec", |
| 158 | wrong_codec, |
| 159 | Some(RefusalCode::DidKeyInvalid), |
| 160 | ), |
| 161 | ("forged", forged, Some(RefusalCode::AuthSignatureInvalid)), |
| 162 | ( |
| 163 | "tampered", |
| 164 | tampered, |
| 165 | Some(RefusalCode::AuthSignatureInvalid), |
| 166 | ), |
| 167 | ( |
| 168 | "short signature", |
| 169 | short_sig, |
| 170 | Some(RefusalCode::AuthSignatureInvalid), |
| 171 | ), |
| 172 | ]; |
| 173 | for round in ["cold", "warm"] { |
| 174 | good.validate().expect("genuine envelope admitted"); |
| 175 | for (name, env, want) in &cases { |
| 176 | assert_eq!(code(env.validate()), *want, "{name} ({round})"); |
| 177 | assert_eq!( |
| 178 | code(uncached_signature_verdict(env)), |
| 179 | *want, |
| 180 | "{name} reference" |
| 181 | ); |
| 182 | } |
| 183 | assert_eq!( |
| 184 | code(small_order.validate().map(|_| ())), |
| 185 | code(uncached_signature_verdict(&small_order)), |
| 186 | "small-order key ({round}) agrees with the uncached check" |
| 187 | ); |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | #[test] |
| 192 | fn invalid_author_keys_are_refused_every_time_and_never_cached() { |
| 193 | let (len0, d0) = key_cache_stats(); |
| 194 | let calls = 4 * KEY_CACHE_CAPACITY as u64; |
| 195 | for n in 0..calls { |
| 196 | let mut env = signed(&key("author", 2), n); |
| 197 | env.author_did = encode_did_key_ed25519(&invalid_point(&format!("bad-{}", n % 8))); |
| 198 | assert_eq!(code(env.validate()), Some(RefusalCode::DidKeyInvalid)); |
| 199 | } |
| 200 | let (len1, d1) = key_cache_stats(); |
| 201 | assert_eq!(len1, len0, "invalid keys never enter the cache"); |
| 202 | assert_eq!(d1 - d0, calls, "every call with an invalid key decodes"); |
| 203 | } |
| 204 | |
| 205 | #[test] |
| 206 | fn hostile_author_churn_stays_at_the_cap() { |
| 207 | let churn = 10 * KEY_CACHE_CAPACITY as u64; |
| 208 | for n in 0..churn { |
| 209 | signed(&key("churn", n), n) |
| 210 | .validate() |
| 211 | .expect("valid envelope"); |
| 212 | assert!(key_cache_stats().0 <= KEY_CACHE_CAPACITY); |
| 213 | } |
| 214 | assert_eq!(key_cache_stats().0, KEY_CACHE_CAPACITY); |
| 215 | } |
| 216 | |
| 217 | /// Negative control: a warm cache holds the genuine author key, and still no envelope the |
| 218 | /// author did not sign is admitted; the cache returns the same key `from_bytes` does. |
| 219 | #[test] |
| 220 | fn warm_cache_admits_nothing_the_author_did_not_sign() { |
| 221 | let author = key("author", 3); |
| 222 | let good = signed(&author, 0); |
| 223 | good.validate().expect("warm the cache"); |
| 224 | for n in 1..16 { |
| 225 | let mut env = signed(&author, n); |
| 226 | env.signature = good.signature.clone(); |
| 227 | assert_eq!( |
| 228 | code(env.validate()), |
| 229 | Some(RefusalCode::AuthSignatureInvalid) |
| 230 | ); |
| 231 | } |
| 232 | let bytes = author.verifying_key().to_bytes(); |
| 233 | assert_eq!( |
| 234 | cached_verifying_key(&bytes).unwrap(), |
| 235 | VerifyingKey::from_bytes(&bytes).unwrap() |
| 236 | ); |
| 237 | } |