Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-auth/src/key_cache/tests.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-auth / src / key_cache / tests.rs` 332 lines ยท 11377 bytes Raw Blame History 1 //! Issue #93: the decoded-key cache decodes each key once, stays bounded under hostile key 2 //! churn, and leaves every refusal code for malformed or invalid keys unchanged. 3 //! 4 //! Keys, nonces and grant ids are derived from labels and counters (SHA-256), never written 5 //! as literals. Each `#[test]` runs on its own thread, so it starts with an empty cache; 6 //! the assertions still use before/after deltas. 7 8 use super::{stats, verifying_key, KEY_CACHE_CAPACITY}; 9 use crate::{ 10 AgentCapabilityGrant, AuthenticatedRequest, BoundaryKind, Capability, CapabilityChain, 11 CapabilityLink, ChainQuotas, ChainedRequest, ChangeScope, LinkCaveats, OperationSet, PathScope, 12 PolicyEnforcer, ReferenceKind, ReferenceScope, RequestScope, ROOT_PARENT, 13 }; 14 use `ed25519`_dalek::{Signer, SigningKey, VerifyingKey}; 15 use sha2::{Digest, Sha256}; 16 use synapse_core::{encode_did_key_`ed25519`, RefusalCode, RepoId, WalSeq}; 17 18 const NOW: u64 = 1_000_000; 19 20 fn derived(label: &str, n: u64) -> [u8; 32] { 21 let mut h = Sha256::new(); 22 h.update(b"SYNAPSE_AUTH_KEY_CACHE_TEST_V1\0"); 23 h.update(label.as_bytes()); 24 h.update(n.to_le_bytes()); 25 h.finalize().into() 26 } 27 28 fn key(label: &str, n: u64) -> SigningKey { 29 SigningKey::from_bytes(&derived(label, n)) 30 } 31 32 fn did(k: &SigningKey) -> String { 33 encode_did_key_`ed25519`(&k.verifying_key().to_bytes()) 34 } 35 36 /// 32 derived bytes that are not the encoding of a curve point (`from_bytes` refuses them). 37 fn invalid_point(label: &str) -> [u8; 32] { 38 (0u64..) 39 .map(|n| derived(label, n)) 40 .find(|b| VerifyingKey::from_bytes(b).is_err()) 41 .expect("about half of all encodings are not points") 42 } 43 44 /// A small-order point encoding (decodes, but `verify_strict` refuses it as weak): 45 /// y = n for the first small n whose point is weak. 46 fn weak_point() -> [u8; 32] { 47 (0u8..=u8::MAX) 48 .map(|n| std::array::from_fn(|i| if i == 0 { n } else { 0 })) 49 .find(|b: &[u8; 32]| VerifyingKey::from_bytes(b).is_ok_and(|k| k.is_weak())) 50 .expect("y = 0 and y = 1 are small-order points") 51 } 52 53 fn repo() -> RepoId { 54 RepoId::new("github.com/aien-dev/synapse-key-cache-test").unwrap() 55 } 56 57 fn caveats() -> LinkCaveats { 58 LinkCaveats { 59 operations: OperationSet::from_capabilities(&[Capability::Read, Capability::Propose]), 60 paths: PathScope::whole_repository(), 61 references: ReferenceScope::from_kinds(&[ReferenceKind::OwnDrafts]), 62 changes: ChangeScope::any(), 63 quotas: ChainQuotas { 64 max_ops_per_window: 1_000, 65 window_duration_ms: 60_000, 66 storage_bytes: 1 << 30, 67 footprint_paths: 1 << 20, 68 max_bytes_per_op: 1 << 20, 69 }, 70 issued_at_ms: NOW - 1, 71 expires_at_ms: NOW + 60_000, 72 } 73 } 74 75 fn grant(authority: &SigningKey, agent_did: String, n: u64) -> AgentCapabilityGrant { 76 AgentCapabilityGrant::issue( 77 authority, 78 derived("grant", n), 79 repo(), 80 agent_did, 81 vec![Capability::Read, Capability::Propose], 82 1 << 20, 83 1 << 20, 84 60_000, 85 NOW - 1, 86 NOW + 60_000, 87 ) 88 } 89 90 fn request( 91 agent: &SigningKey, 92 grant: AgentCapabilityGrant, 93 n: u64, 94 ) -> AuthenticatedRequest> { 95 AuthenticatedRequest::sign_new( 96 agent, 97 grant, 98 repo(), 99 Capability::Propose, 100 derived("nonce", n), 101 NOW, 102 0, 103 derived("payload", n).to_vec(), 104 ) 105 .unwrap() 106 } 107 108 fn authorize( 109 enf: &mut PolicyEnforcer, 110 req: &AuthenticatedRequest>, 111 ) -> Result<(), RefusalCode> { 112 enf.authorize( 113 BoundaryKind::Api, 114 "submit", 115 &repo(), 116 Capability::Propose, 117 req, 118 NOW, 119 ) 120 .map_err(|e| e.code) 121 } 122 123 /// The authority and agent keys are decoded once each, however many requests they sign. 124 #[test] 125 fn each_key_decodes_once_across_repeated_authorizations() { 126 let authority = key("authority", 1); 127 let agent = key("agent", 1); 128 let mut enf = PolicyEnforcer::new(); 129 enf.register_repo_authority(repo(), did(&authority)); 130 let g = grant(&authority, did(&agent), 1); 131 let (_, before) = stats(); 132 for n in 0..32 { 133 assert_eq!(authorize(&mut enf, &request(&agent, g.clone(), n)), Ok(())); 134 } 135 let (len, after) = stats(); 136 assert_eq!( 137 after - before, 138 2, 139 "authority and agent key decoded once each" 140 ); 141 assert!(len >= 2); 142 } 143 144 /// Hostile churn of valid keys: every new key costs one decode and the cache never holds 145 /// more than the cap; the oldest keys are the ones evicted. 146 #[test] 147 fn hostile_valid_key_churn_stays_at_the_cap() { 148 let churn = 10 * KEY_CACHE_CAPACITY as u64; 149 let (_, before) = stats(); 150 for n in 0..churn { 151 let bytes = key("churn", n).verifying_key().to_bytes(); 152 assert_eq!( 153 verifying_key(&bytes).unwrap(), 154 VerifyingKey::from_bytes(&bytes).unwrap() 155 ); 156 assert!( 157 stats().0 <= KEY_CACHE_CAPACITY, 158 "cache above the cap at key {n}" 159 ); 160 } 161 let (len, after) = stats(); 162 assert_eq!(len, KEY_CACHE_CAPACITY); 163 assert_eq!(after - before, churn, "every new key is one decode"); 164 165 // Newest key: a hit. Oldest key: evicted, decoded again. 166 verifying_key(&key("churn", churn - 1).verifying_key().to_bytes()).unwrap(); 167 assert_eq!(stats().1, after); 168 verifying_key(&key("churn", 0).verifying_key().to_bytes()).unwrap(); 169 assert_eq!(stats().1, after + 1); 170 assert_eq!(stats().0, KEY_CACHE_CAPACITY); 171 } 172 173 /// Bytes that are not a point are refused on every call and never enter the cache, so 174 /// churn of invalid keys cannot grow it either. 175 #[test] 176 fn invalid_key_bytes_are_refused_every_time_and_never_cached() { 177 let (len0, d0) = stats(); 178 for n in 0..(4 * KEY_CACHE_CAPACITY as u64) { 179 let bad = invalid_point(&format!("invalid-churn-{n}")); 180 assert!(verifying_key(&bad).is_err()); 181 assert!(verifying_key(&bad).is_err(), "second call refused too"); 182 } 183 let (len1, d1) = stats(); 184 assert_eq!(len1, len0, "invalid keys are never cached"); 185 assert_eq!(d1 - d0, 8 * KEY_CACHE_CAPACITY as u64, "every call decodes"); 186 } 187 188 /// Refusal codes for invalid authority and agent keys on the grant path, unchanged, both 189 /// before and after the valid keys are cached. 190 #[test] 191 fn grant_path_refusal_codes_for_bad_keys_are_unchanged_cold_and_warm() { 192 let authority = key("authority", 2); 193 let agent = key("agent", 2); 194 let mut enf = PolicyEnforcer::new(); 195 enf.register_repo_authority(repo(), did(&authority)); 196 197 // Invalid authority key: a trusted issuer DID whose 32 bytes are not a point. 198 let bad_issuer_did = encode_did_key_`ed25519`(&invalid_point("issuer")); 199 enf.register_repo_authority(repo(), bad_issuer_did.clone()); 200 let mut bad_issuer = grant(&authority, did(&agent), 2); 201 bad_issuer.issuer_did = bad_issuer_did; 202 203 // Invalid agent key in a validly signed grant. 204 let bad_agent_did = encode_did_key_`ed25519`(&invalid_point("agent")); 205 let bad_agent = grant(&authority, bad_agent_did, 3); 206 207 // Malformed DIDs: not multibase z, and the wrong multicodec prefix. 208 let no_z = grant( 209 &authority, 210 did(&agent).replacen("did:key:z", "did:key:m", 1), 211 4, 212 ); 213 let wrong_codec = grant( 214 &authority, 215 did(&agent).replacen("did:key:z6Mk", "did:key:z6Mj", 1), 216 5, 217 ); 218 219 // Valid keys, wrong signatures. 220 let mut forged_grant = grant(&authority, did(&agent), 6); 221 forged_grant.signature = key("forger", 0) 222 .sign(&forged_grant.canonical_signable_bytes()) 223 .to_bytes() 224 .to_vec(); 225 let good = grant(&authority, did(&agent), 7); 226 227 let cases = |enf: &mut PolicyEnforcer, round: u64| { 228 let n = 100 * round; 229 assert_eq!( 230 authorize(enf, &request(&agent, bad_issuer.clone(), n)), 231 Err(RefusalCode::DidKeyInvalid) 232 ); 233 assert_eq!( 234 authorize(enf, &request(&agent, bad_agent.clone(), n + 1)), 235 Err(RefusalCode::DidKeyInvalid) 236 ); 237 assert_eq!( 238 authorize(enf, &request(&agent, no_z.clone(), n + 2)), 239 Err(RefusalCode::DidKeyInvalid) 240 ); 241 assert_eq!( 242 authorize(enf, &request(&agent, wrong_codec.clone(), n + 3)), 243 Err(RefusalCode::DidKeyInvalid) 244 ); 245 assert_eq!( 246 authorize(enf, &request(&agent, forged_grant.clone(), n + 4)), 247 Err(RefusalCode::AuthGrantSignatureInvalid) 248 ); 249 assert_eq!( 250 authorize(enf, &request(&key("impostor", round), good.clone(), n + 5)), 251 Err(RefusalCode::AuthSignatureInvalid) 252 ); 253 assert_eq!( 254 authorize(enf, &request(&agent, good.clone(), n + 6)), 255 Ok(()) 256 ); 257 }; 258 cases(&mut enf, 1); // cold: nothing cached yet 259 cases(&mut enf, 2); // warm: authority and agent keys cached 260 } 261 262 /// Refusal codes on the capability-chain path (`verify_strict`), unchanged cold and warm: 263 /// a link issuer key that is not a point and a small-order issuer key are both 264 /// `AuthGrantSignatureInvalid`; an agent key that is not a point is `DidKeyInvalid`. 265 #[test] 266 fn chain_path_refusal_codes_for_bad_keys_are_unchanged_cold_and_warm() { 267 let authority = key("chain-authority", 1); 268 let link = CapabilityLink::issue( 269 &authority, 270 ROOT_PARENT, 271 derived("link-nonce", 1), 272 repo(), 273 key("chain-agent", 1).verifying_key().to_bytes(), 274 caveats(), 275 ); 276 let mut not_a_point = link.clone(); 277 not_a_point.issuer_key = invalid_point("link-issuer"); 278 let mut weak = link.clone(); 279 weak.issuer_key = weak_point(); 280 for _round in 0..2 { 281 assert_eq!(link.verify_signature(), Ok(())); 282 assert_eq!( 283 not_a_point.verify_signature().map_err(|e| e.code), 284 Err(RefusalCode::AuthGrantSignatureInvalid) 285 ); 286 assert_eq!( 287 weak.verify_signature().map_err(|e| e.code), 288 Err(RefusalCode::AuthGrantSignatureInvalid) 289 ); 290 } 291 292 // Agent key that is not a point: a granted root link whose audience is those bytes. 293 let bad_agent = invalid_point("chain-agent-bad"); 294 let mut enf = PolicyEnforcer::new(); 295 enf.register_repo_authority(repo(), did(&authority)); 296 let root = CapabilityLink::issue( 297 &authority, 298 ROOT_PARENT, 299 derived("link-nonce", 2), 300 repo(), 301 bad_agent, 302 caveats(), 303 ); 304 let chain = CapabilityChain::new(vec![root]); 305 enf.grant_link(&chain, WalSeq(1), NOW).unwrap(); 306 for round in 0..2u64 { 307 let mut req = ChainedRequest::sign_new( 308 &key("chain-signer", round), 309 chain.clone(), 310 repo(), 311 Capability::Propose, 312 RequestScope::default(), 313 derived("chain-nonce", round), 314 NOW, 315 derived("chain-payload", round).to_vec(), 316 ); 317 req.agent_key = bad_agent; 318 assert_eq!( 319 enf.authorize_chain( 320 BoundaryKind::Api, 321 "submit", 322 &repo(), 323 Capability::Propose, 324 &req, 325 WalSeq(2 + round), 326 NOW, 327 ) 328 .map_err(|e| e.code), 329 Err(RefusalCode::DidKeyInvalid) 330 ); 331 } 332 }