Skip to main content

kute_cli/
registry.rs

1//! `kute fetch`: take a vocabulary from a `kute serve --registry` by its
2//! digest, and keep it only if it is that vocabulary.
3//!
4//! The registry is not trusted and neither is the network between. What
5//! is asked for is named by the hash of its content, the hash is
6//! recomputed here from what arrives, and with `--trusted-key` a
7//! signature is checked as `kute verify` checks one. So a registry, or
8//! anyone on the path, can refuse, stall or send something else, and
9//! something else is not kept. It can also see what was asked for and
10//! what was sent: the connection is plain HTTP.
11//!
12//! The client is written on `std::net` like the service, with every
13//! bound in this file: one request, a deadline for the whole exchange, a
14//! cap on the header block and on the body.
15
16use crate::sign;
17use kute::{vocab, Engine, KuteError};
18use serde_json::{json, Value};
19use std::io::{Read, Write};
20use std::net::{TcpStream, ToSocketAddrs};
21use std::path::Path;
22use std::time::{Duration, Instant};
23
24/// Most bytes of status line and headers in an answer.
25const MAX_HEAD_BYTES: usize = 16 * 1024;
26/// Most bytes of a listing, or of the body of a refusal.
27const MAX_LISTING_BYTES: u64 = 16 << 20;
28
29/// The registry routes, under the service's `/v1/`.
30pub const LIST_PATH: &str = "/v1/vocabularies";
31
32/// A digest as the registry names files: `sha256:` and 64 lowercase hex
33/// digits. Nothing else reaches a path.
34pub fn is_digest(text: &str) -> bool {
35    text.strip_prefix("sha256:").is_some_and(|hex| hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
36}
37
38fn failed(what: impl Into<String>) -> KuteError {
39    KuteError::Backend(format!("registry: {}", what.into()))
40}
41
42/// Host and port, and the path the registry's routes are under.
43fn parse_url(url: &str) -> kute::Result<(String, String)> {
44    let bad = |why: &str| KuteError::InvalidConfig(format!("registry address {url:?}: {why}"));
45    if url.starts_with("https://") {
46        return Err(bad("https is not built. What is fetched is checked against its digest whatever carried it, but a plain connection shows the network what was asked for and what was sent"));
47    }
48    let rest = url.strip_prefix("http://").ok_or_else(|| bad("expected http://host:port"))?;
49    let (authority, path) = rest.split_once('/').map_or((rest, ""), |(a, p)| (a, p));
50    if authority.is_empty() || authority.contains('@') || authority.bytes().any(|b| b.is_ascii_whitespace() || b.is_ascii_control()) {
51        return Err(bad("expected http://host:port"));
52    }
53    let path = path.trim_end_matches('/');
54    if path.bytes().any(|b| !(b.is_ascii_alphanumeric() || b"-._~/".contains(&b))) {
55        return Err(bad("the path may hold letters, digits and - . _ ~ / only"));
56    }
57    // A bare IPv6 address has colons of its own; in brackets it is told
58    // from a port.
59    let has_port = authority.rsplit_once(':').is_some_and(|(host, port)| !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) && (!host.contains(':') || host.ends_with(']')));
60    let authority = if has_port { authority.to_string() } else { format!("{authority}:80") };
61    Ok((authority, if path.is_empty() { String::new() } else { format!("/{path}") }))
62}
63
64/// One GET. Returns the status and the body, which is at most `max_bytes`.
65fn get(authority: &str, path: &str, max_bytes: u64, timeout: Duration) -> kute::Result<(u16, Vec<u8>)> {
66    let deadline = Instant::now() + timeout;
67    let left = || deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()).ok_or_else(|| failed("no complete answer in time"));
68    let mut stream = None;
69    let mut last = None;
70    for address in authority.to_socket_addrs().map_err(|e| failed(format!("{authority}: {e}")))? {
71        match TcpStream::connect_timeout(&address, left()?) {
72            Ok(s) => {
73                stream = Some(s);
74                break;
75            }
76            Err(e) => last = Some(e),
77        }
78    }
79    let mut stream = stream.ok_or_else(|| failed(format!("could not connect to {authority}: {}", last.map_or("no address".to_string(), |e| e.to_string()))))?;
80    stream.set_write_timeout(Some(left()?))?;
81    stream.write_all(format!("GET {path} HTTP/1.1\r\nHost: {authority}\r\nAccept: application/json\r\nConnection: close\r\n\r\n").as_bytes())?;
82    let mut buffer: Vec<u8> = Vec::with_capacity(4096);
83    let mut chunk = [0u8; 16 * 1024];
84    let head_end = loop {
85        if let Some(at) = buffer.windows(4).position(|w| w == b"\r\n\r\n") {
86            break at;
87        }
88        if buffer.len() > MAX_HEAD_BYTES {
89            return Err(failed("the answer's headers are larger than any this client reads"));
90        }
91        stream.set_read_timeout(Some(left()?))?;
92        match stream.read(&mut chunk) {
93            Ok(0) => return Err(failed("the connection closed before an answer")),
94            Ok(n) => buffer.extend_from_slice(&chunk[..n]),
95            Err(_) => return Err(failed("no complete answer in time")),
96        }
97    };
98    let head = std::str::from_utf8(&buffer[..head_end]).map_err(|_| failed("the answer's headers are not text"))?;
99    let mut lines = head.split("\r\n");
100    let status: u16 = lines
101        .next()
102        .and_then(|line| line.strip_prefix("HTTP/1."))
103        .and_then(|rest| rest.split(' ').nth(1))
104        .and_then(|code| code.parse().ok())
105        .ok_or_else(|| failed("the answer is not HTTP"))?;
106    let mut length = None;
107    for line in lines {
108        let Some((name, value)) = line.split_once(':') else { continue };
109        if name.eq_ignore_ascii_case("content-length") {
110            length = Some(value.trim().parse::<u64>().map_err(|_| failed("Content-Length is not a number"))?);
111        } else if name.eq_ignore_ascii_case("transfer-encoding") {
112            return Err(failed("the answer is in a transfer encoding; this client reads a body of stated length only"));
113        }
114    }
115    // A stated length, so that a body cut short is told from a whole one.
116    let length = length.ok_or_else(|| failed("the answer does not state its length"))?;
117    if length > max_bytes {
118        return Err(KuteError::LimitExceeded(format!("the registry's answer is {length} bytes; the limit is {max_bytes} (--max-bytes)")));
119    }
120    let mut body = buffer.split_off(head_end + 4);
121    if body.len() as u64 > length {
122        return Err(failed("more bytes than the stated length"));
123    }
124    while (body.len() as u64) < length {
125        stream.set_read_timeout(Some(left()?))?;
126        let want = chunk.len().min((length - body.len() as u64) as usize);
127        match stream.read(&mut chunk[..want]) {
128            Ok(0) => return Err(failed("the connection closed before the whole answer")),
129            Ok(n) => body.extend_from_slice(&chunk[..n]),
130            Err(_) => return Err(failed("no complete answer in time")),
131        }
132    }
133    Ok((status, body))
134}
135
136/// The reason a registry gave for not answering 200, kept short: it is
137/// text from the other side.
138fn refusal(status: u16, body: &[u8]) -> KuteError {
139    let said = serde_json::from_slice::<Value>(body).ok().and_then(|v| v["error"]["message"].as_str().map(|m| m.chars().filter(|c| !c.is_control()).take(300).collect::<String>()));
140    failed(format!("answered {status}{}", said.map_or(String::new(), |m| format!(": {m}"))))
141}
142
143/// What the registry says it holds. Nothing in it is checked: it is the
144/// other side's account, and a file is checked when it is fetched.
145pub fn list(from: &str, timeout: Duration) -> kute::Result<Value> {
146    let (authority, base) = parse_url(from)?;
147    let (status, body) = get(&authority, &format!("{base}{LIST_PATH}"), MAX_LISTING_BYTES, timeout)?;
148    if status != 200 {
149        return Err(refusal(status, &body));
150    }
151    let listing: Value = serde_json::from_slice(&body).map_err(|_| failed("the listing is not JSON"))?;
152    Ok(json!({
153        "registry": from,
154        "says_it_holds": listing["vocabularies"],
155        "checked": "nothing: this is what the registry says. A vocabulary is checked when it is fetched by digest.",
156    }))
157}
158
159/// Fetch the vocabulary with this digest, check it, and write it.
160#[allow(clippy::too_many_arguments)]
161pub fn fetch(engine: &Engine, from: &str, digest: &str, output: &Path, trusted: &[String], force: bool, max_bytes: u64, timeout: Duration) -> kute::Result<Value> {
162    if !is_digest(digest) {
163        return Err(KuteError::InvalidConfig(format!("{digest:?} is not a digest: expected sha256: and 64 lowercase hex digits")));
164    }
165    // Before anything is asked for: a key that cannot be read, or an
166    // output that may not be written, is this side's mistake.
167    let gate = if trusted.is_empty() { None } else { Some(sign::gate(trusted)?) };
168    if output.exists() && !force {
169        return Err(KuteError::InvalidConfig(format!("{} exists; pass --force to replace it", output.display())));
170    }
171    let (authority, base) = parse_url(from)?;
172    let (status, body) = get(&authority, &format!("{base}{LIST_PATH}/{digest}"), max_bytes, timeout)?;
173    if status != 200 {
174        return Err(refusal(status, &body[..body.len().min(MAX_LISTING_BYTES as usize)]));
175    }
176    let vocabulary = vocab::from_slice(&body)?;
177    vocabulary.validate()?;
178    // The digest of what arrived, not the one the file states.
179    let arrived = vocabulary.compute_digest()?;
180    if arrived != digest {
181        return Err(KuteError::Integrity(format!("the registry sent a vocabulary with digest {arrived}, not the one asked for; nothing was written")));
182    }
183    let report = engine.verify(&vocabulary)?;
184    if !report.ok() {
185        return Err(KuteError::Integrity(format!("the vocabulary fails its own test vectors: {}; nothing was written", report.failures.join("; "))));
186    }
187    if let Some(gate) = &gate {
188        gate(&vocabulary).map_err(|why| KuteError::Integrity(format!("the vocabulary is not kept: {why}; nothing was written")))?;
189    }
190    vocab::save(&vocabulary, output, force)?;
191    Ok(json!({
192        "registry": from,
193        "digest": digest,
194        "digest_recomputed_from_content": true,
195        "id": vocabulary.id().as_str(),
196        "version": vocabulary.version().to_string(),
197        "tokens": vocabulary.len(),
198        "bytes_received": body.len(),
199        "test_vectors_pass": true,
200        "signature": if gate.is_some() { "a trusted key signed exactly this content" } else { "not checked: no --trusted-key was given" },
201        "output": output,
202        "means": "the file is the content this digest names. Whether that content is the one you wanted depends on where the digest came from; who made it is known only if a signature was checked.",
203    }))
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    #[test]
211    fn addresses_and_digests_are_read_strictly() {
212        assert_eq!(parse_url("http://127.0.0.1:8787").unwrap(), ("127.0.0.1:8787".to_string(), String::new()));
213        assert_eq!(parse_url("http://example.org/kute/").unwrap(), ("example.org:80".to_string(), "/kute".to_string()));
214        assert_eq!(parse_url("http://[::1]:9000").unwrap().0, "[::1]:9000");
215        assert_eq!(parse_url("http://[::1]").unwrap().0, "[::1]:80");
216        for bad in ["https://example.org", "example.org:80", "http://", "http://user@host", "http://host/a b", "http://host/x?y=1", "http://host/\r\nX: 1"] {
217            assert!(parse_url(bad).is_err(), "{bad:?}");
218        }
219        assert!(is_digest(&format!("sha256:{}", "0a".repeat(32))));
220        for bad in [format!("sha256:{}", "0A".repeat(32)), format!("sha256:{}", "0a".repeat(31)), format!("sha256:{}/..", "0a".repeat(31)), "0a".repeat(32)] {
221            assert!(!is_digest(&bad), "{bad:?}");
222        }
223    }
224}