use crate::sign;
use kute::{vocab, Engine, KuteError};
use serde_json::{json, Value};
use std::io::{Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::path::Path;
use std::time::{Duration, Instant};
const MAX_HEAD_BYTES: usize = 16 * 1024;
const MAX_LISTING_BYTES: u64 = 16 << 20;
pub const LIST_PATH: &str = "/v1/vocabularies";
pub fn is_digest(text: &str) -> bool {
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)))
}
fn failed(what: impl Into<String>) -> KuteError {
KuteError::Backend(format!("registry: {}", what.into()))
}
pub fn parse_url(url: &str) -> kute::Result<(String, String)> {
let bad = |why: &str| KuteError::InvalidConfig(format!("registry address {url:?}: {why}"));
if url.starts_with("https://") {
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"));
}
let rest = url.strip_prefix("http://").ok_or_else(|| bad("expected http://host:port"))?;
let (authority, path) = rest.split_once('/').map_or((rest, ""), |(a, p)| (a, p));
if authority.is_empty() || authority.contains('@') || authority.bytes().any(|b| b.is_ascii_whitespace() || b.is_ascii_control()) {
return Err(bad("expected http://host:port"));
}
let path = path.trim_end_matches('/');
if path.bytes().any(|b| !(b.is_ascii_alphanumeric() || b"-._~/".contains(&b))) {
return Err(bad("the path may hold letters, digits and - . _ ~ / only"));
}
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(']')));
let authority = if has_port { authority.to_string() } else { format!("{authority}:80") };
Ok((authority, if path.is_empty() { String::new() } else { format!("/{path}") }))
}
pub const VIA_HEADER: &str = "Kute-Registry-Via";
const MAX_LOOKUPS: usize = 16;
fn get(authority: &str, path: &str, max_bytes: u64, timeout: Duration, via: bool) -> kute::Result<(u16, Vec<u8>)> {
let deadline = Instant::now() + timeout;
let left = || deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()).ok_or_else(|| failed("no complete answer in time"));
static LOOKUPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
use std::sync::atomic::Ordering::SeqCst;
if LOOKUPS.fetch_add(1, SeqCst) >= MAX_LOOKUPS {
LOOKUPS.fetch_sub(1, SeqCst);
return Err(failed(format!("{authority} was not looked up: {MAX_LOOKUPS} earlier lookups are still unanswered")));
}
let (found, lookup) = std::sync::mpsc::channel();
let name = authority.to_string();
std::thread::spawn(move || {
let _ = found.send(name.to_socket_addrs().map(|addresses| addresses.collect::<Vec<_>>()));
LOOKUPS.fetch_sub(1, SeqCst);
});
let addresses = lookup.recv_timeout(left()?).map_err(|_| failed(format!("{authority} was not looked up in time")))?.map_err(|e| failed(format!("{authority}: {e}")))?;
let mut stream = None;
let mut last = None;
for address in addresses {
match TcpStream::connect_timeout(&address, left()?) {
Ok(s) => {
stream = Some(s);
break;
}
Err(e) => last = Some(e),
}
}
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()))))?;
stream.set_write_timeout(Some(left()?))?;
let via = if via { format!("{VIA_HEADER}: 1\r\n") } else { String::new() };
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())?;
let mut buffer: Vec<u8> = Vec::with_capacity(4096);
let mut chunk = [0u8; 16 * 1024];
let head_end = loop {
if let Some(at) = buffer.windows(4).position(|w| w == b"\r\n\r\n") {
break at;
}
if buffer.len() > MAX_HEAD_BYTES {
return Err(failed("the answer's headers are larger than any this client reads"));
}
stream.set_read_timeout(Some(left()?))?;
match stream.read(&mut chunk) {
Ok(0) => return Err(failed("the connection closed before an answer")),
Ok(n) => buffer.extend_from_slice(&chunk[..n]),
Err(_) => return Err(failed("no complete answer in time")),
}
};
let head = std::str::from_utf8(&buffer[..head_end]).map_err(|_| failed("the answer's headers are not text"))?;
let mut lines = head.split("\r\n");
let status: u16 = lines
.next()
.and_then(|line| line.strip_prefix("HTTP/1."))
.and_then(|rest| rest.split(' ').nth(1))
.and_then(|code| code.parse().ok())
.ok_or_else(|| failed("the answer is not HTTP"))?;
let mut length = None;
for line in lines {
let Some((name, value)) = line.split_once(':') else { continue };
if name.eq_ignore_ascii_case("content-length") {
length = Some(value.trim().parse::<u64>().map_err(|_| failed("Content-Length is not a number"))?);
} else if name.eq_ignore_ascii_case("transfer-encoding") {
return Err(failed("the answer is in a transfer encoding; this client reads a body of stated length only"));
}
}
let length = length.ok_or_else(|| failed("the answer does not state its length"))?;
if length > max_bytes {
return Err(KuteError::LimitExceeded(format!("the registry's answer is {length} bytes; the limit is {max_bytes} (--max-bytes)")));
}
let mut body = buffer.split_off(head_end + 4);
if body.len() as u64 > length {
return Err(failed("more bytes than the stated length"));
}
while (body.len() as u64) < length {
stream.set_read_timeout(Some(left()?))?;
let want = chunk.len().min((length - body.len() as u64) as usize);
match stream.read(&mut chunk[..want]) {
Ok(0) => return Err(failed("the connection closed before the whole answer")),
Ok(n) => body.extend_from_slice(&chunk[..n]),
Err(_) => return Err(failed("no complete answer in time")),
}
}
Ok((status, body))
}
fn refusal(status: u16, body: &[u8]) -> KuteError {
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>()));
failed(format!("answered {status}{}", said.map_or(String::new(), |m| format!(": {m}"))))
}
pub fn list(from: &[String], timeout: Duration) -> kute::Result<Value> {
let one = |registry: &str| -> kute::Result<Value> {
let (authority, base) = parse_url(registry)?;
let (status, body) = get(&authority, &format!("{base}{LIST_PATH}"), MAX_LISTING_BYTES, timeout, false)?;
if status != 200 {
return Err(refusal(status, &body));
}
let listing: Value = serde_json::from_slice(&body).map_err(|_| failed("the listing is not JSON"))?;
Ok(json!({ "registry": registry, "says_it_holds": listing["vocabularies"], "says_it_asks": listing["upstreams"] }))
};
if let [registry] = from {
let mut row = one(registry)?;
row["checked"] = json!("nothing: this is what the registry says. A vocabulary is checked when it is fetched by digest.");
return Ok(row);
}
for registry in from {
parse_url(registry)?;
}
let rows: Vec<Value> = from.iter().map(|registry| one(registry).unwrap_or_else(|e| json!({ "registry": registry, "error": e.to_string() }))).collect();
Ok(json!({
"registries": rows,
"checked": "nothing: this is what each registry says. A vocabulary is checked when it is fetched by digest.",
}))
}
pub enum Taken {
Found(Box<kute::Vocabulary>, usize),
Absent(String),
}
pub fn take(engine: &Engine, registry: &str, digest: &str, max_bytes: u64, timeout: Duration, via: bool) -> kute::Result<Taken> {
let (authority, base) = parse_url(registry)?;
let (status, body) = get(&authority, &format!("{base}{LIST_PATH}/{digest}"), max_bytes, timeout, via)?;
if status == 404 {
return Ok(Taken::Absent(refusal(status, &body[..body.len().min(MAX_LISTING_BYTES as usize)]).to_string()));
}
if status != 200 {
return Err(refusal(status, &body[..body.len().min(MAX_LISTING_BYTES as usize)]));
}
let vocabulary = vocab::from_slice(&body)?;
vocabulary.validate()?;
let arrived = vocabulary.compute_digest()?;
if arrived != digest {
return Err(KuteError::Integrity(format!("the registry sent a vocabulary with digest {arrived}, not the one asked for")));
}
let report = engine.verify(&vocabulary)?;
if !report.ok() {
return Err(KuteError::Integrity(format!("the vocabulary fails its own test vectors: {}", report.failures.join("; "))));
}
Ok(Taken::Found(Box::new(vocabulary), body.len()))
}
#[allow(clippy::too_many_arguments)]
pub fn fetch(engine: &Engine, from: &[String], digest: &str, output: &Path, trusted: &[String], force: bool, max_bytes: u64, timeout: Duration) -> kute::Result<Value> {
if !is_digest(digest) {
return Err(KuteError::InvalidConfig(format!("{digest:?} is not a digest: expected sha256: and 64 lowercase hex digits")));
}
let gate = if trusted.is_empty() { None } else { Some(sign::gate(trusted)?) };
if output.exists() && !force {
return Err(KuteError::InvalidConfig(format!("{} exists; pass --force to replace it", output.display())));
}
for registry in from {
parse_url(registry)?;
}
let mut passed_over: Vec<Value> = Vec::new();
for registry in from {
let why = match take(engine, registry, digest, max_bytes, timeout, false) {
Ok(Taken::Found(vocabulary, bytes)) => match gate.as_ref().map_or(Ok(()), |gate| gate(&vocabulary)) {
Ok(()) => {
let signatures = vocabulary.integrity.as_ref().map_or(0, |i| i.signatures.len());
vocab::save(&vocabulary, output, force)?;
return Ok(json!({
"registry": registry,
"registries_passed_over": passed_over,
"digest": digest,
"digest_recomputed_from_content": true,
"id": vocabulary.id().as_str(),
"version": vocabulary.version().to_string(),
"tokens": vocabulary.len(),
"bytes_received": bytes,
"test_vectors_pass": true,
"signature": if gate.is_some() { "a trusted key signed exactly this content" } else { "not checked: no --trusted-key was given" },
"signatures_in_the_file": signatures,
"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" },
"output": output,
"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.",
}));
}
Err(why) => format!("the vocabulary is not kept: {why}"),
},
Ok(Taken::Absent(said)) => said,
Err(e) => e.to_string(),
};
passed_over.push(json!({ "registry": registry, "why": why }));
}
let said: Vec<String> = passed_over.iter().map(|p| format!("{}: {}", p["registry"].as_str().unwrap_or(""), p["why"].as_str().unwrap_or(""))).collect();
Err(KuteError::Integrity(format!("nothing was written. {}", said.join(" | "))))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn addresses_and_digests_are_read_strictly() {
assert_eq!(parse_url("http://127.0.0.1:8787").unwrap(), ("127.0.0.1:8787".to_string(), String::new()));
assert_eq!(parse_url("http://example.org/kute/").unwrap(), ("example.org:80".to_string(), "/kute".to_string()));
assert_eq!(parse_url("http://[::1]:9000").unwrap().0, "[::1]:9000");
assert_eq!(parse_url("http://[::1]").unwrap().0, "[::1]:80");
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"] {
assert!(parse_url(bad).is_err(), "{bad:?}");
}
assert!(is_digest(&format!("sha256:{}", "0a".repeat(32))));
for bad in [format!("sha256:{}", "0A".repeat(32)), format!("sha256:{}", "0a".repeat(31)), format!("sha256:{}/..", "0a".repeat(31)), "0a".repeat(32)] {
assert!(!is_digest(&bad), "{bad:?}");
}
}
}