interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

GitHub aien-dev/synapse#97 (code only)

closed derived 36b5b2c30cd095e2 #97

Imported from GitHub aien-dev/synapse#97 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base 3d78efe83d5d08b67848e4b32a83112a95dd2a9d · Head 872134c8fe409d7885443f7c70c527eb6c82fcd7

Apply it

git checkout -b patch-36b5b2c30cd095e2 3d78efe83d5d08b67848e4b32a83112a95dd2a9d
curl -fsSL https://interplane.io/drakestapleton/synapse/patches/36b5b2c30cd095e2.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/synapse
97
872134c8fe409d7885443f7c70c527eb6c82fcd7
{"kind":"github-import","owner":"aien-dev","repo":"synapse","number":97,"url":"https://github.com/aien-dev/synapse/pull/97","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:20Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/.crumb b/.crumb
index 495a32d..3890dd7 100644
--- a/.crumb
+++ b/.crumb
@@ -45,14 +45,14 @@
     "generated": {
       "children": [],
       "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "compiled_at": "2026-10-16T09:12:08Z",
+      "compiled_at": "2026-10-17T02:43:37Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:279410a8da95ac0a5c9e9cf32a56684e2ca85469ad52267efcce5e6dbbbef821",
-      "evidence_files": 241,
-      "evidence_root": "sha256:f103bd6c7728e5a399cede51d9c64e4d42afc97e0d48dd424536b6cc72e48314",
-      "files": 411,
-      "generated_at_commit": "5d287e0e4ab4439f79711243518c0a83cce56eff",
-      "source_tree": "sha256:07947598e29d8d8fca9b546541ebe7e575c954cf18901eeb74304d2a9f594e2b"
+      "digest": "sha256:f388b9db2a299499c25834f57315166cc5195a94daa580703792ff813bef6b19",
+      "evidence_files": 244,
+      "evidence_root": "sha256:f315c6bd537c64571a2e69e3f7a39ec2ab2a84af8d6f6a3ce7a34085b9e92629",
+      "files": 421,
+      "generated_at_commit": "3d78efe83d5d08b67848e4b32a83112a95dd2a9d",
+      "source_tree": "sha256:20124d71ca4853a366b02eec3509a367596040abb7de76ae3e15f45c87dbffa0"
     },
     "synapse": {
       "component_paths": {
diff --git a/crates/synapse-auth/src/chain.rs b/crates/synapse-auth/src/chain.rs
index 920ed8e..b319c86 100644
--- a/crates/synapse-auth/src/chain.rs
+++ b/crates/synapse-auth/src/chain.rs
@@ -11,7 +11,7 @@
 //! encoding of `docs/F1_CAPABILITY_CHAINS.md` (ADR 0003 principle P5); there is no serde form.
 
 use crate::{AuditOutcome, BoundaryKind, Capability, PolicyEnforcer};
-use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
+use ed25519_dalek::{Signature, Signer, SigningKey};
 use sha2::{Digest, Sha256};
 use std::collections::BTreeMap;
 use synapse_core::{
@@ -513,7 +513,7 @@ impl CapabilityLink {
     /// Verify the issuer's Ed25519 signature over `signable_bytes()`.
     pub fn verify_signature(&self) -> SynapseResult<()> {
         let invalid = |msg: &str| SynapseError::new(RefusalCode::AuthGrantSignatureInvalid, msg);
-        let key = VerifyingKey::from_bytes(&self.issuer_key)
+        let key = crate::key_cache::verifying_key(&self.issuer_key)
             .map_err(|_| invalid("link issuer key is not a valid Ed25519 key"))?;
         key.verify_strict(
             &self.signable_bytes(),
@@ -1010,7 +1010,7 @@ impl PolicyEnforcer {
                 ),
             ));
         }
-        let agent_key = VerifyingKey::from_bytes(&req.agent_key).map_err(|_| {
+        let agent_key = crate::key_cache::verifying_key(&req.agent_key).map_err(|_| {
             SynapseError::new(RefusalCode::DidKeyInvalid, "invalid agent Ed25519 key")
         })?;
         agent_key
diff --git a/crates/synapse-auth/src/key_cache.rs b/crates/synapse-auth/src/key_cache.rs
new file mode 100644
index 0000000..51c4c27
--- /dev/null
+++ b/crates/synapse-auth/src/key_cache.rs
@@ -0,0 +1,73 @@
+//! Bounded per-thread cache of decoded Ed25519 verifying keys (issue #93).
+//!
+//! `VerifyingKey::from_bytes` decompresses the curve point on every call. One accepted
+//! submit verifies the grant (authority key) and the request (agent key), and both keys
+//! repeat across requests, so the decoded key is cached here, keyed by the exact 32 key
+//! bytes. Only the decode is cached: every signature is still verified in full, with the
+//! same `verify` or `verify_strict` call as before, by the existing `ed25519-dalek` crate.
+//!
+//! Bounds and refusals:
+//! - Only keys that decode are cached. Bytes that do not decode are refused on every call,
+//!   exactly as before (the caller maps the error to its refusal code), and never enter
+//!   the cache, so churn of invalid keys cannot grow it.
+//! - At most [`KEY_CACHE_CAPACITY`] keys per thread; the oldest insertion is evicted first.
+//!   Churn of valid keys (each new key one decode) therefore keeps the cache at the cap.
+//! - Per thread: no lock on the verify path and nothing shared between threads.
+
+use ed25519_dalek::{SignatureError, VerifyingKey};
+use std::cell::RefCell;
+use std::collections::{HashMap, VecDeque};
+
+/// Most decoded keys one thread keeps.
+pub const KEY_CACHE_CAPACITY: usize = 64;
+
+#[derive(Default)]
+struct KeyCache {
+    keys: HashMap<[u8; 32], VerifyingKey>,
+    /// Insertion order, oldest first; always the same key set as `keys`.
+    order: VecDeque<[u8; 32]>,
+    /// Point decodes performed (cache misses that reached `VerifyingKey::from_bytes`).
+    decodes: u64,
+}
+
+thread_local! {
+    static CACHE: RefCell<KeyCache> = RefCell::new(KeyCache::default());
+}
+
+/// The decoded verifying key for `bytes`: from this thread's cache, or decoded with
+/// `VerifyingKey::from_bytes` (and cached when it decodes). Same result and same error as
+/// calling `VerifyingKey::from_bytes(bytes)` directly.
+pub(crate) fn verifying_key(bytes: &[u8; 32]) -> Result<VerifyingKey, SignatureError> {
+    CACHE
+        .try_with(|cell| {
+            let mut cache = cell.borrow_mut();
+            if let Some(key) = cache.keys.get(bytes) {
+                return Ok(*key);
+            }
+            cache.decodes += 1;
+            let key = VerifyingKey::from_bytes(bytes)?;
+            if cache.keys.len() >= KEY_CACHE_CAPACITY {
+                if let Some(oldest) = cache.order.pop_front() {
+                    cache.keys.remove(&oldest);
+                }
+            }
+            cache.keys.insert(*bytes, key);
+            cache.order.push_back(*bytes);
+            Ok(key)
+        })
+        // Thread-local storage already torn down (thread exit): decode without caching.
+        .unwrap_or_else(|_| VerifyingKey::from_bytes(bytes))
+}
+
+/// `(cached keys, point decodes)` for this thread.
+#[cfg(test)]
+pub(crate) fn stats() -> (usize, u64) {
+    CACHE.with(|cell| {
+        let cache = cell.borrow();
+        debug_assert_eq!(cache.keys.len(), cache.order.len());
+        (cache.keys.len(), cache.decodes)
+    })
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/synapse-auth/src/key_cache/tests.rs b/crates/synapse-auth/src/key_cache/tests.rs
new file mode 100644
index 0000000..f669299
--- /dev/null
+++ b/crates/synapse-auth/src/key_cache/tests.rs
@@ -0,0 +1,332 @@
+//! Issue #93: the decoded-key cache decodes each key once, stays bounded under hostile key
+//! churn, and leaves every refusal code for malformed or invalid keys unchanged.
+//!
+//! Keys, nonces and grant ids are derived from labels and counters (SHA-256), never written
+//! as literals. Each `#[test]` runs on its own thread, so it starts with an empty cache;
+//! the assertions still use before/after deltas.
+
+use super::{stats, verifying_key, KEY_CACHE_CAPACITY};
+use crate::{
+    AgentCapabilityGrant, AuthenticatedRequest, BoundaryKind, Capability, CapabilityChain,
+    CapabilityLink, ChainQuotas, ChainedRequest, ChangeScope, LinkCaveats, OperationSet, PathScope,
+    PolicyEnforcer, ReferenceKind, ReferenceScope, RequestScope, ROOT_PARENT,
+};
+use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
+use sha2::{Digest, Sha256};
+use synapse_core::{encode_did_key_ed25519, RefusalCode, RepoId, WalSeq};
+
+const NOW: u64 = 1_000_000;
+
+fn derived(label: &str, n: u64) -> [u8; 32] {
+    let mut h = Sha256::new();
+    h.update(b"SYNAPSE_AUTH_KEY_CACHE_TEST_V1\0");
+    h.update(label.as_bytes());
+    h.update(n.to_le_bytes());
+    h.finalize().into()
+}
+
+fn key(label: &str, n: u64) -> SigningKey {
+    SigningKey::from_bytes(&derived(label, n))
+}
+
+fn did(k: &SigningKey) -> String {
+    encode_did_key_ed25519(&k.verifying_key().to_bytes())
+}
+
+/// 32 derived bytes that are not the encoding of a curve point (`from_bytes` refuses them).
+fn invalid_point(label: &str) -> [u8; 32] {
+    (0u64..)
+        .map(|n| derived(label, n))
+        .find(|b| VerifyingKey::from_bytes(b).is_err())
+        .expect("about half of all encodings are not points")
+}
+
+/// A small-order point encoding (decodes, but `verify_strict` refuses it as weak):
+/// y = n for the first small n whose point is weak.
+fn weak_point() -> [u8; 32] {
+    (0u8..=u8::MAX)
+        .map(|n| std::array::from_fn(|i| if i == 0 { n } else { 0 }))
+        .find(|b: &[u8; 32]| VerifyingKey::from_bytes(b).is_ok_and(|k| k.is_weak()))
+        .expect("y = 0 and y = 1 are small-order points")
+}
+
+fn repo() -> RepoId {
+    RepoId::new("github.com/aien-dev/synapse-key-cache-test").unwrap()
+}
+
+fn caveats() -> LinkCaveats {
+    LinkCaveats {
+        operations: OperationSet::from_capabilities(&[Capability::Read, Capability::Propose]),
+        paths: PathScope::whole_repository(),
+        references: ReferenceScope::from_kinds(&[ReferenceKind::OwnDrafts]),
+        changes: ChangeScope::any(),
+        quotas: ChainQuotas {
+            max_ops_per_window: 1_000,
+            window_duration_ms: 60_000,
+            storage_bytes: 1 << 30,
+            footprint_paths: 1 << 20,
+            max_bytes_per_op: 1 << 20,
+        },
+        issued_at_ms: NOW - 1,
+        expires_at_ms: NOW + 60_000,
+    }
+}
+
+fn grant(authority: &SigningKey, agent_did: String, n: u64) -> AgentCapabilityGrant {
+    AgentCapabilityGrant::issue(
+        authority,
+        derived("grant", n),
+        repo(),
+        agent_did,
+        vec![Capability::Read, Capability::Propose],
+        1 << 20,
+        1 << 20,
+        60_000,
+        NOW - 1,
+        NOW + 60_000,
+    )
+}
+
+fn request(
+    agent: &SigningKey,
+    grant: AgentCapabilityGrant,
+    n: u64,
+) -> AuthenticatedRequest<Vec<u8>> {
+    AuthenticatedRequest::sign_new(
+        agent,
+        grant,
+        repo(),
+        Capability::Propose,
+        derived("nonce", n),
+        NOW,
+        0,
+        derived("payload", n).to_vec(),
+    )
+    .unwrap()
+}
+
+fn authorize(
+    enf: &mut PolicyEnforcer,
+    req: &AuthenticatedRequest<Vec<u8>>,
+) -> Result<(), RefusalCode> {
+    enf.authorize(
+        BoundaryKind::Api,
+        "submit",
+        &repo(),
+        Capability::Propose,
+        req,
+        NOW,
+    )
+    .map_err(|e| e.code)
+}
+
+/// The authority and agent keys are decoded once each, however many requests they sign.
+#[test]
+fn each_key_decodes_once_across_repeated_authorizations() {
+    let authority = key("authority", 1);
+    let agent = key("agent", 1);
+    let mut enf = PolicyEnforcer::new();
+    enf.register_repo_authority(repo(), did(&authority));
+    let g = grant(&authority, did(&agent), 1);
+    let (_, before) = stats();
+    for n in 0..32 {
+        assert_eq!(authorize(&mut enf, &request(&agent, g.clone(), n)), Ok(()));
+    }
+    let (len, after) = stats();
+    assert_eq!(
+        after - before,
+        2,
+        "authority and agent key decoded once each"
+    );
+    assert!(len >= 2);
+}
+
+/// Hostile churn of valid keys: every new key costs one decode and the cache never holds
+/// more than the cap; the oldest keys are the ones evicted.
+#[test]
+fn hostile_valid_key_churn_stays_at_the_cap() {
+    let churn = 10 * KEY_CACHE_CAPACITY as u64;
+    let (_, before) = stats();
+    for n in 0..churn {
+        let bytes = key("churn", n).verifying_key().to_bytes();
+        assert_eq!(
+            verifying_key(&bytes).unwrap(),
+            VerifyingKey::from_bytes(&bytes).unwrap()
+        );
+        assert!(
+            stats().0 <= KEY_CACHE_CAPACITY,
+            "cache above the cap at key {n}"
+        );
+    }
+    let (len, after) = stats();
+    assert_eq!(len, KEY_CACHE_CAPACITY);
+    assert_eq!(after - before, churn, "every new key is one decode");
+
+    // Newest key: a hit. Oldest key: evicted, decoded again.
+    verifying_key(&key("churn", churn - 1).verifying_key().to_bytes()).unwrap();
+    assert_eq!(stats().1, after);
+    verifying_key(&key("churn", 0).verifying_key().to_bytes()).unwrap();
+    assert_eq!(stats().1, after + 1);
+    assert_eq!(stats().0, KEY_CACHE_CAPACITY);
+}
+
+/// Bytes that are not a point are refused on every call and never enter the cache, so
+/// churn of invalid keys cannot grow it either.
+#[test]
+fn invalid_key_bytes_are_refused_every_time_and_never_cached() {
+    let (len0, d0) = stats();
+    for n in 0..(4 * KEY_CACHE_CAPACITY as u64) {
+        let bad = invalid_point(&format!("invalid-churn-{n}"));
+        assert!(verifying_key(&bad).is_err());
+        assert!(verifying_key(&bad).is_err(), "second call refused too");
+    }
+    let (len1, d1) = stats();
+    assert_eq!(len1, len0, "invalid keys are never cached");
+    assert_eq!(d1 - d0, 8 * KEY_CACHE_CAPACITY as u64, "every call decodes");
+}
+
+/// Refusal codes for invalid authority and agent keys on the grant path, unchanged, both
+/// before and after the valid keys are cached.
+#[test]
+fn grant_path_refusal_codes_for_bad_keys_are_unchanged_cold_and_warm() {
+    let authority = key("authority", 2);
+    let agent = key("agent", 2);
+    let mut enf = PolicyEnforcer::new();
+    enf.register_repo_authority(repo(), did(&authority));
+
+    // Invalid authority key: a trusted issuer DID whose 32 bytes are not a point.
+    let bad_issuer_did = encode_did_key_ed25519(&invalid_point("issuer"));
+    enf.register_repo_authority(repo(), bad_issuer_did.clone());
+    let mut bad_issuer = grant(&authority, did(&agent), 2);
+    bad_issuer.issuer_did = bad_issuer_did;
+
+    // Invalid agent key in a validly signed grant.
+    let bad_agent_did = encode_did_key_ed25519(&invalid_point("agent"));
+    let bad_agent = grant(&authority, bad_agent_did, 3);
+
+    // Malformed DIDs: not multibase z, and the wrong multicodec prefix.
+    let no_z = grant(
+        &authority,
+        did(&agent).replacen("did:key:z", "did:key:m", 1),
+        4,
+    );
+    let wrong_codec = grant(
+        &authority,
+        did(&agent).replacen("did:key:z6Mk", "did:key:z6Mj", 1),
+        5,
+    );
+
+    // Valid keys, wrong signatures.
+    let mut forged_grant = grant(&authority, did(&agent), 6);
+    forged_grant.signature = key("forger", 0)
+        .sign(&forged_grant.canonical_signable_bytes())
+        .to_bytes()
+        .to_vec();
+    let good = grant(&authority, did(&agent), 7);
+
+    let cases = |enf: &mut PolicyEnforcer, round: u64| {
+        let n = 100 * round;
+        assert_eq!(
+            authorize(enf, &request(&agent, bad_issuer.clone(), n)),
+            Err(RefusalCode::DidKeyInvalid)
+        );
+        assert_eq!(
+            authorize(enf, &request(&agent, bad_agent.clone(), n + 1)),
+            Err(RefusalCode::DidKeyInvalid)
+        );
+        assert_eq!(
+            authorize(enf, &request(&agent, no_z.clone(), n + 2)),
+            Err(RefusalCode::DidKeyInvalid)
+        );
+        assert_eq!(
+            authorize(enf, &request(&agent, wrong_codec.clone(), n + 3)),
+            Err(RefusalCode::DidKeyInvalid)
+        );
+        assert_eq!(
+            authorize(enf, &request(&agent, forged_grant.clone(), n + 4)),
+            Err(RefusalCode::AuthGrantSignatureInvalid)
+        );
+        assert_eq!(
+            authorize(enf, &request(&key("impostor", round), good.clone(), n + 5)),
+            Err(RefusalCode::AuthSignatureInvalid)
+        );
+        assert_eq!(
+            authorize(enf, &request(&agent, good.clone(), n + 6)),
+            Ok(())
+        );
+    };
+    cases(&mut enf, 1); // cold: nothing cached yet
+    cases(&mut enf, 2); // warm: authority and agent keys cached
+}
+
+/// Refusal codes on the capability-chain path (`verify_strict`), unchanged cold and warm:
+/// a link issuer key that is not a point and a small-order issuer key are both
+/// `AuthGrantSignatureInvalid`; an agent key that is not a point is `DidKeyInvalid`.
+#[test]
+fn chain_path_refusal_codes_for_bad_keys_are_unchanged_cold_and_warm() {
+    let authority = key("chain-authority", 1);
+    let link = CapabilityLink::issue(
+        &authority,
+        ROOT_PARENT,
+        derived("link-nonce", 1),
+        repo(),
+        key("chain-agent", 1).verifying_key().to_bytes(),
+        caveats(),
+    );
+    let mut not_a_point = link.clone();
+    not_a_point.issuer_key = invalid_point("link-issuer");
+    let mut weak = link.clone();
+    weak.issuer_key = weak_point();
+    for _round in 0..2 {
+        assert_eq!(link.verify_signature(), Ok(()));
+        assert_eq!(
+            not_a_point.verify_signature().map_err(|e| e.code),
+            Err(RefusalCode::AuthGrantSignatureInvalid)
+        );
+        assert_eq!(
+            weak.verify_signature().map_err(|e| e.code),
+            Err(RefusalCode::AuthGrantSignatureInvalid)
+        );
+    }
+
+    // Agent key that is not a point: a granted root link whose audience is those bytes.
+    let bad_agent = invalid_point("chain-agent-bad");
+    let mut enf = PolicyEnforcer::new();
+    enf.register_repo_authority(repo(), did(&authority));
+    let root = CapabilityLink::issue(
+        &authority,
+        ROOT_PARENT,
+        derived("link-nonce", 2),
+        repo(),
+        bad_agent,
+        caveats(),
+    );
+    let chain = CapabilityChain::new(vec![root]);
+    enf.grant_link(&chain, WalSeq(1), NOW).unwrap();
+    for round in 0..2u64 {
+        let mut req = ChainedRequest::sign_new(
+            &key("chain-signer", round),
+            chain.clone(),
+            repo(),
+            Capability::Propose,
+            RequestScope::default(),
+            derived("chain-nonce", round),
+            NOW,
+            derived("chain-payload", round).to_vec(),
+        );
+        req.agent_key = bad_agent;
+        assert_eq!(
+            enf.authorize_chain(
+                BoundaryKind::Api,
+                "submit",
+                &repo(),
+                Capability::Propose,
+                &req,
+                WalSeq(2 + round),
+                NOW,
+            )
+            .map_err(|e| e.code),
+            Err(RefusalCode::DidKeyInvalid)
+        );
+    }
+}
diff --git a/crates/synapse-auth/src/lib.rs b/crates/synapse-auth/src/lib.rs
index 8fc4cbc..5819c6e 100644
--- a/crates/synapse-auth/src/lib.rs
+++ b/crates/synapse-auth/src/lib.rs
@@ -1,7 +1,7 @@
 //! Capability-scoped Ed25519 authentication, replay protection, quota enforcement,
 //! and tamper-evident hash-chained security audit logging (`synapse-auth`, Gate 2a).
 
-use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
+use ed25519_dalek::{Signature, Signer, SigningKey, Verifier};
 use serde::{Deserialize, Serialize};
 use sha2::{Digest, Sha256};
 use std::collections::{BTreeMap, BTreeSet};
@@ -11,7 +11,9 @@ use synapse_core::{
 };
 
 mod chain;
+mod key_cache;
 pub use chain::*;
+pub use key_cache::KEY_CACHE_CAPACITY;
 
 /// Current capability grant schema version.
 pub const CAPABILITY_GRANT_VERSION: u16 = 1;
@@ -153,7 +155,7 @@ impl AgentCapabilityGrant {
             ));
         }
         let pubkey_bytes = decode_did_key_ed25519(&self.issuer_did)?;
-        let verifying_key = VerifyingKey::from_bytes(&pubkey_bytes).map_err(|_| {
+        let verifying_key = key_cache::verifying_key(&pubkey_bytes).map_err(|_| {
             SynapseError::new(
                 RefusalCode::DidKeyInvalid,
                 "invalid authority Ed25519 public key",
@@ -538,7 +540,7 @@ impl PolicyEnforcer {
         }
 
         let agent_pubkey_bytes = decode_did_key_ed25519(&req.grant.agent_did)?;
-        let agent_verifying_key = VerifyingKey::from_bytes(&agent_pubkey_bytes).map_err(|_| {
+        let agent_verifying_key = key_cache::verifying_key(&agent_pubkey_bytes).map_err(|_| {
             SynapseError::new(RefusalCode::DidKeyInvalid, "invalid agent Ed25519 key")
         })?;
         let sig_arr: [u8; 64] = req.agent_signature.as_slice().try_into().map_err(|_| {