Skip to main content

moq_net/
identity.rs

1use std::fmt;
2use std::str::FromStr;
3use std::sync::Arc;
4
5/// Names one continuous stream at a path.
6///
7/// Within an identity, group keys never restart and never name two different groups,
8/// so a reader continues across every route that shares it. Different identities are
9/// independent streams, never stitched together.
10///
11/// Two identities are equal only when both their text and whether they were
12/// [minted](Identity::is_minted) match, so a named identity never matches a minted one.
13#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct Identity {
15	text: Arc<str>,
16	minted: bool,
17}
18
19/// The identity is empty or longer than 256 UTF-8 bytes.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
21#[error("invalid identity: {0}")]
22#[non_exhaustive]
23pub struct InvalidIdentity(&'static str);
24
25/// The most UTF-8 bytes an identity holds: room for a public key in any common text encoding
26/// (hex, base64url, `did:key`, or a JWK) while bounding what a claim makes a relay hold.
27pub(crate) const MAX_LEN: usize = 256;
28
29impl Identity {
30	/// A fresh random identity, for a new stream.
31	pub fn random() -> Self {
32		Self::named(random().into())
33	}
34
35	fn named(text: Arc<str>) -> Self {
36		Self { text, minted: false }
37	}
38
39	/// A fresh identity a session mints for a route its wire delivered without one.
40	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
41	pub(crate) fn minted() -> Self {
42		Self {
43			text: random().into(),
44			minted: true,
45		}
46	}
47
48	/// An identity a lite-07 peer carried, keeping whether a session minted it.
49	pub(crate) fn decoded(text: &str, minted: bool) -> Result<Self, InvalidIdentity> {
50		Ok(Self {
51			minted,
52			..text.parse()?
53		})
54	}
55
56	/// The identity's text, which alone does not tell a minted identity from a named one.
57	pub fn as_str(&self) -> &str {
58		&self.text
59	}
60
61	/// Whether a session minted this identity, for a route whose wire (an older moq-lite, or
62	/// moq-transport) carries none. It names the announcement rather than the publisher's
63	/// stream, so it can neither match nor contradict an identity the publisher named. Hops
64	/// that forward it keep the flag, and only a session sets it: parsing text never builds a
65	/// minted identity.
66	pub fn is_minted(&self) -> bool {
67		self.minted
68	}
69}
70
71/// 128 random bits as hex, from the ambient generator so a simulated run replays them.
72fn random() -> String {
73	use rand::RngExt;
74	format!("{:032x}", kio::clock::rng().random::<u128>())
75}
76
77impl FromStr for Identity {
78	type Err = InvalidIdentity;
79
80	fn from_str(text: &str) -> Result<Self, Self::Err> {
81		check(text)?;
82		Ok(Self::named(text.into()))
83	}
84}
85
86/// Refuse an empty identity, or one longer than [`MAX_LEN`] bytes.
87fn check(text: &str) -> Result<(), InvalidIdentity> {
88	match text.len() {
89		0 => Err(InvalidIdentity("empty")),
90		len if len > MAX_LEN => Err(InvalidIdentity("longer than 256 bytes")),
91		_ => Ok(()),
92	}
93}
94
95impl TryFrom<String> for Identity {
96	type Error = InvalidIdentity;
97
98	fn try_from(text: String) -> Result<Self, Self::Error> {
99		check(&text)?;
100		Ok(Self::named(text.into()))
101	}
102}
103
104impl fmt::Debug for Identity {
105	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106		let mut debug = f.debug_tuple("Identity");
107		debug.field(&self.as_str());
108		if self.minted {
109			debug.field(&"minted");
110		}
111		debug.finish()
112	}
113}
114
115impl fmt::Display for Identity {
116	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117		f.write_str(self.as_str())
118	}
119}
120
121impl AsRef<str> for Identity {
122	fn as_ref(&self) -> &str {
123		self.as_str()
124	}
125}
126
127#[cfg(test)]
128mod tests {
129	use super::*;
130
131	#[test]
132	fn random_is_fresh_and_round_trips() {
133		let identity = Identity::random();
134		assert_ne!(identity, Identity::random());
135		assert_eq!(identity.as_str().parse::<Identity>().unwrap(), identity);
136		assert!("".parse::<Identity>().is_err());
137		assert!(!identity.is_minted());
138	}
139
140	#[test]
141	fn text_never_builds_a_minted_identity() {
142		let minted = Identity::minted();
143		assert!(minted.is_minted());
144		let named: Identity = minted.as_str().parse().unwrap();
145		assert!(!named.is_minted());
146		assert_ne!(named, minted, "the same text, named, is another identity");
147		assert!(!"~tilde".parse::<Identity>().unwrap().is_minted());
148		assert_eq!(Identity::decoded(minted.as_str(), true).unwrap(), minted);
149		assert!(Identity::decoded("", true).is_err());
150	}
151
152	#[test]
153	fn caps_at_256_utf8_bytes() {
154		let full = "é".repeat(128);
155		assert_eq!(full.parse::<Identity>().unwrap().as_str(), full);
156		assert!(format!("{full}a").parse::<Identity>().is_err());
157		assert!(Identity::try_from(format!("{full}a")).is_err());
158		assert!(Identity::decoded(&format!("{full}a"), true).is_err());
159	}
160}