dustnet_server/session.rs
1//! Resolving a session token to an identity, and issuing session directives.
2//!
3//! # The token stops here
4//!
5//! This is the whole reason the module exists. A request may carry a session
6//! token; a [`SessionResolver`] turns that into an identity; and the include
7//! resolver and input handler are told **the identity, never the token**.
8//!
9//! That boundary matters because a token is a bearer credential and an identity
10//! is not. A handler holding a raw token could replay it, log it, or embed it in
11//! a generated page — and a token in a page is a session-stealing bug that looks
12//! like a rendering bug. A handler holding a username can do none of those
13//! things, and the code that *can* is one small implementation of one trait.
14//!
15//! It is the same arrangement the quarantined prototype got right — the one
16//! part of it worth keeping — with the difference that the trust boundary is a
17//! trait here rather than a convention.
18//!
19//! # What a resolver is not asked to do
20//!
21//! Expiry, revocation and storage are the resolver's business, not this
22//! module's. It is asked one question — who does this token belong to *now* —
23//! and answering `None` for an expired or revoked token is how expiry is
24//! enforced. There is deliberately no "is this valid" call separate from "who
25//! is this", because two calls invite a gap between them.
26
27use dustnet_core::session::SessionDirective;
28
29/// Turns a session token into the identity it belongs to.
30///
31/// `None` means the token is unknown, expired or revoked. Those are one answer
32/// on purpose: a caller that distinguished them would leak whether a token had
33/// ever existed, and nothing downstream would do anything different.
34pub trait SessionResolver: Send + Sync {
35 fn identity(&self, token: &str) -> Option<String>;
36
37 /// Destroy the session `token` names.
38 ///
39 /// Called by the server, not by a handler, when a handler's outcome clears
40 /// the session — because a handler holds the *identity* and not the token,
41 /// and so cannot name its own session to end it. Routing revocation
42 /// through here keeps that boundary intact and still ends exactly the one
43 /// session that was presented, rather than every session the person has.
44 ///
45 /// A no-op by default, for a resolver whose sessions cannot be revoked.
46 fn revoke(&self, token: &str) {
47 let _ = token;
48 }
49}
50
51/// Who a request is from, as far as anything downstream is told.
52///
53/// `None` is anonymous. There is no variant for "presented a token we did not
54/// recognise", because a handler should treat that identically to presenting
55/// none — anything else is an oracle.
56pub type Identity = Option<String>;
57
58/// Session changes a handler wants applied to the response.
59///
60/// Returned rather than performed, so that issuing a session is visible in a
61/// handler's return type instead of happening as a side effect somewhere in the
62/// middle of it.
63#[derive(Debug, Clone, Default)]
64pub struct SessionChange {
65 directives: Vec<SessionDirective>,
66}
67
68impl SessionChange {
69 pub fn none() -> Self {
70 Self::default()
71 }
72
73 /// Issue `token` for `scope`, expiring at the given Unix timestamp.
74 ///
75 /// The expiry travels to the client so it can drop the token when it lapses,
76 /// but it is not what enforces expiry: a client that ignores it still gets
77 /// `None` from the resolver. Client-side expiry is a courtesy, server-side
78 /// expiry is the control.
79 pub fn set(token: impl Into<String>, scope: impl Into<String>, expires: u64) -> Self {
80 Self {
81 directives: vec![SessionDirective::Set {
82 token: token.into(),
83 scope: scope.into(),
84 expires: Some(expires),
85 }],
86 }
87 }
88
89 /// Clear whatever token the client holds for `scope`.
90 ///
91 /// Returning this also revokes the presented token server-side, through
92 /// [`SessionResolver::revoke`]. The destruction is the part that matters: a
93 /// client that ignores `Clear-Session` keeps a token, and that token has to
94 /// stop working regardless.
95 pub fn clear(scope: impl Into<String>) -> Self {
96 Self {
97 directives: vec![SessionDirective::Clear {
98 scope: scope.into(),
99 }],
100 }
101 }
102
103 pub fn is_empty(&self) -> bool {
104 self.directives.is_empty()
105 }
106
107 /// The token this change issues, if it issues one.
108 ///
109 /// Deliberately narrow: the token is already in the caller's hand here — it
110 /// put it there — so exposing it reveals nothing new. It exists so a caller
111 /// can act on the session it just granted without threading the token
112 /// separately through its own return values.
113 pub fn token(&self) -> Option<&str> {
114 self.directives
115 .iter()
116 .find_map(|directive| match directive {
117 SessionDirective::Set { token, .. } => Some(token.as_str()),
118 SessionDirective::Clear { .. } => None,
119 })
120 }
121
122 /// Whether this change clears the session, and so should revoke the token
123 /// that was presented.
124 pub(crate) fn clears(&self) -> bool {
125 self.directives
126 .iter()
127 .any(|directive| matches!(directive, SessionDirective::Clear { .. }))
128 }
129
130 pub(crate) fn into_directives(self) -> Vec<SessionDirective> {
131 self.directives
132 }
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 #[test]
140 fn a_set_carries_its_scope_and_expiry() {
141 let change = SessionChange::set("abc", "/", 1_800_000_000);
142 let directives = change.into_directives();
143 assert_eq!(directives.len(), 1);
144 match &directives[0] {
145 SessionDirective::Set {
146 token,
147 scope,
148 expires,
149 } => {
150 assert_eq!(token, "abc");
151 assert_eq!(scope, "/");
152 assert_eq!(*expires, Some(1_800_000_000));
153 }
154 other => panic!("expected Set, got {other:?}"),
155 }
156 }
157
158 #[test]
159 fn a_clear_names_only_its_scope() {
160 match &SessionChange::clear("/").into_directives()[0] {
161 SessionDirective::Clear { scope } => assert_eq!(scope, "/"),
162 other => panic!("expected Clear, got {other:?}"),
163 }
164 }
165
166 #[test]
167 fn the_issued_token_is_readable_and_a_clear_has_none() {
168 assert_eq!(SessionChange::set("abc", "/", 1).token(), Some("abc"));
169 assert_eq!(SessionChange::clear("/").token(), None);
170 assert_eq!(SessionChange::none().token(), None);
171 }
172
173 #[test]
174 fn only_a_clear_asks_for_revocation() {
175 assert!(SessionChange::clear("/").clears());
176 assert!(!SessionChange::set("t", "/", 1).clears());
177 assert!(!SessionChange::none().clears());
178 }
179
180 #[test]
181 fn no_change_is_empty() {
182 assert!(SessionChange::none().is_empty());
183 assert!(SessionChange::none().into_directives().is_empty());
184 }
185
186 /// A directive must survive serialization, since an invalid one is refused
187 /// at encode time and would turn a successful login into a failed response.
188 #[test]
189 fn issued_directives_serialize() {
190 for change in [
191 SessionChange::set("a".repeat(64), "/", 1_800_000_000),
192 SessionChange::clear("/"),
193 ] {
194 for directive in change.into_directives() {
195 directive.serialize().expect("directive serializes");
196 }
197 }
198 }
199}