moq-token 0.7.0

Media over QUIC - Token Generation and Validation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
use crate::path;
use serde::{Deserialize, Serialize};
use serde_with::{OneOrMany, TimestampSeconds, formats::PreferMany, serde_as};

/// The immutable ceiling on what a key may grant, embedded in its JWK.
///
/// Paths in `publish` and `subscribe` are relative to `root`, matching token claim
/// semantics. A key signs a token only when every path the token grants sits at or
/// beneath one the scope allows, in the same role; see [`allows`](Self::allows).
///
/// The scope is fixed at key generation. Widening it means minting a new key, which
/// is the point: a leaked scoped key can never be talked into signing more than it
/// already could. A key with no scope at all is unrestricted, so keys minted before
/// scopes existed keep working.
#[derive(Debug, Serialize, Deserialize, Default, Clone, PartialEq, Eq)]
pub struct Scope {
	/// The root for the publish/subscribe prefixes below.
	#[serde(default, skip_serializing_if = "String::is_empty")]
	pub root: String,

	/// Prefixes this key may grant to publishers.
	#[serde(default, rename = "put", skip_serializing_if = "Vec::is_empty")]
	pub publish: Vec<String>,

	/// Prefixes this key may grant to subscribers.
	#[serde(default, rename = "get", skip_serializing_if = "Vec::is_empty")]
	pub subscribe: Vec<String>,
}

impl Scope {
	/// Returns an error when the scope permits nothing, making the key unusable.
	pub fn validate(&self) -> crate::Result<()> {
		if self.publish.is_empty() && self.subscribe.is_empty() {
			return Err(crate::Error::UselessScope);
		}

		Ok(())
	}

	/// Whether every path `claims` grants is covered by this scope, per role.
	///
	/// Both sides are resolved against their own root before comparing, so the same
	/// grant expressed as `root: "demo"` + `put: ["room"]` or as `put: ["demo/room"]`
	/// is treated identically. Matching is segment-aware, so a scope of `live` does
	/// not cover `lively`, and the roles are checked independently: a publish-only
	/// scope never authorizes a subscribe grant.
	///
	/// An empty prefix covers everything beneath the scope root, so a scope of
	/// `root: "demo"` + `put: [""]` grants publish anywhere under `demo`.
	pub fn allows(&self, claims: &Claims) -> bool {
		covers(&self.root, &self.publish, &claims.root, &claims.publish)
			&& covers(&self.root, &self.subscribe, &claims.root, &claims.subscribe)
	}
}

/// Whether every `requested` path (relative to `claims_root`) sits beneath some
/// `granted` prefix (relative to `scope_root`).
///
/// An empty `granted` denies everything, which is what makes a publish-only scope
/// reject subscribe grants rather than ignoring them.
fn covers(scope_root: &str, granted: &[String], claims_root: &str, requested: &[String]) -> bool {
	let absolute = |root: &str, relative: &str| path::join(&path::normalize(root), &path::normalize(relative));

	requested.iter().all(|request| {
		let request = absolute(claims_root, request);
		granted
			.iter()
			.any(|grant| path::has_prefix(&request, &absolute(scope_root, grant)))
	})
}

/// The access a [`Claims`] grants at a specific path, with every prefix rebased so
/// it is relative to that path.
///
/// Produced by [`Claims::authorize`]. An empty string grants the path itself and
/// everything beneath it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Permissions {
	/// Paths the holder may subscribe to, relative to the authorized path.
	pub subscribe: Vec<String>,

	/// Paths the holder may publish to, relative to the authorized path.
	pub publish: Vec<String>,
}

/// The payload of a token: a root, plus the publish/subscribe prefixes granted beneath it.
///
/// Build one from [`Default`] with the `with_*` setters, sign it with
/// [`Key::sign`](crate::Key::sign), and scope it to a connection with
/// [`authorize`](Self::authorize).
///
/// ```no_run
/// let claims = moq_token::Claims::default()
///     .with_root("room/123")
///     .with_publish(["alice"])
///     .with_subscribe([""]);
/// ```
#[serde_with::skip_serializing_none]
#[serde_as]
#[derive(Debug, Serialize, Deserialize, Default, Clone)]
#[serde(default)]
#[non_exhaustive]
pub struct Claims {
	/// The root for the publish/subscribe options below.
	/// It's mostly for compression and is optional, defaulting to the empty string.
	#[serde(default, rename = "root", skip_serializing_if = "String::is_empty")]
	pub root: String,

