Skip to main content

simulator_api/
session_endpoint.rs

1//! The one mapping between a session id and the DNS name of its endpoint.
2
3use std::{fmt, net::Ipv4Addr, str::FromStr};
4
5use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
6use http::{Uri, uri::Scheme};
7use serde::{Deserialize, Serialize};
8use serde_with::{DeserializeFromStr, SerializeDisplay};
9use subtle::ConstantTimeEq;
10use uuid::Uuid;
11use zeroize::{Zeroize, ZeroizeOnDrop};
12
13use crate::{ControlSessionId, SessionId, SlotRange, session_name::SessionName};
14
15/// Header that carries the [`SessionToken`].
16pub const SESSION_TOKEN_HEADER: &str = "x-token";
17/// Query parameter that carries the [`SessionToken`].
18pub const SESSION_TOKEN_QUERY_PARAM: &str = "token";
19
20const TOKEN_BYTES: usize = 32;
21
22/// Admits a client to one session's endpoint. 256 random bits, base64url. No lifetime, not signed.
23///
24/// No `PartialEq` or `Display`: compare only with `matches`, so a token never compares in variable time or prints.
25#[derive(Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
26#[serde(transparent)]
27pub struct SessionToken(String);
28
29impl SessionToken {
30    /// A new token from the thread-local CSPRNG.
31    pub fn generate() -> Self {
32        let mut bytes = [0u8; TOKEN_BYTES];
33        rand::fill(&mut bytes);
34        let token = Self(URL_SAFE_NO_PAD.encode(bytes));
35        bytes.zeroize();
36        token
37    }
38
39    /// The secret.
40    pub fn expose(&self) -> &str {
41        &self.0
42    }
43
44    /// Constant time.
45    pub fn matches(&self, presented: &[u8]) -> bool {
46        self.0.as_bytes().ct_eq(presented).into()
47    }
48}
49
50/// The token in one `key=value` pair of a query, when the key is [`SESSION_TOKEN_QUERY_PARAM`].
51pub fn token_in_query_pair(pair: &str) -> Option<&str> {
52    let (key, value) = pair.split_once('=')?;
53    (key == SESSION_TOKEN_QUERY_PARAM).then_some(value)
54}
55
56impl fmt::Debug for SessionToken {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        f.write_str("SessionToken(..)")
59    }
60}
61
62const MAX_HOST_NAME_LEN: usize = 253;
63const MAX_LABEL_LEN: usize = 63;
64const SESSION_LABEL_LEN: usize = 32;
65const SESSION_PREFIX_LEN: usize = SESSION_LABEL_LEN + 1;
66
67/// `<scheme>://<host>[:<port>][/]` only; the scheme is not checked.
68pub fn parse_origin(s: &str) -> Option<Uri> {
69    let uri: Uri = s.parse().ok()?;
70    let is_origin = uri.authority().is_some_and(|a| !a.as_str().contains('@'))
71        && uri.path() == "/"
72        && uri.query().is_none()
73        && !s.contains('#');
74    is_origin.then_some(uri)
75}
76
77/// The domain of the sessions zone, such as `sessions.simulator.termina.technology`. Lowercase, with no leading or trailing dot.
78#[derive(Debug, Clone, PartialEq, Eq, Hash, SerializeDisplay, DeserializeFromStr)]
79pub struct SessionsDomain(String);
80
81/// Why a string is not a valid [`SessionsDomain`].
82#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
83#[error("`{0}` is not a lowercase DNS domain")]
84pub struct InvalidSessionsDomain(String);
85
86impl SessionsDomain {
87    /// The domain, without a trailing dot.
88    pub fn as_str(&self) -> &str {
89        &self.0
90    }
91
92    /// `*.<domain>`: the one name on the certificate that covers every session.
93    pub fn wildcard(&self) -> String {
94        format!("*.{}", self.0)
95    }
96}
97
98fn is_valid_label(label: &str) -> bool {
99    let is_label_byte = |b: &u8| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-';
100    (1..=MAX_LABEL_LEN).contains(&label.len())
101        && label.bytes().all(|b| is_label_byte(&b))
102        && !label.starts_with('-')
103        && !label.ends_with('-')
104}
105
106impl FromStr for SessionsDomain {
107    type Err = InvalidSessionsDomain;
108
109    fn from_str(s: &str) -> Result<Self, Self::Err> {
110        let fits = SESSION_PREFIX_LEN + s.len() <= MAX_HOST_NAME_LEN;
111        if fits && s.contains('.') && s.split('.').all(is_valid_label) {
112            Ok(Self(s.to_owned()))
113        } else {
114            Err(InvalidSessionsDomain(s.to_owned()))
115        }
116    }
117}
118
119impl fmt::Display for SessionsDomain {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        f.write_str(&self.0)
122    }
123}
124
125/// The DNS name of one session's endpoint: `<32 lowercase hex of the session id>.<domain>`. The `backtest_` prefix is left out because `_` is not valid in a host name.
126#[derive(Debug, Clone, PartialEq, Eq, Hash, SerializeDisplay, DeserializeFromStr)]
127pub struct SessionHostName {
128    session_id: SessionId,
129    domain: SessionsDomain,
130}
131
132/// Why a string is not a valid [`SessionHostName`].
133#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
134pub enum InvalidSessionHostName {
135    /// The first label is not 32 lowercase hex characters, or there is no dot.
136    #[error("`{0}` does not start with a 32-hex session label")]
137    Label(String),
138    /// The part after the first dot is not a valid domain.
139    #[error(transparent)]
140    Domain(#[from] InvalidSessionsDomain),
141}
142
143impl SessionHostName {
144    /// The host name of `session_id` in `domain`.
145    pub fn new(session_id: SessionId, domain: SessionsDomain) -> Self {
146        Self { session_id, domain }
147    }
148
149    /// The session this host name belongs to.
150    pub fn session_id(&self) -> SessionId {
151        self.session_id
152    }
153
154    /// The domain after the session label.
155    pub fn domain(&self) -> &SessionsDomain {
156        &self.domain
157    }
158}
159
160impl fmt::Display for SessionHostName {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        write!(f, "{}.{}", self.session_id.as_uuid().simple(), self.domain)
163    }
164}
165
166impl FromStr for SessionHostName {
167    type Err = InvalidSessionHostName;
168
169    fn from_str(s: &str) -> Result<Self, Self::Err> {
170        let label_error = || InvalidSessionHostName::Label(s.to_owned());
171        let (label, domain) = s.split_once('.').ok_or_else(label_error)?;
172        let is_lower_hex = |b: u8| b.is_ascii_digit() || (b'a'..=b'f').contains(&b);
173        if label.len() != SESSION_LABEL_LEN || !label.bytes().all(is_lower_hex) {
174            return Err(label_error());
175        }
176        #[expect(
177            clippy::map_err_ignore,
178            reason = "host label error reports the full hostname"
179        )]
180        let uuid = Uuid::try_parse(label).map_err(|_| label_error())?;
181        Ok(Self::new(SessionId::from_uuid(uuid), domain.parse()?))
182    }
183}
184
185const HTTPS_PORT: u16 = 443;
186
187/// Scheme, host and optional port; no path or query.
188#[derive(Debug, Clone, PartialEq, Eq, SerializeDisplay, DeserializeFromStr)]
189pub struct SessionEndpointUrl(String);
190
191/// Why a string is not a valid [`SessionEndpointUrl`].
192#[derive(Debug, thiserror::Error)]
193pub enum InvalidSessionEndpointUrl {
194    /// The scheme is not `http` or `https`, or the text is not a URL.
195    #[error("`{0}` is not an http or https URL")]
196    NotHttp(String),
197    /// The URL has an empty host.
198    #[error("`{0}` has no host")]
199    NoHost(String),
200    /// The URL is plain `http` and its host is not `127.0.0.1`.
201    #[error("`{0}` is plain http on a host that is not loopback")]
202    PlainHttp(String),
203    /// The URL has a path, a query, a fragment or user info.
204    #[error("`{0}` has a path or a query")]
205    NotAnOrigin(String),
206}
207
208impl SessionEndpointUrl {
209    /// `https://<host name>`, with `:<port>` unless the port is 443.
210    pub fn https(host: &SessionHostName, port: u16) -> Self {
211        if port == HTTPS_PORT {
212            Self(format!("https://{host}"))
213        } else {
214            Self(format!("https://{host}:{port}"))
215        }
216    }
217
218    /// `http://127.0.0.1:<port>`
219    pub fn loopback(port: u16) -> Self {
220        Self(format!("http://{}:{port}", Ipv4Addr::LOCALHOST))
221    }
222
223    /// The origin, without a trailing slash.
224    pub fn as_str(&self) -> &str {
225        &self.0
226    }
227}
228
229impl FromStr for SessionEndpointUrl {
230    type Err = InvalidSessionEndpointUrl;
231
232    fn from_str(s: &str) -> Result<Self, Self::Err> {
233        let uri =
234            parse_origin(s).ok_or_else(|| InvalidSessionEndpointUrl::NotAnOrigin(s.to_owned()))?;
235        if uri.scheme() != Some(&Scheme::HTTP) && uri.scheme() != Some(&Scheme::HTTPS) {
236            return Err(InvalidSessionEndpointUrl::NotHttp(s.to_owned()));
237        }
238        let Some(host) = uri.host().filter(|host| !host.is_empty()) else {
239            return Err(InvalidSessionEndpointUrl::NoHost(s.to_owned()));
240        };
241        let is_loopback = host == Ipv4Addr::LOCALHOST.to_string();
242        if uri.scheme() == Some(&Scheme::HTTP) && !is_loopback {
243            return Err(InvalidSessionEndpointUrl::PlainHttp(s.to_owned()));
244        }
245        Ok(Self(s.trim_end_matches('/').to_owned()))
246    }
247}
248
249impl fmt::Display for SessionEndpointUrl {
250    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251        f.write_str(&self.0)
252    }
253}
254
255/// Everything a client needs to reach one endpoint session.
256#[derive(Debug, Clone, Serialize, Deserialize)]
257#[serde(rename_all = "camelCase")]
258pub struct SessionGrant {
259    /// Keep it to attach again.
260    pub session_id: SessionId,
261    /// The parallel run's name, for a session in one.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub session_name: Option<SessionName>,
264    /// Quote it when reporting a problem.
265    #[serde(default, skip_serializing_if = "Option::is_none")]
266    pub task_id: Option<String>,
267    /// The name can take a few seconds to resolve after the grant; retry a failed lookup.
268    pub endpoint: SessionEndpointUrl,
269    /// Admits the client to [`Self::endpoint`].
270    pub token: SessionToken,
271    /// The slots the session replays.
272    pub slots: SlotRange,
273}
274
275impl SessionGrant {
276    /// `ws(s)://<host>/backtest/<its own id>/control`: the session's control socket.
277    pub fn control_url(&self) -> String {
278        let after_http = self
279            .endpoint
280            .as_str()
281            .strip_prefix(Scheme::HTTP.as_str())
282            .unwrap_or_else(|| unreachable!("an endpoint URL is an http or https origin"));
283        format!("ws{after_http}/backtest/{}/control", self.session_id)
284    }
285
286    /// The session's JSON-RPC endpoint over HTTP, without the token.
287    pub fn rpc_url(&self) -> String {
288        format!("{}/backtest/{}", self.endpoint, self.session_id)
289    }
290
291    /// [`Self::rpc_url`] with the token in the query, for a client that cannot set a header.
292    pub fn rpc_url_with_token(&self) -> String {
293        format!(
294            "{}?{SESSION_TOKEN_QUERY_PARAM}={}",
295            self.rpc_url(),
296            self.token.expose()
297        )
298    }
299}
300
301/// Every session of a parallel run, as [`SessionGrant`]s.
302#[derive(Debug, Clone, Serialize, Deserialize)]
303#[serde(rename_all = "camelCase")]
304pub struct ParallelGrant {
305    /// Keep it to attach again.
306    pub control_session_id: ControlSessionId,
307    /// The parallel run's name.
308    #[serde(default, skip_serializing_if = "Option::is_none")]
309    pub control_session_name: Option<SessionName>,
310    /// In slot order; never empty.
311    pub sessions: Vec<SessionGrant>,
312}
313
314#[cfg(test)]
315mod tests {
316    use rstest::rstest;
317
318    use super::*;
319
320    const PRODUCTION: &str = "sessions.simulator.termina.technology";
321    const STAGING: &str = "sessions.staging.simulator.termina.technology";
322    const LABEL: &str = "3f9a2c1b4d5e6f708192a3b4c5d6e7f8";
323
324    #[test]
325    fn the_example_host_name_round_trips() {
326        let text = format!("{LABEL}.{PRODUCTION}");
327        let name: SessionHostName = text.parse().expect("parse");
328        assert_eq!(name.to_string(), text);
329        assert_eq!(name.domain().as_str(), PRODUCTION);
330        assert_eq!(
331            SessionHostName::new(name.session_id(), PRODUCTION.parse().expect("domain")),
332            name
333        );
334    }
335
336    #[rstest]
337    #[case::hyphenated_uuid(
338        "3f9a2c1b-4d5e-6f70-8192-a3b4c5d6e7f8.sessions.simulator.termina.technology"
339    )]
340    #[case::uppercase_label(
341        "3F9A2C1B4D5E6F708192A3B4C5D6E7F8.sessions.simulator.termina.technology"
342    )]
343    #[case::label_31("3f9a2c1b4d5e6f708192a3b4c5d6e7f.sessions.simulator.termina.technology")]
344    #[case::label_33("3f9a2c1b4d5e6f708192a3b4c5d6e7f88.sessions.simulator.termina.technology")]
345    #[case::prefixed_label(
346        "backtest_3f9a2c1b4d5e6f708192a3b4c5d6e7f8.sessions.simulator.termina.technology"
347    )]
348    #[case::no_domain("3f9a2c1b4d5e6f708192a3b4c5d6e7f8")]
349    #[case::empty_domain("3f9a2c1b4d5e6f708192a3b4c5d6e7f8.")]
350    #[case::one_label_domain("3f9a2c1b4d5e6f708192a3b4c5d6e7f8.sessions")]
351    #[case::uppercase_domain("3f9a2c1b4d5e6f708192a3b4c5d6e7f8.Sessions.Termina.Technology")]
352    fn host_name_rejects(#[case] text: &str) {
353        assert!(text.parse::<SessionHostName>().is_err());
354    }
355
356    #[rstest]
357    #[case::production(PRODUCTION)]
358    #[case::staging(STAGING)]
359    fn domain_accepts(#[case] text: &str) {
360        assert_eq!(
361            text.parse::<SessionsDomain>().expect("parse").as_str(),
362            text
363        );
364    }
365
366    #[rstest]
367    #[case::uppercase("Sessions.simulator.termina.technology")]
368    #[case::leading_dot(".sessions.simulator.termina.technology")]
369    #[case::trailing_dot("sessions.simulator.termina.technology.")]
370    #[case::one_label("sessions")]
371    #[case::empty("")]
372    #[case::empty_label("sessions..termina.technology")]
373    #[case::label_starts_with_hyphen("-sessions.termina.technology")]
374    #[case::label_ends_with_hyphen("sessions-.termina.technology")]
375    #[case::label_too_long(&format!("{}.termina.technology", "a".repeat(64)))]
376    #[case::name_too_long(&["a".repeat(63).as_str(); 4].join("."))]
377    fn domain_rejects(#[case] text: &str) {
378        assert!(text.parse::<SessionsDomain>().is_err());
379    }
380
381    #[test]
382    fn token_debug_hides_the_secret() {
383        let token = SessionToken::generate();
384        assert!(!format!("{token:?}").contains(token.expose()));
385    }
386
387    #[test]
388    fn tokens_are_distinct_43_char_base64url() {
389        let (a, b) = (SessionToken::generate(), SessionToken::generate());
390        assert_ne!(a.expose(), b.expose());
391        assert_eq!(a.expose().len(), 43);
392        assert!(
393            a.expose()
394                .bytes()
395                .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
396        );
397    }
398
399    #[rstest]
400    #[case::default_port(443, format!("https://{LABEL}.{PRODUCTION}"))]
401    #[case::other_port(8443, format!("https://{LABEL}.{PRODUCTION}:8443"))]
402    fn https_url_names_the_port_unless_it_is_443(#[case] port: u16, #[case] expected: String) {
403        let host: SessionHostName = format!("{LABEL}.{PRODUCTION}").parse().expect("host");
404        assert_eq!(SessionEndpointUrl::https(&host, port).as_str(), expected);
405    }
406
407    #[test]
408    fn loopback_url_is_plain_http_on_127_0_0_1() {
409        assert_eq!(
410            SessionEndpointUrl::loopback(8899).as_str(),
411            "http://127.0.0.1:8899"
412        );
413    }
414
415    #[rstest]
416    #[case::https_without_port(&format!("https://{LABEL}.{PRODUCTION}"))]
417    #[case::https_with_port(&format!("https://{LABEL}.{PRODUCTION}:8443"))]
418    #[case::loopback("http://127.0.0.1:8899")]
419    fn endpoint_url_parse_accepts_an_origin(#[case] text: &str) {
420        assert_eq!(
421            text.parse::<SessionEndpointUrl>().expect("parse").as_str(),
422            text
423        );
424    }
425
426    #[rstest]
427    #[case::path("https://example.com/backtest")]
428    #[case::query("https://example.com?token=a")]
429    #[case::no_scheme("example.com")]
430    fn endpoint_url_parse_rejects_a_path_or_query(#[case] text: &str) {
431        assert!(matches!(
432            text.parse::<SessionEndpointUrl>(),
433            Err(InvalidSessionEndpointUrl::NotAnOrigin(_))
434        ));
435    }
436
437    #[rstest]
438    #[case::named_host("http://example.com")]
439    #[case::other_address("http://10.0.0.1:8899")]
440    #[case::localhost_name("http://localhost:8899")]
441    fn endpoint_url_parse_rejects_plain_http_off_loopback(#[case] text: &str) {
442        assert!(matches!(
443            text.parse::<SessionEndpointUrl>(),
444            Err(InvalidSessionEndpointUrl::PlainHttp(_))
445        ));
446    }
447
448    #[rstest]
449    #[case::ws_scheme("ws://example.com")]
450    fn endpoint_url_parse_rejects_a_non_http_scheme(#[case] text: &str) {
451        assert!(matches!(
452            text.parse::<SessionEndpointUrl>(),
453            Err(InvalidSessionEndpointUrl::NotHttp(_))
454        ));
455    }
456
457    #[rstest]
458    #[case::loopback(SessionEndpointUrl::loopback(8899), "ws://127.0.0.1:8899")]
459    #[case::https(
460        SessionEndpointUrl::https(&format!("{LABEL}.{PRODUCTION}").parse().expect("host"), 443),
461        &format!("wss://{LABEL}.{PRODUCTION}"),
462    )]
463    fn control_url_is_the_websocket_origin_and_the_control_path(
464        #[case] endpoint: SessionEndpointUrl,
465        #[case] origin: &str,
466    ) {
467        let session_id = SessionId::new();
468        let grant = SessionGrant {
469            session_id,
470            session_name: None,
471            task_id: None,
472            endpoint,
473            token: SessionToken::generate(),
474            slots: SlotRange::new_unchecked(1, 2),
475        };
476        assert_eq!(
477            grant.control_url(),
478            format!("{origin}/backtest/{session_id}/control")
479        );
480    }
481
482    #[rstest]
483    #[case::loopback(SessionEndpointUrl::loopback(8899), "http://127.0.0.1:8899")]
484    #[case::https(
485        SessionEndpointUrl::https(&format!("{LABEL}.{PRODUCTION}").parse().expect("host"), 443),
486        &format!("https://{LABEL}.{PRODUCTION}"),
487    )]
488    fn rpc_url_is_the_origin_and_the_session_path(
489        #[case] endpoint: SessionEndpointUrl,
490        #[case] origin: &str,
491    ) {
492        let session_id = SessionId::new();
493        let token = SessionToken::generate();
494        let grant = SessionGrant {
495            session_id,
496            session_name: None,
497            task_id: None,
498            endpoint,
499            token: token.clone(),
500            slots: SlotRange::new_unchecked(1, 2),
501        };
502        let rpc_url = format!("{origin}/backtest/{session_id}");
503        assert_eq!(grant.rpc_url(), rpc_url);
504
505        let with_token = grant.rpc_url_with_token();
506        let query = with_token
507            .strip_prefix(&format!("{rpc_url}?"))
508            .expect("the token URL extends the RPC URL with a query");
509        assert_eq!(token_in_query_pair(query), Some(token.expose()));
510    }
511
512    #[test]
513    fn wildcard_prefixes_the_domain() {
514        let domain: SessionsDomain = PRODUCTION.parse().expect("parse");
515        assert_eq!(domain.wildcard(), "*.sessions.simulator.termina.technology");
516    }
517
518    #[test]
519    fn both_types_serialize_as_plain_strings() {
520        let domain: SessionsDomain = PRODUCTION.parse().expect("domain");
521        let json = serde_json::to_string(&domain).expect("serialize");
522        assert_eq!(json, format!("\"{PRODUCTION}\""));
523        assert_eq!(
524            serde_json::from_str::<SessionsDomain>(&json).expect("deserialize"),
525            domain
526        );
527
528        let name = SessionHostName::new(SessionId::new(), domain);
529        let json = serde_json::to_string(&name).expect("serialize");
530        assert_eq!(json, format!("\"{name}\""));
531        assert_eq!(
532            serde_json::from_str::<SessionHostName>(&json).expect("deserialize"),
533            name
534        );
535    }
536}