1use 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
24const MAX_HEAD_BYTES: usize = 16 * 1024;
26const MAX_LISTING_BYTES: u64 = 16 << 20;
28
29pub const LIST_PATH: &str = "/v1/vocabularies";
31
32pub 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
42pub 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 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
64pub const VIA_HEADER: &str = "Kute-Registry-Via";
70
71const 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 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 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
165fn 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
172pub 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
203pub enum Taken {
205 Found(Box<kute::Vocabulary>, usize),
207 Absent(String),
209}
210
211pub 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 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#[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 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 "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}