1use anyhow::{bail, ensure, Result};
24
25use crate::cid::Cid;
26use crate::dag_cbor::DagCbor;
27
28pub fn map_get_str<'a>(value: &'a DagCbor, key: &str, nsid: &str) -> Result<&'a str> {
32 value
33 .get(key)
34 .ok_or_else(|| anyhow::anyhow!("{nsid}: missing required field {key:?}"))?
35 .as_str()
36}
37
38pub fn map_get_opt_str<'a>(value: &'a DagCbor, key: &str) -> Result<Option<&'a str>> {
41 match value.get(key) {
42 None => Ok(None),
43 Some(v) => Ok(Some(v.as_str()?)),
44 }
45}
46
47pub fn validate_at_uri(s: &str) -> Result<()> {
50 ensure!(
51 s.starts_with("at://"),
52 "at-uri must start with \"at://\": {s:?}"
53 );
54 let rest = &s[5..];
55 ensure!(!rest.is_empty(), "at-uri must have an authority: {s:?}");
56 ensure!(
57 !rest.chars().any(char::is_whitespace),
58 "at-uri must not contain whitespace: {s:?}"
59 );
60 Ok(())
61}
62
63pub fn validate_did(s: &str) -> Result<()> {
66 ensure!(s.starts_with("did:"), "did must start with \"did:\": {s:?}");
67 let rest = &s[4..];
68 ensure!(!rest.is_empty(), "did must have a method: {s:?}");
69 ensure!(
70 !rest.chars().any(char::is_whitespace),
71 "did must not contain whitespace: {s:?}"
72 );
73 let mut parts = rest.splitn(2, ':');
74 let method = parts.next().unwrap_or("");
75 let id = parts.next().unwrap_or("");
76 ensure!(
77 !method.is_empty() && !id.is_empty(),
78 "did must be \"did:<method>:<id>\": {s:?}"
79 );
80 Ok(())
81}
82
83pub fn validate_datetime(s: &str) -> Result<()> {
89 ensure!(s.ends_with('Z'), "datetime must end with 'Z' (UTC): {s:?}");
90 let pre = &s[..s.len() - 1];
91 let bytes = pre.as_bytes();
92 ensure!(
93 bytes.len() == 23,
94 "datetime must be YYYY-MM-DDTHH:MM:SS.mmm (millisecond precision): {s:?}"
95 );
96 ensure!(
97 bytes[4] == b'-'
98 && bytes[7] == b'-'
99 && bytes[10] == b'T'
100 && bytes[13] == b':'
101 && bytes[16] == b':'
102 && bytes[19] == b'.',
103 "datetime must be ISO-8601 (YYYY-MM-DDTHH:MM:SS.mmm): {s:?}"
104 );
105 ensure!(
106 bytes
107 .iter()
108 .enumerate()
109 .all(|(i, b)| matches!(i, 4 | 7 | 10 | 13 | 16 | 19) || b.is_ascii_digit()),
110 "datetime must be all digits outside its separators: {s:?}"
111 );
112 let num = |lo: usize, hi: usize| pre[lo..hi].parse::<u32>().unwrap_or(u32::MAX);
115 let (year, month, day) = (num(0, 4), num(5, 7), num(8, 10));
116 let (hour, minute, second) = (num(11, 13), num(14, 16), num(17, 19));
117 ensure!(
118 (1..=12).contains(&month),
119 "datetime month out of range: {s:?}"
120 );
121 let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
122 let days_in_month = match month {
123 4 | 6 | 9 | 11 => 30,
124 2 if leap => 29,
125 2 => 28,
126 _ => 31,
127 };
128 ensure!(
129 (1..=days_in_month).contains(&day),
130 "datetime day out of range: {s:?}"
131 );
132 ensure!(
133 hour <= 23 && minute <= 59 && second <= 59,
134 "datetime time out of range: {s:?}"
135 );
136 Ok(())
137}
138
139pub fn validate_nonempty(s: &str, field: &str) -> Result<()> {
142 ensure!(!s.is_empty(), "{field} must not be empty");
143 Ok(())
144}
145
146#[derive(Clone, Debug, Eq, PartialEq)]
153pub struct ListItemRecord {
154 pub group: String,
156 pub subject: String,
158 pub created_at: String,
160}
161
162impl ListItemRecord {
163 pub fn new(
165 group: impl Into<String>,
166 subject: impl Into<String>,
167 created_at: impl Into<String>,
168 ) -> Result<Self> {
169 let group = group.into();
170 let subject = subject.into();
171 let created_at = created_at.into();
172 validate_at_uri(&group)?;
173 validate_did(&subject)?;
174 validate_datetime(&created_at)?;
175 Ok(Self {
176 group,
177 subject,
178 created_at,
179 })
180 }
181
182 pub fn to_dag_cbor(&self) -> Vec<u8> {
184 self.to_value().encode()
185 }
186
187 pub fn cid(&self) -> Cid {
189 Cid::from_dag_cbor(&self.to_dag_cbor())
190 }
191
192 pub fn to_value(&self) -> DagCbor {
193 DagCbor::str_map([
194 ("createdAt", DagCbor::Text(self.created_at.clone())),
195 ("group", DagCbor::Text(self.group.clone())),
196 ("subject", DagCbor::Text(self.subject.clone())),
197 ])
198 }
199
200 pub fn from_dag_cbor(bytes: &[u8], nsid: &str) -> Result<Self> {
203 Self::from_value(&DagCbor::decode(bytes)?, nsid)
204 }
205
206 pub fn from_value(value: &DagCbor, nsid: &str) -> Result<Self> {
207 let map = value.as_map()?;
208 let group = map_get_str(value, "group", nsid)?.to_owned();
209 let subject = map_get_str(value, "subject", nsid)?.to_owned();
210 let created_at = map_get_str(value, "createdAt", nsid)?.to_owned();
211 for (k, _v) in map {
212 match k.as_str()? {
213 "group" | "subject" | "createdAt" => {}
214 other => bail!("{nsid}: unknown field {other:?} (lexicon is 3 fields)"),
215 }
216 }
217 Self::new(group, subject, created_at)
218 }
219}
220
221pub fn check_bidirectional_consent(
230 owner_claim: &ListItemRecord,
231 group_uri: &str,
232 member_did: &str,
233 member_consented_groups: &[String],
234) -> bool {
235 owner_claim.group == group_uri
236 && owner_claim.subject == member_did
237 && member_consented_groups.iter().any(|g| g == group_uri)
238}
239
240pub trait ListExtra: Clone + std::fmt::Debug + Eq + Sized {
246 fn field_names() -> &'static [&'static str];
249 fn encode_into(&self, pairs: &mut Vec<(&'static str, DagCbor)>);
251 fn decode_from(value: &DagCbor, nsid: &str) -> Result<Self>;
254 fn validate(&self) -> Result<()> {
260 Ok(())
261 }
262}
263
264impl ListExtra for () {
266 fn field_names() -> &'static [&'static str] {
267 &[]
268 }
269 fn encode_into(&self, _pairs: &mut Vec<(&'static str, DagCbor)>) {}
270 fn decode_from(_value: &DagCbor, _nsid: &str) -> Result<Self> {
271 Ok(())
272 }
273}
274
275#[derive(Clone, Debug, Eq, PartialEq)]
278pub struct ListRecord<E: ListExtra> {
279 pub name: String,
281 pub owner_did: String,
283 pub purpose: Option<String>,
285 pub created_at: String,
287 pub extra: E,
289}
290
291impl<E: ListExtra> ListRecord<E> {
292 pub fn new(
294 name: impl Into<String>,
295 owner_did: impl Into<String>,
296 purpose: Option<String>,
297 created_at: impl Into<String>,
298 extra: E,
299 ) -> Result<Self> {
300 let name = name.into();
301 let owner_did = owner_did.into();
302 let created_at = created_at.into();
303 validate_nonempty(&name, "name")?;
304 validate_did(&owner_did)?;
305 if let Some(p) = &purpose {
306 validate_nonempty(p, "purpose")?;
307 }
308 validate_datetime(&created_at)?;
309 extra.validate()?;
310 Ok(Self {
311 name,
312 owner_did,
313 purpose,
314 created_at,
315 extra,
316 })
317 }
318
319 pub fn to_dag_cbor(&self) -> Vec<u8> {
320 self.to_value().encode()
321 }
322
323 pub fn cid(&self) -> Cid {
324 Cid::from_dag_cbor(&self.to_dag_cbor())
325 }
326
327 pub fn to_value(&self) -> DagCbor {
328 let mut pairs: Vec<(&str, DagCbor)> = vec![
329 ("name", DagCbor::Text(self.name.clone())),
330 ("ownerDid", DagCbor::Text(self.owner_did.clone())),
331 ("createdAt", DagCbor::Text(self.created_at.clone())),
332 ];
333 if let Some(purpose) = &self.purpose {
334 pairs.push(("purpose", DagCbor::Text(purpose.clone())));
335 }
336 self.extra.encode_into(&mut pairs);
337 DagCbor::str_map(pairs)
338 }
339
340 pub fn from_dag_cbor(bytes: &[u8], nsid: &str) -> Result<Self> {
343 Self::from_value(&DagCbor::decode(bytes)?, nsid)
344 }
345
346 pub fn from_value(value: &DagCbor, nsid: &str) -> Result<Self> {
347 let map = value.as_map()?;
348 let name = map_get_str(value, "name", nsid)?.to_owned();
349 let owner_did = map_get_str(value, "ownerDid", nsid)?.to_owned();
350 let purpose = map_get_opt_str(value, "purpose")?.map(str::to_owned);
351 let created_at = map_get_str(value, "createdAt", nsid)?.to_owned();
352 let extra = E::decode_from(value, nsid)?;
353 let known_extra = E::field_names();
354 for (k, _v) in map {
355 let key = k.as_str()?;
356 match key {
357 "name" | "ownerDid" | "purpose" | "createdAt" => {}
358 other if known_extra.contains(&other) => {}
359 other => bail!("{nsid}: unknown field {other:?}"),
360 }
361 }
362 Self::new(name, owner_did, purpose, created_at, extra)
363 }
364}
365
366#[cfg(test)]
367mod tests {
368 #![allow(
369 clippy::unwrap_used,
370 clippy::expect_used,
371 clippy::indexing_slicing,
372 clippy::panic
373 )]
374 use super::*;
375
376 const NSID: &str = "ai.hyprstream.test.group";
377 const ITEM_NSID: &str = "ai.hyprstream.test.groupItem";
378
379 fn sample_list() -> ListRecord<()> {
380 ListRecord::new(
381 "east-coast-gpus",
382 "did:web:alice.example.com",
383 Some("GPU nodes in us-east".into()),
384 "2026-06-23T12:34:56.789Z",
385 (),
386 )
387 .expect("valid sample")
388 }
389
390 fn sample_item() -> ListItemRecord {
391 ListItemRecord::new(
392 "at://did:web:alice.example.com/ai.hyprstream.test.group/3kxy",
393 "did:web:node1.example.com",
394 "2026-06-23T12:34:56.789Z",
395 )
396 .expect("valid sample")
397 }
398
399 #[test]
400 fn list_round_trip_same_cid_no_extra() {
401 let r = sample_list();
402 let bytes = r.to_dag_cbor();
403 let back = ListRecord::<()>::from_dag_cbor(&bytes, NSID).expect("round-trip");
404 assert_eq!(r, back);
405 assert_eq!(r.cid(), back.cid());
406 }
407
408 #[test]
409 fn list_optional_purpose_omitted() {
410 let mut r = sample_list();
411 r.purpose = None;
412 let v = r.to_value();
413 assert!(v.get("purpose").is_none(), "absent purpose must be omitted");
414 let back = ListRecord::<()>::from_dag_cbor(&r.to_dag_cbor(), NSID).expect("round-trip");
415 assert_eq!(r, back);
416 }
417
418 #[test]
419 fn list_fields_canonical_order_no_extra() {
420 let r = sample_list();
421 let v = DagCbor::decode(&r.to_dag_cbor()).expect("decode");
422 let map = v.as_map().expect("map");
423 let keys: Vec<&str> = map.iter().map(|(k, _)| k.as_str().expect("str")).collect();
424 assert_eq!(keys, vec!["createdAt", "name", "ownerDid", "purpose"]);
425 }
426
427 #[test]
428 fn list_rejects_extra_fields() {
429 let mut extra = sample_list().to_value();
430 if let DagCbor::Map(ref mut v) = extra {
431 v.push((DagCbor::Text("bogus".into()), DagCbor::Unsigned(1)));
432 v.sort_by(|a, b| a.0.as_str().unwrap_or("").cmp(b.0.as_str().unwrap_or("")));
433 }
434 assert!(ListRecord::<()>::from_value(&extra, NSID).is_err());
435 }
436
437 #[test]
438 fn list_validates_formats() {
439 assert!(ListRecord::new("", "did:web:x", None, "2026-06-23T12:34:56.789Z", ()).is_err());
440 assert!(ListRecord::new("g", "not-a-did", None, "2026-06-23T12:34:56.789Z", ()).is_err());
441 assert!(ListRecord::new(
442 "g",
443 "did:web:x",
444 Some("".into()),
445 "2026-06-23T12:34:56.789Z",
446 ()
447 )
448 .is_err());
449 assert!(ListRecord::new("g", "did:web:x", None, "2026", ()).is_err());
450 }
451
452 #[test]
453 fn datetime_is_validated_semantically() {
454 for ok in [
456 "2026-06-23T12:34:56.789Z",
457 "2024-02-29T00:00:00.000Z", "2026-12-31T23:59:59.999Z",
459 ] {
460 assert!(validate_datetime(ok).is_ok(), "{ok:?} must be accepted");
461 }
462 for bad in [
463 "2026-99-99T99:99:99.999Z", "2026-00-10T12:00:00.000Z", "2026-13-10T12:00:00.000Z", "2026-04-31T12:00:00.000Z", "2026-02-29T12:00:00.000Z", "2026-06-23T24:00:00.000Z", "2026-06-23T12:60:00.000Z", "2026-06-23T12:34:60.000Z", "2026-06-23T12:34:56.Z", "2026-06-23T12:34:56.78Z", "2026-06-23T12:34:56.7890Z", "2026-06-23T12:34:56.789", "aaaa-aa-aaTaa:aa:aa.aaaZ", ] {
477 assert!(validate_datetime(bad).is_err(), "{bad:?} must be rejected");
478 }
479 }
480
481 #[test]
482 fn item_round_trip_same_cid() {
483 let r = sample_item();
484 let bytes = r.to_dag_cbor();
485 let back = ListItemRecord::from_dag_cbor(&bytes, ITEM_NSID).expect("round-trip");
486 assert_eq!(r, back);
487 assert_eq!(r.cid(), back.cid());
488 }
489
490 #[test]
491 fn item_fields_canonical_order() {
492 let r = sample_item();
493 let v = DagCbor::decode(&r.to_dag_cbor()).expect("decode");
494 let map = v.as_map().expect("map");
495 let keys: Vec<&str> = map.iter().map(|(k, _)| k.as_str().expect("str")).collect();
496 assert_eq!(keys, vec!["createdAt", "group", "subject"]);
497 }
498
499 #[test]
500 fn item_rejects_extra_fields() {
501 let mut extra = sample_item().to_value();
502 if let DagCbor::Map(ref mut v) = extra {
503 v.push((DagCbor::Text("bogus".into()), DagCbor::Unsigned(1)));
504 v.sort_by(|a, b| a.0.as_str().unwrap_or("").cmp(b.0.as_str().unwrap_or("")));
505 }
506 assert!(ListItemRecord::from_value(&extra, ITEM_NSID).is_err());
507 }
508
509 #[test]
510 fn item_validates_formats() {
511 assert!(ListItemRecord::new("nope", "did:web:n", "2026-06-23T12:34:56.789Z").is_err());
512 assert!(ListItemRecord::new(
513 "at://did:web:x/ai.hyprstream.test.group/3kxy",
514 "not-a-did",
515 "2026-06-23T12:34:56.789Z"
516 )
517 .is_err());
518 }
519
520 #[test]
521 fn bidirectional_consent_requires_both_sides() {
522 let item = sample_item();
523 let group_uri = item.group.clone();
524 let member = item.subject.clone();
525
526 assert!(!check_bidirectional_consent(
527 &item,
528 &group_uri,
529 &member,
530 &[]
531 ));
532 assert!(!check_bidirectional_consent(
533 &item,
534 &group_uri,
535 &member,
536 &["at://did:web:other/ai.hyprstream.test.group/zzzz".to_owned()],
537 ));
538 assert!(check_bidirectional_consent(
539 &item,
540 &group_uri,
541 &member,
542 std::slice::from_ref(&group_uri),
543 ));
544 }
545
546 #[derive(Clone, Debug, Eq, PartialEq)]
548 struct TestExtra {
549 keyset_id: String,
550 }
551 impl ListExtra for TestExtra {
552 fn field_names() -> &'static [&'static str] {
553 &["keysetId"]
554 }
555 fn encode_into(&self, pairs: &mut Vec<(&'static str, DagCbor)>) {
556 pairs.push(("keysetId", DagCbor::Text(self.keyset_id.clone())));
557 }
558 fn decode_from(value: &DagCbor, nsid: &str) -> Result<Self> {
559 Ok(Self {
560 keyset_id: map_get_str(value, "keysetId", nsid)?.to_owned(),
561 })
562 }
563 }
564
565 #[test]
566 fn list_with_extra_round_trips_and_orders_canonically() {
567 let r = ListRecord::new(
568 "qwen3-serving",
569 "did:web:nodeA.example.com",
570 None,
571 "2026-06-30T12:00:00.000Z",
572 TestExtra {
573 keyset_id: "ks-1".into(),
574 },
575 )
576 .expect("valid");
577 let back = ListRecord::<TestExtra>::from_dag_cbor(&r.to_dag_cbor(), NSID).expect("decode");
578 assert_eq!(r, back);
579
580 let v = DagCbor::decode(&r.to_dag_cbor()).expect("decode");
581 let map = v.as_map().expect("map");
582 let keys: Vec<&str> = map.iter().map(|(k, _)| k.as_str().expect("str")).collect();
583 assert_eq!(keys, vec!["createdAt", "keysetId", "name", "ownerDid"]);
585 }
586
587 #[test]
588 fn list_with_extra_rejects_unknown_field_outside_both_sets() {
589 let r = ListRecord::new(
590 "g",
591 "did:web:x",
592 None,
593 "2026-06-30T12:00:00.000Z",
594 TestExtra {
595 keyset_id: "ks-1".into(),
596 },
597 )
598 .expect("valid");
599 let mut v = r.to_value();
600 if let DagCbor::Map(ref mut m) = v {
601 m.push((DagCbor::Text("bogus".into()), DagCbor::Unsigned(1)));
602 m.sort_by(|a, b| a.0.as_str().unwrap_or("").cmp(b.0.as_str().unwrap_or("")));
603 }
604 assert!(ListRecord::<TestExtra>::from_value(&v, NSID).is_err());
605 }
606}