1use std::{
38 collections::{BTreeMap, VecDeque},
39 task::Poll,
40 time::Duration,
41};
42
43use bytes::Bytes;
44
45use crate::{Error, Prefixes, Result, SessionError, time::Instant};
46
47mod tokens;
48
49pub(crate) use tokens::{Dial, locate};
50pub use tokens::{EmptyToken, Token, Tokens};
51
52pub(crate) fn protocol_error(err: Error) -> Error {
54 match err {
55 Error::Decode(_)
56 | Error::BoundsExceeded(_)
57 | Error::WrongSize
58 | Error::UnexpectedMessage
59 | Error::UnexpectedStream => Error::ProtocolViolation,
60 err => err,
61 }
62}
63
64macro_rules! ready_or {
66 ($e:expr) => {
67 match $e {
68 Poll::Ready(guard) => guard,
69 Poll::Pending => return Poll::Pending,
70 }
71 };
72}
73
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub(crate) enum Answer {
77 Granted,
79 Requests,
81}
82
83#[derive(Clone, Debug, Default, PartialEq, Eq)]
90#[non_exhaustive]
91pub struct Grant {
92 pub publish: Prefixes,
94 pub subscribe: Prefixes,
96 pub expires: Option<Instant>,
98}
99
100impl Grant {
101 pub fn all() -> Self {
103 Self {
104 publish: Prefixes::all(),
105 subscribe: Prefixes::all(),
106 expires: None,
107 }
108 }
109
110 fn union<'a>(grants: impl IntoIterator<Item = &'a Self>) -> Self {
113 let mut publish = Vec::new();
114 let mut subscribe = Vec::new();
115 let mut expires = None;
116 for grant in grants {
117 publish.extend(grant.publish.iter().cloned());
118 subscribe.extend(grant.subscribe.iter().cloned());
119 expires = earliest(expires, grant.expires);
120 }
121 Self {
122 publish: publish.into_iter().collect(),
123 subscribe: subscribe.into_iter().collect(),
124 expires,
125 }
126 }
127
128 fn intersect(&self, other: &Self) -> Self {
130 Self {
131 publish: self.publish.intersect(&other.publish),
132 subscribe: self.subscribe.intersect(&other.subscribe),
133 expires: earliest(self.expires, other.expires),
134 }
135 }
136}
137
138fn earliest(a: Option<Instant>, b: Option<Instant>) -> Option<Instant> {
140 match (a, b) {
141 (Some(a), Some(b)) => Some(a.min(b)),
142 (a, b) => a.or(b),
143 }
144}
145
146pub(crate) const RETRY_INITIAL: Duration = Duration::from_secs(1);
150const RETRY_MAX: Duration = Duration::from_secs(30);
151
152fn verdict(phase: &Phase, err: &Error) -> bool {
156 matches!(phase, Phase::Refused { undecided: false, .. })
157 || matches!(err, Error::Unsupported)
158 || (matches!(err, Error::Cancel) && matches!(phase, Phase::Granted(_)))
160}
161
162#[derive(Default)]
165pub(crate) struct State {
166 bound: bool,
168 closed: Option<Error>,
170 next_id: u64,
171 tokens: BTreeMap<u64, Entry>,
173 next_link: u64,
174 links: BTreeMap<u64, Box<Attached>>,
177 limit: Option<Grant>,
181 next_issue: u64,
182 acceptor: Acceptor,
183 configured: Option<tokens::Configured>,
185}
186
187struct Entry {
189 value: Bytes,
190 answered: Option<Result<Answer>>,
192 ended: Option<Error>,
194}
195
196struct Attached {
198 supported: bool,
200 requests: bool,
203 closed: Option<Error>,
205 cut: Vec<u64>,
207 goaway: Option<std::sync::Arc<crate::goaway::Handle>>,
209 slots: BTreeMap<u64, Slot>,
211 opening: VecDeque<u64>,
213 union: Option<Grant>,
215 replied: bool,
217 issued: BTreeMap<u64, Grant>,
220 scope: Option<Grant>,
223 epoch: u64,
226 acceptance: Acceptance,
230}
231
232#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234enum Acceptance {
235 Accepted,
237 Awaiting,
240 Silent,
243}
244
245struct Slot {
247 token: Bytes,
248 setup: bool,
250 phase: Phase,
251}
252
253enum Phase {
256 Queued { backoff: Option<Duration> },
258 Pending { backoff: Option<Duration> },
260 Granted(Grant),
262 Refused { backoff: Option<Duration>, undecided: bool },
266 Withdrawn { grant: Option<Grant> },
269 Requests,
271 Ended(Error),
273}
274
275impl Phase {
276 fn grant(&self) -> Option<&Grant> {
278 match self {
279 Self::Granted(grant) | Self::Withdrawn { grant: Some(grant) } => Some(grant),
280 _ => None,
281 }
282 }
283
284 fn answered(&self) -> bool {
286 !matches!(
287 self,
288 Self::Queued { .. } | Self::Pending { .. } | Self::Refused { .. } | Self::Withdrawn { grant: None }
289 )
290 }
291
292 fn ended(&self) -> Option<&Error> {
294 match self {
295 Self::Ended(err) => Some(err),
296 _ => None,
297 }
298 }
299
300 fn live(&self) -> bool {
302 !matches!(self, Self::Withdrawn { .. } | Self::Ended(_))
303 }
304}
305
306#[derive(Default)]
308enum Acceptor {
309 #[default]
311 Undecided,
312 App(Pending),
314 Default,
316}
317
318impl Attached {
319 fn new(supported: bool, requests: bool, limit: Option<&Grant>) -> Self {
320 let mut attached = Self {
321 supported,
322 requests,
323 closed: None,
324 cut: Vec::new(),
325 goaway: None,
326 slots: BTreeMap::new(),
327 opening: VecDeque::new(),
328 union: None,
329 replied: false,
330 issued: BTreeMap::new(),
331 scope: None,
332 epoch: 0,
333 acceptance: Acceptance::Accepted,
334 };
335 attached.rescope(limit);
336 attached
337 }
338
339 fn active(&self) -> bool {
341 self.closed.is_none() && !self.goaway.as_ref().is_some_and(|goaway| goaway.draining())
342 }
343
344 fn offer(&mut self, id: u64, token: &Bytes) -> Option<Result<()>> {
351 if !self.active() {
352 return None;
353 }
354 let (phase, answered) = match (self.supported, self.requests) {
355 (true, _) => (Phase::Queued { backoff: None }, None),
356 (false, true) => (Phase::Requests, Some(Ok(()))),
357 (false, false) => (Phase::Ended(Error::Unsupported), Some(Err(Error::Unsupported))),
358 };
359 self.slots.insert(
360 id,
361 Slot {
362 token: token.clone(),
363 setup: false,
364 phase,
365 },
366 );
367 if self.supported {
368 self.opening.push_back(id);
369 }
370 answered
371 }
372
373 fn end(&mut self, id: u64, err: &Error) {
375 let Some(slot) = self.slots.get_mut(&id) else {
376 return;
377 };
378 match slot.phase {
379 Phase::Ended(_) => return,
380 Phase::Withdrawn { .. } => {
382 self.slots.remove(&id);
383 }
384 _ => slot.phase = Phase::Ended(err.clone()),
385 }
386 self.epoch += 1;
387 self.recompute();
388 }
389
390 fn withdraw(&mut self, id: u64) {
392 let Some(slot) = self.slots.get_mut(&id) else {
393 return;
394 };
395 slot.phase = match &mut slot.phase {
396 Phase::Pending { .. } | Phase::Refused { .. } => Phase::Withdrawn { grant: None },
398 Phase::Granted(grant) => Phase::Withdrawn {
399 grant: Some(std::mem::take(grant)),
400 },
401 Phase::Withdrawn { .. } => return,
402 Phase::Queued { .. } | Phase::Requests | Phase::Ended(_) => {
404 self.opening.retain(|opening| *opening != id);
405 self.slots.remove(&id);
406 self.recompute();
407 return;
408 }
409 };
410 }
411
412 fn recompute(&mut self) {
413 let mut granted = self.slots.values().filter_map(|slot| slot.phase.grant()).peekable();
414 if granted.peek().is_none() && !self.replied {
415 return;
416 }
417 let union = Grant::union(granted);
418 if self.union.as_ref() != Some(&union) {
419 self.union = Some(union);
420 self.epoch += 1;
421 }
422 }
423
424 fn rescope(&mut self, limit: Option<&Grant>) {
426 let scope = limit.map(|limit| Grant::union(std::iter::once(limit).chain(self.issued.values())));
427 if self.scope != scope {
428 self.scope = scope;
429 self.epoch += 1;
430 }
431 }
432
433 fn parts(&self, direction: Direction) -> (Option<&Prefixes>, Option<&Prefixes>) {
436 match direction {
439 Direction::Publish => (
440 self.union.as_ref().map(|union| &union.publish),
441 self.scope.as_ref().map(|scope| &scope.subscribe),
442 ),
443 Direction::Subscribe => (
444 self.union.as_ref().map(|union| &union.subscribe),
445 self.scope.as_ref().map(|scope| &scope.publish),
446 ),
447 }
448 }
449
450 fn permit(&self, direction: Direction) -> Permit {
452 let (granted, limit) = self.parts(direction);
453 Permit {
454 granted: granted.cloned(),
455 limit: limit.cloned(),
456 }
457 }
458
459 fn allows(&self, direction: Direction, path: &str) -> bool {
461 let (granted, limit) = self.parts(direction);
462 granted.is_none_or(|granted| granted.matches(path)) && limit.is_none_or(|limit| limit.matches(path))
463 }
464}
465
466impl State {
467 fn live(&self) -> Option<&Attached> {
469 self.links
470 .values()
471 .rev()
472 .map(|link| &**link)
473 .find(|link| link.closed.is_none())
474 }
475
476 fn answer(&mut self, id: u64, answer: Result<Answer>) {
479 match answer {
480 Ok(answer) => {
481 if let Some(token) = self.tokens.get_mut(&id) {
482 token.answered.get_or_insert(Ok(answer));
483 }
484 if answer == Answer::Requests {
485 self.unsupported(id);
486 }
487 self.settle();
488 }
489 Err(err) => self.end_token(id, err),
490 }
491 }
492
493 fn end_token(&mut self, id: u64, err: Error) {
495 let Some(token) = self.tokens.get_mut(&id) else {
496 return;
497 };
498 if token.ended.is_some() {
499 return;
500 }
501 token.answered.get_or_insert(Err(err.clone()));
502 token.ended = Some(err.clone());
503 for link in self.links.values_mut() {
504 link.end(id, &err);
505 }
506 if self.closed.is_none() && self.configured(id) {
507 match err {
508 Error::Unsupported => self.unsupported(id),
509 err => tracing::warn!(%err, "a configured token was refused"),
510 }
511 }
512 self.settle();
513 }
514
515 fn present(&mut self, token: Bytes) -> u64 {
517 let id = self.next_id;
518 self.next_id += 1;
519 self.tokens.insert(
520 id,
521 Entry {
522 value: token.clone(),
523 answered: None,
524 ended: None,
525 },
526 );
527 let answers: Vec<_> = self
528 .links
529 .values_mut()
530 .filter_map(|link| link.offer(id, &token))
531 .collect();
532 for answer in answers {
533 self.answer(id, answer.map(|()| Answer::Requests));
534 }
535 id
536 }
537
538 fn withdraw(&mut self, id: u64) {
540 self.tokens.remove(&id);
541 for link in self.links.values_mut() {
542 link.withdraw(id);
543 }
544 }
545
546 fn abort(&mut self, err: Error) -> Option<Pending> {
549 if self.closed.is_some() {
550 return None;
551 }
552 self.record();
553 self.closed = Some(err.clone());
554 let ids: Vec<u64> = self.tokens.keys().copied().collect();
555 for id in ids {
556 self.end_token(id, err.clone());
557 }
558 match &self.acceptor {
559 Acceptor::App(queue) => Some(queue.clone()),
560 _ => None,
561 }
562 }
563}
564
565#[derive(Clone, Debug, Default, PartialEq, Eq)]
569pub(crate) struct Permit {
570 granted: Option<Prefixes>,
571 limit: Option<Prefixes>,
572}
573
574impl Permit {
575 #[cfg(test)]
577 pub(crate) fn limited(limit: Prefixes) -> Self {
578 Self {
579 granted: None,
580 limit: Some(limit),
581 }
582 }
583
584 #[cfg(test)]
586 pub(crate) fn granting(granted: Prefixes) -> Self {
587 Self {
588 granted: Some(granted),
589 limit: None,
590 }
591 }
592
593 pub(crate) fn matches(&self, path: &str) -> bool {
595 self.granted(path) && self.within_limit(path)
596 }
597
598 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
600 pub(crate) fn within(&self, scope: Prefixes) -> Prefixes {
601 [&self.granted, &self.limit]
602 .into_iter()
603 .flatten()
604 .fold(scope, |scope, prefixes| scope.intersect(prefixes))
605 }
606
607 #[cfg(feature = "async")]
609 pub(crate) fn limiting(&self, scope: Prefixes) -> Prefixes {
610 match &self.limit {
611 Some(limit) => scope.intersect(limit),
612 None => scope,
613 }
614 }
615
616 pub(crate) fn granted(&self, path: &str) -> bool {
618 self.granted.as_ref().is_none_or(|granted| granted.matches(path))
619 }
620
621 pub(crate) fn within_limit(&self, path: &str) -> bool {
624 self.limit.as_ref().is_none_or(|limit| limit.matches(path))
625 }
626
627 #[cfg(feature = "async")]
631 pub(crate) fn granted_regions(&self) -> Option<Vec<crate::Path>> {
632 confining(self.granted.as_ref()?)
633 }
634
635 #[cfg(feature = "async")]
638 pub(crate) fn regions(&self) -> Option<Vec<crate::Path>> {
639 fn confines(prefixes: &Option<Prefixes>) -> Option<&Prefixes> {
642 prefixes.as_ref().filter(|prefixes| !prefixes.matches(""))
643 }
644 match (confines(&self.granted), confines(&self.limit)) {
645 (None, None) => None,
646 (Some(one), None) | (None, Some(one)) => confining(one),
647 (Some(granted), Some(limit)) => confining(&granted.intersect(limit)),
648 }
649 }
650
651 #[cfg(feature = "async")]
653 pub(crate) fn grant(&self) -> Option<&Prefixes> {
654 self.granted.as_ref()
655 }
656
657 #[cfg(feature = "async")]
660 pub(crate) fn beyond(&self, covered: Option<&Prefixes>) -> Vec<(crate::Prefix, crate::Path)> {
661 let Some(covered) = covered else {
662 return Vec::new();
663 };
664 let granted = match &self.granted {
665 Some(granted) => granted.clone(),
666 None => Prefixes::all(),
667 };
668 (granted.into_iter())
669 .filter(|prefix| !covered.matches(prefix.as_str()))
670 .filter_map(|prefix| {
671 let region = crate::Path::new(prefix.as_str()).ok()?;
673 Some((prefix, region))
674 })
675 .collect()
676 }
677
678 #[cfg(feature = "async")]
680 pub(crate) fn same_grant(&self, other: &Self) -> bool {
681 self.granted == other.granted
682 }
683
684 #[cfg(feature = "async")]
686 pub(crate) fn same_limit(&self, other: &Self) -> bool {
687 self.limit == other.limit
688 }
689
690 pub(crate) fn covers(&self, other: &Self) -> bool {
692 let covers = |this: &Option<Prefixes>, other: &Option<Prefixes>| match (this, other) {
693 (None, _) => true,
694 (Some(_), None) => false,
695 (Some(this), Some(other)) => this.covers(other),
696 };
697 covers(&self.granted, &other.granted) && covers(&self.limit, &other.limit)
698 }
699}
700
701#[cfg(feature = "async")]
704fn confining(prefixes: &Prefixes) -> Option<Vec<crate::Path>> {
705 match prefixes.matches("") {
706 true => None,
707 false => Some(
708 prefixes
709 .iter()
710 .filter_map(|prefix| crate::Path::new(prefix.as_str()).ok())
711 .collect(),
712 ),
713 }
714}
715
716#[derive(Clone, Default)]
726pub struct Handle {
727 state: kio::Shared<State>,
728}
729
730impl Handle {
731 pub fn new() -> Self {
733 Self::default()
734 }
735
736 pub fn grant(&self) -> Watch {
740 Watch::new(self.state.clone(), Selector::Union)
741 }
742
743 pub fn add(&self, token: impl Into<Bytes>) -> Result<Credential> {
755 let token = token.into();
756 let mut guard = self.state.lock();
757 let state = &mut *guard;
758 if let Some(err) = &state.closed {
759 return Err(err.clone());
760 }
761 if state.bound && !state.links.values().any(|link| link.active()) {
763 return Err(Error::GoingAway);
764 }
765 let id = state.present(token);
766 Ok(Credential {
767 presented: std::sync::Arc::new(Presented {
768 state: self.state.clone(),
769 id,
770 link: None,
771 }),
772 })
773 }
774
775 pub(crate) fn requests(&self) -> Requests {
781 let queue = Pending::default();
782 let (earlier, closed) = {
783 let mut state = self.state.lock();
784 debug_assert!(
785 !matches!(state.acceptor, Acceptor::Default),
786 "the driver already answers the peer's tokens"
787 );
788 let earlier = std::mem::replace(&mut state.acceptor, Acceptor::App(queue.clone()));
789 (earlier, state.closed.is_some())
790 };
791 if let Acceptor::App(earlier) = earlier {
793 earlier.close();
794 }
795 if closed {
796 queue.close();
797 }
798 Requests { queue }
799 }
800
801 pub fn authorize(&self, grant: &Grant) {
824 let mut guard = self.state.lock();
825 let state = &mut *guard;
826 if state.limit.as_ref() == Some(grant) {
827 return;
828 }
829 state.limit = Some(grant.clone());
830 for link in state.links.values_mut() {
831 link.epoch += 1;
832 link.rescope(state.limit.as_ref());
833 }
834 }
835
836 pub fn abort(&self, err: Error) {
840 let queue = self.state.lock().abort(err);
841 if let Some(queue) = queue {
842 queue.close();
843 }
844 }
845
846 fn acceptor(&self) -> Option<Pending> {
849 let mut state = self.state.lock();
850 match &state.acceptor {
851 Acceptor::App(queue) => Some(queue.clone()),
852 Acceptor::Default => None,
853 Acceptor::Undecided => {
854 state.acceptor = Acceptor::Default;
855 None
856 }
857 }
858 }
859}
860
861#[derive(Clone)]
866pub(crate) struct Link {
867 handle: Handle,
868 attached: std::sync::Arc<Detach>,
869}
870
871struct Detach {
873 state: kio::Shared<State>,
874 id: u64,
875 request_tokens: std::sync::Mutex<BTreeMap<Bytes, std::sync::Weak<RequestLifetime>>>,
878}
879
880impl Drop for Detach {
881 fn drop(&mut self) {
882 let queue = {
883 let mut state = self.state.lock();
884 state.record();
886 state.links.remove(&self.id);
887 match state.bound {
889 true => state.abort(Error::Cancel),
890 false => None,
891 }
892 };
893 if let Some(queue) = queue {
894 queue.close();
895 }
896 }
897}
898
899impl Link {
900 pub(crate) fn new(supported: bool) -> Self {
902 Self::bound(supported, false)
903 }
904
905 pub(crate) fn ietf() -> Self {
908 Self::bound(false, true)
909 }
910
911 fn bound(supported: bool, requests: bool) -> Self {
912 let handle = Handle {
913 state: kio::Shared::new(State {
914 bound: true,
915 ..Default::default()
916 }),
917 };
918 Self::attach(&handle, supported, requests).expect("a fresh handle backs no session")
919 }
920
921 pub(crate) fn attach(handle: &Handle, supported: bool, requests: bool) -> Result<Self> {
928 let mut guard = handle.state.lock();
929 let state = &mut *guard;
930 if let Some(err) = &state.closed {
931 return Err(err.clone());
932 }
933 if state.links.values().any(|link| link.active()) {
934 return Err(Error::Duplicate);
935 }
936 let id = state.next_link;
937 state.next_link += 1;
938 let mut link = Attached::new(supported, requests, state.limit.as_ref());
939 let answers: Vec<_> = state
940 .tokens
941 .iter()
942 .filter(|(_, token)| token.ended.is_none())
943 .filter_map(|(token_id, token)| Some((*token_id, link.offer(*token_id, &token.value)?)))
944 .collect();
945 state.links.insert(id, Box::new(link));
946 for (token_id, answer) in answers {
947 state.answer(token_id, answer.map(|()| Answer::Requests));
948 }
949 Ok(Self {
950 handle: handle.clone(),
951 attached: std::sync::Arc::new(Detach {
952 state: handle.state.clone(),
953 id,
954 request_tokens: Default::default(),
955 }),
956 })
957 }
958
959 pub(crate) fn handle(&self) -> &Handle {
961 &self.handle
962 }
963
964 fn state(&self) -> &kio::Shared<State> {
965 &self.handle.state
966 }
967
968 pub(crate) fn id(&self) -> u64 {
969 self.attached.id
970 }
971
972 fn with<R>(&self, f: impl FnOnce(&mut Attached) -> R) -> R {
974 self.with_state(|state, id| f(attached(&mut state.links, id)))
975 }
976
977 fn with_state<R>(&self, f: impl FnOnce(&mut State, u64) -> R) -> R {
979 f(&mut self.state().lock(), self.id())
980 }
981
982 fn read<R>(&self, f: impl FnOnce(&Attached, &State) -> R) -> R {
984 let state = self.state().read();
985 let link = state
986 .links
987 .get(&self.id())
988 .expect("a link outlives its session's state");
989 f(link, &state)
990 }
991
992 pub(crate) fn drain_with(&self, goaway: std::sync::Arc<crate::goaway::Handle>) {
995 self.with(|link| link.goaway = Some(goaway));
996 }
997
998 pub(crate) fn active(&self) -> bool {
1000 self.read(|link, _| link.active())
1001 }
1002
1003 pub(crate) fn present(&self, token: Bytes, setup: bool) -> Result<Credential> {
1006 if !setup {
1007 return self.handle.add(token);
1008 }
1009 let id = self.with_state(|state, link| {
1010 let id = state.next_id;
1011 let link = attached(&mut state.links, link);
1012 if !link.supported && !link.requests {
1013 return Err(Error::Unsupported);
1014 }
1015 if let Some(err) = &link.closed {
1016 return Err(err.clone());
1017 }
1018 let phase = match link.supported {
1020 true => {
1021 link.opening.push_back(id);
1022 Phase::Queued { backoff: None }
1023 }
1024 false => Phase::Requests,
1025 };
1026 link.slots.insert(
1027 id,
1028 Slot {
1029 token,
1030 setup: true,
1031 phase,
1032 },
1033 );
1034 state.next_id += 1;
1035 Ok(id)
1036 })?;
1037 Ok(Credential {
1038 presented: std::sync::Arc::new(Presented {
1039 state: self.state().clone(),
1040 id,
1041 link: Some(self.id()),
1042 }),
1043 })
1044 }
1045
1046 pub(crate) fn token(&self, auth: &Credential) -> Option<Bytes> {
1050 if !auth.presented.state.is_clone(self.state()) {
1051 return None;
1052 }
1053 self.read(|link, _| {
1054 if !link.requests {
1055 return None;
1056 }
1057 let slot = link.slots.get(&auth.presented.id)?;
1058 slot.phase.ended().is_none().then(|| slot.token.clone())
1059 })
1060 }
1061
1062 pub(crate) fn verify_request(&self, token: crate::setup::Token, hold: Option<Hold>) -> RequestVerdict {
1064 let unsupported = || RequestVerdict {
1065 issue: None,
1066 _lifetime: None,
1067 seen: Default::default(),
1068 };
1069 if token.kind != crate::setup::Token::OUT_OF_BAND || token.value.is_empty() {
1070 return unsupported();
1071 }
1072 let Some(queue) = self.acceptor() else {
1073 return unsupported();
1074 };
1075 let token = Bytes::from(token.value);
1076 let mut stale = None;
1079 let (lifetime, fresh) = {
1080 let mut tokens = self.attached.request_tokens.lock().unwrap();
1081 match tokens.get(&token).and_then(std::sync::Weak::upgrade) {
1082 Some(lifetime) if !lifetime.issue.read().done => (lifetime, false),
1085 existing => {
1086 stale = existing;
1087 let lifetime = std::sync::Arc::new(RequestLifetime {
1088 issue: kio::Shared::new(Issue {
1089 hold,
1090 ..Default::default()
1091 }),
1092 handle: self.clone(),
1093 token: token.clone(),
1094 });
1095 tokens.insert(token.clone(), std::sync::Arc::downgrade(&lifetime));
1096 (lifetime, true)
1097 }
1098 }
1099 };
1100 drop(stale);
1101 if fresh {
1102 queue.push(Request::new(token, lifetime.issue.clone()));
1103 }
1104 RequestVerdict {
1105 issue: Some(lifetime.issue.clone()),
1106 _lifetime: Some(lifetime),
1107 seen: Default::default(),
1108 }
1109 }
1110
1111 pub(crate) fn acceptor(&self) -> Option<Pending> {
1114 self.handle.acceptor()
1115 }
1116
1117 pub(crate) fn poll_opening(&self, waiter: &kio::Waiter) -> Poll<Option<(u64, Bytes)>> {
1119 let id = self.id();
1120 loop {
1121 let mut guard = ready_or!(self.state().poll(waiter, |state| {
1122 match state.links.get(&id) {
1123 Some(link) if link.opening.is_empty() && link.closed.is_none() => Poll::Pending,
1124 _ => Poll::Ready(()),
1125 }
1126 }));
1127 let Some(link) = guard.links.get_mut(&id) else {
1128 return Poll::Ready(None);
1129 };
1130 if link.closed.is_some() {
1131 return Poll::Ready(None);
1132 }
1133 let token = link.opening.pop_front().expect("checked non-empty");
1134 if let Some(slot) = link.slots.get_mut(&token)
1136 && let Phase::Queued { backoff } = slot.phase
1137 {
1138 slot.phase = Phase::Pending { backoff };
1139 return Poll::Ready(Some((token, slot.token.clone())));
1140 }
1141 }
1142 }
1143
1144 pub(crate) fn poll_withdrawn(&self, id: u64, waiter: &kio::Waiter) -> Poll<()> {
1147 let link = self.id();
1148 let _ = ready_or!(self.state().poll(waiter, |state| {
1149 match state.links.get(&link).and_then(|link| link.slots.get(&id)) {
1150 Some(slot) if slot.phase.live() => Poll::Pending,
1151 _ => Poll::Ready(()),
1152 }
1153 }));
1154 Poll::Ready(())
1155 }
1156
1157 pub(crate) fn granted(&self, id: u64, grant: Grant) {
1159 let list = |prefixes: &Prefixes| format!("{:?}", prefixes.iter().map(|p| p.to_string()).collect::<Vec<_>>());
1162 tracing::debug!(
1163 publish = %list(&grant.publish),
1164 subscribe = %list(&grant.subscribe),
1165 "auth granted"
1166 );
1167 self.with_state(|state, link| {
1168 let link = attached(&mut state.links, link);
1169 let Some(slot) = link.slots.get_mut(&id) else {
1170 return;
1171 };
1172 if !matches!(slot.phase, Phase::Pending { .. } | Phase::Granted(_)) {
1174 return;
1175 }
1176 if slot.setup && link.acceptance == Acceptance::Awaiting {
1178 link.acceptance = Acceptance::Accepted;
1179 }
1180 slot.phase = Phase::Granted(grant);
1181 link.replied = true;
1182 link.recompute();
1183 state.answer(id, Ok(Answer::Granted));
1184 state.record();
1186 });
1187 }
1188
1189 #[cfg(test)]
1191 pub(crate) fn open(&self, id: u64) {
1192 self.with(|link| {
1193 if let Some(slot) = link.slots.get_mut(&id)
1194 && let Phase::Queued { backoff } = slot.phase
1195 {
1196 link.opening.retain(|opening| *opening != id);
1197 slot.phase = Phase::Pending { backoff };
1198 }
1199 });
1200 }
1201
1202 #[cfg(test)]
1205 pub(crate) fn grant(&self, id: u64, grant: Grant) {
1206 self.open(id);
1207 self.granted(id, grant);
1208 }
1209
1210 pub(crate) fn refused(&self, id: u64, undecided: bool) {
1216 self.with(|link| {
1217 let Some(slot) = link.slots.get_mut(&id) else {
1218 return;
1219 };
1220 link.replied = true;
1221 slot.phase = match slot.phase {
1222 Phase::Pending { backoff } | Phase::Refused { backoff, .. } => Phase::Refused { backoff, undecided },
1223 Phase::Granted(_) => Phase::Refused {
1225 backoff: None,
1226 undecided,
1227 },
1228 _ => return,
1229 };
1230 link.recompute();
1231 });
1232 }
1233
1234 pub(crate) fn retry(&self, id: u64, err: &Error) -> Option<Duration> {
1243 self.with_state(|state, link| {
1244 let bound = state.bound;
1245 let link = attached(&mut state.links, link);
1246 if !link.active() {
1247 return None;
1248 }
1249 let slot = link.slots.get_mut(&id)?;
1250 let backoff = match slot.phase {
1252 Phase::Pending { backoff } | Phase::Refused { backoff, .. } => backoff,
1253 Phase::Granted(_) => None,
1254 _ => return None,
1255 };
1256 if verdict(&slot.phase, err) || matches!(err, Error::ProtocolViolation) {
1258 return None;
1259 }
1260 if bound && !matches!(slot.phase, Phase::Refused { .. }) {
1261 return None;
1262 }
1263 let delay = backoff.map_or(RETRY_INITIAL, |delay| (delay * 2).min(RETRY_MAX));
1264 slot.phase = Phase::Queued { backoff: Some(delay) };
1267 link.epoch += 1;
1268 link.recompute();
1269 Some(delay)
1270 })
1271 }
1272
1273 pub(crate) fn reopen(&self, id: u64) -> Result<Bytes> {
1281 self.with(|link| {
1282 if !link.active() {
1283 return Err(Error::GoingAway);
1284 }
1285 match link.slots.get_mut(&id) {
1286 Some(slot) if let Phase::Queued { backoff } = slot.phase => {
1287 slot.phase = Phase::Pending { backoff };
1288 Ok(slot.token.clone())
1289 }
1290 _ => Err(Error::Cancel),
1291 }
1292 })
1293 }
1294
1295 pub(crate) fn ended(&self, id: u64, err: Error) {
1301 self.with_state(|state, link_id| {
1302 state.record();
1304 let superseded = !attached(&mut state.links, link_id).active()
1307 && state.links.iter().any(|(other, link)| {
1308 *other != link_id && link.active() && link.slots.get(&id).is_some_and(|slot| slot.phase.live())
1309 });
1310 let bound = state.bound;
1312 let link = attached(&mut state.links, link_id);
1313 let Some(slot) = link.slots.get_mut(&id) else {
1314 return;
1315 };
1316 let settled = !slot.setup
1317 && !superseded
1318 && link.closed.is_none()
1319 && slot.phase.live()
1320 && (bound || verdict(&slot.phase, &err));
1321 match slot.phase {
1322 Phase::Ended(_) => {}
1323 Phase::Withdrawn { .. } => {
1325 link.slots.remove(&id);
1326 }
1327 _ => slot.phase = Phase::Ended(err.clone()),
1328 }
1329 link.epoch += 1;
1331 link.recompute();
1332 if settled {
1333 state.end_token(id, err);
1334 }
1335 });
1336 }
1337
1338 pub(crate) fn poll_setup_answered(&self, waiter: &kio::Waiter) -> Poll<()> {
1341 let id = self.id();
1342 let _ = ready_or!(self.state().poll(waiter, |state| {
1343 let pending = state
1344 .links
1345 .get(&id)
1346 .is_some_and(|link| link.slots.values().any(|slot| slot.setup && !slot.phase.answered()));
1347 match pending {
1348 true => Poll::Pending,
1349 false => Poll::Ready(()),
1350 }
1351 }));
1352 Poll::Ready(())
1353 }
1354
1355 fn poll_presented(&self, direction: Direction, path: &str, waiter: &kio::Waiter) -> Poll<()> {
1357 let id = self.id();
1358 let _ = ready_or!(self.state().poll(waiter, |state| {
1359 let Some(link) = state.links.get(&id) else {
1360 return Poll::Ready(());
1361 };
1362 let (granted, _) = link.parts(direction);
1363 if granted.is_some_and(|grant| grant.matches(path))
1364 || !link
1365 .slots
1366 .values()
1367 .any(|slot| !slot.token.is_empty() && !slot.phase.answered() && slot.phase.live())
1368 {
1369 Poll::Ready(())
1370 } else {
1371 Poll::Pending
1372 }
1373 }));
1374 Poll::Ready(())
1375 }
1376
1377 fn issue(&self, id: u64, grant: Option<Grant>) {
1380 self.with_state(|state, link| {
1381 let link = attached(&mut state.links, link);
1382 match grant {
1383 Some(grant) => link.issued.insert(id, grant),
1384 None => link.issued.remove(&id),
1385 };
1386 link.rescope(state.limit.as_ref());
1387 });
1388 }
1389
1390 pub(crate) fn poll_union(&self, epoch: &mut u64, waiter: &kio::Waiter) -> Poll<Option<Grant>> {
1393 let state = ready_or!(self.poll_epoch(*epoch, waiter));
1394 let link = &state.links[&self.id()];
1395 *epoch = link.epoch;
1396 Poll::Ready(link.union.clone())
1397 }
1398
1399 pub(crate) fn poll_permit(&self, direction: Direction, epoch: &mut u64, waiter: &kio::Waiter) -> Poll<Permit> {
1402 let state = ready_or!(self.poll_epoch(*epoch, waiter));
1403 let link = &state.links[&self.id()];
1404 *epoch = link.epoch;
1405 Poll::Ready(link.permit(direction))
1406 }
1407
1408 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1410 pub(crate) fn permit(&self, direction: Direction) -> Permit {
1411 self.read(|link, _| link.permit(direction))
1412 }
1413
1414 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1417 pub(crate) fn admits_whole(&self) -> bool {
1418 [Direction::Publish, Direction::Subscribe]
1419 .into_iter()
1420 .all(|direction| self.within_limit(direction, ""))
1421 }
1422
1423 pub(crate) fn poll_limit(&self, epoch: &mut u64, waiter: &kio::Waiter) -> Poll<Option<Grant>> {
1425 let state = ready_or!(self.poll_epoch(*epoch, waiter));
1426 *epoch = state.links[&self.id()].epoch;
1427 Poll::Ready(state.limit.clone())
1428 }
1429
1430 fn poll_epoch(&self, seen: u64, waiter: &kio::Waiter) -> Poll<kio::Mut<'_, State>> {
1431 let id = self.id();
1432 self.state().poll(waiter, |state| match state.links[&id].epoch != seen {
1433 true => Poll::Ready(()),
1434 false => Poll::Pending,
1435 })
1436 }
1437
1438 pub(crate) fn allows(&self, direction: Direction, path: &str) -> bool {
1442 self.read(|link, _| link.allows(direction, path))
1443 }
1444
1445 pub(crate) fn token_decides(&self, direction: Direction) -> bool {
1452 self.read(|link, state| {
1453 let (_, scope) = link.parts(direction);
1454 scope.is_some() || matches!(state.acceptor, Acceptor::App(_))
1455 })
1456 }
1457
1458 pub(crate) fn within_grant(&self, direction: Direction, path: &str) -> bool {
1461 self.read(|link, _| {
1462 let (granted, _) = link.parts(direction);
1463 granted.is_none_or(|granted| granted.matches(path))
1464 })
1465 }
1466
1467 pub(crate) fn within_limit(&self, direction: Direction, path: &str) -> bool {
1470 self.read(|link, _| {
1471 let (_, scope) = link.parts(direction);
1472 scope.is_none_or(|scope| scope.matches(path))
1473 })
1474 }
1475
1476 fn closed(&self) -> Option<Error> {
1478 self.read(|link, _| link.closed.clone())
1479 }
1480
1481 pub(crate) fn await_acceptance(&self) {
1485 self.with(|link| link.acceptance = Acceptance::Awaiting);
1486 }
1487
1488 pub(crate) fn silent(&self) {
1491 self.with(|link| link.acceptance = Acceptance::Silent);
1492 }
1493
1494 pub(crate) fn is_silent(&self) -> bool {
1497 self.read(|link, _| link.acceptance == Acceptance::Silent)
1498 }
1499
1500 pub(crate) fn accepted(&self) {
1502 self.with_state(|state, link| {
1503 let link = attached(&mut state.links, link);
1504 if link.acceptance == Acceptance::Awaiting {
1505 link.acceptance = Acceptance::Accepted;
1506 }
1507 state.record();
1509 });
1510 }
1511
1512 pub(crate) fn poll_accepted(&self, waiter: &kio::Waiter) -> Poll<()> {
1515 let id = self.id();
1516 let _ = ready_or!(self.state().poll(waiter, |state| {
1517 match state.links.get(&id).map(|link| link.acceptance) {
1518 Some(Acceptance::Accepted) => Poll::Ready(()),
1519 _ => Poll::Pending,
1520 }
1521 }));
1522 Poll::Ready(())
1523 }
1524
1525 pub(crate) fn close(&self, err: Error) {
1528 let closing = self.with_state(|state, link| {
1529 if state.links[&link].closed.is_some() {
1530 return None;
1531 }
1532 state.record();
1534 let link = attached(&mut state.links, link);
1535 link.closed = Some(err.clone());
1536 link.opening.clear();
1537 link.cut = link
1538 .slots
1539 .iter()
1540 .filter(|(_, slot)| !slot.phase.answered())
1541 .map(|(id, _)| *id)
1542 .collect();
1543 for slot in link.slots.values_mut() {
1544 if !matches!(slot.phase, Phase::Ended(_)) {
1545 slot.phase = Phase::Ended(err.clone());
1546 }
1547 }
1548 link.recompute();
1549 Some(match state.bound {
1550 true => state.abort(err.clone()),
1551 false => None,
1552 })
1553 });
1554 let Some(queue) = closing else {
1555 return;
1556 };
1557 let lifetimes: Vec<_> = (self.attached.request_tokens.lock().unwrap().values())
1559 .filter_map(std::sync::Weak::upgrade)
1560 .collect();
1561 for lifetime in &lifetimes {
1562 lifetime.issue.lock().peer.get_or_insert(err.clone());
1563 }
1564 drop(lifetimes);
1565 if let Some(queue) = queue {
1567 queue.close();
1568 }
1569 }
1570}
1571
1572fn attached(links: &mut BTreeMap<u64, Box<Attached>>, id: u64) -> &mut Attached {
1574 links.get_mut(&id).expect("a link outlives its session's state")
1575}
1576
1577#[derive(Clone)]
1584pub struct Credential {
1585 presented: std::sync::Arc<Presented>,
1586}
1587
1588#[cfg(test)]
1589impl Credential {
1590 pub(crate) fn id(&self) -> u64 {
1592 self.presented.id
1593 }
1594}
1595
1596struct Presented {
1598 state: kio::Shared<State>,
1599 id: u64,
1600 link: Option<u64>,
1603}
1604
1605impl Presented {
1606 fn selector(&self) -> Selector {
1607 match self.link {
1608 Some(link) => Selector::Setup { link, id: self.id },
1609 None => Selector::Token(self.id),
1610 }
1611 }
1612}
1613
1614impl Credential {
1615 pub fn grant(&self) -> Watch {
1619 Watch::new(self.presented.state.clone(), self.presented.selector())
1620 }
1621
1622 #[cfg(feature = "async")]
1626 pub async fn closed(&self) -> Error {
1627 kio::wait(|waiter| self.poll_closed(waiter)).await
1628 }
1629
1630 fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<Error> {
1632 let selector = self.presented.selector();
1633 let state = ready_or!(self.presented.state.poll(waiter, |state| {
1634 match selector.ended(state) {
1635 Some(_) => Poll::Ready(()),
1636 None => Poll::Pending,
1637 }
1638 }));
1639 Poll::Ready(selector.ended(&state).unwrap_or(Error::Cancel))
1640 }
1641
1642 #[cfg_attr(feature = "async", kio::wrapper)]
1651 pub fn poll_answered(&self, waiter: &kio::Waiter) -> Poll<Result<()>> {
1652 self.poll_answer(waiter).map(|answer| answer.map(drop))
1653 }
1654
1655 fn poll_answer(&self, waiter: &kio::Waiter) -> Poll<Result<Answer>> {
1658 let id = self.presented.id;
1659 let answered = |state: &State| match state.tokens.get(&id) {
1660 Some(token) => token.answered.clone(),
1661 None => Some(Err(Error::Cancel)),
1662 };
1663 let state = ready_or!(self.presented.state.poll(waiter, |state| match answered(state) {
1664 Some(_) => Poll::Ready(()),
1665 None => Poll::Pending,
1666 }));
1667 Poll::Ready(answered(&state).unwrap_or(Err(Error::Cancel)))
1668 }
1669}
1670
1671impl PartialEq for Credential {
1672 fn eq(&self, other: &Self) -> bool {
1673 std::sync::Arc::ptr_eq(&self.presented, &other.presented)
1674 }
1675}
1676
1677impl Eq for Credential {}
1678
1679impl std::fmt::Debug for Credential {
1680 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1682 f.debug_tuple("Credential").field(&self.presented.id).finish()
1683 }
1684}
1685
1686impl Drop for Presented {
1687 fn drop(&mut self) {
1688 let mut guard = self.state.lock();
1689 let state = &mut *guard;
1690 match self.link {
1691 Some(link) => {
1692 if let Some(link) = state.links.get_mut(&link) {
1693 link.withdraw(self.id);
1694 }
1695 }
1696 None => state.withdraw(self.id),
1697 }
1698 }
1699}
1700
1701#[derive(Clone, Copy)]
1703enum Selector {
1704 Union,
1706 Token(u64),
1708 Setup { link: u64, id: u64 },
1710}
1711
1712impl Selector {
1713 fn current<'a>(&self, state: &'a State) -> Option<&'a Grant> {
1714 match *self {
1715 Self::Union => state.live()?.union.as_ref(),
1716 Self::Token(id) => state.live()?.slots.get(&id)?.phase.grant(),
1717 Self::Setup { link, id } => state.links.get(&link)?.slots.get(&id)?.phase.grant(),
1718 }
1719 }
1720
1721 fn ended(&self, state: &State) -> Option<Error> {
1723 if let Some(err) = &state.closed {
1724 return Some(err.clone());
1725 }
1726 match *self {
1727 Self::Union => None,
1728 Self::Token(id) => match state.tokens.get(&id) {
1729 Some(token) => token.ended.clone(),
1730 None => Some(Error::Cancel),
1731 },
1732 Self::Setup { link, id } => match state.links.get(&link).and_then(|link| link.slots.get(&id)) {
1733 Some(slot) => slot.phase.ended().cloned(),
1734 None => Some(Error::Cancel),
1735 },
1736 }
1737 }
1738}
1739
1740pub struct Watch {
1744 state: kio::Shared<State>,
1745 selector: Selector,
1746 last: Option<Grant>,
1747}
1748
1749impl Watch {
1750 fn new(state: kio::Shared<State>, selector: Selector) -> Self {
1751 let mut watch = Self {
1752 state,
1753 selector,
1754 last: None,
1755 };
1756 watch.last = watch.peek();
1757 watch
1758 }
1759
1760 pub fn peek(&self) -> Option<Grant> {
1762 self.selector.current(&self.state.read()).cloned()
1763 }
1764
1765 #[cfg_attr(feature = "async", kio::wrapper)]
1773 pub fn poll_changed(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Grant>>> {
1774 let last = &self.last;
1775 let selector = self.selector;
1776 let state = ready_or!(self.state.poll(waiter, |state| {
1777 match selector.current(state) != last.as_ref() || selector.ended(state).is_some() {
1778 true => Poll::Ready(()),
1779 false => Poll::Pending,
1780 }
1781 }));
1782 let current = selector.current(&state).cloned();
1783 if current != self.last {
1784 self.last = current.clone();
1785 return Poll::Ready(Ok(current));
1786 }
1787 Poll::Ready(Err(selector.ended(&state).unwrap_or(Error::Cancel)))
1788 }
1789}
1790
1791pub struct Requests {
1795 queue: Pending,
1796}
1797
1798impl Requests {
1799 #[cfg_attr(feature = "async", kio::wrapper)]
1801 pub fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<Option<Request>> {
1802 self.queue.poll_next(waiter)
1803 }
1804}
1805
1806impl Drop for Requests {
1807 fn drop(&mut self) {
1808 self.queue.close();
1809 }
1810}
1811
1812#[derive(Clone, Default)]
1814pub(crate) struct Pending {
1815 state: kio::Shared<PendingState>,
1816}
1817
1818#[derive(Default)]
1819struct PendingState {
1820 requests: VecDeque<Request>,
1821 survivors: usize,
1824 closed: bool,
1825}
1826
1827impl Pending {
1828 fn close(&self) {
1831 let refused = {
1832 let mut state = self.state.lock();
1833 state.closed = true;
1834 std::mem::take(&mut state.requests)
1835 };
1836 drop(refused);
1837 }
1838
1839 pub(crate) fn push(&self, request: Request) {
1841 let mut state = self.state.lock();
1842 if state.closed {
1844 return;
1845 }
1846 if state.requests.len() >= 2 * state.survivors.max(1) {
1849 state.requests.retain(|request| request.issue().read().peer.is_none());
1850 state.survivors = state.requests.len();
1851 }
1852 state.requests.push_back(request);
1853 }
1854
1855 fn poll_next(&self, waiter: &kio::Waiter) -> Poll<Option<Request>> {
1856 loop {
1857 let mut state = std::task::ready!(self.state.poll(waiter, |state| {
1858 if state.closed || !state.requests.is_empty() {
1859 Poll::Ready(())
1860 } else {
1861 Poll::Pending
1862 }
1863 }));
1864 while let Some(request) = state.requests.pop_front() {
1865 let mut issue = request.issue().lock();
1868 if issue.peer.is_none() {
1869 issue.taken = true;
1870 drop(issue);
1871 return Poll::Ready(Some(request));
1872 }
1873 }
1874 if state.closed {
1875 return Poll::Ready(None);
1876 }
1877 }
1878 }
1879}
1880
1881#[derive(Clone)]
1883pub(crate) enum Reply {
1884 Grant(Grant),
1885 Refuse { code: SessionError, reason: String },
1886}
1887
1888#[derive(Default)]
1890pub(crate) struct Issue {
1891 outbox: VecDeque<Reply>,
1894 latest: Option<Reply>,
1896 revision: u64,
1897 done: bool,
1899 pub peer: Option<Error>,
1901 hold: Option<Hold>,
1903 taken: bool,
1905 scoped: Option<(Link, u64)>,
1908}
1909
1910impl Issue {
1911 fn reply(&mut self, reply: Reply) {
1914 if let Some((handle, id)) = &self.scoped {
1915 match &reply {
1916 Reply::Grant(grant) if self.peer.is_none() => handle.issue(*id, Some(grant.clone())),
1917 _ => handle.issue(*id, None),
1918 }
1919 }
1920 self.revision += 1;
1921 if self.scoped.is_some() {
1922 self.queue(reply);
1923 } else {
1924 self.latest = Some(reply);
1925 }
1926 }
1927
1928 pub(crate) fn queue(&mut self, reply: Reply) {
1932 if self.done {
1933 return;
1934 }
1935 match self.outbox.back_mut() {
1936 Some(queued @ Reply::Grant(_)) => *queued = reply,
1937 _ => self.outbox.push_back(reply),
1938 }
1939 }
1940
1941 pub(crate) fn next(&mut self) -> Option<Reply> {
1943 self.outbox.pop_front()
1944 }
1945
1946 pub(crate) fn idle(&self) -> bool {
1948 self.outbox.is_empty() && !self.done
1949 }
1950
1951 pub(crate) fn refused(&mut self) {
1954 self.outbox.clear();
1955 self.finish();
1956 }
1957
1958 pub(crate) fn finish(&mut self) {
1960 self.done = true;
1961 if let Some((handle, id)) = &self.scoped {
1962 handle.issue(*id, None);
1963 }
1964 }
1965}
1966
1967pub(crate) type Hold = std::sync::Arc<dyn std::any::Any + Send + Sync>;
1971
1972pub(crate) struct Serving {
1977 pub issue: kio::Shared<Issue>,
1978 handle: Link,
1979}
1980
1981impl Serving {
1982 pub(crate) fn new(handle: Link) -> Self {
1984 let id = {
1985 let mut state = handle.state().lock();
1986 state.next_issue += 1;
1987 state.next_issue
1988 };
1989 Self {
1990 issue: kio::Shared::new(Issue {
1991 scoped: Some((handle.clone(), id)),
1992 ..Default::default()
1993 }),
1994 handle,
1995 }
1996 }
1997
1998 pub(crate) fn end(&self, err: Error) {
2001 let mut issue = self.issue.lock();
2002 issue.peer.get_or_insert(err);
2003 if let Some((handle, id)) = &issue.scoped {
2004 handle.issue(*id, None);
2005 }
2006 }
2007}
2008
2009impl Drop for Serving {
2010 fn drop(&mut self) {
2011 let err = self.handle.closed().unwrap_or(Error::Cancel);
2012 self.end(err);
2013 }
2014}
2015
2016pub struct Request {
2024 token: Bytes,
2025 issue: Option<kio::Shared<Issue>>,
2026}
2027
2028impl Request {
2029 pub(crate) fn new(token: Bytes, issue: kio::Shared<Issue>) -> Self {
2030 Self {
2031 token,
2032 issue: Some(issue),
2033 }
2034 }
2035
2036 fn issue(&self) -> &kio::Shared<Issue> {
2037 self.issue.as_ref().expect("unanswered request")
2038 }
2039
2040 pub fn token(&self) -> &Bytes {
2043 &self.token
2044 }
2045
2046 #[cfg(feature = "async")]
2049 pub async fn closed(&self) -> Error {
2050 kio::wait(|waiter| poll_closed(self.issue(), waiter)).await
2051 }
2052
2053 pub fn accept(mut self, grant: Grant) -> Issued {
2059 let issue = self.issue.take().expect("answered once");
2060 let mut locked = issue.lock();
2061 locked.reply(Reply::Grant(grant));
2062 locked.hold = None;
2063 drop(locked);
2064 Issued { issue }
2065 }
2066
2067 pub fn reject(mut self, code: SessionError, reason: impl Into<String>) {
2073 let issue = self.issue.take().expect("answered once");
2074 refuse(&issue, code, reason.into());
2075 issue.lock().hold = None;
2076 }
2077}
2078
2079impl Drop for Request {
2080 fn drop(&mut self) {
2081 if let Some(issue) = self.issue.take() {
2082 refuse(&issue, SessionError::Unauthorized, "unanswered".to_string());
2083 issue.lock().hold = None;
2084 }
2085 }
2086}
2087
2088fn refuse(issue: &kio::Shared<Issue>, code: SessionError, reason: String) {
2089 let mut issue = issue.lock();
2090 if !issue.done {
2091 issue.reply(Reply::Refuse { code, reason });
2092 issue.finish();
2093 }
2094}
2095
2096#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2099pub(crate) enum RequestKind {
2100 Subscribe,
2103 PublishNamespace,
2106 Discover,
2109 Publish,
2111}
2112
2113impl RequestKind {
2114 pub(crate) fn covers(self, grant: &Grant, path: &str) -> bool {
2120 match self {
2121 Self::Subscribe => grant.subscribe.matches(path),
2122 Self::Discover => !grant.subscribe.is_empty(),
2123 Self::Publish | Self::PublishNamespace => grant.publish.matches(path),
2124 }
2125 }
2126}
2127
2128pub(crate) struct RequestVerdict {
2133 issue: Option<kio::Shared<Issue>>,
2134 _lifetime: Option<std::sync::Arc<RequestLifetime>>,
2136 seen: std::sync::Mutex<u64>,
2137}
2138
2139struct RequestLifetime {
2140 issue: kio::Shared<Issue>,
2141 handle: Link,
2142 token: Bytes,
2143}
2144
2145impl Drop for RequestLifetime {
2146 fn drop(&mut self) {
2147 let mut tokens = self.handle.attached.request_tokens.lock().unwrap();
2148 if tokens.get(&self.token).is_some_and(|token| token.strong_count() == 0) {
2149 tokens.remove(&self.token);
2150 }
2151 drop(tokens);
2152 let mut issue = self.issue.lock();
2153 issue.peer.get_or_insert(Error::Cancel);
2154 if !issue.taken {
2155 issue.hold = None;
2156 }
2157 }
2158}
2159
2160#[derive(Debug, Clone)]
2163pub(crate) struct Refusal {
2164 pub error: Error,
2165 pub reason: String,
2166}
2167
2168impl Refusal {
2169 fn new(error: Error, reason: &str) -> Self {
2170 Self {
2171 error,
2172 reason: reason.to_string(),
2173 }
2174 }
2175}
2176
2177impl From<Error> for Refusal {
2178 fn from(error: Error) -> Self {
2179 let reason = error.to_string();
2180 Self { error, reason }
2181 }
2182}
2183
2184impl RequestVerdict {
2185 #[cfg(test)]
2187 pub(crate) async fn grant(&self) -> std::result::Result<Grant, Refusal> {
2188 kio::wait(|waiter| self.poll_grant(waiter)).await
2189 }
2190
2191 pub(crate) fn poll_grant(&self, waiter: &kio::Waiter) -> Poll<std::result::Result<Grant, Refusal>> {
2197 let Some(issue) = &self.issue else {
2198 return Poll::Ready(Err(Error::Unsupported.into()));
2199 };
2200 let guard = ready_or!(issue.poll(waiter, |issue| {
2201 if issue.latest.is_none() && !issue.done {
2202 Poll::Pending
2203 } else {
2204 Poll::Ready(())
2205 }
2206 }));
2207 *self.seen.lock().unwrap() = guard.revision;
2208 Poll::Ready(match (&guard.latest, guard.done) {
2209 (Some(Reply::Refuse { code, reason }), _) => Err(Refusal::new(Error::Session(code.clone()), reason)),
2210 (Some(Reply::Grant(grant)), false) => Ok(grant.clone()),
2211 _ => Err(Refusal::new(
2212 Error::Session(SessionError::Unauthorized),
2213 "grant dropped",
2214 )),
2215 })
2216 }
2217
2218 fn poll_reply(&self, waiter: &kio::Waiter) -> Poll<Option<Reply>> {
2220 let Some(issue) = &self.issue else {
2221 return Poll::Ready(None);
2222 };
2223 let mut seen = self.seen.lock().unwrap();
2224 let guard = ready_or!(issue.poll(waiter, |issue| {
2225 if issue.revision == *seen && !issue.done {
2226 Poll::Pending
2227 } else {
2228 Poll::Ready(())
2229 }
2230 }));
2231 if guard.revision != *seen {
2232 *seen = guard.revision;
2233 return Poll::Ready(guard.latest.clone());
2234 }
2235 Poll::Ready(None)
2236 }
2237}
2238
2239#[derive(Clone)]
2248pub(crate) struct RequestGrant(std::sync::Arc<std::sync::Mutex<Held>>);
2249
2250struct Held {
2251 verdict: RequestVerdict,
2252 grant: Grant,
2253 deadline: crate::time::Deadline,
2254 path: crate::Path,
2256 kind: RequestKind,
2257 hold: Option<Hold>,
2259 renewing: Option<kio::Shared<Issue>>,
2261 clock: crate::time::Deadlines,
2262 epoch: u64,
2263 ended: kio::Producer<Option<Refusal>>,
2266}
2267
2268impl Held {
2269 fn poll_end(&mut self, waiter: &kio::Waiter) -> Poll<Refusal> {
2271 loop {
2272 if let Some(err) = self.verdict.issue.as_ref().and_then(|issue| issue.read().peer.clone()) {
2273 return Poll::Ready(err.into());
2274 }
2275 let handover = self.renewing.as_ref().is_some_and(|issue| {
2280 issue
2281 .poll(waiter, |issue| match granted(issue) {
2282 true => Poll::Pending,
2283 false => Poll::Ready(()),
2284 })
2285 .is_pending()
2286 });
2287 let ended = match self.verdict.poll_reply(waiter) {
2290 Poll::Ready(Some(Reply::Grant(grant))) => {
2291 if !self.kind.covers(&grant, self.path.as_str()) {
2292 return Poll::Ready(Refusal::new(Error::Unauthorized, "request token no longer granted"));
2293 }
2294 self.deadline.set(grant.expires);
2295 self.grant = grant;
2296 self.epoch += 1;
2297 continue;
2300 }
2301 Poll::Ready(None) if handover => None,
2302 Poll::Ready(None) => Some(Refusal::new(
2303 Error::Session(SessionError::Unauthorized),
2304 "grant dropped",
2305 )),
2306 Poll::Ready(Some(Reply::Refuse { code, reason })) => Some(Refusal::new(Error::Session(code), &reason)),
2307 Poll::Pending => None,
2308 };
2309 if self.deadline.poll(waiter).is_ready() {
2311 if handover {
2312 return Poll::Pending;
2313 }
2314 return Poll::Ready(Refusal::new(Error::Expired, "request token expired"));
2315 }
2316 return match ended {
2317 Some(refusal) => Poll::Ready(refusal),
2318 None => Poll::Pending,
2319 };
2320 }
2321 }
2322}
2323
2324impl RequestGrant {
2325 pub(crate) fn new(
2329 clock: &crate::time::Deadlines,
2330 verdict: RequestVerdict,
2331 res: std::result::Result<Grant, Refusal>,
2332 path: crate::Path,
2333 kind: RequestKind,
2334 hold: Option<Hold>,
2335 ) -> std::result::Result<Self, Refusal> {
2336 let grant = res?;
2337 if !live(clock, kind, path.as_str(), &grant) {
2338 return Err(Refusal::new(Error::Unauthorized, "request token not granted"));
2339 }
2340 let mut deadline = crate::time::Deadline::new(clock);
2341 deadline.set(grant.expires);
2342 Ok(Self(std::sync::Arc::new(std::sync::Mutex::new(Held {
2343 verdict,
2344 grant,
2345 deadline,
2346 path,
2347 kind,
2348 hold,
2349 renewing: None,
2350 clock: clock.clone(),
2351 epoch: 1,
2352 ended: kio::Producer::new(None),
2353 }))))
2354 }
2355
2356 fn held(&self) -> std::sync::MutexGuard<'_, Held> {
2357 self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
2358 }
2359
2360 #[cfg(test)]
2362 pub(crate) fn grant(&self) -> Grant {
2363 self.held().grant.clone()
2364 }
2365
2366 #[cfg(test)]
2368 pub(crate) fn hold(&self) -> Option<Hold> {
2369 self.held().hold.clone()
2370 }
2371
2372 pub(crate) fn verify_renewal(&self, handle: &Link, token: crate::setup::Token) -> RequestVerdict {
2374 let hold = self.held().hold.clone();
2375 self.verify_renewal_holding(handle, token, hold)
2376 }
2377
2378 pub(crate) fn verify_renewal_holding(
2381 &self,
2382 handle: &Link,
2383 token: crate::setup::Token,
2384 hold: Option<Hold>,
2385 ) -> RequestVerdict {
2386 let mut held = self.held();
2387 let verdict = handle.verify_request(token, hold);
2388 held.renewing = verdict.issue.clone();
2389 verdict
2390 }
2391
2392 pub(crate) fn renew(
2399 &self,
2400 verdict: RequestVerdict,
2401 res: std::result::Result<Grant, Refusal>,
2402 ) -> std::result::Result<(), Refusal> {
2403 let mut held = self.held();
2404 held.renewing = None;
2405 let grant = res?;
2406 if !live(&held.clock, held.kind, held.path.as_str(), &grant) {
2407 return Err(Refusal::new(Error::Unauthorized, "renewal not granted"));
2408 }
2409 held.verdict = verdict;
2410 held.deadline.set(grant.expires);
2411 held.grant = grant;
2412 held.epoch += 1;
2413 Ok(())
2414 }
2415
2416 pub(crate) fn end(&self, refusal: Refusal) {
2421 latch(&self.held().ended, refusal);
2422 }
2423
2424 pub(crate) fn poll_ended(&self, waiter: &kio::Waiter) -> Poll<Refusal> {
2430 let held = &mut *self.held();
2431 let latched = match held.ended.poll_ref(waiter, |ended| match &**ended {
2434 Some(ended) => Poll::Ready(ended.clone()),
2435 None => Poll::Pending,
2436 }) {
2437 Poll::Ready(Ok(ended)) => Some(ended),
2438 Poll::Ready(Err(_)) | Poll::Pending => None,
2440 };
2441 if let Some(ended) = latched {
2442 return Poll::Ready(ended);
2443 }
2444 let ended = std::task::ready!(held.poll_end(waiter));
2445 latch(&held.ended, ended.clone());
2446 Poll::Ready(ended)
2447 }
2448}
2449
2450fn latch(ended: &kio::Producer<Option<Refusal>>, refusal: Refusal) {
2452 if let Ok(mut ended) = ended.write()
2453 && ended.is_none()
2454 {
2455 *ended = Some(refusal);
2456 }
2457}
2458
2459fn live(clock: &crate::time::Deadlines, kind: RequestKind, path: &str, grant: &Grant) -> bool {
2462 kind.covers(grant, path) && grant.expires.is_none_or(|expires| expires > clock.now())
2463}
2464
2465fn granted(issue: &Issue) -> bool {
2468 issue.peer.is_none() && !issue.done && matches!(issue.latest, Some(Reply::Grant(_)))
2469}
2470
2471pub struct Issued {
2474 issue: kio::Shared<Issue>,
2475}
2476
2477impl Issued {
2478 pub fn update(&self, grant: Grant) {
2481 let mut issue = self.issue.lock();
2482 if !issue.done {
2483 issue.reply(Reply::Grant(grant));
2484 }
2485 }
2486
2487 pub fn revoke(self, code: SessionError, reason: impl Into<String>) {
2489 refuse(&self.issue, code, reason.into());
2490 }
2491
2492 #[cfg(feature = "async")]
2497 pub fn closed(&self) -> impl Future<Output = Error> + Send + 'static {
2498 let issue = self.issue.clone();
2499 kio::wait(move |waiter| poll_closed(&issue, waiter))
2500 }
2501}
2502
2503impl Drop for Issued {
2504 fn drop(&mut self) {
2505 self.issue.lock().finish();
2506 }
2507}
2508
2509fn poll_closed(issue: &kio::Shared<Issue>, waiter: &kio::Waiter) -> Poll<Error> {
2511 let issue = ready_or!(issue.poll(waiter, |issue| {
2512 if issue.peer.is_some() {
2513 Poll::Ready(())
2514 } else {
2515 Poll::Pending
2516 }
2517 }));
2518 Poll::Ready(issue.peer.clone().expect("checked above"))
2519}
2520
2521#[derive(Clone, Copy)]
2523pub(crate) enum Direction {
2524 Publish,
2526 Subscribe,
2528}
2529
2530pub(crate) struct Gate {
2537 handle: Link,
2538 path: crate::Path,
2539 direction: Direction,
2540 epoch: u64,
2541 part: Part,
2542 token: Option<RequestGrant>,
2543 discovery: bool,
2544 within_limit: bool,
2546 admitted: bool,
2547 waiting: Option<Waiting>,
2548}
2549
2550struct Waiting {
2552 path: crate::Path,
2553 started: Instant,
2554}
2555
2556impl Drop for Waiting {
2557 fn drop(&mut self) {
2558 tracing::debug!(path = %self.path, waited = ?self.started.elapsed(), "request waited for authorization");
2559 }
2560}
2561
2562enum Part {
2564 Both,
2566 Granted,
2568 Announced(kio::Consumer<()>),
2570}
2571
2572impl Gate {
2573 pub(crate) fn new(handle: Link, path: crate::Path, direction: Direction) -> Self {
2574 let within_limit = handle.within_limit(direction, path.as_str());
2575 Self {
2576 handle,
2577 path,
2578 direction,
2579 epoch: 0,
2580 part: Part::Both,
2581 token: None,
2582 discovery: false,
2583 within_limit,
2584 admitted: false,
2585 waiting: None,
2586 }
2587 }
2588
2589 pub(crate) fn name(&mut self) {
2591 self.part = Part::Granted;
2592 }
2593
2594 pub(crate) fn discovery(mut self) -> Self {
2596 self.discovery = true;
2597 self
2598 }
2599
2600 pub(crate) fn admit(
2602 &mut self,
2603 clock: &crate::time::Deadlines,
2604 answer: (RequestVerdict, std::result::Result<Grant, Refusal>),
2605 ) -> std::result::Result<(), Refusal> {
2606 let (verdict, answer) = answer;
2607 if let Some(token) = &self.token {
2608 return token.renew(verdict, answer);
2609 }
2610 let token = RequestGrant::new(clock, verdict, answer, self.path.clone(), self.kind(), None)?;
2611 self.bind(token);
2612 Ok(())
2613 }
2614
2615 fn kind(&self) -> RequestKind {
2619 match (self.discovery, self.direction) {
2620 (true, _) => RequestKind::Discover,
2621 (false, Direction::Publish) => RequestKind::Subscribe,
2622 (false, Direction::Subscribe) => RequestKind::PublishNamespace,
2623 }
2624 }
2625
2626 pub(crate) fn bind(&mut self, token: RequestGrant) {
2628 self.token = Some(token);
2629 self.part = Part::Both;
2630 self.epoch = 0;
2631 }
2632
2633 pub(crate) fn token_guard(&self) -> Option<RequestGrant> {
2635 self.token.clone()
2636 }
2637
2638 pub(crate) fn unnamed(&self) -> Self {
2640 let mut gate = Self::new(self.handle.clone(), self.path.clone(), self.direction);
2641 gate.part = match &self.part {
2642 Part::Both => Part::Both,
2643 Part::Granted => Part::Granted,
2644 Part::Announced(live) => Part::Announced(live.clone()),
2645 };
2646 gate
2647 }
2648
2649 pub(crate) fn poll_token_ended(&self, waiter: &kio::Waiter) -> Poll<Refusal> {
2651 match &self.token {
2652 Some(token) => token.poll_ended(waiter),
2653 None => Poll::Pending,
2654 }
2655 }
2656
2657 pub(crate) fn announced(handle: Link, path: crate::Path, direction: Direction, live: kio::Consumer<()>) -> Self {
2660 Self {
2661 part: Part::Announced(live),
2662 ..Self::new(handle, path, direction)
2663 }
2664 }
2665
2666 pub(crate) fn allows(&self) -> bool {
2668 let path = self.path.as_str();
2669 self.handle.within_grant(self.direction, path)
2670 && match &self.part {
2671 Part::Both => match &self.token {
2672 Some(token) => {
2673 let token = token.held();
2674 match self.direction {
2675 Direction::Publish => token.grant.subscribe.matches(path),
2676 Direction::Subscribe => token.grant.publish.matches(path),
2677 }
2678 }
2679 None => self.within_limit,
2680 },
2681 Part::Granted => true,
2682 Part::Announced(live) => self.within_limit || !live.is_closed(),
2683 }
2684 }
2685
2686 pub(crate) fn token_decides(&self) -> bool {
2688 self.handle.token_decides(self.direction)
2689 }
2690
2691 pub(crate) fn verify(&self, token: crate::setup::Token, hold: Option<Hold>) -> RequestVerdict {
2695 match &self.token {
2696 Some(grant) => grant.verify_renewal_holding(&self.handle, token, hold),
2697 None => self.handle.verify_request(token, hold),
2698 }
2699 }
2700
2701 pub(crate) fn poll_permit(&self, epoch: &mut u64, waiter: &kio::Waiter) -> Poll<Permit> {
2703 let Some(token) = &self.token else {
2704 return self.handle.poll_permit(self.direction, epoch, waiter);
2705 };
2706 let ended = token.poll_ended(waiter).is_ready();
2707 let token = token.held();
2708 let mut version = u64::MAX;
2712 let mut permit = None;
2713 while let Poll::Ready(next) = self.handle.poll_permit(self.direction, &mut version, waiter) {
2714 permit = Some(next);
2715 }
2716 let mut permit = permit.expect("a session epoch is never u64::MAX");
2717 permit.limit = Some(if ended {
2718 Prefixes::new()
2719 } else {
2720 match self.direction {
2721 Direction::Publish => token.grant.subscribe.clone(),
2722 Direction::Subscribe => token.grant.publish.clone(),
2723 }
2724 });
2725 version += token.epoch + u64::from(ended);
2727 if version == *epoch {
2728 return Poll::Pending;
2729 }
2730 *epoch = version;
2731 Poll::Ready(permit)
2732 }
2733
2734 pub(crate) fn poll_setup_answered(&self, waiter: &kio::Waiter) -> Poll<()> {
2736 self.handle.poll_setup_answered(waiter)
2737 }
2738
2739 pub(crate) fn poll_ready(&mut self, waiter: &kio::Waiter) -> Poll<()> {
2741 if self.admitted {
2742 return Poll::Ready(());
2743 }
2744 let withdrawn = matches!(&self.part, Part::Announced(live) if live.poll_closed(waiter).is_ready());
2747 if !withdrawn
2748 && self
2749 .handle
2750 .poll_presented(self.direction, self.path.as_str(), waiter)
2751 .is_pending()
2752 {
2753 self.waiting.get_or_insert_with(|| Waiting {
2754 path: self.path.clone(),
2755 started: Instant::now(),
2756 });
2757 return Poll::Pending;
2758 }
2759 drop(self.waiting.take());
2760 self.admitted = true;
2761 Poll::Ready(())
2762 }
2763
2764 pub(crate) fn poll_refused(&mut self, waiter: &kio::Waiter) -> Poll<Error> {
2767 if let Poll::Ready(refusal) = self.poll_token_ended(waiter) {
2769 return Poll::Ready(refusal.error);
2770 }
2771 self.poll_denied(waiter).map(|()| Error::Unauthorized)
2772 }
2773
2774 pub(crate) fn poll_denied(&mut self, waiter: &kio::Waiter) -> Poll<()> {
2778 if self.poll_token_ended(waiter).is_ready() {
2779 return Poll::Ready(());
2780 }
2781 let mut epoch = self.epoch;
2782 while let Poll::Ready(permit) = self.poll_permit(&mut epoch, waiter) {
2783 self.epoch = epoch;
2784 let path = self.path.as_str();
2785 self.within_limit = permit.within_limit(path);
2786 let allowed = match self.part {
2787 Part::Both => permit.matches(path),
2788 Part::Granted | Part::Announced(_) => permit.granted(path),
2789 };
2790 if !allowed {
2791 return Poll::Ready(());
2792 }
2793 }
2794 match &self.part {
2795 Part::Announced(live) if !self.within_limit => live.poll_closed(waiter),
2796 _ => Poll::Pending,
2797 }
2798 }
2799}
2800
2801pub(crate) struct DefaultGrant {
2804 handle: Link,
2805 base: Grant,
2806 epoch: u64,
2807 limit: Option<Grant>,
2808 sent: Option<Grant>,
2810}
2811
2812impl DefaultGrant {
2813 pub(crate) fn new(handle: Link, base: Grant) -> Self {
2814 let limit = handle.state().read().limit.clone();
2815 Self {
2816 handle,
2817 base,
2818 epoch: 0,
2819 limit,
2820 sent: None,
2821 }
2822 }
2823
2824 pub(crate) fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Grant> {
2826 while let Poll::Ready(limit) = self.handle.poll_limit(&mut self.epoch, waiter) {
2827 self.limit = limit;
2828 }
2829 let grant = match &self.limit {
2830 Some(limit) => self.base.intersect(limit),
2831 None => self.base.clone(),
2832 };
2833 if self.sent.as_ref() == Some(&grant) {
2834 return Poll::Pending;
2835 }
2836 self.sent = Some(grant.clone());
2837 Poll::Ready(grant)
2838 }
2839}
2840
2841pub(crate) fn unauthorized_reason(path: &crate::Path) -> String {
2844 format!("unauthorized: {path}")
2845}
2846
2847#[derive(Default)]
2857pub(crate) struct Enforce {
2858 epoch: u64,
2859 permit: Option<Prefixes>,
2860 live: std::collections::HashSet<crate::Path>,
2862 setup: bool,
2863 pending: Vec<Gate>,
2866}
2867
2868impl Enforce {
2869 pub(crate) fn poll(
2872 &mut self,
2873 handle: &Link,
2874 announced: &mut crate::origin::Routes,
2875 waiter: &kio::Waiter,
2876 ) -> Poll<Option<crate::Path>> {
2877 if !self.setup {
2878 ready_or!(handle.poll_setup_answered(waiter));
2879 self.setup = true;
2880 }
2881 while let Poll::Ready(union) = handle.poll_union(&mut self.epoch, waiter) {
2882 self.permit = union.map(|grant| grant.publish);
2883 }
2884 if self.permit.is_none() {
2886 return Poll::Pending;
2887 }
2888
2889 while let Poll::Ready(event) = announced.poll_next(waiter) {
2892 let Some(event) = event else {
2893 return Poll::Ready(None);
2894 };
2895 match event {
2896 crate::origin::RouteEvent {
2897 kind: crate::origin::RouteKind::Start | crate::origin::RouteKind::Update,
2898 announce: update,
2899 } if !self.live.contains(&update.prefix) => {
2900 if self.pending.iter().any(|gate| gate.path == update.prefix) {
2901 continue;
2902 }
2903 let mut gate = Gate::new(handle.clone(), update.prefix, Direction::Publish);
2904 if gate.poll_ready(waiter).is_pending() {
2905 self.pending.push(gate);
2906 continue;
2907 }
2908 if !handle.within_grant(Direction::Publish, gate.path.as_str()) {
2909 return Poll::Ready(Some(gate.path));
2910 }
2911 self.live.insert(gate.path);
2912 }
2913 crate::origin::RouteEvent {
2914 kind: crate::origin::RouteKind::End | crate::origin::RouteKind::Offline,
2915 announce: update,
2916 } => {
2917 self.live.remove(&update.prefix);
2918 self.pending.retain(|gate| gate.path != update.prefix);
2919 }
2920 _ => {}
2921 }
2922 }
2923
2924 while let Some(index) = self
2925 .pending
2926 .iter_mut()
2927 .position(|gate| gate.poll_ready(waiter).is_ready())
2928 {
2929 let gate = self.pending.remove(index);
2930 if !handle.within_grant(Direction::Publish, gate.path.as_str()) {
2931 return Poll::Ready(Some(gate.path));
2932 }
2933 self.live.insert(gate.path);
2934 }
2935 Poll::Pending
2936 }
2937}
2938
2939#[cfg(test)]
2940mod tests {
2941 use super::*;
2942
2943 #[kio::test]
2944 async fn a_request_waits_for_an_unanswered_token() {
2945 let handle = Link::new(true);
2946 let setup = handle.present(Bytes::new(), true).unwrap();
2947 handle.grant(setup.presented.id, Grant::default());
2948 let token = handle.present(Bytes::from_static(b"new"), false).unwrap();
2949 let mut gate = Gate::new(handle.clone(), crate::Path::from_static("room"), Direction::Subscribe);
2950 let waiter = kio::Waiter::noop();
2951 assert!(
2952 gate.poll_ready(&waiter).is_pending(),
2953 "request refused before token answered"
2954 );
2955 handle.grant(token.presented.id, Grant::all());
2956 assert!(gate.poll_ready(&waiter).is_ready());
2957 assert!(gate.poll_denied(&waiter).is_pending());
2958 }
2959
2960 #[test]
2963 fn a_retrying_token_holds_a_publication() {
2964 let handle = Link::new(true);
2965 let _token = handle.present(Bytes::from_static(b"jwt"), false).unwrap();
2966 let id = opened(&handle);
2967 handle.refused(id, true);
2968 let busy = Error::Session(SessionError::TooManyRequests);
2969 assert_eq!(handle.retry(id, &busy), Some(RETRY_INITIAL));
2970
2971 let mut gate = Gate::new(handle.clone(), crate::Path::from_static("room"), Direction::Publish);
2972 let waiter = kio::Waiter::noop();
2973 assert!(
2974 gate.poll_ready(&waiter).is_pending(),
2975 "judged before the retry answered"
2976 );
2977 handle.reopen(id).unwrap();
2978 handle.grant(id, Grant::all());
2979 assert!(gate.poll_ready(&waiter).is_ready());
2980 assert!(handle.within_grant(Direction::Publish, "room"));
2981 }
2982
2983 #[test]
2986 fn a_withdrawn_route_ends_the_wait() {
2987 let handle = Link::new(true);
2988 let setup = handle.present(Bytes::new(), true).unwrap();
2989 handle.grant(setup.presented.id, Grant::default());
2990 let _unanswered = handle.present(Bytes::from_static(b"new"), false).unwrap();
2991 let route = kio::Producer::<()>::default();
2992 let mut gate = Gate::announced(
2993 handle,
2994 crate::Path::from_static("room"),
2995 Direction::Subscribe,
2996 route.consume(),
2997 );
2998 let waiter = kio::Waiter::noop();
2999 assert!(gate.poll_ready(&waiter).is_pending(), "waits while the route stands");
3000 drop(route);
3001 assert!(gate.poll_ready(&waiter).is_ready(), "a withdrawn route kept the wait");
3002 assert!(gate.poll_denied(&waiter).is_ready());
3003 }
3004
3005 #[test]
3006 fn an_empty_token_never_holds_a_request() {
3007 let handle = Link::new(true);
3008 let _setup = handle.present(Bytes::new(), true).unwrap();
3009 let mut gate = Gate::new(handle, crate::Path::from_static("room"), Direction::Subscribe);
3010 assert!(gate.poll_ready(&kio::Waiter::noop()).is_ready());
3011 }
3012
3013 #[test]
3014 fn a_covered_request_never_waits_for_an_unanswered_token() {
3015 let handle = Link::new(true);
3016 let first = handle.present(Bytes::from_static(b"first"), false).unwrap();
3017 handle.grant(first.presented.id, Grant::all());
3018 let _unanswered = handle.present(Bytes::from_static(b"renewal"), false).unwrap();
3019 let mut gate = Gate::new(handle, crate::Path::from_static("room"), Direction::Subscribe);
3020 assert!(gate.poll_ready(&kio::Waiter::noop()).is_ready());
3021 }
3022
3023 #[test]
3024 fn an_auth_ok_is_queued_after_its_scope_widens() {
3025 let handle = Link::new(true);
3026 handle.handle().authorize(&Grant::default());
3027 let serving = Serving::new(handle.clone());
3028 let request = Request::new(Bytes::from_static(b"token"), serving.issue.clone());
3029 let _issued = request.accept(Grant::all());
3030 let issue = serving.issue.read();
3031 assert!(matches!(issue.outbox.front(), Some(Reply::Grant(_))));
3032 assert!(handle.within_limit(Direction::Subscribe, "room"));
3033 }
3034
3035 #[test]
3038 fn a_refused_grant_leaves_the_scope() {
3039 let handle = Link::new(true);
3040 handle.handle().authorize(&Grant::default());
3041 let serving = Serving::new(handle.clone());
3042 let request = Request::new(Bytes::from_static(b"token"), serving.issue.clone());
3043 let issued = request.accept(grant(&["room"], &[]));
3044 assert!(handle.allows(Direction::Subscribe, "room"));
3045 serving.issue.lock().refused();
3046 assert!(
3047 !handle.allows(Direction::Subscribe, "room"),
3048 "the refused grant still admits"
3049 );
3050 issued.update(grant(&["room"], &[]));
3051 assert!(
3052 !handle.allows(Direction::Subscribe, "room"),
3053 "an update revived the refused grant"
3054 );
3055 }
3056
3057 #[test]
3060 fn a_blocked_stream_queues_one_grant() {
3061 let handle = Link::new(true);
3062 let serving = Serving::new(handle.clone());
3063 let request = Request::new(Bytes::from_static(b"token"), serving.issue.clone());
3064 let issued = request.accept(grant(&["0"], &[]));
3065 for i in 1..100 {
3066 issued.update(grant(&[&i.to_string()], &[]));
3067 }
3068 {
3069 let issue = serving.issue.read();
3070 assert_eq!(issue.outbox.len(), 1, "grants piled up");
3071 assert!(matches!(issue.outbox.front(), Some(Reply::Grant(grant)) if grant.publish == prefixes(&["99"])));
3072 }
3073 issued.revoke(SessionError::Unauthorized, "revoked");
3074 let issue = serving.issue.read();
3075 assert!(matches!(
3076 issue.outbox.iter().collect::<Vec<_>>()[..],
3077 [Reply::Refuse { .. }]
3078 ));
3079 }
3080
3081 #[test]
3084 fn a_new_acceptor_refuses_the_queue_without_deadlock() {
3085 let handle = Link::new(true);
3086 let _requests = handle.handle().requests();
3087 let serving = Serving::new(handle.clone());
3088 handle
3089 .acceptor()
3090 .unwrap()
3091 .push(Request::new(Bytes::from_static(b"token"), serving.issue.clone()));
3092 let _next = handle.handle().requests();
3093 assert!(matches!(
3094 serving.issue.read().outbox.front(),
3095 Some(Reply::Refuse { .. })
3096 ));
3097 }
3098
3099 #[test]
3102 fn a_queued_request_token_holds_its_slot() {
3103 let handle = Link::new(true);
3104 let mut requests = handle.handle().requests();
3105 let slot: Hold = std::sync::Arc::new(());
3106 let token = crate::setup::Token {
3107 kind: crate::setup::Token::OUT_OF_BAND,
3108 value: b"jwt".to_vec(),
3109 };
3110 let _verdict = handle.verify_request(token, Some(slot.clone()));
3111 assert_eq!(
3112 std::sync::Arc::strong_count(&slot),
3113 2,
3114 "queued, the token holds the slot"
3115 );
3116 let Poll::Ready(Some(request)) = requests.poll_next(&kio::Waiter::noop()) else {
3117 panic!("request token missing")
3118 };
3119 assert_eq!(
3120 std::sync::Arc::strong_count(&slot),
3121 2,
3122 "taken, the token still holds the slot"
3123 );
3124 let _issued = request.accept(Grant::all());
3125 assert_eq!(std::sync::Arc::strong_count(&slot), 1, "answered, the slot is released");
3126 }
3127
3128 #[test]
3131 fn withdrawn_tokens_leave_the_queue() {
3132 let handle = Link::new(true);
3133 let mut requests = handle.handle().requests();
3134 let queue = handle.acceptor().unwrap();
3135 queue.push(Request::new(Bytes::from_static(b"live"), Default::default()));
3136 let withdrawn = kio::Shared::<Issue>::default();
3137 withdrawn.lock().peer = Some(Error::Cancel);
3138 for _ in 0..1000 {
3139 queue.push(Request::new(Bytes::from_static(b"withdrawn"), withdrawn.clone()));
3140 assert!(queue.state.read().requests.len() <= 3, "withdrawn tokens piled up");
3141 }
3142 let Poll::Ready(Some(request)) = requests.poll_next(&kio::Waiter::noop()) else {
3143 panic!("live request missing")
3144 };
3145 assert_eq!(request.token().as_ref(), b"live");
3146 assert!(requests.poll_next(&kio::Waiter::noop()).is_pending());
3147 }
3148
3149 fn prefixes(texts: &[&str]) -> Prefixes {
3150 texts
3151 .iter()
3152 .map(|text| crate::Prefix::try_from(*text).unwrap())
3153 .collect()
3154 }
3155
3156 fn grant(publish: &[&str], subscribe: &[&str]) -> Grant {
3157 Grant {
3158 publish: prefixes(publish),
3159 subscribe: prefixes(subscribe),
3160 expires: None,
3161 }
3162 }
3163
3164 #[cfg(feature = "async")]
3166 #[test]
3167 fn the_granted_regions_follow_the_grant_alone() {
3168 let permit = |granted: Option<&[&str]>, limit: Option<&[&str]>| Permit {
3169 granted: granted.map(prefixes),
3170 limit: limit.map(prefixes),
3171 };
3172 let path = crate::Path::from_static;
3173 assert_eq!(permit(None, None).granted_regions(), None);
3174 assert_eq!(permit(None, Some(&["a/b"])).granted_regions(), None);
3175 assert_eq!(
3176 permit(Some(&[""]), Some(&["a"])).granted_regions(),
3177 None,
3178 "a root grant"
3179 );
3180 assert_eq!(permit(Some(&["a"]), None).granted_regions(), Some(vec![path("a")]));
3181 assert_eq!(
3182 permit(Some(&["a", "b"]), Some(&["c"])).granted_regions(),
3183 Some(vec![path("a"), path("b")])
3184 );
3185 }
3186
3187 #[cfg(feature = "async")]
3190 #[test]
3191 fn the_regions_follow_the_grant_and_the_limit() {
3192 let permit = |granted: Option<&[&str]>, limit: Option<&[&str]>| Permit {
3193 granted: granted.map(prefixes),
3194 limit: limit.map(prefixes),
3195 };
3196 let path = crate::Path::from_static;
3197 assert_eq!(permit(None, None).regions(), None);
3198 assert_eq!(permit(None, Some(&["a/b"])).regions(), Some(vec![path("a/b")]));
3199 assert_eq!(permit(Some(&[""]), Some(&["a"])).regions(), Some(vec![path("a")]));
3200 assert_eq!(
3201 permit(Some(&["a", "c/d"]), Some(&["a/b", "c", "e"])).regions(),
3202 Some(vec![path("a/b"), path("c/d")])
3203 );
3204 assert_eq!(permit(Some(&[""]), Some(&[""])).regions(), None, "neither confines");
3205 assert_eq!(
3206 permit(Some(&["a"]), Some(&["b"])).regions(),
3207 Some(vec![]),
3208 "nothing in both"
3209 );
3210 }
3211
3212 #[test]
3215 fn a_permit_allows_what_all_three_allow() {
3216 let permit = |granted: Option<&[&str]>, limit: Option<&[&str]>| Permit {
3217 granted: granted.map(prefixes),
3218 limit: limit.map(prefixes),
3219 };
3220 let within = |permit: Permit, scope: &[&str]| permit.within(prefixes(scope));
3221 assert_eq!(within(permit(Some(&["a/b"]), None), &[""]), prefixes(&["a/b"]));
3222 assert_eq!(within(permit(None, Some(&["a"])), &["a/b", "c"]), prefixes(&["a/b"]));
3223 assert_eq!(
3224 within(permit(Some(&["a"]), Some(&["a/b/c"])), &["a/b"]),
3225 prefixes(&["a/b/c"])
3226 );
3227 assert!(within(permit(Some(&["a/x"]), Some(&["a/y"])), &["a"]).is_empty());
3228 assert_eq!(within(permit(None, None), &["a"]), prefixes(&["a"]));
3229 }
3230
3231 #[test]
3234 fn a_limit_replaces_the_last() {
3235 let handle = Link::new(false);
3236 assert!(handle.allows(Direction::Publish, "room/alice/audio"));
3237
3238 handle.handle().authorize(&grant(&["room/bob"], &["room/alice"]));
3239 assert!(handle.allows(Direction::Publish, "room/alice/audio"));
3241 assert!(!handle.allows(Direction::Publish, "room/bob/cam"));
3242 assert!(handle.allows(Direction::Subscribe, "room/bob/cam"));
3243 assert!(!handle.allows(Direction::Subscribe, "room/alice/audio"));
3244
3245 handle.handle().authorize(&grant(&[""], &["room/alice/video"]));
3246 assert!(!handle.allows(Direction::Publish, "room/alice/audio"));
3247 assert!(handle.allows(Direction::Publish, "room/alice/video"));
3248 assert!(handle.allows(Direction::Subscribe, "other"));
3249
3250 handle.handle().authorize(&Grant::all());
3251 assert!(handle.allows(Direction::Publish, "room/alice/audio"));
3252 assert!(handle.allows(Direction::Subscribe, "other"));
3253 }
3254
3255 #[test]
3258 fn a_scope_admits_whole_only_when_it_leaves_nothing_out() {
3259 let handle = Link::new(false);
3260 assert!(handle.admits_whole());
3261
3262 handle.handle().authorize(&grant(&["tenant-a"], &["tenant-a"]));
3263 assert!(!handle.admits_whole());
3264 handle.handle().authorize(&grant(&[""], &["tenant-a"]));
3265 assert!(!handle.admits_whole());
3266 handle.handle().authorize(&grant(&["tenant-a"], &[""]));
3267 assert!(!handle.admits_whole());
3268 handle.handle().authorize(&Grant::default());
3269 assert!(!handle.admits_whole());
3270
3271 handle.handle().authorize(&grant(&[""], &[""]));
3272 assert!(handle.admits_whole());
3273 }
3274
3275 #[test]
3277 fn the_limit_alone_decides_what_the_peer_offers() {
3278 let handle = Link::new(true);
3279 let token = handle.present(Bytes::new(), true).unwrap();
3280 handle.grant(0, grant(&[], &[]));
3281 assert!(!handle.allows(Direction::Subscribe, "room/bob/cam"));
3282 assert!(handle.within_limit(Direction::Subscribe, "room/bob/cam"));
3283
3284 handle.handle().authorize(&grant(&["room/alice"], &[]));
3285 assert!(!handle.within_limit(Direction::Subscribe, "room/bob/cam"));
3286 assert!(handle.within_limit(Direction::Subscribe, "room/alice/cam"));
3287 drop(token);
3288 }
3289
3290 #[test]
3293 fn the_default_grant_follows_the_limit() {
3294 let handle = Link::new(true);
3295 let mut default = DefaultGrant::new(handle.clone(), grant(&["room"], &["room"]));
3296 let waiter = kio::Waiter::noop();
3297
3298 assert_eq!(default.poll(&waiter), Poll::Ready(grant(&["room"], &["room"])));
3299 assert!(default.poll(&waiter).is_pending());
3300
3301 handle.handle().authorize(&grant(&["room"], &["room/alice"]));
3302 assert_eq!(default.poll(&waiter), Poll::Ready(grant(&["room"], &["room/alice"])));
3303
3304 handle.handle().authorize(&Grant::all());
3306 assert_eq!(default.poll(&waiter), Poll::Ready(grant(&["room"], &["room"])));
3307
3308 handle.handle().authorize(&grant(&[""], &[""]));
3310 assert!(default.poll(&waiter).is_pending());
3311 }
3312
3313 #[test]
3317 fn a_request_carries_an_auth_without_the_auth_stream() {
3318 let ietf = Link::ietf();
3319 let auth = ietf.present(Bytes::from_static(b"jwt"), false).unwrap();
3320 assert!(matches!(
3321 auth.poll_answer(&kio::Waiter::noop()),
3322 Poll::Ready(Ok(Answer::Requests))
3323 ));
3324 assert_eq!(auth.grant().peek(), None);
3325 assert_eq!(ietf.token(&auth).as_deref(), Some(b"jwt".as_slice()));
3326 assert!(
3327 ietf.read(|link, _| link.opening.is_empty()),
3328 "nothing to open a stream for"
3329 );
3330
3331 let lite = Link::new(false);
3332 let auth = lite.present(Bytes::from_static(b"jwt"), false).unwrap();
3333 assert!(matches!(
3334 auth.poll_answer(&kio::Waiter::noop()),
3335 Poll::Ready(Err(Error::Unsupported))
3336 ));
3337 }
3338
3339 #[test]
3342 fn another_handle_does_not_carry_an_auth() {
3343 let issuer = Link::ietf();
3344 let auth = issuer.present(Bytes::from_static(b"jwt"), false).unwrap();
3345 assert_eq!(Link::ietf().token(&auth), None);
3346 }
3347
3348 #[test]
3350 fn the_last_clone_withdraws_the_auth() {
3351 let handle = Link::new(true);
3352 let auth = handle.present(Bytes::from_static(b"jwt"), false).unwrap();
3353 let Poll::Ready(Some((id, _))) = handle.poll_opening(&kio::Waiter::noop()) else {
3354 panic!("nothing to open");
3355 };
3356 let clone = auth.clone();
3357 assert_eq!(clone, auth, "a clone is the same auth");
3358 assert_ne!(
3359 handle.present(Bytes::from_static(b"jwt"), false).unwrap(),
3360 auth,
3361 "the same bytes presented again are another auth"
3362 );
3363
3364 drop(auth);
3365 assert!(
3366 handle.poll_withdrawn(id, &kio::Waiter::noop()).is_pending(),
3367 "withdrawn while a clone lives"
3368 );
3369 drop(clone);
3370 assert!(handle.poll_withdrawn(id, &kio::Waiter::noop()).is_ready());
3371 }
3372
3373 #[test]
3376 fn a_withdrawn_token_takes_no_grant() {
3377 let handle = Link::new(true);
3378 let setup = handle.present(Bytes::new(), true).unwrap();
3379 handle.grant(setup.presented.id, Grant::default());
3380 let auth = handle.present(Bytes::from_static(b"jwt"), false).unwrap();
3381 let id = opened(&handle);
3382 drop(auth);
3383 assert!(handle.poll_withdrawn(id, &kio::Waiter::noop()).is_ready());
3384 handle.granted(id, Grant::all());
3385 assert!(!handle.within_grant(Direction::Publish, "room"));
3386 }
3387
3388 fn opened(link: &Link) -> u64 {
3389 match link.poll_opening(&kio::Waiter::noop()) {
3390 Poll::Ready(Some((id, _))) => id,
3391 _ => panic!("nothing to open"),
3392 }
3393 }
3394
3395 #[test]
3398 fn only_a_verdict_ends_a_shared_token() {
3399 let handle = Handle::new();
3400 let first = Link::attach(&handle, true, false).unwrap();
3401 assert!(matches!(Link::attach(&handle, true, false), Err(Error::Duplicate)));
3402 let auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3403 let id = opened(&first);
3404 first.grant(id, Grant::all());
3405 assert!(matches!(
3406 auth.poll_answer(&kio::Waiter::noop()),
3407 Poll::Ready(Ok(Answer::Granted))
3408 ));
3409 assert_eq!(auth.grant().peek(), Some(Grant::all()));
3410
3411 first.close(Error::Cancel);
3412 assert_eq!(auth.grant().peek(), None, "no session is live");
3413 assert!(Selector::Token(id).ended(&handle.state.read()).is_none());
3414
3415 let second = Link::attach(&handle, true, false).unwrap();
3416 assert_eq!(opened(&second), id, "the next session presents it again");
3417 second.refused(id, false);
3418 let refused = Error::Session(SessionError::Unauthorized);
3419 assert_eq!(second.retry(id, &refused), None);
3420 second.ended(id, refused);
3421 assert!(matches!(
3422 Selector::Token(id).ended(&handle.state.read()),
3423 Some(Error::Session(SessionError::Unauthorized))
3424 ));
3425
3426 second.close(Error::Cancel);
3427 let third = Link::attach(&handle, true, false).unwrap();
3428 assert!(
3429 third.poll_opening(&kio::Waiter::noop()).is_pending(),
3430 "a refused token stays ended"
3431 );
3432 }
3433
3434 #[test]
3437 fn the_answer_outlives_its_session() {
3438 let handle = Handle::new();
3439 let session = Link::attach(&handle, true, false).unwrap();
3440 let auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3441 session.grant(opened(&session), Grant::all());
3442 session.close(Error::Cancel);
3443 assert_eq!(auth.grant().peek(), None);
3444 assert!(matches!(
3445 auth.poll_answer(&kio::Waiter::noop()),
3446 Poll::Ready(Ok(Answer::Granted))
3447 ));
3448
3449 let handle = Handle::new();
3450 let _session = Link::attach(&handle, false, true).unwrap();
3451 let auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3452 assert!(matches!(
3453 auth.poll_answer(&kio::Waiter::noop()),
3454 Poll::Ready(Ok(Answer::Requests))
3455 ));
3456 }
3457
3458 #[test]
3461 fn a_sessions_own_handle_ends_its_tokens() {
3462 let link = Link::new(true);
3463 let auth = link.present(Bytes::from_static(b"jwt"), false).unwrap();
3464 let id = opened(&link);
3465 let lost = Error::Stream(crate::StreamError::Internal);
3466 assert_eq!(link.retry(id, &lost), None, "the application hears of a lost token");
3467 link.ended(id, lost);
3468 assert!(matches!(
3469 auth.poll_answer(&kio::Waiter::noop()),
3470 Poll::Ready(Err(Error::Stream(_)))
3471 ));
3472
3473 let (goaway, _protocol) = crate::goaway::Handle::new(false);
3474 goaway.send(crate::goaway::Goaway::new()).unwrap();
3475 link.drain_with(std::sync::Arc::new(goaway));
3476 assert!(matches!(
3477 link.present(Bytes::from_static(b"late"), false),
3478 Err(Error::GoingAway)
3479 ));
3480 }
3481
3482 #[test]
3485 fn a_draining_session_takes_no_new_token() {
3486 let handle = Handle::new();
3487 let draining = Link::attach(&handle, false, false).unwrap();
3488 let (goaway, _protocol) = crate::goaway::Handle::new(false);
3489 goaway.send(crate::goaway::Goaway::new()).unwrap();
3490 draining.drain_with(std::sync::Arc::new(goaway));
3491 let successor = Link::attach(&handle, true, false).unwrap();
3492
3493 let auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3494 assert!(Selector::Token(auth.id()).ended(&handle.state.read()).is_none());
3495 let id = opened(&successor);
3496 successor.grant(id, Grant::all());
3497 assert!(matches!(
3498 auth.poll_answer(&kio::Waiter::noop()),
3499 Poll::Ready(Ok(Answer::Granted))
3500 ));
3501 }
3502
3503 #[test]
3506 fn a_draining_refusal_leaves_the_successors_grant() {
3507 let handle = Handle::new();
3508 let draining = Link::attach(&handle, true, false).unwrap();
3509 let auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3510 let id = opened(&draining);
3511 let (goaway, _protocol) = crate::goaway::Handle::new(false);
3512 goaway.send(crate::goaway::Goaway::new()).unwrap();
3513 draining.drain_with(std::sync::Arc::new(goaway));
3514
3515 let successor = Link::attach(&handle, true, false).unwrap();
3516 assert_eq!(opened(&successor), id);
3517 successor.grant(id, Grant::all());
3518 draining.refused(id, false);
3519 draining.ended(id, Error::Session(SessionError::Unauthorized));
3520 assert!(Selector::Token(id).ended(&handle.state.read()).is_none());
3521 assert_eq!(auth.grant().peek(), Some(Grant::all()));
3522 }
3523
3524 #[test]
3527 fn a_draining_refusal_defers_to_the_successors_retry() {
3528 let handle = Handle::new();
3529 let draining = Link::attach(&handle, true, false).unwrap();
3530 let auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3531 let id = opened(&draining);
3532 let (goaway, _protocol) = crate::goaway::Handle::new(false);
3533 goaway.send(crate::goaway::Goaway::new()).unwrap();
3534 draining.drain_with(std::sync::Arc::new(goaway));
3535
3536 let successor = Link::attach(&handle, true, false).unwrap();
3537 assert_eq!(opened(&successor), id);
3538 successor.grant(id, Grant::all());
3539 successor.refused(id, true);
3540 let busy = Error::Session(SessionError::TooManyRequests);
3541 assert_eq!(successor.retry(id, &busy), Some(RETRY_INITIAL));
3542
3543 draining.refused(id, false);
3544 draining.ended(id, Error::Session(SessionError::Unauthorized));
3545 assert!(Selector::Token(id).ended(&handle.state.read()).is_none());
3546
3547 assert_eq!(successor.reopen(id).unwrap().as_ref(), b"jwt");
3548 successor.grant(id, Grant::all());
3549 assert_eq!(auth.grant().peek(), Some(Grant::all()));
3550 }
3551
3552 #[test]
3555 fn a_draining_session_presents_no_retry() {
3556 let link = Link::new(true);
3557 let (goaway, _protocol) = crate::goaway::Handle::new(false);
3558 let goaway = std::sync::Arc::new(goaway);
3559 link.drain_with(goaway.clone());
3560 let auth = link.present(Bytes::from_static(b"jwt"), false).unwrap();
3561 let id = opened(&link);
3562 link.refused(id, true);
3563 let busy = Error::Session(SessionError::TooManyRequests);
3564 assert_eq!(link.retry(id, &busy), Some(RETRY_INITIAL));
3565
3566 goaway.send(crate::goaway::Goaway::new()).unwrap();
3567 assert!(!link.active());
3568 let err = link.reopen(id).unwrap_err();
3569 assert!(matches!(err, Error::GoingAway), "{err:?}");
3570 link.ended(id, err);
3571 assert!(matches!(
3572 Selector::Token(auth.id()).ended(&link.state().read()),
3573 Some(Error::GoingAway)
3574 ));
3575 }
3576
3577 #[test]
3581 fn a_lost_stream_is_presented_again() {
3582 let handle = Handle::new();
3583 let link = Link::attach(&handle, true, true).unwrap();
3584 let auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3585 let id = opened(&link);
3586 let lost = Error::Stream(crate::StreamError::Internal);
3587
3588 link.grant(id, Grant::all());
3589 assert_eq!(link.retry(id, &lost), Some(RETRY_INITIAL));
3590 assert_eq!(auth.grant().peek(), None, "the lost stream's grant is gone");
3591 assert_eq!(link.token(&auth).as_deref(), Some(&b"jwt"[..]));
3592 let mut gate = Gate::new(link.clone(), crate::Path::from_static("room"), Direction::Publish);
3593 assert!(gate.poll_ready(&kio::Waiter::noop()).is_pending());
3594
3595 assert_eq!(link.reopen(id).unwrap().as_ref(), b"jwt");
3596 assert_eq!(link.retry(id, &lost), Some(RETRY_INITIAL * 2));
3597 link.reopen(id).unwrap();
3598 link.grant(id, Grant::all());
3599 assert!(gate.poll_ready(&kio::Waiter::noop()).is_ready());
3600 assert_eq!(link.retry(id, &lost), Some(RETRY_INITIAL), "a grant resets the backoff");
3601 assert!(Selector::Token(id).ended(&handle.state.read()).is_none());
3602
3603 link.reopen(id).unwrap();
3605 link.grant(id, Grant::all());
3606 assert_eq!(link.retry(id, &Error::Cancel), None);
3607 link.ended(id, Error::Cancel);
3608 assert!(matches!(
3609 Selector::Token(id).ended(&handle.state.read()),
3610 Some(Error::Cancel)
3611 ));
3612 }
3613
3614 #[test]
3617 fn a_draining_session_leaves_an_undecided_token() {
3618 let handle = Handle::new();
3619 let draining = Link::attach(&handle, true, false).unwrap();
3620 let _auth = handle.add(Bytes::from_static(b"jwt")).unwrap();
3621 let id = opened(&draining);
3622 let (goaway, _protocol) = crate::goaway::Handle::new(false);
3623 goaway.send(crate::goaway::Goaway::new()).unwrap();
3624 draining.drain_with(std::sync::Arc::new(goaway));
3625
3626 let busy = Error::Session(SessionError::TooManyRequests);
3627 draining.refused(id, true);
3628 assert_eq!(draining.retry(id, &busy), None);
3629 draining.ended(id, busy);
3630 assert!(Selector::Token(id).ended(&handle.state.read()).is_none());
3631
3632 let successor = Link::attach(&handle, true, false).unwrap();
3633 assert_eq!(opened(&successor), id, "the successor presents it");
3634 }
3635
3636 #[test]
3638 fn a_transient_refusal_backs_off() {
3639 let link = Link::new(true);
3640 let auth = link.present(Bytes::from_static(b"jwt"), false).unwrap();
3641 let id = opened(&link);
3642 let busy = Error::Session(SessionError::TooManyRequests);
3643
3644 link.refused(id, true);
3645 assert_eq!(link.retry(id, &busy), Some(RETRY_INITIAL));
3646 assert!(auth.poll_answer(&kio::Waiter::noop()).is_pending());
3647 assert_eq!(link.reopen(id).unwrap().as_ref(), b"jwt");
3648 link.refused(id, true);
3649 assert_eq!(link.retry(id, &busy), Some(RETRY_INITIAL * 2));
3650 assert_eq!(link.retry(id, &busy), None, "only a refusal retries");
3651
3652 link.reopen(id).unwrap();
3653 link.grant(id, Grant::all());
3654 assert!(matches!(
3655 auth.poll_answer(&kio::Waiter::noop()),
3656 Poll::Ready(Ok(Answer::Granted))
3657 ));
3658 }
3659}
3660
3661#[cfg(all(test, feature = "async"))]
3662mod request_token_tests {
3663 use super::*;
3664 use futures::FutureExt;
3665
3666 fn token(value: &[u8], kind: u64) -> crate::setup::Token {
3667 crate::setup::Token {
3668 kind,
3669 value: value.to_vec(),
3670 }
3671 }
3672
3673 fn subscribe_path() -> crate::Path {
3674 crate::Path::from_static("room/alice")
3675 }
3676
3677 #[kio::test]
3680 async fn a_request_token_reaches_the_acceptor() {
3681 let handle = Link::new(true);
3682 let mut requests = handle.handle().requests();
3683 let verdict = handle.verify_request(token(b"jwt", 0), None);
3684
3685 let request = requests.next().await.expect("a request");
3686 assert_eq!(request.token().as_ref(), b"jwt");
3687 let _issued = request.accept(Grant::all());
3688
3689 let grant = verdict.grant().await.expect("granted");
3690 assert!(grant.publish.matches("room/alice"));
3691 }
3692
3693 #[kio::test]
3694 async fn naming_requests_share_verification_and_withdraw_together() {
3695 let handle = Link::new(true);
3696 let mut requests = handle.handle().requests();
3697 let first = handle.verify_request(token(b"shared", 0), None);
3698 let second = handle.verify_request(token(b"shared", 0), None);
3699 let issued = requests.next().await.unwrap().accept(Grant::all());
3700 assert!(requests.poll_next(&kio::Waiter::noop()).is_pending());
3701 first.grant().await.unwrap();
3702 second.grant().await.unwrap();
3703 drop(first);
3704 assert!(issued.closed().now_or_never().is_none());
3705 drop(second);
3706 assert!(matches!(issued.closed().await, Error::Cancel));
3707 let later = handle.verify_request(token(b"shared", 0), None);
3708 let _issued = requests.next().await.unwrap().accept(Grant::default());
3709 assert_eq!(later.grant().await.unwrap(), Grant::default());
3710 }
3711
3712 #[kio::test]
3715 async fn a_token_the_acceptor_dropped_verifies_again() {
3716 let handle = Link::new(true);
3717 let mut requests = handle.handle().requests();
3718 let first = handle.verify_request(token(b"shared", 0), None);
3719 let issued = requests.next().await.unwrap().accept(Grant::all());
3720 first.grant().await.unwrap();
3721 drop(issued);
3722 let later = handle.verify_request(token(b"shared", 0), None);
3723 let _issued = requests.next().await.unwrap().accept(Grant::default());
3724 assert_eq!(later.grant().await.unwrap(), Grant::default());
3725 drop(first);
3726 let again = handle.verify_request(token(b"shared", 0), None);
3727 assert!(
3728 requests.poll_next(&kio::Waiter::noop()).is_pending(),
3729 "the live verdict is shared"
3730 );
3731 assert_eq!(again.grant().await.unwrap(), Grant::default());
3732 }
3733
3734 #[kio::test]
3735 async fn every_naming_request_observes_updates_revocation_and_expiry() {
3736 for revoke in [false, true] {
3737 let runtime = crate::time::sim();
3738 let handle = Link::new(true);
3739 let mut requests = handle.handle().requests();
3740 let first = handle.verify_request(token(b"shared", 0), None);
3741 let second = handle.verify_request(token(b"shared", 0), None);
3742 let issued = requests.next().await.unwrap().accept(grant_in(&runtime, 60));
3743 let mut grants = Vec::new();
3744 for verdict in [first, second] {
3745 let answer = verdict.grant().await;
3746 grants.push(
3747 RequestGrant::new(
3748 &runtime,
3749 verdict,
3750 answer,
3751 subscribe_path(),
3752 RequestKind::Subscribe,
3753 None,
3754 )
3755 .unwrap(),
3756 );
3757 }
3758 issued.update(grant_in(&runtime, 30));
3759 for grant in &grants {
3760 assert!(grant.poll_ended(&kio::Waiter::noop()).is_pending());
3761 assert_eq!(grant.grant(), grant_in(&runtime, 30));
3762 }
3763 if revoke {
3764 issued.revoke(SessionError::Unauthorized, "revoked");
3765 } else {
3766 kio::clock::sleep(Duration::from_secs(30)).await;
3767 }
3768 for grant in grants {
3769 let Poll::Ready(refusal) = grant.poll_ended(&kio::Waiter::noop()) else {
3770 panic!("token stayed live");
3771 };
3772 if revoke {
3773 assert_eq!(refusal.reason, "revoked");
3774 } else {
3775 assert!(matches!(refusal.error, Error::Expired));
3776 }
3777 }
3778 }
3779 }
3780
3781 #[kio::test]
3782 async fn discovery_uses_its_token_alone() {
3783 let runtime = crate::time::sim();
3784 let handle = Link::new(true);
3785 handle.handle().authorize(&Grant::all());
3786 let mut requests = handle.handle().requests();
3787 let mut gate = Gate::new(handle.clone(), crate::Path::default(), Direction::Publish).discovery();
3788 let verdict = gate.verify(token(b"room", 0), None);
3789 let issued = requests.next().await.unwrap().accept(subscribe_only("room"));
3790 let answer = verdict.grant().await;
3791 gate.admit(&runtime, (verdict, answer)).unwrap();
3792 let mut epoch = 0;
3793 let Poll::Ready(permit) = gate.poll_permit(&mut epoch, &kio::Waiter::noop()) else {
3794 panic!("no initial permit");
3795 };
3796 assert!(permit.matches("room/alice"));
3797 assert!(!permit.matches("elsewhere"));
3798 issued.update(subscribe_only("room/bob"));
3799 let Poll::Ready(permit) = gate.poll_permit(&mut epoch, &kio::Waiter::noop()) else {
3800 panic!("update missed");
3801 };
3802 assert!(permit.matches("room/bob"));
3803 assert!(!permit.matches("room/alice"));
3804 drop(gate);
3805 assert!(matches!(issued.closed().await, Error::Cancel));
3806 }
3807
3808 #[kio::test]
3811 async fn a_bound_token_ending_is_a_new_permit() {
3812 let runtime = crate::time::sim();
3813 let handle = Link::new(true);
3814 handle.handle().authorize(&Grant::all());
3815 let mut requests = handle.handle().requests();
3816 let mut gate = Gate::new(handle.clone(), crate::Path::default(), Direction::Publish).discovery();
3817 let verdict = gate.verify(token(b"room", 0), None);
3818 let issued = requests.next().await.unwrap().accept(subscribe_only("room"));
3819 let answer = verdict.grant().await;
3820 gate.admit(&runtime, (verdict, answer)).unwrap();
3821 let mut epoch = 0;
3822 let Poll::Ready(permit) = gate.poll_permit(&mut epoch, &kio::Waiter::noop()) else {
3823 panic!("no initial permit");
3824 };
3825 assert!(permit.matches("room/alice"));
3826 issued.revoke(SessionError::Unauthorized, "revoked");
3827 let Poll::Ready(permit) = gate.poll_permit(&mut epoch, &kio::Waiter::noop()) else {
3828 panic!("the token's end went unreported");
3829 };
3830 assert!(!permit.matches("room/alice"));
3831 assert!(gate.poll_permit(&mut epoch, &kio::Waiter::noop()).is_pending());
3832 }
3833
3834 #[kio::test]
3837 async fn a_bound_gate_hands_over_to_a_granted_replacement() {
3838 let runtime = crate::time::sim();
3839 let handle = Link::new(true);
3840 handle.handle().authorize(&Grant::all());
3841 let mut requests = handle.handle().requests();
3842 let mut gate = Gate::new(handle.clone(), crate::Path::default(), Direction::Publish).discovery();
3843 let verdict = gate.verify(token(b"jwt", 0), None);
3844 let _issued = requests.next().await.unwrap().accept(grant_in(&runtime, 60));
3845 let answer = verdict.grant().await;
3846 gate.admit(&runtime, (verdict, answer)).unwrap();
3847
3848 let renewal = gate.verify(token(b"jwt2", 0), None);
3849 let _issued2 = requests.next().await.unwrap().accept(grant_in(&runtime, 600));
3850 kio::clock::sleep(Duration::from_secs(61)).await;
3851 let pending = kio::wait(|waiter| Poll::Ready(gate.poll_token_ended(waiter).is_pending())).await;
3852 assert!(pending, "the old grant lapsed ahead of its granted replacement");
3853
3854 let answer = renewal.grant().await;
3855 gate.admit(&runtime, (renewal, answer)).unwrap();
3856 let pending = kio::wait(|waiter| Poll::Ready(gate.poll_token_ended(waiter).is_pending())).await;
3857 assert!(pending, "the replacement holds the gate");
3858 }
3859
3860 #[kio::test]
3864 async fn request_tokens_do_not_wake_permit_waiters() {
3865 struct Woken(std::sync::atomic::AtomicBool);
3866 impl std::task::Wake for Woken {
3867 fn wake(self: std::sync::Arc<Self>) {
3868 self.0.store(true, std::sync::atomic::Ordering::SeqCst);
3869 }
3870 }
3871 let handle = Link::new(true);
3872 let mut requests = handle.handle().requests();
3873 let first = handle.verify_request(token(b"warm", 0), None);
3874 let _first = requests.next().await.unwrap().accept(Grant::all());
3875 first.grant().await.unwrap();
3876
3877 let woken = std::sync::Arc::new(Woken(Default::default()));
3878 let waiter = kio::Waiter::new(std::task::Waker::from(woken.clone()));
3879 let mut epoch = 0;
3880 while handle.poll_permit(Direction::Publish, &mut epoch, &waiter).is_ready() {}
3881 let second = handle.verify_request(token(b"shared", 0), None);
3882 let third = handle.verify_request(token(b"shared", 0), None);
3883 drop((second, third));
3884 assert!(
3885 !woken.0.load(std::sync::atomic::Ordering::SeqCst),
3886 "a request token woke the permit waiters"
3887 );
3888 }
3889
3890 #[kio::test]
3891 async fn request_tokens_are_scoped_to_one_session_on_a_shared_handle() {
3892 let handle = Handle::new();
3893 let first = Link::attach(&handle, false, true).unwrap();
3894 let mut requests = handle.requests();
3895 let verdict = first.verify_request(token(b"token", 0), None);
3896 let issued = requests.next().await.unwrap().accept(Grant::all());
3897 verdict.grant().await.unwrap();
3898 first.close(Error::Cancel);
3899 let second = Link::attach(&handle, false, true).unwrap();
3900 let next = second.verify_request(token(b"token", 0), None);
3901 let _next = requests.next().await.unwrap().accept(Grant::default());
3902 assert_eq!(next.grant().await.unwrap(), Grant::default());
3903 assert!(matches!(issued.closed().await, Error::Cancel));
3904 }
3905
3906 #[kio::test]
3909 async fn a_typed_request_token_is_unsupported() {
3910 let handle = Link::new(true);
3911 let mut requests = handle.handle().requests();
3912 let verdict = handle.verify_request(token(b"cat", 1), None);
3913 let err = verdict.grant().await.expect_err("a typed token");
3914 assert!(matches!(err.error, Error::Unsupported), "{err:?}");
3915 assert!(
3916 requests.poll_next(&kio::Waiter::noop()).is_pending(),
3917 "nothing reached the acceptor"
3918 );
3919 }
3920
3921 #[test]
3924 fn an_empty_request_token_is_unsupported() {
3925 let handle = Link::new(true);
3926 let mut requests = handle.handle().requests();
3927 let verdict = handle.verify_request(token(b"", crate::setup::Token::OUT_OF_BAND), None);
3928 assert!(matches!(
3929 verdict.poll_grant(&kio::Waiter::noop()),
3930 Poll::Ready(Err(Refusal {
3931 error: Error::Unsupported,
3932 ..
3933 }))
3934 ));
3935 assert!(
3936 requests.poll_next(&kio::Waiter::noop()).is_pending(),
3937 "nothing reached the acceptor"
3938 );
3939 }
3940
3941 #[kio::test]
3944 async fn a_request_token_is_verified_without_the_auth_stream() {
3945 let handle = Link::new(false);
3946 let mut requests = handle.handle().requests();
3947 let verdict = handle.verify_request(token(b"jwt", 0), None);
3948 let request = requests.next().await.expect("a request reaches the acceptor");
3949 let _issued = request.accept(Grant::all());
3950 assert!(
3951 verdict.grant().await.expect("granted").publish.matches("room/alice"),
3952 "admitted without AUTH"
3953 );
3954 }
3955
3956 #[kio::test]
3959 async fn no_consumer_refuses_a_request_token_as_unsupported() {
3960 let handle = Link::new(true);
3961 let verdict = handle.verify_request(token(b"jwt", 0), None);
3962 let err = verdict.grant().await.expect_err("no verifier");
3963 assert!(matches!(err.error, Error::Unsupported), "{err:?}");
3964 }
3965
3966 #[kio::test]
3969 async fn a_refused_request_token_is_unauthorized() {
3970 let handle = Link::new(true);
3971 let mut requests = handle.handle().requests();
3972 let verdict = handle.verify_request(token(b"jwt", 0), None);
3973 requests.next().await.unwrap().reject(SessionError::Unauthorized, "no");
3974 let err = verdict.grant().await.expect_err("refused");
3975 assert!(
3976 matches!(err.error, Error::Session(SessionError::Unauthorized)),
3977 "{err:?}"
3978 );
3979 }
3980
3981 #[kio::test]
3984 async fn a_grant_ended_before_admission_is_refused() {
3985 let handle = Link::new(true);
3986 let mut requests = handle.handle().requests();
3987
3988 let verdict = handle.verify_request(token(b"jwt", 0), None);
3989 let issued = requests.next().await.unwrap().accept(Grant::all());
3990 issued.revoke(SessionError::Unauthorized, "revoked");
3991 let err = verdict.grant().await.expect_err("revoked before admission");
3992 assert_eq!(err.reason, "revoked");
3993 drop(verdict);
3994
3995 let verdict = handle.verify_request(token(b"jwt", 0), None);
3996 drop(requests.next().await.unwrap().accept(Grant::all()));
3997 let err = verdict.grant().await.expect_err("dropped before admission");
3998 assert!(
3999 matches!(err.error, Error::Session(SessionError::Unauthorized)),
4000 "{err:?}"
4001 );
4002 drop(verdict);
4003
4004 let verdict = handle.verify_request(token(b"jwt", 0), None);
4005 let issued = requests.next().await.unwrap().accept(Grant::all());
4006 issued.update(Grant::default());
4007 let grant = verdict.grant().await.expect("still granted");
4008 assert!(
4009 !grant.publish.matches("room/alice"),
4010 "the replacement is what is admitted"
4011 );
4012 }
4013
4014 #[kio::test]
4017 async fn dropping_the_verdict_ends_the_grant() {
4018 let handle = Link::new(true);
4019 let mut requests = handle.handle().requests();
4020 let verdict = handle.verify_request(token(b"jwt", 0), None);
4021 let issued = requests.next().await.unwrap().accept(Grant::all());
4022 verdict.grant().await.expect("granted");
4023 drop(verdict);
4024 let err = issued.closed().await;
4025 assert!(matches!(err, Error::Cancel), "{err:?}");
4026 }
4027
4028 #[kio::test]
4031 async fn a_request_token_never_joins_the_union() {
4032 let handle = Link::new(true);
4033 let mut requests = handle.handle().requests();
4034 let verdict = handle.verify_request(token(b"jwt", 0), None);
4035 let _issued = requests.next().await.unwrap().accept(Grant::all());
4036 verdict.grant().await.expect("granted");
4037 assert_eq!(
4040 handle.handle().grant().peek(),
4041 None,
4042 "a request token must not widen the union"
4043 );
4044 }
4045
4046 fn subscribe_only(prefix: &str) -> Grant {
4047 Grant {
4048 publish: Prefixes::new(),
4049 subscribe: crate::Prefix::try_from(prefix).unwrap().into(),
4050 expires: None,
4051 }
4052 }
4053
4054 #[kio::test]
4058 async fn the_scope_is_session_tokens_only() {
4059 let handle = Link::new(true);
4060 let mut requests = handle.handle().requests();
4061 handle.handle().authorize(&subscribe_only("room/alice"));
4062 assert!(!handle.allows(Direction::Publish, "room/bob"));
4063
4064 let verdict = handle.verify_request(token(b"request", 0), None);
4066 let _request = requests.next().await.unwrap().accept(subscribe_only("room/bob"));
4067 verdict.grant().await.expect("granted");
4068 assert!(
4069 !handle.allows(Direction::Publish, "room/bob"),
4070 "a request token widened the scope"
4071 );
4072
4073 let serving = Serving::new(handle.clone());
4075 requests
4076 .queue
4077 .push(Request::new(Bytes::from_static(b"auth"), serving.issue.clone()));
4078 let issued = requests.next().await.unwrap().accept(subscribe_only("room/carol"));
4079 assert!(handle.allows(Direction::Publish, "room/carol"));
4080 assert!(
4081 handle.allows(Direction::Publish, "room/alice"),
4082 "the connection grant still stands"
4083 );
4084
4085 issued.update(subscribe_only("room/dave"));
4086 assert!(
4087 !handle.allows(Direction::Publish, "room/carol"),
4088 "the update replaced it"
4089 );
4090 assert!(handle.allows(Direction::Publish, "room/dave"));
4091
4092 serving.end(Error::Cancel);
4094 assert!(!handle.allows(Direction::Publish, "room/dave"));
4095 issued.update(subscribe_only("room/dave"));
4096 assert!(
4097 !handle.allows(Direction::Publish, "room/dave"),
4098 "a withdrawn token rejoined the scope"
4099 );
4100 }
4101
4102 #[kio::test]
4104 async fn an_ended_auth_grant_leaves_the_scope() {
4105 let handle = Link::new(true);
4106 let mut requests = handle.handle().requests();
4107 handle.handle().authorize(&Grant::default());
4108 for revoke in [true, false] {
4109 let serving = Serving::new(handle.clone());
4110 requests
4111 .queue
4112 .push(Request::new(Bytes::from_static(b"auth"), serving.issue.clone()));
4113 let issued = requests.next().await.unwrap().accept(subscribe_only("room"));
4114 assert!(handle.allows(Direction::Publish, "room/alice"));
4115 match revoke {
4116 true => issued.revoke(SessionError::Unauthorized, "revoked"),
4117 false => drop(issued),
4118 }
4119 assert!(!handle.allows(Direction::Publish, "room/alice"), "revoke={revoke}");
4120 }
4121 }
4122
4123 #[kio::test]
4126 async fn an_unauthorized_session_has_no_scope() {
4127 let handle = Link::new(true);
4128 let mut requests = handle.handle().requests();
4129 let serving = Serving::new(handle.clone());
4130 requests
4131 .queue
4132 .push(Request::new(Bytes::from_static(b"auth"), serving.issue.clone()));
4133 let _issued = requests.next().await.unwrap().accept(subscribe_only("room"));
4134 assert!(handle.allows(Direction::Publish, "other"));
4135 }
4136
4137 use std::time::Duration;
4138
4139 fn grant_in(runtime: &crate::time::Deadlines, secs: u64) -> Grant {
4140 Grant {
4141 publish: Prefixes::new(),
4142 subscribe: Prefixes::all(),
4143 expires: runtime.now().checked_add(Duration::from_secs(secs)),
4144 }
4145 }
4146
4147 #[kio::test]
4149 async fn a_request_grant_has_the_acceptors_expiry() {
4150 let runtime = crate::time::sim();
4151 let handle = Link::new(true);
4152 let mut requests = handle.handle().requests();
4153 let verdict = handle.verify_request(token(b"jwt", 0), None);
4154 let grant = grant_in(&runtime, 60);
4155 let expires = grant.expires;
4156 let _issued = requests.next().await.unwrap().accept(grant);
4157 let answered = verdict.grant().await.unwrap();
4158 let request_grant = RequestGrant::new(
4159 &runtime,
4160 verdict,
4161 Ok(answered),
4162 subscribe_path(),
4163 RequestKind::Subscribe,
4164 None,
4165 )
4166 .unwrap();
4167 assert_eq!(request_grant.grant().expires, expires);
4168 assert!(expires.is_some());
4169 }
4170
4171 #[kio::test]
4174 async fn an_already_expired_grant_is_refused() {
4175 let runtime = crate::time::sim();
4176 let handle = Link::new(true);
4177 let mut requests = handle.handle().requests();
4178 let expired = || Grant {
4179 expires: Some(runtime.now()),
4180 ..grant_in(&runtime, 0)
4181 };
4182
4183 let verdict = handle.verify_request(token(b"old", 0), None);
4184 let _issued = requests.next().await.unwrap().accept(expired());
4185 let answered = verdict.grant().await;
4186 let refused = RequestGrant::new(
4187 &runtime,
4188 verdict,
4189 answered,
4190 subscribe_path(),
4191 RequestKind::Subscribe,
4192 None,
4193 );
4194 assert!(
4195 matches!(&refused, Err(refusal) if matches!(refusal.error, Error::Unauthorized)),
4196 "an expired grant admits nothing"
4197 );
4198
4199 let verdict = handle.verify_request(token(b"jwt", 0), None);
4200 let _issued = requests.next().await.unwrap().accept(grant_in(&runtime, 60));
4201 let answered = verdict.grant().await;
4202 let request_grant = RequestGrant::new(
4203 &runtime,
4204 verdict,
4205 answered,
4206 subscribe_path(),
4207 RequestKind::Subscribe,
4208 None,
4209 )
4210 .unwrap();
4211 let renewal = handle.verify_request(token(b"old2", 0), None);
4212 let _issued = requests.next().await.unwrap().accept(expired());
4213 let renewed = renewal.grant().await;
4214 assert!(
4215 request_grant.renew(renewal, renewed).is_err(),
4216 "an expired grant renews nothing"
4217 );
4218 }
4219
4220 #[kio::test]
4222 async fn a_renewal_token_replaces_the_grant_and_expiry() {
4223 let runtime = crate::time::sim();
4224 let handle = Link::new(true);
4225 let mut requests = handle.handle().requests();
4226
4227 let verdict = handle.verify_request(token(b"jwt", 0), None);
4228 let first = grant_in(&runtime, 60);
4229 let first_expires = first.expires;
4230 let _issued = requests.next().await.unwrap().accept(first);
4231 let answered = verdict.grant().await.unwrap();
4232 let request_grant = RequestGrant::new(
4233 &runtime,
4234 verdict,
4235 Ok(answered),
4236 subscribe_path(),
4237 RequestKind::Subscribe,
4238 None,
4239 )
4240 .unwrap();
4241
4242 let renewal = handle.verify_request(token(b"jwt2", 0), None);
4244 let second = grant_in(&runtime, 600);
4245 let second_expires = second.expires;
4246 let _issued2 = requests.next().await.unwrap().accept(second);
4247 let renewed = renewal.grant().await;
4248 assert!(
4249 request_grant.renew(renewal, renewed).is_ok(),
4250 "a covering renewal renews"
4251 );
4252
4253 assert_eq!(request_grant.grant().expires, second_expires);
4254 assert_ne!(second_expires, first_expires);
4255 }
4256
4257 #[kio::test]
4260 async fn the_deadline_expires_the_request_without_renewal() {
4261 let runtime = crate::time::sim();
4262 let handle = Link::new(true);
4263 let mut requests = handle.handle().requests();
4264 let verdict = handle.verify_request(token(b"jwt", 0), None);
4265 let _issued = requests.next().await.unwrap().accept(grant_in(&runtime, 60));
4267 let answered = verdict.grant().await.unwrap();
4268 let request_grant = RequestGrant::new(
4269 &runtime,
4270 verdict,
4271 Ok(answered),
4272 subscribe_path(),
4273 RequestKind::Subscribe,
4274 None,
4275 )
4276 .unwrap();
4277
4278 let err = kio::wait(|waiter| request_grant.poll_ended(waiter)).await.error;
4279 assert!(matches!(err, Error::Expired), "{err:?}");
4280 assert_eq!(handle.handle().grant().peek(), None, "the session grant is untouched");
4281 }
4282
4283 #[kio::test]
4288 async fn an_extension_read_after_the_old_expiry_keeps_the_request() {
4289 let runtime = crate::time::sim();
4290 let handle = Link::new(true);
4291 let mut requests = handle.handle().requests();
4292 let verdict = handle.verify_request(token(b"jwt", 0), None);
4293 let issued = requests.next().await.unwrap().accept(grant_in(&runtime, 60));
4294 let answered = verdict.grant().await.unwrap();
4295 let request_grant = RequestGrant::new(
4296 &runtime,
4297 verdict,
4298 Ok(answered),
4299 subscribe_path(),
4300 RequestKind::Subscribe,
4301 None,
4302 )
4303 .unwrap();
4304 let pending = kio::wait(|waiter| Poll::Ready(request_grant.poll_ended(waiter).is_pending())).await;
4305 assert!(pending, "the first grant stands");
4306
4307 let extended = grant_in(&runtime, 600);
4309 let expires = extended.expires;
4310 issued.update(extended);
4311 kio::clock::sleep(Duration::from_secs(61)).await;
4312
4313 let pending = kio::wait(|waiter| Poll::Ready(request_grant.poll_ended(waiter).is_pending())).await;
4314 assert!(pending, "the old expiry ended a request its acceptor had extended");
4315 assert_eq!(request_grant.grant().expires, expires);
4316
4317 kio::clock::sleep(Duration::from_secs(600)).await;
4319 let ended = kio::wait(|waiter| Poll::Ready(request_grant.poll_ended(waiter))).await;
4320 assert!(matches!(ended, Poll::Ready(refusal) if matches!(refusal.error, Error::Expired)));
4321 }
4322
4323 #[kio::test]
4324 async fn a_granted_renewal_outlives_the_old_deadline() {
4325 let runtime = crate::time::sim();
4326 let handle = Link::new(true);
4327 let mut requests = handle.handle().requests();
4328 let verdict = handle.verify_request(token(b"jwt", 0), None);
4329 let _issued = requests.next().await.unwrap().accept(grant_in(&runtime, 60));
4330 let answered = verdict.grant().await.unwrap();
4331 let request_grant = RequestGrant::new(
4332 &runtime,
4333 verdict,
4334 Ok(answered),
4335 subscribe_path(),
4336 RequestKind::Subscribe,
4337 None,
4338 )
4339 .unwrap();
4340
4341 let renewal = request_grant.verify_renewal(&handle, token(b"jwt2", 0));
4342 let second = grant_in(&runtime, 600);
4343 let second_expires = second.expires;
4344 let _issued2 = requests.next().await.unwrap().accept(second);
4345 kio::clock::sleep(Duration::from_secs(61)).await;
4346
4347 let pending = kio::wait(|waiter| Poll::Ready(request_grant.poll_ended(waiter).is_pending())).await;
4348 assert!(pending, "the lapsed deadline ended a request whose renewal was granted");
4349
4350 let renewed = renewal.grant().await;
4351 assert!(request_grant.renew(renewal, renewed).is_ok());
4352 assert_eq!(request_grant.grant().expires, second_expires);
4353 let pending = kio::wait(|waiter| Poll::Ready(request_grant.poll_ended(waiter).is_pending())).await;
4354 assert!(pending, "the renewal holds the request");
4355 }
4356
4357 #[kio::test]
4362 async fn a_refused_renewal_leaves_the_grant() {
4363 let runtime = crate::time::sim();
4364 let handle = Link::new(true);
4365 let mut requests = handle.handle().requests();
4366 let verdict = handle.verify_request(token(b"jwt", 0), None);
4367 let first = grant_in(&runtime, 60);
4368 let first_expires = first.expires;
4369 let _issued = requests.next().await.unwrap().accept(first);
4370 let answered = verdict.grant().await.unwrap();
4371 let request_grant = RequestGrant::new(
4372 &runtime,
4373 verdict,
4374 Ok(answered),
4375 subscribe_path(),
4376 RequestKind::Subscribe,
4377 None,
4378 )
4379 .unwrap();
4380
4381 let renewal = handle.verify_request(token(b"bad", 0), None);
4383 requests
4384 .next()
4385 .await
4386 .unwrap()
4387 .reject(SessionError::Unauthorized, "bad token");
4388 let refused = renewal.grant().await;
4389 assert!(
4390 matches!(&refused, Err(refusal) if matches!(refusal.error, Error::Session(SessionError::Unauthorized)) && refusal.reason == "bad token"),
4391 "the acceptor's code and reason reach the caller: {refused:?}"
4392 );
4393 assert!(
4394 request_grant.renew(renewal, refused).is_err(),
4395 "a refusal does not renew"
4396 );
4397
4398 assert_eq!(request_grant.grant().expires, first_expires);
4401 let err = kio::wait(|waiter| request_grant.poll_ended(waiter)).await.error;
4402 assert!(matches!(err, Error::Expired), "{err:?}");
4403 }
4404
4405 #[kio::test]
4408 async fn an_update_that_stops_covering_ends_the_request() {
4409 let runtime = crate::time::sim();
4410 let handle = Link::new(true);
4411 let mut requests = handle.handle().requests();
4412 let verdict = handle.verify_request(token(b"jwt", 0), None);
4413 let issued = requests.next().await.unwrap().accept(Grant::all());
4414 let answered = verdict.grant().await.unwrap();
4415 let request_grant = RequestGrant::new(
4416 &runtime,
4417 verdict,
4418 Ok(answered),
4419 subscribe_path(),
4420 RequestKind::Subscribe,
4421 None,
4422 )
4423 .unwrap();
4424
4425 issued.update(Grant::all());
4427 let pending = kio::wait(|waiter| Poll::Ready(request_grant.poll_ended(waiter).is_pending())).await;
4428 assert!(pending, "a covering update keeps the request");
4429
4430 issued.update(Grant::default());
4431 let err = kio::clock::timeout(
4432 Duration::from_secs(1),
4433 kio::wait(|waiter| request_grant.poll_ended(waiter)),
4434 )
4435 .await
4436 .expect("an uncovering update must end the request")
4437 .error;
4438 assert!(matches!(err, Error::Unauthorized), "{err:?}");
4439 }
4440
4441 #[test]
4444 fn request_coverage_is_from_the_presenters_side() {
4445 let read_only = Grant {
4446 publish: Prefixes::new(),
4447 subscribe: Prefixes::all(),
4448 expires: None,
4449 };
4450 let write_only = Grant {
4451 publish: Prefixes::all(),
4452 subscribe: Prefixes::new(),
4453 expires: None,
4454 };
4455 assert!(RequestKind::Subscribe.covers(&read_only, "room"));
4456 assert!(!RequestKind::Subscribe.covers(&write_only, "room"));
4457 assert!(RequestKind::PublishNamespace.covers(&write_only, "room"));
4458 assert!(!RequestKind::PublishNamespace.covers(&read_only, "room"));
4459 }
4460
4461 #[test]
4464 fn an_announce_needs_its_whole_subtree() {
4465 let room = Grant {
4466 publish: crate::Prefix::try_from("room").unwrap().into(),
4467 subscribe: Prefixes::new(),
4468 expires: None,
4469 };
4470 assert!(RequestKind::PublishNamespace.covers(&room, "room"));
4471 assert!(RequestKind::PublishNamespace.covers(&room, "room/cam"));
4472 assert!(!RequestKind::PublishNamespace.covers(&room, ""));
4473 assert!(!RequestKind::PublishNamespace.covers(&room, "other"));
4474 assert!(!RequestKind::PublishNamespace.covers(&room, "roomy"));
4475 assert!(RequestKind::PublishNamespace.covers(&room, "room/cam-*"));
4477 }
4478
4479 #[kio::test]
4482 async fn an_acceptor_revoke_ends_the_request() {
4483 let runtime = crate::time::sim();
4484 let handle = Link::new(true);
4485 let mut requests = handle.handle().requests();
4486 let verdict = handle.verify_request(token(b"jwt", 0), None);
4487 let issued = requests.next().await.unwrap().accept(Grant::all());
4489 let answered = verdict.grant().await.unwrap();
4490 let request_grant = RequestGrant::new(
4491 &runtime,
4492 verdict,
4493 Ok(answered),
4494 subscribe_path(),
4495 RequestKind::Subscribe,
4496 None,
4497 )
4498 .unwrap();
4499
4500 issued.revoke(SessionError::Unauthorized, "revoked");
4501 let refusal = kio::wait(|waiter| request_grant.poll_ended(waiter)).await;
4502 assert!(
4503 matches!(refusal.error, Error::Session(SessionError::Unauthorized)),
4504 "{refusal:?}"
4505 );
4506 assert_eq!(refusal.reason, "revoked", "the acceptor's reason is kept");
4507 assert_eq!(handle.handle().grant().peek(), None, "the session grant is untouched");
4508 }
4509}