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        let uuid = Uuid::try_parse(label).map_err(|_| label_error())?;
177        Ok(Self::new(SessionId::from_uuid(uuid), domain.parse()?))
178    }
179}
180
181const HTTPS_PORT: u16 = 443;
182
183/// Scheme, host and optional port; no path or query.
184#[derive(Debug, Clone, PartialEq, Eq, SerializeDisplay, DeserializeFromStr)]
185pub struct SessionEndpointUrl(String);
186
187/// Why a string is not a valid [`SessionEndpointUrl`].
188#[derive(Debug, thiserror::Error)]
189pub enum InvalidSessionEndpointUrl {
190    /// The scheme is not `http` or `https`, or the text is not a URL.
191    #[error("`{0}` is not an http or https URL")]
192    NotHttp(String),
193    /// The URL has an empty host.
194    #[error("`{0}` has no host")]
195    NoHost(String),
196    /// The URL is plain `http` and its host is not `127.0.0.1`.
197    #[error("`{0}` is plain http on a host that is not loopback")]
198    PlainHttp(String),
199    /// The URL has a path, a query, a fragment or user info.
200    #[error("`{0}` has a path or a query")]
201    NotAnOrigin(String),
202}
203
204impl SessionEndpointUrl {
205    /// `https://<host name>`, with `:<port>` unless the port is 443.
206    pub fn https(host: &SessionHostName, port: u16) -> Self {
207        if port == HTTPS_PORT {
208            Self(format!("https://{host}"))
209        } else {
210            Self(format!("https://{host}:{port}"))
211        }
212    }
213
214    /// `http://127.0.0.1:<port>`
215    pub fn loopback(port: u16) -> Self {
216        Self(format!("http://{}:{port}", Ipv4Addr::LOCALHOST))
217    }
218
219    /// The origin, without a trailing slash.
220    pub fn as_str(&self) -> &str {
221        &self.0
222    }
223}
224
225impl FromStr for SessionEndpointUrl {
226    type Err = InvalidSessionEndpointUrl;
227
228    fn from_str(s: &str) -> Result<Self, Self::Err> {
229        let uri =
230            parse_origin(s).ok_or_else(|| InvalidSessionEndpointUrl::NotAnOrigin(s.to_owned()))?;
231        if uri.scheme() != Some(&Scheme::HTTP) && uri.scheme() != Some(&Scheme::HTTPS) {
232            return Err(InvalidSessionEndpointUrl::NotHttp(s.to_owned()));
233        }
234        let Some(host) = uri.host().filter(|host| !host.is_empty()) else {
235            return Err(InvalidSessionEndpointUrl::NoHost(s.to_owned()));
236        };
237        let is_loopback = host == Ipv4Addr::LOCALHOST.to_string();
238        if uri.scheme() == Some(&Scheme::HTTP) && !is_loopback {
239            return Err(InvalidSessionEndpointUrl::PlainHttp(s.to_owned()));
240        }
241        Ok(Self(s.trim_end_matches('/').to_owned()))
242    }
243}
244
245impl fmt::Display for SessionEndpointUrl {
246    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247        f.write_str(&self.0)
248    }
249}
250
251/// Everything a client needs to reach one endpoint session.
252#[derive(Debug, Clone, Serialize, Deserialize)]
253#[serde(rename_all = "camelCase")]
254pub struct SessionGrant {
255    /// Keep it to attach again.
256    pub session_id: SessionId,
257    /// The parallel run's name, for a session in one.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub session_name: Option<SessionName>,
260    /// Quote it when reporting a problem.
261    #[serde(default, skip_serializing_if = "Option::is_none")]
262    pub task_id: Option<String>,
263    /// The name can take a few seconds to resolve after the grant; retry a failed lookup.
264    pub endpoint: SessionEndpointUrl,
265    /// Admits the client to [`Self::endpoint`].
266    pub token: SessionToken,
267    /// The slots the session replays.
268    pub slots: SlotRange,
269}
270
271impl SessionGrant {
272    /// `ws(s)://<host>/backtest/<its own id>/control`: the session's control socket.
273    pub fn control_url(&self) -> String {
274        let after_http = self
275            .endpoint
276            .as_str()
277            .strip_prefix(Scheme::HTTP.as_str())
278            .unwrap_or_else(|| unreachable!("an endpoint URL is an http or https origin"));
279        format!("ws{after_http}/backtest/{}/control", self.session_id)
280    }
281
282    /// The session's JSON-RPC endpoint over HTTP, without the token.
283    pub fn rpc_url(&self) -> String {
284        format!("{}/backtest/{}", self.endpoint, self.session_id)
285    }
286
287    /// [`Self::rpc_url`] with the token in the query, for a client that cannot set a header.
288    pub fn rpc_url_with_token(&self) -> String {
289        format!(
290            "{}?{SESSION_TOKEN_QUERY_PARAM}={}",
291            self.rpc_url(),
292            self.token.expose()
293        )
294    }
295}
296
297/// Every session of a parallel run, as [`SessionGrant`]s.
298#[derive(Debug, Clone, Serialize, Deserialize)]
299#[serde(rename_all = "camelCase")]
300pub struct ParallelGrant {
301    /// Keep it to attach again.
302    pub control_session_id: ControlSessionId,
303    /// The parallel run's name.
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub control_session_name: Option<SessionName>,
306    /// In slot order; never empty.
307    pub sessions: Vec<SessionGrant>,
308}
309
310#[cfg(test)]
311mod tests {
312    use rstest::rstest;
313
314    use super::*;
315
316    const PRODUCTION: &str = "sessions.simulator.termina.technology";
317    const STAGING: &str = "sessions.staging.simulator.termina.technology";
318    const LABEL: &str = "3f9a2c1b4d5e6f708192a3b4c5d6e7f8";
319
320    #[test]
321    fn the_example_host_name_round_trips() {
322        let text = format!("{LABEL}.{PRODUCTION}");
323        let name: SessionHostName = text.parse().expect("parse");
324        assert_eq!(name.to_string(), text);
325        assert_eq!(name.domain().as_str(), PRODUCTION);
326        assert_eq!(
327            SessionHostName::new(name.session_id(), PRODUCTION.parse().expect("domain")),
328            name
329        );
330    }
331
332    #[rstest]
333    #[case::hyphenated_uuid(
334        "3f9a2c1b-4d5e-6f70-8192-a3b4c5d6e7f8.sessions.simulator.termina.technology"
335    )]
336    #[case::uppercase_label(
337        "3F9A2C1B4D5E6F708192A3B4C5D6E7F8.sessions.simulator.termina.technology"
338    )]
339    #[case::label_31("3f9a2c1b4d5e6f708192a3b4c5d6e7f.sessions.simulator.termina.technology")]
340    #[case::label_33("3f9a2c1b4d5e6f708192a3b4c5d6e7f88.sessions.simulator.termina.technology")]
341    #[case::prefixed_label(
342        "backtest_3f9a2c1b4d5e6f708192a3b4c5d6e7f8.sessions.simulator.termina.technology"
343    )]
344    #[case::no_domain("3f9a2c1b4d5e6f708192a3b4c5d6e7f8")]
345    #[case::empty_domain("3f9a2c1b4d5e6f708192a3b4c5d6e7f8.")]
346    #[case::one_label_domain("3f9a2c1b4d5e6f708192a3b4c5d6e7f8.sessions")]
347    #[case::uppercase_domain("3f9a2c1b4d5e6f708192a3b4c5d6e7f8.Sessions.Termina.Technology")]
348    fn host_name_rejects(#[case] text: &str) {
349        assert!(text.parse::<SessionHostName>().is_err());
350    }
351
352    #[rstest]
353    #[case::production(PRODUCTION)]
354    #[case::staging(STAGING)]
355    fn domain_accepts(#[case] text: &str) {
356        assert_eq!(
357            text.parse::<SessionsDomain>().expect("parse").as_str(),
358            text
359        );
360    }
361
362    #[rstest]
363    #[case::uppercase("Sessions.simulator.termina.technology")]
364    #[case::leading_dot(".sessions.simulator.termina.technology")]
365    #[case::trailing_dot("sessions.simulator.termina.technology.")]
366    #[case::one_label("sessions")]
367    #[case::empty("")]
368    #[case::empty_label("sessions..termina.technology")]
369    #[case::label_starts_with_hyphen("-sessions.termina.technology")]
370    #[case::label_ends_with_hyphen("sessions-.termina.technology")]
371    #[case::label_too_long(&format!("{}.termina.technology", "a".repeat(64)))]
372    #[case::name_too_long(&["a".repeat(63).as_str(); 4].join("."))]
373    fn domain_rejects(#[case] text: &str) {
374        assert!(text.parse::<SessionsDomain>().is_err());
375    }
376
377    #[test]
378    fn token_debug_hides_the_secret() {
379        let token = SessionToken::generate();
380        assert!(!format!("{token:?}").contains(token.expose()));
381    }
382
383    #[test]
384    fn tokens_are_distinct_43_char_base64url() {
385        let (a, b) = (SessionToken::generate(), SessionToken::generate());
386        assert_ne!(a.expose(), b.expose());
387        assert_eq!(a.expose().len(), 43);
388        assert!(
389            a.expose()
390                .bytes()
391                .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
392        );
393    }
394
395    #[rstest]
396    #[case::default_port(443, format!("https://{LABEL}.{PRODUCTION}"))]
397    #[case::other_port(8443, format!("https://{LABEL}.{PRODUCTION}:8443"))]
398    fn https_url_names_the_port_unless_it_is_443(#[case] port: u16, #[case] expected: String) {
399        let host: SessionHostName = format!("{LABEL}.{PRODUCTION}").parse().expect("host");
400        assert_eq!(SessionEndpointUrl::https(&host, port).as_str(), expected);
401    }
402
403    #[test]
404    fn loopback_url_is_plain_http_on_127_0_0_1() {
405        assert_eq!(
406            SessionEndpointUrl::loopback(8899).as_str(),
407            "http://127.0.0.1:8899"
408        );
409    }
410
411    #[rstest]
412    #[case::https_without_port(&format!("https://{LABEL}.{PRODUCTION}"))]
413    #[case::https_with_port(&format!("https://{LABEL}.{PRODUCTION}:8443"))]
414    #[case::loopback("http://127.0.0.1:8899")]
415    fn endpoint_url_parse_accepts_an_origin(#[case] text: &str) {
416        assert_eq!(
417            text.parse::<SessionEndpointUrl>().expect("parse").as_str(),
418            text
419        );
420    }
421
422    #[rstest]
423    #[case::path("https://example.com/backtest")]
424    #[case::query("https://example.com?token=a")]
425    #[case::no_scheme("example.com")]
426    fn endpoint_url_parse_rejects_a_path_or_query(#[case] text: &str) {
427        assert!(matches!(
428            text.parse::<SessionEndpointUrl>(),
429            Err(InvalidSessionEndpointUrl::NotAnOrigin(_))
430        ));
431    }
432
433    #[rstest]
434    #[case::named_host("http://example.com")]
435    #[case::other_address("http://10.0.0.1:8899")]
436    #[case::localhost_name("http://localhost:8899")]
437    fn endpoint_url_parse_rejects_plain_http_off_loopback(#[case] text: &str) {
438        assert!(matches!(
439            text.parse::<SessionEndpointUrl>(),
440            Err(InvalidSessionEndpointUrl::PlainHttp(_))
441        ));
442    }
443
444    #[rstest]
445    #[case::ws_scheme("ws://example.com")]
446    fn endpoint_url_parse_rejects_a_non_http_scheme(#[case] text: &str) {
447        assert!(matches!(
448            text.parse::<SessionEndpointUrl>(),
449            Err(InvalidSessionEndpointUrl::NotHttp(_))
450        ));
451    }
452
453    #[rstest]
454    #[case::loopback(SessionEndpointUrl::loopback(8899), "ws://127.0.0.1:8899")]
455    #[case::https(
456        SessionEndpointUrl::https(&format!("{LABEL}.{PRODUCTION}").parse().expect("host"), 443),
457        &format!("wss://{LABEL}.{PRODUCTION}"),
458    )]
459    fn control_url_is_the_websocket_origin_and_the_control_path(
460        #[case] endpoint: SessionEndpointUrl,
461        #[case] origin: &str,
462    ) {
463        let session_id = SessionId::new();
464        let grant = SessionGrant {
465            session_id,
466            session_name: None,
467            task_id: None,
468            endpoint,
469            token: SessionToken::generate(),
470            slots: SlotRange::new_unchecked(1, 2),
471        };
472        assert_eq!(
473            grant.control_url(),
474            format!("{origin}/backtest/{session_id}/control")
475        );
476    }
477
478    #[rstest]
479    #[case::loopback(SessionEndpointUrl::loopback(8899), "http://127.0.0.1:8899")]
480    #[case::https(
481        SessionEndpointUrl::https(&format!("{LABEL}.{PRODUCTION}").parse().expect("host"), 443),
482        &format!("https://{LABEL}.{PRODUCTION}"),
483    )]
484    fn rpc_url_is_the_origin_and_the_session_path(
485        #[case] endpoint: SessionEndpointUrl,
486        #[case] origin: &str,
487    ) {
488        let session_id = SessionId::new();
489        let token = SessionToken::generate();
490        let grant = SessionGrant {
491            session_id,
492            session_name: None,
493            task_id: None,
494            endpoint,
495            token: token.clone(),
496            slots: SlotRange::new_unchecked(1, 2),
497        };
498        let rpc_url = format!("{origin}/backtest/{session_id}");
499        assert_eq!(grant.rpc_url(), rpc_url);
500
501        let with_token = grant.rpc_url_with_token();
502        let query = with_token
503            .strip_prefix(&format!("{rpc_url}?"))
504            .expect("the token URL extends the RPC URL with a query");
505        assert_eq!(token_in_query_pair(query), Some(token.expose()));
506    }
507
508    #[test]
509    fn wildcard_prefixes_the_domain() {
510        let domain: SessionsDomain = PRODUCTION.parse().expect("parse");
511        assert_eq!(domain.wildcard(), "*.sessions.simulator.termina.technology");
512    }
513
514    #[test]
515    fn both_types_serialize_as_plain_strings() {
516        let domain: SessionsDomain = PRODUCTION.parse().expect("domain");
517        let json = serde_json::to_string(&domain).expect("serialize");
518        assert_eq!(json, format!("\"{PRODUCTION}\""));
519        assert_eq!(
520            serde_json::from_str::<SessionsDomain>(&json).expect("deserialize"),
521            domain
522        );
523
524        let name = SessionHostName::new(SessionId::new(), domain);
525        let json = serde_json::to_string(&name).expect("serialize");
526        assert_eq!(json, format!("\"{name}\""));
527        assert_eq!(
528            serde_json::from_str::<SessionHostName>(&json).expect("deserialize"),
529            name
530        );
531    }
532}