	/// If specified, the user can publish any matching broadcasts.
	/// If not specified, the user will not publish any broadcasts.
	#[serde(default, rename = "put", skip_serializing_if = "Vec::is_empty")]
	#[serde_as(as = "OneOrMany<_, PreferMany>")]
	pub publish: Vec<String>,

	/// If specified, the user can subscribe to any matching broadcasts.
	/// If not specified, the user will not receive announcements and cannot subscribe to any broadcasts.
	// NOTE: This can't be renamed to "sub" because that's a reserved JWT field.
	#[serde(default, rename = "get", skip_serializing_if = "Vec::is_empty")]
	#[serde_as(as = "OneOrMany<_, PreferMany>")]
	pub subscribe: Vec<String>,

	/// The expiration time of the token as a unix timestamp.
	#[serde(rename = "exp")]
	#[serde_as(as = "Option<TimestampSeconds<i64>>")]
	pub expires: Option<std::time::SystemTime>,

	/// The issued time of the token as a unix timestamp.
	#[serde(rename = "iat")]
	#[serde_as(as = "Option<TimestampSeconds<i64>>")]
	pub issued: Option<std::time::SystemTime>,
}

impl Claims {
	/// Set the root that the publish/subscribe prefixes are relative to.
	pub fn with_root(mut self, root: impl Into<String>) -> Self {
		self.root = root.into();
		self
	}

	/// Grant publish access to these prefixes, relative to the root.
	pub fn with_publish(mut self, paths: impl IntoIterator<Item = impl Into<String>>) -> Self {
		self.publish = paths.into_iter().map(Into::into).collect();
		self
	}

	/// Grant subscribe access to these prefixes, relative to the root.
	pub fn with_subscribe(mut self, paths: impl IntoIterator<Item = impl Into<String>>) -> Self {
		self.subscribe = paths.into_iter().map(Into::into).collect();
		self
	}

	/// Expire the token at this time. Enforced by [`Key::verify`](crate::Key::verify).
	///
	/// Accepts an `Option` so a caller can pass one through without unwrapping it.
	pub fn with_expires(mut self, at: impl Into<Option<std::time::SystemTime>>) -> Self {
		self.expires = at.into();
		self
	}

	/// Record when the token was issued. Purely informational; nothing enforces it.
	///
	/// Accepts an `Option` so a caller can pass one through without unwrapping it.
	pub fn with_issued(mut self, at: impl Into<Option<std::time::SystemTime>>) -> Self {
		self.issued = at.into();
		self
	}

	/// Returns an error when the token grants nothing at all, making it useless.
	pub fn validate(&self) -> crate::Result<()> {
		if self.publish.is_empty() && self.subscribe.is_empty() {
			return Err(crate::Error::UselessToken);
		}

		Ok(())
	}

