Skip to main content

spoolframe_protocol/
relay_access.rs

1//! Who a relay of the server's own lets through.
2//!
3//! The relay runs as a process of its own (`spoolframe-server relay`),
4//! with no users of its own: it asks the main server, over an Iroh
5//! connection on [`RELAY_ACCESS_ALPN`], which tier an endpoint that
6//! connects to it is in. The main server answers only the relays its
7//! config names. One bidirectional stream per question: an
8//! [`AccessQuery`] frame, answered by an [`AccessAnswer`] frame.
9//!
10//! A device redeeming an invite is no one's yet: it proves it holds the
11//! code with an [`invite_token`], which the relay reads from the
12//! `Authorization` header of its connection and passes in the question.
13//! A device about to play a paired server's item proves it holds
14//! that server's play token the same way, with a [`play_relay_token`].
15//!
16//! The main server tells its relays when an answer no longer holds: on a
17//! unidirectional stream it opens on the relay's connection, an
18//! [`AccessRevoked`] frame. A relay forgets what it kept for that endpoint
19//! and asks again about those it carries.
20
21use base64::Engine;
22use base64::engine::general_purpose::URL_SAFE_NO_PAD;
23use serde::{Deserialize, Serialize};
24
25/// The ALPN a relay asks the main server on.
26pub const RELAY_ACCESS_ALPN: &[u8] = b"spoolframe/relay-access/1";
27
28/// What an invite holder's token starts with: its scheme and version.
29pub const INVITE_TOKEN_PREFIX: &str = "sf-invite.1.";
30
31/// What a play token holder's relay token starts with.
32pub const PLAY_TOKEN_PREFIX: &str = "sf-play.1.";
33
34/// Which tier `endpoint` is in.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36pub struct AccessQuery {
37    /// The endpoint's key, hex.
38    pub endpoint: String,
39    /// The invite holder's token it connected to the relay with,
40    /// or a play token holder's, if it is one. Left out without
41    /// one; an older server ignores it, and answers as without it.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub invite: Option<String>,
44}
45
46/// The tier of the endpoint asked about.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
48pub struct AccessAnswer {
49    pub tier: Tier,
50}
51
52/// The most bytes an access frame takes, on either side: a query, an
53/// answer or a revocation is a key and some framing, so anything larger
54/// is not one.
55pub const MAX_FRAME: u32 = 1024;
56
57/// The main server's word that what it answered for `endpoint` no longer
58/// holds: a paired server unpaired, or moved to a new key.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60pub struct AccessRevoked {
61    /// The endpoint's key, hex.
62    pub endpoint: String,
63}
64
65/// Who an endpoint is to the main server, for its relay.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case")]
68pub enum Tier {
69    /// The server itself, a device of its users (one with a live session
70    /// or trusted for a user), or the holder of an invite that
71    /// makes an account here (`create-user`, any role).
72    Owner,
73    /// The holder of an invite for a portable user or a server,
74    /// and later those users and servers themselves; a paired server's
75    /// user's device holding a play token, and while the session it opened
76    /// lives.
77    Friend,
78    /// Anyone else.
79    Stranger,
80    /// A tier this build does not know: a stranger.
81    #[serde(other)]
82    Unknown,
83}
84
85/// The token whoever holds invite `code` connects to the server's relay
86/// with, as `endpoint` (its key's bytes): `sf-invite.1.` and the base64url
87/// of BLAKE3 keyed with the code's hash, over the key. It proves the code
88/// without carrying it, and admits no other endpoint: the relay's
89/// handshake proved the key it was made for. `None` for a code that
90/// cannot be one.
91pub fn invite_token(code: &str, endpoint: &[u8; 32]) -> Option<String> {
92    let code = crate::invite::normalize_code(code)?;
93    let mac = invite_mac(blake3::hash(code.as_bytes()).as_bytes(), endpoint);
94    Some(format!(
95        "{INVITE_TOKEN_PREFIX}{}",
96        URL_SAFE_NO_PAD.encode(mac)
97    ))
98}
99
100/// What a token for the invite whose code hashes to `code_hash` carries,
101/// as `endpoint`: the server keeps only the hash, and checks with this.
102pub fn invite_mac(code_hash: &[u8; 32], endpoint: &[u8; 32]) -> [u8; 32] {
103    *blake3::keyed_hash(code_hash, endpoint).as_bytes()
104}
105
106/// The MAC `token` carries, if it is an invite holder's token at all.
107/// The relay passes on only these, and play token holders' ([`is_relay_token`]):
108/// anything else is no token.
109pub fn parse_invite_token(token: &str) -> Option<[u8; 32]> {
110    mac_after(token, INVITE_TOKEN_PREFIX)
111}
112
113/// The token whoever holds paired-server play token `token` connects to
114/// that server's relay with, as `endpoint`: `sf-play.1.` and the
115/// base64url of BLAKE3 keyed with the play token's hash, over the key, as
116/// an invite holder's is made with the code's. The server keeps only the
117/// play token's hash, and checks with it.
118pub fn play_relay_token(token: &str, endpoint: &[u8; 32]) -> String {
119    let mac = invite_mac(blake3::hash(token.as_bytes()).as_bytes(), endpoint);
120    format!("{PLAY_TOKEN_PREFIX}{}", URL_SAFE_NO_PAD.encode(mac))
121}
122
123/// The MAC `token` carries, if it is a play token holder's relay token.
124pub fn parse_play_token(token: &str) -> Option<[u8; 32]> {
125    mac_after(token, PLAY_TOKEN_PREFIX)
126}
127
128/// Whether `token` is one a relay passes on: an invite holder's or a play
129/// token holder's.
130pub fn is_relay_token(token: &str) -> bool {
131    parse_invite_token(token).is_some() || parse_play_token(token).is_some()
132}
133
134fn mac_after(token: &str, prefix: &str) -> Option<[u8; 32]> {
135    let encoded = token.strip_prefix(prefix)?;
136    // 32 bytes are 43 characters unpadded: nothing longer is decoded.
137    if encoded.len() != 43 {
138        return None;
139    }
140    URL_SAFE_NO_PAD.decode(encoded).ok()?.try_into().ok()
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146    use crate::codec;
147
148    #[test]
149    fn a_query_and_its_answer_go_both_ways() {
150        for invite in [None, Some("sf-invite.1.x".to_owned())] {
151            let query = AccessQuery {
152                endpoint: "3f9a".into(),
153                invite,
154            };
155            let back: AccessQuery = codec::decode(&codec::encode(&query).unwrap()).unwrap();
156            assert_eq!(back, query);
157        }
158        for tier in [Tier::Owner, Tier::Friend, Tier::Stranger] {
159            let answer = AccessAnswer { tier };
160            let back: AccessAnswer = codec::decode(&codec::encode(&answer).unwrap()).unwrap();
161            assert_eq!(back, answer);
162        }
163        let revoked = AccessRevoked {
164            endpoint: "3f9a".into(),
165        };
166        let back: AccessRevoked = codec::decode(&codec::encode(&revoked).unwrap()).unwrap();
167        assert_eq!(back, revoked);
168    }
169
170    #[test]
171    fn a_tier_this_build_does_not_know_is_unknown() {
172        let answer: AccessAnswer =
173            serde_json::from_value(serde_json::json!({ "tier": "neighbour" })).unwrap();
174        assert_eq!(answer.tier, Tier::Unknown);
175    }
176
177    /// P6-08: a relay from before the token asks without it, and one with
178    /// it asks a server from before it in a shape that server reads.
179    #[test]
180    fn a_query_without_a_token_is_the_one_before_it() {
181        #[derive(Debug, Serialize, Deserialize)]
182        struct Before {
183            endpoint: String,
184        }
185        let before = codec::encode(&Before {
186            endpoint: "3f9a".into(),
187        })
188        .unwrap();
189        let read: AccessQuery = codec::decode(&before).unwrap();
190        assert_eq!(read.invite, None);
191        let without = AccessQuery {
192            endpoint: "3f9a".into(),
193            invite: None,
194        };
195        assert_eq!(codec::encode(&without).unwrap(), before);
196        let with = AccessQuery {
197            invite: Some("sf-invite.1.x".into()),
198            ..without
199        };
200        let old: Before = codec::decode(&codec::encode(&with).unwrap()).unwrap();
201        assert_eq!(old.endpoint, "3f9a");
202    }
203
204    #[test]
205    fn a_token_is_the_code_s_mac_over_the_endpoint_and_reads_back() {
206        let me = [7u8; 32];
207        let token = invite_token("qw7k-2mfp-xr4t", &me).unwrap();
208        assert!(token.starts_with(INVITE_TOKEN_PREFIX), "{token}");
209        assert!(!token.contains("QW7K"), "{token}");
210        // However the code is typed.
211        assert_eq!(invite_token("QW7K2MFPXR4T", &me), Some(token.clone()));
212        let hash = blake3::hash(b"QW7K2MFPXR4T");
213        assert_eq!(
214            parse_invite_token(&token),
215            Some(invite_mac(hash.as_bytes(), &me))
216        );
217        // Another endpoint, another code: another token.
218        assert_ne!(
219            invite_token("QW7K2MFPXR4T", &[8u8; 32]),
220            Some(token.clone())
221        );
222        assert_ne!(invite_token("QW7K2MFPXR4A", &me), Some(token));
223        assert_eq!(invite_token("not a code", &me), None);
224    }
225
226    /// P8-04: a play token holder's relay token is the token hash's MAC
227    /// over the endpoint, and is never an invite holder's.
228    #[test]
229    fn a_play_relay_token_is_its_token_s_mac_over_the_endpoint() {
230        let me = [7u8; 32];
231        let token = play_relay_token("bearer", &me);
232        assert!(token.starts_with(PLAY_TOKEN_PREFIX), "{token}");
233        assert!(!token.contains("bearer"), "{token}");
234        let hash = blake3::hash(b"bearer");
235        assert_eq!(
236            parse_play_token(&token),
237            Some(invite_mac(hash.as_bytes(), &me))
238        );
239        assert_eq!(parse_invite_token(&token), None);
240        assert!(is_relay_token(&token));
241        assert_ne!(play_relay_token("bearer", &[8u8; 32]), token);
242        assert!(!is_relay_token("sf-play.1.x"));
243    }
244
245    #[test]
246    fn only_a_well_formed_token_is_one() {
247        let token = invite_token("QW7K2MFPXR4T", &[7u8; 32]).unwrap();
248        for not in [
249            "".to_owned(),
250            "Bearer x".to_owned(),
251            token.replace("sf-invite.1.", "sf-invite.2."),
252            format!("{token}A"),
253            token[..token.len() - 1].to_owned(),
254            format!("{INVITE_TOKEN_PREFIX}{}", "!".repeat(43)),
255        ] {
256            assert_eq!(parse_invite_token(&not), None, "{not:?}");
257        }
258    }
259}