Skip to main content

hyprstream_rpc/
event_subject.rs

1//! Canonical at-record subject + keyed group-scoped routing leaf (EV3, epic #600).
2//!
3//! Replaces the unkeyed 64-bit `oid_hash`/`publication_broadcast_path` (in
4//! [`crate::moq_event`]) with a construction that is:
5//! 1. **Canonical** — a record addressed three ways (handle vs DID, NSID case,
6//!    trailing fragment) hashes to exactly one value.
7//! 2. **Keyed** — the routing leaf is a PRF of `(K_group, subject, epoch)`, so
8//!    knowing the at-uri is NOT enough to derive the topic (confidentiality of
9//!    the subject against the relay). `K_group` is the PRF key.
10//! 3. **Epoch-rotated** — rotating the group key (EV2's `GroupKeyRegistry`)
11//!    rotates every leaf, giving cross-time unlinkability.
12//!
13//! The leaf is a MoQ-path-safe (hex) segment; the semantic topic name moves
14//! UNDER the payload AEAD (see [`crate::crypto::event_crypto`]), with the AAD
15//! binding the keyed leaf + epoch so cross-topic/cross-epoch ciphertext replay
16//! is rejected.
17//!
18//! Lexicon: events address records by their atproto collection NSID. The formal
19//! `ai.hyprstream.event.*` lexicon is a separate follow-up; this module is
20//! NSID-agnostic (takes the NSID as a validated string).
21
22use crate::crypto::keyed_mac;
23
24/// Separator-free canonical encoding prefix — every field is length-prefixed so
25/// two distinct subjects cannot collide on concatenation (the `build_*_aad`
26/// discipline used elsewhere in the crate).
27const SUBJECT_DOMAIN: &str = "hyprstream event-subject v1";
28
29/// A canonical at-record subject: the publishing/owning DID, the collection
30/// NSID, and the record key (rkey).
31///
32/// All three are normalized on construction:
33/// - `did` must already be a DID (`did:` prefix); handle→DID resolution is the
34///   caller's job (see [`resolve_handle_to_did`], a stub until the live
35///   `getRecord` path lands).
36/// - `nsid` is lowercased (NSIDs are ASCII reverse-DNS, case-normalized).
37/// - `rkey` is taken as-is (atproto record-key syntax).
38#[derive(Clone, Debug, Eq, PartialEq, Hash)]
39pub struct CanonicalSubject {
40    pub did: String,
41    pub nsid: String,
42    pub rkey: String,
43}
44
45impl CanonicalSubject {
46    /// Construct a canonical subject, normalizing the NSID and validating the
47    /// DID + rkey are non-empty. `did` must be a DID (not a handle) — resolve
48    /// handles first via [`resolve_handle_to_did`].
49    pub fn new(
50        did: impl Into<String>,
51        nsid: impl Into<String>,
52        rkey: impl Into<String>,
53    ) -> Result<Self, String> {
54        let did = did.into();
55        let nsid = nsid.into().to_ascii_lowercase();
56        let rkey = rkey.into();
57        if !did.starts_with("did:") {
58            return Err(format!("subject did must be a DID (did:...), got {did:?}"));
59        }
60        if did.chars().any(char::is_whitespace) {
61            return Err("subject did must not contain whitespace".to_owned());
62        }
63        if nsid.is_empty() || nsid.chars().any(char::is_whitespace) {
64            return Err(format!(
65                "subject nsid must be non-empty/no-whitespace, got {nsid:?}"
66            ));
67        }
68        if rkey.is_empty() || rkey.chars().any(char::is_whitespace) {
69            return Err(format!(
70                "subject rkey must be non-empty/no-whitespace, got {rkey:?}"
71            ));
72        }
73        Ok(Self { did, nsid, rkey })
74    }
75
76    /// Length-prefixed canonical bytes: `domain || u32_le(len(did)) || did ||
77    /// u32_le(len(nsid)) || nsid || u32_le(len(rkey)) || rkey`. Deterministic;
78    /// two distinct subjects cannot produce the same bytes.
79    pub fn to_canonical_bytes(&self) -> Vec<u8> {
80        let did = self.did.as_bytes();
81        let nsid = self.nsid.as_bytes();
82        let rkey = self.rkey.as_bytes();
83        let mut out =
84            Vec::with_capacity(SUBJECT_DOMAIN.len() + 4 * 3 + did.len() + nsid.len() + rkey.len());
85        out.extend_from_slice(SUBJECT_DOMAIN.as_bytes());
86        for field in [did, nsid, rkey] {
87            out.extend_from_slice(&(field.len() as u32).to_le_bytes());
88            out.extend_from_slice(field);
89        }
90        out
91    }
92}
93
94/// Resolve a bare handle (e.g. `alice.example.com`) to a DID.
95///
96/// **STUB** — atproto handles are mutable and resolve via DID discovery; the
97/// live `getRecord`/DID-resolution path is not wired here yet. Callers that
98/// already hold a DID should pass it directly to [`CanonicalSubject::new`]; this
99/// function exists so the handle→DID seam is explicit and fail-closed (a real
100/// handle is rejected, not silently treated as a DID).
101pub fn resolve_handle_to_did(_handle: &str) -> Result<String, String> {
102    // TODO(atproto getRecord wiring): implement handle→DID resolution.
103    Err(
104        "handle→DID resolution not wired — pass a DID (did:...) to CanonicalSubject::new"
105            .to_owned(),
106    )
107}
108
109/// The keyed routing leaf for a subject under a group key + epoch.
110///
111/// `topic = hex(keyed_mac(K_group, canonical_subject_bytes ‖ epoch_le))` — a
112/// 256-bit BLAKE3 keyed hash (HMAC-SHA256 under FIPS), hex-encoded to a 64-char
113/// MoQ-path-safe segment. This is the opaque routing leaf that replaces
114/// `oid_hash`; the semantic `(did, nsid, rkey)` stays under the payload AEAD.
115///
116/// Knowing the at-uri is NOT enough to derive this leaf — `K_group` is required
117/// (relay-opaque, unguessable). A different group key or epoch produces a
118/// different leaf (cross-group/cross-epoch unlinkability).
119pub fn topic_leaf(k_group: &[u8; 32], subject: &CanonicalSubject, epoch: u64) -> String {
120    let mut data = subject.to_canonical_bytes();
121    data.extend_from_slice(&epoch.to_le_bytes());
122    let mac = keyed_mac(k_group, &data);
123    hex::encode(mac)
124}
125
126/// Full broadcast path: `{prefix}/{topic_leaf}`. Defaults to the publications
127/// prefix used by the per-OID firehose tier; pass a group-scoped prefix for the
128/// confidential profile.
129pub fn keyed_broadcast_path(k_group: &[u8; 32], subject: &CanonicalSubject, epoch: u64) -> String {
130    keyed_broadcast_path_with(
131        crate::moq_event::PUBLICATIONS_PREFIX,
132        k_group,
133        subject,
134        epoch,
135    )
136}
137
138/// `keyed_broadcast_path` with an explicit prefix (e.g. a group-scoped path for
139/// the confidential profile, vs the public firehose prefix).
140pub fn keyed_broadcast_path_with(
141    prefix: &str,
142    k_group: &[u8; 32],
143    subject: &CanonicalSubject,
144    epoch: u64,
145) -> String {
146    format!("{prefix}/{}", topic_leaf(k_group, subject, epoch))
147}
148
149#[cfg(test)]
150#[allow(clippy::unwrap_used)]
151mod tests {
152    use super::*;
153
154    fn sub(did: &str, nsid: &str, rkey: &str) -> CanonicalSubject {
155        CanonicalSubject::new(did, nsid, rkey).unwrap()
156    }
157
158    #[test]
159    fn canonical_bytes_are_deterministic() {
160        let a = sub("did:web:node.example", "ai.hyprstream.model", "v1");
161        let b = sub("did:web:node.example", "ai.hyprstream.model", "v1");
162        assert_eq!(a.to_canonical_bytes(), b.to_canonical_bytes());
163    }
164
165    #[test]
166    fn nsid_is_lowercased() {
167        let a = sub("did:web:n", "AI.HyprStream.Model", "v1");
168        let b = sub("did:web:n", "ai.hyprstream.model", "v1");
169        assert_eq!(a.to_canonical_bytes(), b.to_canonical_bytes());
170    }
171
172    #[test]
173    fn distinct_subjects_have_distinct_bytes() {
174        let a = sub("did:web:n", "ai.hyprstream.model", "v1");
175        let b = sub("did:web:n", "ai.hyprstream.model", "v2");
176        assert_ne!(a.to_canonical_bytes(), b.to_canonical_bytes());
177    }
178
179    #[test]
180    fn length_prefixing_prevents_concat_collision() {
181        // Without length prefixes, ("ab","c") and ("a","bc") could collide.
182        let a = sub("did:web:ab", "c", "r");
183        let b = sub("did:web:a", "bc", "r");
184        assert_ne!(a.to_canonical_bytes(), b.to_canonical_bytes());
185    }
186
187    #[test]
188    fn rejects_handle_and_garbage() {
189        assert!(CanonicalSubject::new("alice.example.com", "x", "r").is_err());
190        assert!(CanonicalSubject::new("did:web:n", "", "r").is_err());
191        assert!(CanonicalSubject::new("did:web:n", "x", "").is_err());
192        assert!(CanonicalSubject::new("did:web:n", "x y", "r").is_err());
193    }
194
195    #[test]
196    fn resolve_handle_is_fail_closed_stub() {
197        assert!(resolve_handle_to_did("alice.example.com").is_err());
198    }
199
200    #[test]
201    fn topic_leaf_is_keyed_prf() {
202        let s = sub("did:web:n", "ai.hyprstream.model", "v1");
203        let k1 = [1u8; 32];
204        let k2 = [2u8; 32];
205        // Same subject+key+epoch → same leaf (deterministic PRF).
206        assert_eq!(topic_leaf(&k1, &s, 0), topic_leaf(&k1, &s, 0));
207        // Different key → different leaf.
208        assert_ne!(topic_leaf(&k1, &s, 0), topic_leaf(&k2, &s, 0));
209        // Different epoch → different leaf (cross-time unlinkability).
210        assert_ne!(topic_leaf(&k1, &s, 0), topic_leaf(&k1, &s, 1));
211        // Different subject → different leaf.
212        let s2 = sub("did:web:n", "ai.hyprstream.model", "v2");
213        assert_ne!(topic_leaf(&k1, &s, 0), topic_leaf(&k1, &s2, 0));
214    }
215
216    #[test]
217    fn topic_leaf_is_hex_path_safe_256bit() {
218        let s = sub("did:web:n", "ai.hyprstream.model", "v1");
219        let leaf = topic_leaf(&[9u8; 32], &s, 7);
220        // 32 bytes → 64 hex chars; only [0-9a-f].
221        assert_eq!(leaf.len(), 64);
222        assert!(leaf
223            .chars()
224            .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));
225    }
226
227    #[test]
228    fn keyed_broadcast_path_shape() {
229        let s = sub("did:web:n", "ai.hyprstream.model", "v1");
230        let p = keyed_broadcast_path(&[1u8; 32], &s, 0);
231        assert!(p.starts_with("local/events/publications/"));
232        assert_eq!(p.split('/').next_back().unwrap().len(), 64);
233        let p2 = keyed_broadcast_path_with("local/events/g", &[1u8; 32], &s, 0);
234        assert!(p2.starts_with("local/events/g/"));
235    }
236}