	/// The access these claims grant at `path`, rebased so each returned prefix is
	/// relative to `path`.
	///
	/// `path` and [`root`](Self::root) must overlap, in either direction:
	///
	/// - `path` extends the root (root `demo`, path `demo/room`), so the extra
	///   `room` narrows each prefix and drops the ones outside it.
	/// - `path` is a parent of the root (root `demo`, path ``), so `demo` is
	///   prepended to each prefix to keep it anchored where the token points.
	///
	/// Matching is segment-aware, so a root of `foo` does not cover `foobar`.
	/// Slashes at the boundaries are implicit: `/demo/` and `demo` are the same path.
	///
	/// Returns [`Error::RootMismatch`](crate::Error::RootMismatch) when the two don't
	/// overlap, and [`Error::NoAccess`](crate::Error::NoAccess) when they do but every
	/// prefix falls outside `path`.
	///
	/// This is authorization only. Verify the signature first with
	/// [`Key::verify`](crate::Key::verify), which is where expiry is enforced.
	pub fn authorize(&self, path: &str) -> crate::Result<Permissions> {
		let path = path::normalize(path);
		let root = path::normalize(&self.root);

		// Exactly one of these is non-empty: `suffix` is how far the path reaches
		// past the root, `prefix` is how far the root reaches past the path.
		let (suffix, prefix) = if let Some(suffix) = path::strip_prefix(&path, &root) {
			(suffix, "")
		} else if let Some(prefix) = path::strip_prefix(&root, &path) {
			("", prefix)
		} else {
			return Err(crate::Error::RootMismatch(path));
		};

		let scope = |paths: &[String]| -> Vec<String> {
			paths
				.iter()
				.filter_map(|granted| {
					let granted = path::join(prefix, &path::normalize(granted));

					if let Some(remaining) = path::strip_prefix(&granted, suffix) {
						// The grant covers the path; keep what's left below it.
						Some(remaining.to_string())
					} else if path::has_prefix(suffix, &granted) {
						// The grant stops short of the path but still contains it,
						// so everything below the path is granted.
						Some(String::new())
					} else {
						None
					}
				})
				.collect()
		};

		let permissions = Permissions {
			subscribe: scope(&self.subscribe),
			publish: scope(&self.publish),
		};

		if permissions.subscribe.is_empty() && permissions.publish.is_empty() {
			return Err(crate::Error::NoAccess(path));
		}

		Ok(permissions)
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	use std::time::{Duration, SystemTime};

	fn create_test_claims() -> Claims {
		Claims {
			root: "test-path".to_string(),
			publish: vec!["test-pub".into()],
			subscribe: vec!["test-sub".into()],
			expires: Some(SystemTime::now() + Duration::from_secs(3600)),
			issued: Some(SystemTime::now()),
		}
	}

	#[test]
	fn scope_allows_contained_claims() {
		let scope = Scope {
			root: "project".into(),
			publish: vec!["live".into()],
			subscribe: vec!["watch".into()],
		};
		let claims = Claims {
			root: "project/live/room".into(),
			publish: vec!["".into()],
			subscribe: vec![],
			..Default::default()
		};
		assert!(scope.allows(&claims));
	}

	#[test]
	fn scope_rejects_sibling_and_role_escalation() {
		let scope = Scope {
			root: "project".into(),
			publish: vec!["live".into()],
			subscribe: vec![],
		};
		let sibling = Claims {
			root: "project/lively".into(),
			publish: vec!["".into()],
			..Default::default()
		};
		let role = Claims {
			root: "project/live".into(),
			subscribe: vec!["".into()],
			..Default::default()
		};
		assert!(!scope.allows(&sibling));
		assert!(!scope.allows(&role));
	}

	#[test]
	fn scope_ignores_how_the_root_is_split() {
		// The same grant, expressed three ways, must compare identically.
		let scope = Scope {
			root: "project".into(),
			publish: vec!["live".into()],
			subscribe: vec![],
		};

		for claims in [
			Claims {
				root: "project".into(),
				publish: vec!["live/room".into()],
				..Default::default()
			},
			Claims {
				root: String::new(),
				publish: vec!["project/live/room".into()],
				..Default::default()
			},
			Claims {
				root: "/project/live/".into(),
				publish: vec!["/room".into()],
				..Default::default()
			},
		] {
			assert!(scope.allows(&claims), "{claims:?}");
		}
	}

	#[test]
	fn scope_rejects_escaping_above_its_root() {
		let scope = Scope {
			root: "project".into(),
			publish: vec!["live".into()],
			subscribe: vec![],
		};

		// A root above the scope's does not widen it, even though the empty prefix
		// would grant everything within the scope.
		let claims = Claims {
			root: String::new(),
			publish: vec!["".into()],
			..Default::default()
		};
		assert!(!scope.allows(&claims));
	}

	#[test]
	fn scope_empty_prefix_grants_everything_beneath_it() {
		let scope = Scope {
			root: "project".into(),
			publish: vec![String::new()],
			subscribe: vec![],
		};
		let claims = Claims {
			root: "project/anything/deep".into(),
			publish: vec!["".into()],
			..Default::default()
		};
		assert!(scope.allows(&claims));
	}

	#[test]
	fn scope_requires_every_requested_path() {
		// One allowed path does not carry an unallowed sibling along with it.
		let scope = Scope {
			root: "project".into(),
			publish: vec!["live".into()],
			subscribe: vec![],
		};
		let claims = Claims {
			root: "project".into(),
			publish: vec!["live/room".into(), "other".into()],
			..Default::default()
		};
		assert!(!scope.allows(&claims));
	}

	#[test]
	fn scope_without_grants_is_useless() {
		assert!(matches!(Scope::default().validate(), Err(crate::Error::UselessScope)));
	}

	#[test]
	fn test_claims_validation_success() {
		let claims = create_test_claims();
		assert!(claims.validate().is_ok());
	}

	#[test]
	fn test_claims_validation_no_publish_or_subscribe() {
		let claims = Claims {
			root: "test-path".to_string(),
			publish: vec![],
			subscribe: vec![],
			expires: None,
			issued: None,
		};

		let result = claims.validate();
		assert!(result.is_err());
		assert!(
			result
				.unwrap_err()
				.to_string()
				.contains("no publish or subscribe allowed; token is useless")
		);
	}

	#[test]
	fn test_claims_validation_only_publish() {
		let claims = Claims {
			root: "test-path".to_string(),
			publish: vec!["test-pub".into()],
			subscribe: vec![],
			expires: None,
			issued: None,
		};

		assert!(claims.validate().is_ok());
	}

	#[test]
	fn test_claims_validation_only_subscribe() {
		let claims = Claims {
			root: "test-path".to_string(),
			publish: vec![],
			subscribe: vec!["test-sub".into()],
			expires: None,
			issued: None,
		};

		assert!(claims.validate().is_ok());
	}

	#[test]
	fn test_claims_validation_path_not_prefix_relative_publish() {
		let claims = Claims {
			root: "test-path".to_string(),        // no trailing slash
			publish: vec!["relative-pub".into()], // relative path without leading slash
			subscribe: vec![],
			expires: None,
			issued: None,
		};

		let result = claims.validate();
		assert!(result.is_ok()); // Now passes because slashes are implicitly added
	}

	#[test]
	fn test_claims_validation_path_not_prefix_relative_subscribe() {
		let claims = Claims {
			root: "test-path".to_string(), // no trailing slash
			publish: vec![],
			subscribe: vec!["relative-sub".into()], // relative path without leading slash
			expires: None,
			issued: None,
		};

		let result = claims.validate();
		assert!(result.is_ok()); // Now passes because slashes are implicitly added
	}

	#[test]
	fn test_claims_validation_path_not_prefix_absolute_publish() {
		let claims = Claims {
			root: "test-path".to_string(),         // no trailing slash
			publish: vec!["/absolute-pub".into()], // absolute path with leading slash
			subscribe: vec![],
			expires: None,
			issued: None,
		};

		assert!(claims.validate().is_ok());
	}

	#[test]
	fn test_claims_validation_path_not_prefix_absolute_subscribe() {
		let claims = Claims {
			root: "test-path".to_string(), // no trailing slash
			publish: vec![],
			subscribe: vec!["/absolute-sub".into()], // absolute path with leading slash
			expires: None,
			issued: None,
		};

		assert!(claims.validate().is_ok());
	}

	#[test]
	fn test_claims_validation_path_not_prefix_empty_publish() {
		let claims = Claims {
			root: "test-path".to_string(), // no trailing slash
			publish: vec!["".into()],      // empty string
			subscribe: vec![],
			expires: None,
			issued: None,
		};

		assert!(claims.validate().is_ok());
	}

	#[test]
	fn test_claims_validation_path_not_prefix_empty_subscribe() {
		let claims = Claims {
			root: "test-path".to_string(), // no trailing slash
			publish: vec![],
			subscribe: vec!["".into()], // empty string
			expires: None,
			issued: None,
		};

		assert!(claims.validate().is_ok());
	}

	#[test]
	fn test_claims_validation_path_is_prefix() {
		let claims = Claims {
			root: "test-path".to_string(),          // with trailing slash
			publish: vec!["relative-pub".into()],   // relative path is ok when path is prefix
			subscribe: vec!["relative-sub".into()], // relative path is ok when path is prefix
			expires: None,
			issued: None,
		};

		assert!(claims.validate().is_ok());
	}

	#[test]
	fn test_claims_validation_empty_path() {
		let claims = Claims {
			root: "".to_string(), // empty path
			publish: vec!["test-pub".into()],
			subscribe: vec![],
			expires: None,
			issued: None,
		};

		assert!(claims.validate().is_ok());
	}

	#[test]
	fn test_claims_serde() {
		let claims = create_test_claims();
		let json = serde_json::to_string(&claims).unwrap();
		let deserialized: Claims = serde_json::from_str(&json).unwrap();

		assert_eq!(deserialized.root, claims.root);
		assert_eq!(deserialized.publish, claims.publish);
		assert_eq!(deserialized.subscribe, claims.subscribe);
	}

	#[test]
	fn test_claims_default() {
		let claims = Claims::default();
		assert_eq!(claims.root, "");
		assert!(claims.publish.is_empty());
		assert!(claims.subscribe.is_empty());
		assert_eq!(claims.expires, None);
		assert_eq!(claims.issued, None);
	}

	fn authorize_claims(root: &str, subscribe: &[&str], publish: &[&str]) -> Claims {
		Claims {
			root: root.to_string(),
			subscribe: subscribe.iter().map(|s| s.to_string()).collect(),
			publish: publish.iter().map(|s| s.to_string()).collect(),
			..Default::default()
		}
	}

	#[test]
	fn test_authorize_path_equals_root() {
		let claims = authorize_claims("room/123", &[""], &["alice"]);
		let permissions = claims.authorize("room/123").unwrap();

		assert_eq!(permissions.subscribe, [""]);
		assert_eq!(permissions.publish, ["alice"]);
	}

	#[test]
	fn test_authorize_path_extends_root() {
		// Connecting below the root consumes the matching part of each grant.
		let claims = authorize_claims("room/123", &["bob"], &["alice"]);
		let permissions = claims.authorize("room/123/alice").unwrap();

		assert_eq!(permissions.subscribe, Vec::<String>::new());
		assert_eq!(permissions.publish, [""]);
	}

	#[test]
	fn test_authorize_path_is_parent_of_root() {
		// Connecting above the root prepends it, keeping the grants anchored.
		let claims = authorize_claims("demo", &[""], &["alice"]);
		let permissions = claims.authorize("/").unwrap();

		assert_eq!(permissions.subscribe, ["demo"]);
		assert_eq!(permissions.publish, ["demo/alice"]);
	}

	#[test]
	fn test_authorize_empty_root() {
		// A root-scoped token grants everything it lists, wherever it connects.
		let claims = authorize_claims("", &["demo"], &[]);
		let permissions = claims.authorize("demo/room").unwrap();

		assert_eq!(permissions.subscribe, [""]);
		assert_eq!(permissions.publish, Vec::<String>::new());
	}

	#[test]
	fn test_authorize_slashes_are_implicit() {
		let claims = authorize_claims("/room/123/", &["/bob/"], &[]);
		let permissions = claims.authorize("//room/123//").unwrap();

		assert_eq!(permissions.subscribe, ["bob"]);
	}

	#[test]
	fn test_authorize_respects_segment_boundaries() {
		// "foo" must not cover "foobar".
		let claims = authorize_claims("foo", &[""], &[""]);
		assert!(matches!(claims.authorize("foobar"), Err(crate::Error::RootMismatch(_))));
	}

	#[test]
	fn test_authorize_unrelated_path() {
		let claims = authorize_claims("demo", &[""], &[""]);
		assert!(matches!(claims.authorize("other"), Err(crate::Error::RootMismatch(_))));
	}

	#[test]
	fn test_authorize_no_access_at_path() {
		// The path overlaps the root, but every grant sits outside it.
		let claims = authorize_claims("", &["demo"], &[]);
		assert!(matches!(claims.authorize("other"), Err(crate::Error::NoAccess(_))));
	}

	#[test]
	fn test_deserialize_string_as_vec() {
		let json = r#"{
			"root": "test",
			"put": "single-publish",
			"get": "single-subscribe"
		}"#;

		let claims: Claims = serde_json::from_str(json).unwrap();
		assert_eq!(claims.publish, vec!["single-publish"]);
		assert_eq!(claims.subscribe, vec!["single-subscribe"]);
	}

	#[test]
	fn test_deserialize_vec_as_vec() {
		let json = r#"{
			"root": "test",
			"put": ["pub1", "pub2"],
			"get": ["sub1", "sub2"]
		}"#;

		let claims: Claims = serde_json::from_str(json).unwrap();
		assert_eq!(claims.publish, vec!["pub1", "pub2"]);
		assert_eq!(claims.subscribe, vec!["sub1", "sub2"]);
	}

	#[test]
	fn test_deserialize_mixed() {
		let json = r#"{
			"root": "test",
			"put": "single",
			"get": ["multi1", "multi2"]
		}"#;

		let claims: Claims = serde_json::from_str(json).unwrap();
		assert_eq!(claims.publish, vec!["single"]);
		assert_eq!(claims.subscribe, vec!["multi1", "multi2"]);
	}
}