Skip to main content

lean_ctx_cloud/
vault_address.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Vault addresses `<ws>/<vault>[@<server>]` (C0 2.0 `common.schema.json`
3//! `$defs/vault_address`, `vectors/vault_address.vectors.json`), used in
4//! `.lean-ctx-cloud.json` (link v2), CLI vault arguments and environment
5//! values. No server or `@cloud.leanctx.com` is the hosted service; a
6//! server with a dot or a port is self-hosted at `https://<server>`.
7
8use std::fmt;
9
10/// The hosted service (LeanCTX Cloud).
11pub const HOSTED_SERVER: &str = "cloud.leanctx.com";
12
13/// True when `server` (lowercase `host[:port]`) is the hosted service.
14pub fn is_hosted_server(server: &str) -> bool {
15    server == HOSTED_SERVER
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct VaultAddress {
20    pub ws: String,
21    pub vault: String,
22    /// Self-hosted server (`host[:port]`, lowercase); `None` = hosted.
23    pub server: Option<String>,
24}
25
26/// Why an address is refused (the vectors' `reason`).
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum AddressRefusal {
29    WsInvalid,
30    VaultMissing,
31    VaultInvalid,
32    ServerEmpty,
33    ServerAmbiguous,
34    ServerInvalid,
35    PortInvalid,
36}
37
38impl AddressRefusal {
39    pub fn code(self) -> &'static str {
40        match self {
41            Self::WsInvalid => "ws_invalid",
42            Self::VaultMissing => "vault_missing",
43            Self::VaultInvalid => "vault_invalid",
44            Self::ServerEmpty => "server_empty",
45            Self::ServerAmbiguous => "server_ambiguous",
46            Self::ServerInvalid => "server_invalid",
47            Self::PortInvalid => "port_invalid",
48        }
49    }
50}
51
52impl fmt::Display for AddressRefusal {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        let hint = match self {
55            Self::ServerAmbiguous => {
56                "a server needs a dot or a port (e.g. cloud.example.com or localhost:8443)"
57            }
58            Self::ServerEmpty => "nothing follows @",
59            Self::PortInvalid => "the port must be 1 to 65535",
60            _ => "use <workspace>/<vault>[@<server>] in lowercase",
61        };
62        write!(f, "{}: {hint}", self.code())
63    }
64}
65
66impl std::error::Error for AddressRefusal {}
67
68impl VaultAddress {
69    pub fn parse(input: &str) -> Result<Self, AddressRefusal> {
70        // The last `@` starts the server, so an `@` inside the path makes
71        // the vault invalid rather than the server.
72        let (path, server) = match input.rsplit_once('@') {
73            Some((path, server)) => (path, Some(server)),
74            None => (input, None),
75        };
76        let mut parts = path.split('/');
77        let ws = parts.next().unwrap_or_default();
78        if !is_ws(ws) {
79            return Err(AddressRefusal::WsInvalid);
80        }
81        let vault = parts.next().ok_or(AddressRefusal::VaultMissing)?;
82        if parts.next().is_some() || !is_vault(vault) {
83            return Err(AddressRefusal::VaultInvalid);
84        }
85        let server = server.map(parse_server).transpose()?;
86        Ok(Self {
87            ws: ws.to_string(),
88            vault: vault.to_string(),
89            server: server.filter(|s| !is_hosted_server(s)),
90        })
91    }
92
93    pub fn is_hosted(&self) -> bool {
94        self.server.is_none()
95    }
96
97    /// `https://<server>`.
98    pub fn origin(&self) -> String {
99        format!(
100            "https://{}",
101            self.server.as_deref().unwrap_or(HOSTED_SERVER)
102        )
103    }
104}
105
106impl fmt::Display for VaultAddress {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        write!(f, "{}/{}", self.ws, self.vault)?;
109        match &self.server {
110            Some(server) => write!(f, "@{server}"),
111            None => Ok(()),
112        }
113    }
114}
115
116/// `[a-z0-9][a-z0-9-]{0,38}`.
117fn is_ws(s: &str) -> bool {
118    let b = s.as_bytes();
119    (1..=39).contains(&b.len())
120        && (b[0].is_ascii_lowercase() || b[0].is_ascii_digit())
121        && b.iter()
122            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
123}
124
125/// `[a-z0-9-]{2,40}`.
126fn is_vault(s: &str) -> bool {
127    (2..=40).contains(&s.len())
128        && s.bytes()
129            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
130}
131
132/// DNS label `[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?`.
133fn is_label(s: &str) -> bool {
134    let b = s.as_bytes();
135    (1..=63).contains(&b.len())
136        && b[0].is_ascii_alphanumeric()
137        && b[b.len() - 1].is_ascii_alphanumeric()
138        && b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-')
139}
140
141/// `host-with-dot[:port] | name:port | [ipv6]:port`, lowercased.
142fn parse_server(raw: &str) -> Result<String, AddressRefusal> {
143    if raw.is_empty() {
144        return Err(AddressRefusal::ServerEmpty);
145    }
146    let server = raw.to_ascii_lowercase();
147    if let Some(rest) = server.strip_prefix('[') {
148        let (ip, port) = rest.split_once("]:").ok_or(AddressRefusal::ServerInvalid)?;
149        let ip_ok = !ip.is_empty()
150            && ip
151                .bytes()
152                .all(|c| c.is_ascii_hexdigit() || c == b':' || c == b'.');
153        if !ip_ok || ip.parse::<std::net::Ipv6Addr>().is_err() {
154            return Err(AddressRefusal::ServerInvalid);
155        }
156        check_port(port)?;
157        return Ok(server);
158    }
159    let (host, port) = match server.rsplit_once(':') {
160        Some((host, port)) => (host, Some(port)),
161        None => (server.as_str(), None),
162    };
163    if !host.split('.').all(is_label) {
164        return Err(AddressRefusal::ServerInvalid);
165    }
166    match port {
167        Some(port) => check_port(port)?,
168        None if !host.contains('.') => return Err(AddressRefusal::ServerAmbiguous),
169        None => {}
170    }
171    Ok(server)
172}
173
174fn check_port(port: &str) -> Result<(), AddressRefusal> {
175    let valid = (1..=5).contains(&port.len())
176        && port.bytes().all(|c| c.is_ascii_digit())
177        && port.parse::<u32>().is_ok_and(|p| (1..=65_535).contains(&p));
178    if valid {
179        Ok(())
180    } else {
181        Err(AddressRefusal::PortInvalid)
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    const VECTORS: &str = include_str!(
190        "../../../crates/lean-ctx-protocol/tests/fixtures/cloud-v2/vectors/vault_address.vectors.json"
191    );
192
193    #[test]
194    fn addresses_match_the_contract_vectors() {
195        let vectors: serde_json::Value = serde_json::from_str(VECTORS).unwrap();
196        let cases = vectors["cases"].as_array().unwrap();
197        assert!(cases.len() >= 15);
198        for case in cases {
199            let input = case["input"].as_str().unwrap();
200            let want = &case["output"];
201            match VaultAddress::parse(input) {
202                Ok(address) => {
203                    assert_eq!(want["valid"], true, "{input}");
204                    assert_eq!(address.ws, want["ws"], "{input}");
205                    assert_eq!(address.vault, want["vault"], "{input}");
206                    assert_eq!(address.is_hosted(), want["hosted"], "{input}");
207                    assert_eq!(address.origin(), want["origin"], "{input}");
208                    assert_eq!(
209                        address
210                            .server
211                            .as_deref()
212                            .map_or(serde_json::Value::Null, Into::into),
213                        want["server"],
214                        "{input}"
215                    );
216                }
217                Err(refusal) => {
218                    assert_eq!(want["valid"], false, "{input}");
219                    assert_eq!(refusal.code(), want["reason"], "{input}");
220                }
221            }
222        }
223    }
224
225    #[test]
226    fn display_round_trips_the_canonical_form() {
227        for input in [
228            "acme/payments",
229            "acme/payments@cloud.acme.example:8443",
230            "acme/p2@[::1]:8443",
231        ] {
232            assert_eq!(VaultAddress::parse(input).unwrap().to_string(), input);
233        }
234        assert_eq!(
235            VaultAddress::parse("acme/payments@Cloud.LeanCTX.com")
236                .unwrap()
237                .to_string(),
238            "acme/payments"
239        );
240        for hosted in [
241            "acme/payments@cloud.leanctx.com",
242            "acme/payments@cloud.leanctx.com",
243        ] {
244            let address = VaultAddress::parse(hosted).unwrap();
245            assert!(address.is_hosted(), "{hosted}");
246            assert_eq!(address.origin(), "https://cloud.leanctx.com", "{hosted}");
247        }
248        assert_eq!(
249            VaultAddress::parse("acme/payments@[zz]:1"),
250            Err(AddressRefusal::ServerInvalid)
251        );
252        assert_eq!(
253            VaultAddress::parse("acme/payments@-bad.example"),
254            Err(AddressRefusal::ServerInvalid)
255        );
256    }
257}