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.
43pub fn 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`.
65/// Sent by a registry asking another on a caller's behalf. A registry
66/// that sees it answers from what it holds and asks nobody further, so
67/// a question travels one registry beyond the one it was put to and
68/// registries that name each other cannot pass it round.
69pub const VIA_HEADER: &str = "Kute-Registry-Via";
70
71/// Name lookups allowed to be unanswered at once in this process.
72const MAX_LOOKUPS: usize = 16;
73
74fn get(authority: &str, path: &str, max_bytes: u64, timeout: Duration, via: bool) -> kute::Result<(u16, Vec<u8>)> {
75    let deadline = Instant::now() + timeout;
76    let left = || deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()).ok_or_else(|| failed("no complete answer in time"));
77    // Looking a name up has no deadline of its own in the standard
78    // library, so it is done on another thread and waited for only as
79    // long as the exchange has. A lookup that outlasts the wait leaves
80    // its thread behind until the resolver of the system gives up. `kute
81    // fetch` ends soon after; a registry asking upstream runs for hours,
82    // so the number left behind at once is capped.
83    static LOOKUPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
84    use std::sync::atomic::Ordering::SeqCst;
85    if LOOKUPS.fetch_add(1, SeqCst) >= MAX_LOOKUPS {
86        LOOKUPS.fetch_sub(1, SeqCst);
87        return Err(failed(format!("{authority} was not looked up: {MAX_LOOKUPS} earlier lookups are still unanswered")));
88    }
89    let (found, lookup) = std::sync::mpsc::channel();
90    let name = authority.to_string();
91    std::thread::spawn(move || {
92        let _ = found.send(name.to_socket_addrs().map(|addresses| addresses.collect::<Vec<_>>()));
93        LOOKUPS.fetch_sub(1, SeqCst);
94    });
95    let addresses = lookup.recv_timeout(left()?).map_err(|_| failed(format!("{authority} was not looked up in time")))?.map_err(|e| failed(format!("{authority}: {e}")))?;
96    let mut stream = None;
97    let mut last = None;
98    for address in addresses {
99        match TcpStream::connect_timeout(&address, left()?) {
100            Ok(s) => {
101                stream = Some(s);
102                break;
103            }
104            Err(e) => last = Some(e),
105        }
106    }
107    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()))))?;
108    stream.set_write_timeout(Some(left()?))?;
109    let via = if via { format!("{VIA_HEADER}: 1\r\n") } else { String::new() };
110    stream.write_all(format!("GET {path} HTTP/1.1\r\nHost: {authority}\r\nAccept: application/json\r\n{via}Connection: close\r\n\r\n").as_bytes())?;
111    let mut buffer: Vec<u8> = Vec::with_capacity(4096);
112    let mut chunk = [0u8; 16 * 1024];
113    let head_end = loop {
114        if let Some(at) = buffer.windows(4).position(|w| w == b"\r\n\r\n") {
115            break at;
116        }
117        if buffer.len() > MAX_HEAD_BYTES {
118            return Err(failed("the answer's headers are larger than any this client reads"));
119        }
120        stream.set_read_timeout(Some(left()?))?;
121        match stream.read(&mut chunk) {
122            Ok(0) => return Err(failed("the connection closed before an answer")),
123            Ok(n) => buffer.extend_from_slice(&chunk[..n]),
124            Err(_) => return Err(failed("no complete answer in time")),
125        }
126    };
127    let head = std::str::from_utf8(&buffer[..head_end]).map_err(|_| failed("the answer's headers are not text"))?;
128    let mut lines = head.split("\r\n");
129    let status: u16 = lines
130        .next()
131        .and_then(|line| line.strip_prefix("HTTP/1."))
132        .and_then(|rest| rest.split(' ').nth(1))
133        .and_then(|code| code.parse().ok())
134        .ok_or_else(|| failed("the answer is not HTTP"))?;
135    let mut length = None;
136    for line in lines {
137        let Some((name, value)) = line.split_once(':') else { continue };
138        if name.eq_ignore_ascii_case("content-length") {
139            length = Some(value.trim().parse::<u64>().map_err(|_| failed("Content-Length is not a number"))?);
140        } else if name.eq_ignore_ascii_case("transfer-encoding") {
141            return Err(failed("the answer is in a transfer encoding; this client reads a body of stated length only"));
142        }
143    }
144    // A stated length, so that a body cut short is told from a whole one.
145    let length = length.ok_or_else(|| failed("the answer does not state its length"))?;
146    if length > max_bytes {
147        return Err(KuteError::LimitExceeded(format!("the registry's answer is {length} bytes; the limit is {max_bytes} (--max-bytes)")));
148    }
149    let mut body = buffer.split_off(head_end + 4);
150    if body.len() as u64 > length {
151        return Err(failed("more bytes than the stated length"));
152    }
153    while (body.len() as u64) < length {
154        stream.set_read_timeout(Some(left()?))?;
155        let want = chunk.len().min((length - body.len() as u64) as usize);
156        match stream.read(&mut chunk[..want]) {
157            Ok(0) => return Err(failed("the connection closed before the whole answer")),
158            Ok(n) => body.extend_from_slice(&chunk[..n]),
159            Err(_) => return Err(failed("no complete answer in time")),
160        }
161    }
162    Ok((status, body))
163}
164
165/// The reason a registry gave for not answering 200, kept short: it is
166/// text from the other side.
167fn refusal(status: u16, body: &[u8]) -> KuteError {
168    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>()));
169    failed(format!("answered {status}{}", said.map_or(String::new(), |m| format!(": {m}"))))
170}
171
172/// What each registry says it holds. Nothing in it is checked: it is the
173/// other side's account, and a file is checked when it is fetched.
174///
175/// One registry is reported as it was before there could be several, and
176/// a failure to reach it is an error. Several are reported one row each,
177/// a failure being that registry's row.
178pub fn list(from: &[String], timeout: Duration) -> kute::Result<Value> {
179    let one = |registry: &str| -> kute::Result<Value> {
180        let (authority, base) = parse_url(registry)?;
181        let (status, body) = get(&authority, &format!("{base}{LIST_PATH}"), MAX_LISTING_BYTES, timeout, false)?;
182        if status != 200 {
183            return Err(refusal(status, &body));
184        }
185        let listing: Value = serde_json::from_slice(&body).map_err(|_| failed("the listing is not JSON"))?;
186        Ok(json!({ "registry": registry, "says_it_holds": listing["vocabularies"], "says_it_asks": listing["upstreams"] }))
187    };
188    if let [registry] = from {
189        let mut row = one(registry)?;
190        row["checked"] = json!("nothing: this is what the registry says. A vocabulary is checked when it is fetched by digest.");
191        return Ok(row);
192    }
193    for registry in from {
194        parse_url(registry)?;
195    }
196    let rows: Vec<Value> = from.iter().map(|registry| one(registry).unwrap_or_else(|e| json!({ "registry": registry, "error": e.to_string() }))).collect();
197    Ok(json!({
198        "registries": rows,
199        "checked": "nothing: this is what each registry says. A vocabulary is checked when it is fetched by digest.",
200    }))
201}
202
203/// What asking one registry for one digest came to.
204pub enum Taken {
205    /// The vocabulary with that digest, checked, and the bytes it came in.
206    Found(Box<kute::Vocabulary>, usize),
207    /// The registry answered 404: it does not have it. In its words.
208    Absent(String),
209}
210
211/// Ask one registry for the vocabulary with this digest and check what
212/// arrives: it parses, it is valid, its content has that digest, and its
213/// own test vectors pass. Signatures are not looked at here.
214pub fn take(engine: &Engine, registry: &str, digest: &str, max_bytes: u64, timeout: Duration, via: bool) -> kute::Result<Taken> {
215    let (authority, base) = parse_url(registry)?;
216    let (status, body) = get(&authority, &format!("{base}{LIST_PATH}/{digest}"), max_bytes, timeout, via)?;
217    if status == 404 {
218        return Ok(Taken::Absent(refusal(status, &body[..body.len().min(MAX_LISTING_BYTES as usize)]).to_string()));
219    }
220    if status != 200 {
221        return Err(refusal(status, &body[..body.len().min(MAX_LISTING_BYTES as usize)]));
222    }
223    let vocabulary = vocab::from_slice(&body)?;
224    vocabulary.validate()?;
225    // The digest of what arrived, not the one the file states.
226    let arrived = vocabulary.compute_digest()?;
227    if arrived != digest {
228        return Err(KuteError::Integrity(format!("the registry sent a vocabulary with digest {arrived}, not the one asked for")));
229    }
230    let report = engine.verify(&vocabulary)?;
231    if !report.ok() {
232        return Err(KuteError::Integrity(format!("the vocabulary fails its own test vectors: {}", report.failures.join("; "))));
233    }
234    Ok(Taken::Found(Box::new(vocabulary), body.len()))
235}
236
237/// Fetch the vocabulary with this digest from the first of the
238/// registries that gives it and passes every check, and write it. The
239/// registries are asked in the order given; one that fails, lies or
240/// does not have it costs its share of the time and nothing else.
241#[allow(clippy::too_many_arguments)]
242pub fn fetch(engine: &Engine, from: &[String], digest: &str, output: &Path, trusted: &[String], force: bool, max_bytes: u64, timeout: Duration) -> kute::Result<Value> {
243    if !is_digest(digest) {
244        return Err(KuteError::InvalidConfig(format!("{digest:?} is not a digest: expected sha256: and 64 lowercase hex digits")));
245    }
246    // Before anything is asked for: a key that cannot be read, an
247    // address that cannot be, or an output that may not be written, is
248    // this side's mistake.
249    let gate = if trusted.is_empty() { None } else { Some(sign::gate(trusted)?) };
250    if output.exists() && !force {
251        return Err(KuteError::InvalidConfig(format!("{} exists; pass --force to replace it", output.display())));
252    }
253    for registry in from {
254        parse_url(registry)?;
255    }
256    let mut passed_over: Vec<Value> = Vec::new();
257    for registry in from {
258        let why = match take(engine, registry, digest, max_bytes, timeout, false) {
259            Ok(Taken::Found(vocabulary, bytes)) => match gate.as_ref().map_or(Ok(()), |gate| gate(&vocabulary)) {
260                Ok(()) => {
261                    let signatures = vocabulary.integrity.as_ref().map_or(0, |i| i.signatures.len());
262                    vocab::save(&vocabulary, output, force)?;
263                    return Ok(json!({
264                        "registry": registry,
265                        "registries_passed_over": passed_over,
266                        "digest": digest,
267                        "digest_recomputed_from_content": true,
268                        "id": vocabulary.id().as_str(),
269                        "version": vocabulary.version().to_string(),
270                        "tokens": vocabulary.len(),
271                        "bytes_received": bytes,
272                        "test_vectors_pass": true,
273                        "signature": if gate.is_some() { "a trusted key signed exactly this content" } else { "not checked: no --trusted-key was given" },
274                        // The file is written with whatever signatures arrived. Only one
275                        // that a trusted key was seen to hold has been checked; the rest
276                        // are entries anyone could have added, the registry included.
277                        "signatures_in_the_file": signatures,
278                        "signatures_in_the_file_means": if gate.is_some() { "at least one is from a trusted key; any others were not checked" } else { "none was checked: they are claims until `kute verify` is run with keys you trust" },
279                        "output": output,
280                        "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.",
281                    }));
282                }
283                Err(why) => format!("the vocabulary is not kept: {why}"),
284            },
285            Ok(Taken::Absent(said)) => said,
286            Err(e) => e.to_string(),
287        };
288        passed_over.push(json!({ "registry": registry, "why": why }));
289    }
290    let said: Vec<String> = passed_over.iter().map(|p| format!("{}: {}", p["registry"].as_str().unwrap_or(""), p["why"].as_str().unwrap_or(""))).collect();
291    Err(KuteError::Integrity(format!("nothing was written. {}", said.join(" | "))))
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297
298    #[test]
299    fn addresses_and_digests_are_read_strictly() {
300        assert_eq!(parse_url("http://127.0.0.1:8787").unwrap(), ("127.0.0.1:8787".to_string(), String::new()));
301        assert_eq!(parse_url("http://example.org/kute/").unwrap(), ("example.org:80".to_string(), "/kute".to_string()));
302        assert_eq!(parse_url("http://[::1]:9000").unwrap().0, "[::1]:9000");
303        assert_eq!(parse_url("http://[::1]").unwrap().0, "[::1]:80");
304        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"] {
305            assert!(parse_url(bad).is_err(), "{bad:?}");
306        }
307        assert!(is_digest(&format!("sha256:{}", "0a".repeat(32))));
308        for bad in [format!("sha256:{}", "0A".repeat(32)), format!("sha256:{}", "0a".repeat(31)), format!("sha256:{}/..", "0a".repeat(31)), "0a".repeat(32)] {
309            assert!(!is_digest(&bad), "{bad:?}");
310        }
311    }
312}