Skip to main content

hyprstream_pds/
event_group.rs

1//! `ai.hyprstream.event.group` / `ai.hyprstream.event.groupItem` — lexicon
2//! records for EventService managed-list groups (epic #600, EV2 #602).
3//!
4//! Built on the generic [`crate::list_record`] module: a **parallel,
5//! pattern-matching lexicon**, deliberately modeled on the signed-off
6//! `ai.hyprstream.placement.group`/`groupItem` pattern from #524 (atproto
7//! **list**, owner-curated, with a separate listitem per member; bidirectional
8//! consent = owner lists the member **and** the member's own record consents) —
9//! but NOT a literal reuse of `ai.hyprstream.placement.group`, since that
10//! lexicon is sign-off-frozen (unknown fields rejected at decode) and event
11//! groups need an extra `keysetId` field placement groups don't have.
12//!
13//! **Resolved design decision** (human review, #602): keep these as separate
14//! NSIDs/collections — this preserves cheap collection-based firehose/AppView
15//! filtering and keeps placement-membership and event-key-membership as
16//! genuinely distinct axes — while sharing the list/listitem/consent
17//! *mechanics* via [`crate::list_record`] so neither lexicon hand-duplicates
18//! validation, encoding, or the consent check.
19//!
20//! # Key material is NOT in the record
21//!
22//! `keysetId` is a stable **opaque reference** ("this group's key material is
23//! generation X"), never the key bytes. The actual `K_group` symmetric key is
24//! generated fresh per rotation (exactly as `SecureEventPublisher::register_prefix`
25//! does today) and delivered **per-member** via DH-wrap-on-join
26//! (`derive_wrap_key`/`wrap_group_key`) — never committed to the public,
27//! firehose-synced atproto repo. This matches #524's "durable facts = atproto
28//! records, volatile/secret facts = ephemeral RPC" split, and keeps the
29//! relay/firehose blind to `K_group` (epic #600's threat model).
30//!
31//! # Member-side consent lexicon — still open
32//!
33//! Membership is **bidirectional**: [`EventGroupItemRecord`] is the owner's
34//! claim that a member belongs to the group; it is NOT sufficient alone — the
35//! member's own identity record must independently consent (carry the group's
36//! at-uri in its own `groups`-style field). Which lexicon carries that
37//! member-side consent for EventService members remains an **open question**:
38//! candidates are reusing `ai.hyprstream.placement.node.groups` for members
39//! that are also placement nodes, or a new minimal `ai.hyprstream.event.member`
40//! record for members that are not. [`check_bidirectional_consent`] implements
41//! the check generically over two already-fetched claims, deliberately not
42//! committing to the member-side lexicon.
43
44use anyhow::{ensure, Result};
45
46use crate::dag_cbor::DagCbor;
47use crate::list_record::{self, ListExtra, ListItemRecord, ListRecord};
48
49/// NSID for the group (list) record.
50pub const GROUP_COLLECTION_NSID: &str = "ai.hyprstream.event.group";
51/// NSID for the groupItem (listitem) record.
52pub const GROUP_ITEM_COLLECTION_NSID: &str = "ai.hyprstream.event.groupItem";
53
54/// `ai.hyprstream.event.group`'s extra field beyond the common list shape.
55///
56/// ```json
57/// {
58///   "lexicon": 1,
59///   "id": "ai.hyprstream.event.group",
60///   "defs": { "main": { "type": "record", "key": "tid", "record": {
61///     "type": "object",
62///     "required": ["name", "ownerDid", "keysetId", "createdAt"],
63///     "properties": {
64///       "name":      { "type": "string" },
65///       "ownerDid":  { "type": "string", "format": "did" },
66///       "purpose":   { "type": "string" },
67///       "keysetId":  { "type": "string" },
68///       "createdAt": { "type": "string", "format": "datetime" }
69///     }
70/// }}}
71/// ```
72#[derive(Clone, Debug, Eq, PartialEq)]
73pub struct EventGroupExtra {
74    /// Opaque reference to the current key-material generation. NOT a secret —
75    /// see module docs. A member resolves `(group_uri, keyset_id, epoch)` to the
76    /// actual `K_group` bytes via the DH-wrap-on-join path, never from this field.
77    pub keyset_id: String,
78}
79
80impl ListExtra for EventGroupExtra {
81    fn field_names() -> &'static [&'static str] {
82        &["keysetId"]
83    }
84
85    fn encode_into(&self, pairs: &mut Vec<(&'static str, DagCbor)>) {
86        pairs.push(("keysetId", DagCbor::Text(self.keyset_id.clone())));
87    }
88
89    fn decode_from(value: &DagCbor, nsid: &str) -> Result<Self> {
90        let keyset_id = list_record::map_get_str(value, "keysetId", nsid)?.to_owned();
91        Ok(Self { keyset_id })
92    }
93
94    fn validate(&self) -> Result<()> {
95        ensure!(!self.keyset_id.is_empty(), "keysetId must be non-empty");
96        Ok(())
97    }
98}
99
100/// `ai.hyprstream.event.group` — the list record, lives in the owner's repo.
101pub type EventGroupRecord = ListRecord<EventGroupExtra>;
102
103/// `ai.hyprstream.event.groupItem` — the owner-side membership claim
104/// (listitem), lives in the owner's repo. Identical shape to every other
105/// listitem lexicon in this crate — see [`ListItemRecord`].
106pub type EventGroupItemRecord = ListItemRecord;
107
108/// Generic bidirectional-consent check — see [`list_record::check_bidirectional_consent`].
109pub use list_record::check_bidirectional_consent;
110
111impl EventGroupRecord {
112    /// Convenience constructor matching this lexicon's field order (`keyset_id`
113    /// as a plain argument rather than wrapping it in [`EventGroupExtra`] by hand).
114    pub fn new_event_group(
115        name: impl Into<String>,
116        owner_did: impl Into<String>,
117        purpose: Option<String>,
118        keyset_id: impl Into<String>,
119        created_at: impl Into<String>,
120    ) -> Result<Self> {
121        ListRecord::new(
122            name,
123            owner_did,
124            purpose,
125            created_at,
126            EventGroupExtra {
127                keyset_id: keyset_id.into(),
128            },
129        )
130    }
131}
132
133impl EventGroupItemRecord {
134    /// Decode using this lexicon's NSID for error attribution.
135    pub fn from_event_dag_cbor(bytes: &[u8]) -> Result<Self> {
136        Self::from_dag_cbor(bytes, GROUP_ITEM_COLLECTION_NSID)
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
143    use super::*;
144
145    fn sample_group() -> EventGroupRecord {
146        EventGroupRecord::new_event_group(
147            "qwen3-serving",
148            "did:web:nodeA.example.com",
149            Some("serve:model:qwen3 subscribers".to_owned()),
150            "ks-2026-06-30-01",
151            "2026-06-30T12:00:00.000Z",
152        )
153        .expect("valid sample")
154    }
155
156    fn sample_item() -> EventGroupItemRecord {
157        EventGroupItemRecord::new(
158            "at://did:web:nodeA.example.com/ai.hyprstream.event.group/3k2x",
159            "did:web:memberB.example.com",
160            "2026-06-30T12:01:00.000Z",
161        )
162        .expect("valid sample")
163    }
164
165    #[test]
166    fn group_deterministic_across_rebuild() {
167        let r1 = sample_group();
168        let r2 = EventGroupRecord::new_event_group(
169            r1.name.clone(),
170            r1.owner_did.clone(),
171            r1.purpose.clone(),
172            r1.extra.keyset_id.clone(),
173            r1.created_at.clone(),
174        )
175        .unwrap();
176        assert_eq!(r1.to_dag_cbor(), r2.to_dag_cbor());
177        assert_eq!(r1.cid(), r2.cid());
178    }
179
180    #[test]
181    fn group_round_trips_through_dag_cbor() {
182        let r = sample_group();
183        let bytes = r.to_dag_cbor();
184        let decoded =
185            EventGroupRecord::from_dag_cbor(&bytes, GROUP_COLLECTION_NSID).expect("decode");
186        assert_eq!(r, decoded);
187    }
188
189    #[test]
190    fn group_round_trips_without_optional_purpose() {
191        let r = EventGroupRecord::new_event_group(
192            "no-purpose-group",
193            "did:web:nodeA.example.com",
194            None,
195            "ks-1",
196            "2026-06-30T12:00:00.000Z",
197        )
198        .unwrap();
199        let decoded = EventGroupRecord::from_dag_cbor(&r.to_dag_cbor(), GROUP_COLLECTION_NSID)
200            .expect("decode");
201        assert_eq!(r, decoded);
202        assert!(decoded.purpose.is_none());
203    }
204
205    #[test]
206    fn group_rejects_extra_fields() {
207        let mut extra = sample_group().to_value();
208        if let DagCbor::Map(ref mut v) = extra {
209            v.push((DagCbor::Text("extra".into()), DagCbor::Unsigned(1)));
210            v.sort_by(|a, b| a.0.as_str().unwrap_or("").cmp(b.0.as_str().unwrap_or("")));
211        }
212        assert!(EventGroupRecord::from_value(&extra, GROUP_COLLECTION_NSID).is_err());
213    }
214
215    #[test]
216    fn group_rejects_bad_did_and_keyset() {
217        assert!(EventGroupRecord::new_event_group(
218            "g",
219            "not-a-did",
220            None,
221            "ks-1",
222            "2026-06-30T12:00:00.000Z"
223        )
224        .is_err());
225        assert!(EventGroupRecord::new_event_group(
226            "g",
227            "did:web:x",
228            None,
229            "",
230            "2026-06-30T12:00:00.000Z"
231        )
232        .is_err());
233    }
234
235    #[test]
236    fn group_field_order_matches_lexicon_canonical_cbor() {
237        let v = DagCbor::decode(&sample_group().to_dag_cbor()).expect("decode");
238        let map = v.as_map().expect("map");
239        let keys: Vec<&str> = map.iter().map(|(k, _)| k.as_str().expect("str")).collect();
240        // lexicographic byte order across base + extra fields.
241        assert_eq!(
242            keys,
243            vec!["createdAt", "keysetId", "name", "ownerDid", "purpose"]
244        );
245    }
246
247    #[test]
248    fn group_item_round_trips() {
249        let item = sample_item();
250        let decoded =
251            EventGroupItemRecord::from_event_dag_cbor(&item.to_dag_cbor()).expect("decode");
252        assert_eq!(item, decoded);
253    }
254
255    #[test]
256    fn group_item_rejects_bad_at_uri_and_did() {
257        assert!(EventGroupItemRecord::new(
258            "not-an-at-uri",
259            "did:web:x",
260            "2026-06-30T12:00:00.000Z"
261        )
262        .is_err());
263        assert!(EventGroupItemRecord::new(
264            "at://did:web:x/ai.hyprstream.event.group/abc",
265            "not-a-did",
266            "2026-06-30T12:00:00.000Z"
267        )
268        .is_err());
269    }
270
271    #[test]
272    fn bidirectional_consent_requires_both_sides() {
273        let item = sample_item();
274        let group_uri = item.group.clone();
275        let member = item.subject.clone();
276
277        assert!(!check_bidirectional_consent(
278            &item,
279            &group_uri,
280            &member,
281            &[]
282        ));
283        assert!(!check_bidirectional_consent(
284            &item,
285            &group_uri,
286            &member,
287            &["at://did:web:other/ai.hyprstream.event.group/zzzz".to_owned()],
288        ));
289        assert!(check_bidirectional_consent(
290            &item,
291            &group_uri,
292            &member,
293            std::slice::from_ref(&group_uri),
294        ));
295        assert!(!check_bidirectional_consent(
296            &item,
297            "at://did:web:nodeA.example.com/ai.hyprstream.event.group/different",
298            &member,
299            &[group_uri],
300        ));
301    }
302}