Skip to main content

recall_wire/
discovery.rs

1//! What a server says about itself, and what a client says about itself.
2//!
3//! `GET /.well-known/recall` answers with a [`Discovery`] document: which
4//! protocol versions the server speaks, which release it is, the oldest
5//! client it accepts, how clients may authenticate, and what it can do. It
6//! is unauthenticated, like `/health`, and at the path RFC 8615 sets aside
7//! for exactly this kind of document.
8//!
9//! The rules that keep it readable by clients that do not exist yet, taken
10//! from git protocol v2, Matrix's `/versions` and MCP:
11//!
12//! 1. **Two layers.** [`Protocol`] changes only for a breaking change; the
13//!    capabilities only ever grow.
14//! 2. **Unknown keys are ignored**, at any depth. Nothing here denies
15//!    unknown fields, and a client must not either.
16//! 3. **Absent means unsupported.** A capability that is not listed is not
17//!    available.
18//! 4. **A map, not a list.** Each capability is an object, so it can carry
19//!    parameters later without a new key.
20//! 5. **Nothing is removed** within a protocol version.
21//!
22//! In the other direction, every request a client sends carries
23//! [`PROTOCOL_HEADER`] and a `User-Agent` of the form [`user_agent`] builds.
24
25use std::collections::BTreeMap;
26
27use serde::{Deserialize, Serialize};
28
29/// Where the discovery document is served.
30pub const DISCOVERY_PATH: &str = "/.well-known/recall";
31
32/// The protocol version this build speaks.
33pub const PROTOCOL: u32 = 1;
34
35/// The request header a client names its protocol version in. A request
36/// without it is treated as protocol 1, which is what every client before
37/// the header existed spoke.
38pub const PROTOCOL_HEADER: &str = "recall-protocol";
39
40/// The discovery document.
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
42pub struct Discovery {
43    /// The protocol versions the server speaks.
44    pub protocol: Protocol,
45    /// Which build of the server this is.
46    pub server: ServerInfo,
47    /// The oldest client version the server accepts, as SemVer.
48    pub min_client: String,
49    /// How clients may authenticate.
50    pub auth: Auth,
51    /// What the server can do, by name. An absent name is unsupported.
52    #[serde(default)]
53    pub capabilities: BTreeMap<String, serde_json::Value>,
54}
55
56impl Discovery {
57    /// Whether the server speaks protocol `version`.
58    pub fn speaks(&self, version: u32) -> bool {
59        self.protocol.supported.contains(&version)
60    }
61
62    /// Whether the server lists the capability `name`.
63    pub fn can(&self, name: &str) -> bool {
64        self.capabilities.contains_key(name)
65    }
66
67    /// Whether the server accepts the authentication method `name`, such
68    /// as [`AUTH_DEVICE_SIG`].
69    pub fn accepts(&self, name: &str) -> bool {
70        self.auth.methods.iter().any(|m| m == name)
71    }
72
73    /// The [`CAPABILITY_DEVICES`] capability, read into its type. [`None`]
74    /// when the server does not list it, and also when it lists one this
75    /// build cannot read, which is the same answer: a client cannot use it.
76    pub fn devices(&self) -> Option<crate::DevicesCapability> {
77        serde_json::from_value(self.capabilities.get(CAPABILITY_DEVICES)?.clone()).ok()
78    }
79}
80
81/// The protocol versions a server speaks.
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct Protocol {
84    /// The newest one, which a server's own client speaks.
85    pub current: u32,
86    /// Every version the server accepts requests in.
87    pub supported: Vec<u32>,
88}
89
90/// Which build of the server answered.
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92pub struct ServerInfo {
93    /// The server's identity, as SemVer: the release version for a release
94    /// build, and a `-dev` pre-release of the next patch for anything else.
95    pub version: String,
96    /// Where the build came from.
97    pub build: Build,
98}
99
100/// Where a build came from. Provenance only: nothing is decided on it.
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102pub struct Build {
103    /// [`CHANNEL_RELEASE`] for a release build, [`CHANNEL_DEV`] otherwise.
104    pub channel: String,
105    /// The commit it was built from, when known.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub revision: Option<String>,
108    /// When it was built, in RFC 3339, when known.
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub created: Option<String>,
111}
112
113/// How a client may authenticate.
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115pub struct Auth {
116    /// The methods the server accepts, by name, e.g. [`AUTH_BEARER`].
117    pub methods: Vec<String>,
118}
119
120/// The one shared bearer token, `RECALL_TOKEN`.
121pub const AUTH_BEARER: &str = "bearer";
122
123/// Requests signed by an enrolled device's key: see
124/// [`crate::signature`].
125pub const AUTH_DEVICE_SIG: &str = "device-sig-v1";
126
127/// The capability a server lists when it enrols devices; its parameters
128/// are a [`crate::DevicesCapability`].
129pub const CAPABILITY_DEVICES: &str = "devices";
130
131/// The capability a server lists when it can queue a stale push for a
132/// merge worker and has the job routes (see [`crate::jobs`]). A worker
133/// asks for it before enrolling, and works for no server without it.
134pub const CAPABILITY_MERGE_QUEUE: &str = "merge_queue";
135
136/// A build made by the release workflow from a release tag.
137pub const CHANNEL_RELEASE: &str = "release";
138
139/// Any other build: from `main`, from a pull request, or on someone's
140/// machine.
141pub const CHANNEL_DEV: &str = "dev";
142
143/// This build's channel, decided at compile time by `build.rs`:
144/// `RECALL_BUILD_CHANNEL` when set, otherwise `dev` for a git checkout and
145/// `release` for a crate built from crates.io, which is what
146/// `cargo install recall` compiles.
147pub fn channel() -> &'static str {
148    match env!("RECALL_RESOLVED_CHANNEL") {
149        CHANNEL_RELEASE => CHANNEL_RELEASE,
150        _ => CHANNEL_DEV,
151    }
152}
153
154/// The commit this build was compiled from, when the build recorded one.
155pub fn revision() -> Option<&'static str> {
156    option_env!("RECALL_GIT_COMMIT").filter(|r| !r.is_empty())
157}
158
159/// When this build was made, when the build recorded it.
160pub fn created() -> Option<&'static str> {
161    option_env!("RECALL_BUILD_CREATED").filter(|c| !c.is_empty())
162}
163
164/// This build's version, as SemVer: see [`version_for`].
165pub fn version() -> String {
166    version_for(channel(), revision())
167}
168
169/// The version a build of this source reports.
170///
171/// A release build reports its release. Anything else reports a
172/// pre-release of the next patch, with the commit as build metadata, so
173/// `0.3.2` built from a later `main` reads `0.3.3-dev+g1a2b3c4`. SemVer
174/// orders that after `0.3.2` and before `0.3.3`, which is where the code
175/// actually sits, and ignores the metadata when comparing.
176pub fn version_for(channel: &str, revision: Option<&str>) -> String {
177    let base = env!("CARGO_PKG_VERSION");
178    if channel == CHANNEL_RELEASE {
179        return base.to_string();
180    }
181    let next = match Version::parse(base) {
182        Some(v) => format!("{}.{}.{}", v.major, v.minor, v.patch + 1),
183        None => base.to_string(),
184    };
185    match revision {
186        Some(rev) => {
187            let short: String = rev.chars().take(7).collect();
188            format!("{next}-dev+g{short}")
189        }
190        None => format!("{next}-dev"),
191    }
192}
193
194/// The `User-Agent` a client sends: `recall/<version> (<os>-<arch>)`, the
195/// way git sends `agent=git/<version>`.
196pub fn user_agent() -> String {
197    format!(
198        "recall/{} ({}-{})",
199        version(),
200        std::env::consts::OS,
201        std::env::consts::ARCH
202    )
203}
204
205/// A SemVer version, enough of it to compare two.
206///
207/// Build metadata is dropped on parsing: SemVer says it *"MUST be ignored
208/// when determining version precedence"*.
209#[derive(Debug, Clone, PartialEq, Eq)]
210pub struct Version {
211    /// Major.
212    pub major: u64,
213    /// Minor.
214    pub minor: u64,
215    /// Patch.
216    pub patch: u64,
217    /// Pre-release identifiers, empty for a release.
218    pub pre: Vec<String>,
219}
220
221impl Version {
222    /// Parses `1.2.3`, `1.2.3-dev`, `1.2.3-rc.1+build`. [`None`] for
223    /// anything else.
224    pub fn parse(text: &str) -> Option<Self> {
225        let text = text.trim().trim_start_matches('v');
226        let text = text.split('+').next()?;
227        let (core, pre) = match text.split_once('-') {
228            Some((core, pre)) => (core, pre.split('.').map(str::to_string).collect()),
229            None => (text, Vec::new()),
230        };
231        let mut parts = core.split('.');
232        let major = parts.next()?.parse().ok()?;
233        let minor = parts.next()?.parse().ok()?;
234        let patch = parts.next()?.parse().ok()?;
235        if parts.next().is_some() {
236            return None;
237        }
238        Some(Self {
239            major,
240            minor,
241            patch,
242            pre,
243        })
244    }
245}
246
247impl PartialOrd for Version {
248    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
249        Some(self.cmp(other))
250    }
251}
252
253impl Ord for Version {
254    /// SemVer §11: major, minor and patch numerically; then a version with
255    /// a pre-release before the same version without one; then pre-release
256    /// identifiers left to right, numeric ones numerically and before
257    /// alphanumeric ones, and a shorter list before a longer one it prefixes.
258    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
259        use std::cmp::Ordering;
260        let core =
261            (self.major, self.minor, self.patch).cmp(&(other.major, other.minor, other.patch));
262        if core != Ordering::Equal {
263            return core;
264        }
265        match (self.pre.is_empty(), other.pre.is_empty()) {
266            (true, true) => return Ordering::Equal,
267            (true, false) => return Ordering::Greater,
268            (false, true) => return Ordering::Less,
269            (false, false) => {}
270        }
271        for (a, b) in self.pre.iter().zip(&other.pre) {
272            let order = match (a.parse::<u64>(), b.parse::<u64>()) {
273                (Ok(x), Ok(y)) => x.cmp(&y),
274                (Ok(_), Err(_)) => Ordering::Less,
275                (Err(_), Ok(_)) => Ordering::Greater,
276                (Err(_), Err(_)) => a.cmp(b),
277            };
278            if order != Ordering::Equal {
279                return order;
280            }
281        }
282        self.pre.len().cmp(&other.pre.len())
283    }
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    fn v(text: &str) -> Version {
291        Version::parse(text).unwrap()
292    }
293
294    /// The ordering examples from SemVer §11, in order.
295    #[test]
296    fn versions_order_the_way_semver_says() {
297        let ordered = [
298            "1.0.0-alpha",
299            "1.0.0-alpha.1",
300            "1.0.0-alpha.beta",
301            "1.0.0-beta",
302            "1.0.0-beta.2",
303            "1.0.0-beta.11",
304            "1.0.0-rc.1",
305            "1.0.0",
306            "2.0.0",
307            "2.1.0",
308            "2.1.1",
309        ];
310        for pair in ordered.windows(2) {
311            assert!(v(pair[0]) < v(pair[1]), "{} < {}", pair[0], pair[1]);
312        }
313    }
314
315    #[test]
316    fn build_metadata_does_not_count() {
317        assert_eq!(v("0.3.3-dev+g1a2b3c4"), v("0.3.3-dev+gffffff0"));
318        assert!(v("0.3.2") < v("0.3.3-dev+g1a2b3c4"));
319        assert!(v("0.3.3-dev+g1a2b3c4") < v("0.3.3"));
320    }
321
322    #[test]
323    fn what_is_not_a_version_is_refused() {
324        for bad in ["", "1", "1.2", "1.2.3.4", "a.b.c", "1.2.x"] {
325            assert_eq!(Version::parse(bad), None, "{bad:?}");
326        }
327        assert_eq!(v("v1.2.3"), v("1.2.3"));
328    }
329
330    #[test]
331    fn a_release_build_is_its_release_and_anything_else_the_next_dev() {
332        let base = env!("CARGO_PKG_VERSION");
333        assert_eq!(version_for(CHANNEL_RELEASE, Some("abc")), base);
334        let dev = version_for(CHANNEL_DEV, Some("e100cfdd88e8a0e6659b"));
335        assert!(dev.ends_with("-dev+ge100cfd"), "{dev}");
336        assert!(v(base) < v(&dev), "{base} < {dev}");
337        assert!(version_for(CHANNEL_DEV, None).ends_with("-dev"));
338    }
339
340    /// A document from a newer server, with a key and a capability this
341    /// build has never heard of, still reads, and still answers.
342    #[test]
343    fn unknown_keys_are_ignored_and_absent_capabilities_are_unsupported() {
344        let doc: Discovery = serde_json::from_str(
345            r#"{
346                "protocol": {"current": 2, "supported": [1, 2]},
347                "server": {"version": "0.9.0", "build": {"channel": "release", "signed": true}},
348                "min_client": "0.3.0",
349                "auth": {"methods": ["device-sig-v1", "bearer"]},
350                "capabilities": {"merge_base": {}, "telepathy": {"level": 3}},
351                "operator": {"contact": "someone"}
352            }"#,
353        )
354        .unwrap();
355        assert!(doc.speaks(1) && doc.speaks(2) && !doc.speaks(3));
356        assert!(doc.can("merge_base") && doc.can("telepathy"));
357        assert!(!doc.can("scopes"));
358        assert!(doc.accepts(AUTH_DEVICE_SIG) && doc.accepts(AUTH_BEARER));
359        assert!(!doc.accepts("passkey"));
360        assert_eq!(doc.devices(), None, "not listed, so not supported");
361    }
362
363    /// A devices capability with keys this build has never heard of still
364    /// reads; one missing a key it needs does not, and so is unusable.
365    #[test]
366    fn the_devices_capability_reads_into_its_type() {
367        let mut doc: Discovery = serde_json::from_str(
368            r#"{
369                "protocol": {"current": 1, "supported": [1]},
370                "server": {"version": "0.4.1", "build": {"channel": "release"}},
371                "min_client": "0.1.0",
372                "auth": {"methods": ["bearer", "device-sig-v1"]},
373                "capabilities": {"devices": {
374                    "enroll_path": "/v1/devices/enroll", "code_ttl_seconds": 900,
375                    "poll_interval_seconds": 5, "signature_window_seconds": 60,
376                    "passkeys": {}
377                }}
378            }"#,
379        )
380        .unwrap();
381        let devices = doc.devices().unwrap();
382        assert_eq!(devices.enroll_path, "/v1/devices/enroll");
383        assert_eq!(devices.signature_window_seconds, 60);
384
385        doc.capabilities.insert(
386            CAPABILITY_DEVICES.into(),
387            serde_json::json!({"enroll_path": "/x"}),
388        );
389        assert_eq!(doc.devices(), None);
390    }
391
392    #[test]
393    fn the_user_agent_names_the_version_and_platform() {
394        let ua = user_agent();
395        assert!(ua.starts_with("recall/"), "{ua}");
396        assert!(ua.contains(std::env::consts::OS), "{ua}");
397    }
398}