mirror of
https://github.com/storytold/craft-libs.git
synced 2026-12-01 02:36:54 +01:00
craft-xtask: report curl size refusals as TooLarge and compose names before folding case
- curl runs with --globoff, so brackets and braces in a pin's address are sent as they are. - curl's exit status 63 (--max-filesize refused the body) becomes an error of kind FileTooLarge, which the fetch reports as TooLarge, the same result as a body stopped while counting. - curl's failure message no longer includes the address. - fold puts a name in NFC before the case mapping as well as after it, so alpha followed by U+0345 and U+0301 in either order gets one key. - entry_parts checks the parts and measures the kept length before collecting anything. - The tests use tempfile for their scratch folders, and the system tar test skips only when tar is not installed.
This commit is contained in:
1 parent
a82336c70b
commit
218d6d5d97
3 files changed
+94
-41
No files matched your search
@@ -203,10 +203,13 @@ followed by a combining accent are one name), and a file name may not also be us
|
||||
address starts with `https://`, the SHA-256 has 64 hexadecimal digits, and `max_bytes` is at
|
||||
least 1.
|
||||
|
||||
`curl` runs with `-q` (no `.curlrc`), `--proto =https` and `--proto-redir =https`, `--fail`,
|
||||
`--max-filesize` set to `max_bytes`, a 10-second connect timeout, and a stop when a transfer stays
|
||||
under 1 KiB per second for 60 seconds. The crate counts the bytes itself as well, so a response of
|
||||
unknown length stops at `max_bytes` with any version of `curl`.
|
||||
`curl` runs with `-q` (no `.curlrc`), `--globoff` (brackets and braces in the address are sent as
|
||||
they are), `--proto =https` and `--proto-redir =https`, `--fail`, `--max-filesize` set to
|
||||
`max_bytes`, a 10-second connect timeout, and a stop when a transfer stays under 1 KiB per second for
|
||||
60 seconds. The crate counts the bytes itself as well, so a response of unknown length stops at
|
||||
`max_bytes` with any version of `curl`. A body over `max_bytes` is reported as `TooLarge` whether
|
||||
`curl` refuses it from its advertised size or the crate stops it while counting; a `Transport`
|
||||
reports such a refusal with an error of kind `FileTooLarge`.
|
||||
|
||||
Neither `dest` nor any path under it may be a link. A link, or a folder where a file goes, or a
|
||||
file where a folder goes, stops the fetch with `FetchError::NotRegular`. The folders above `dest`
|
||||
|
||||
+50
-17
@@ -149,13 +149,17 @@ impl std::error::Error for FetchError {
|
||||
/// Sends the body found at an address to a writer.
|
||||
pub trait Transport {
|
||||
/// Writes the body of `url` to `out`. `max_bytes` is the most the caller accepts; the caller
|
||||
/// counts the bytes itself and stops the transfer with a write error past it.
|
||||
/// counts the bytes itself and stops the transfer with a write error past it. A transport that
|
||||
/// refuses the body itself for being over `max_bytes` returns an error of kind
|
||||
/// [`io::ErrorKind::FileTooLarge`], which the caller reports as [`FetchError::TooLarge`].
|
||||
fn download(&self, url: &str, max_bytes: u64, out: &mut dyn Write) -> io::Result<()>;
|
||||
}
|
||||
|
||||
/// The [`Transport`] of [`fetch_pinned`] and [`fetch_archive`]: the system `curl`, reading no
|
||||
/// configuration file, allowed HTTPS only for the address and every redirect, failing on an HTTP
|
||||
/// error status, and stopping a transfer that stays under 1 KiB per second for 60 seconds.
|
||||
/// configuration file, requesting the address literally (no `[]` or `{}` globbing), allowed HTTPS
|
||||
/// only for the address and every redirect, failing on an HTTP error status, refusing a body whose
|
||||
/// advertised size is over the limit before it arrives, and stopping a transfer that stays under
|
||||
/// 1 KiB per second for 60 seconds.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct Curl;
|
||||
|
||||
@@ -179,7 +183,12 @@ impl Transport for Curl {
|
||||
return Err(e);
|
||||
}
|
||||
let status = child.wait()?;
|
||||
if status.success() { Ok(()) } else { Err(io::Error::other(format!("curl {url} failed: {status}"))) }
|
||||
match status.code() {
|
||||
Some(0) => Ok(()),
|
||||
// Exit status 63: `--max-filesize` refused a body whose advertised size is over the limit.
|
||||
Some(63) => Err(io::Error::new(io::ErrorKind::FileTooLarge, format!("curl refused a body over {max_bytes} bytes"))),
|
||||
_ => Err(io::Error::other(format!("curl failed: {status}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,6 +196,7 @@ impl Transport for Curl {
|
||||
fn curl_args(url: &str, max_bytes: u64) -> Vec<String> {
|
||||
let mut args: Vec<String> = [
|
||||
"-q",
|
||||
"--globoff",
|
||||
"--fail",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
@@ -492,11 +502,13 @@ fn join<S: AsRef<str>>(parts: &[S]) -> String {
|
||||
/// The key under which [`Names`] compares a part: the lowercase of its uppercase. The forms of one
|
||||
/// letter then get one key even when one is not the lowercase of another (`Σ`, `σ` and `ς`). A
|
||||
/// letter whose uppercase is longer gets the key of that spelling (`ß` and `ss`), so such pairs are
|
||||
/// refused even on a file system that keeps them apart. The key is then put in Unicode
|
||||
/// Normalization Form C, so a composed `é` and an `e` followed by a combining acute accent, which
|
||||
/// are one name on macOS, get one key.
|
||||
/// refused even on a file system that keeps them apart. The part is put in Unicode Normalization
|
||||
/// Form C before the case mapping and the key again after it, so a composed `é` and an `e`
|
||||
/// followed by a combining acute accent, which are one name on macOS, get one key, and so do
|
||||
/// `α` followed by U+0345 and U+0301 in either order.
|
||||
fn fold(part: &str) -> String {
|
||||
part.to_uppercase().to_lowercase().nfc().collect()
|
||||
let composed: String = part.nfc().collect();
|
||||
composed.to_uppercase().to_lowercase().nfc().collect()
|
||||
}
|
||||
|
||||
/// Creates `dest` when it is missing and checks that it is a folder and not a link.
|
||||
@@ -630,7 +642,7 @@ impl<W: Write> Write for Sink<W> {
|
||||
/// Turns a finished transfer into its output, or into the error that rejects it: the limit first,
|
||||
/// then the transport's error, then the SHA-256.
|
||||
fn finish<W>(name: &str, sha256: &str, sink: Sink<W>, got: io::Result<()>) -> Result<W, FetchError> {
|
||||
if sink.over {
|
||||
if sink.over || matches!(&got, Err(e) if e.kind() == io::ErrorKind::FileTooLarge) {
|
||||
return Err(too_large(name, format!("{} bytes", sink.max)));
|
||||
}
|
||||
got.map_err(|source| FetchError::Download { name: name.to_string(), source })?;
|
||||
@@ -760,20 +772,26 @@ fn entry_parts(raw: &[u8], strip: usize) -> Result<Option<Vec<String>>, String>
|
||||
if text.starts_with('/') {
|
||||
return Err("the path is absolute".into());
|
||||
}
|
||||
let parts: Vec<&str> = text.strip_suffix('/').unwrap_or(text).split('/').skip_while(|p| *p == ".").collect();
|
||||
if parts.iter().all(|p| p.is_empty()) {
|
||||
let parts = || text.strip_suffix('/').unwrap_or(text).split('/').skip_while(|p| *p == ".");
|
||||
if parts().all(str::is_empty) {
|
||||
return Ok(None);
|
||||
}
|
||||
for part in &parts {
|
||||
// The parts are checked and the kept length measured before anything is collected, so a long
|
||||
// path allocates nothing before it is refused.
|
||||
let mut kept_bytes = 0usize;
|
||||
for (i, part) in parts().enumerate() {
|
||||
check_part(part)?;
|
||||
if i >= strip {
|
||||
kept_bytes = kept_bytes.saturating_add(part.len() + 1);
|
||||
}
|
||||
}
|
||||
let kept: Vec<String> = parts.iter().skip(strip).map(|p| (*p).to_string()).collect();
|
||||
if kept_bytes > MAX_NAME_BYTES {
|
||||
return Err(format!("the path is longer than {MAX_NAME_BYTES} bytes"));
|
||||
}
|
||||
let kept: Vec<String> = parts().skip(strip).map(str::to_string).collect();
|
||||
if kept.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if kept.iter().map(|p| p.len() + 1).sum::<usize>() > MAX_NAME_BYTES {
|
||||
return Err(format!("the path is longer than {MAX_NAME_BYTES} bytes"));
|
||||
}
|
||||
Ok(Some(kept))
|
||||
}
|
||||
|
||||
@@ -798,11 +816,26 @@ mod tests {
|
||||
let args = curl_args("https://example.com/a.png", 1234);
|
||||
assert_eq!(args.first().map(String::as_str), Some("-q"));
|
||||
let joined = args.join(" ");
|
||||
for expected in ["--fail", "--proto =https", "--proto-redir =https", "--max-filesize 1234", "--output -", "--url https://example.com/a.png"] {
|
||||
for expected in
|
||||
["--globoff", "--fail", "--proto =https", "--proto-redir =https", "--max-filesize 1234", "--output -", "--url https://example.com/a.png"]
|
||||
{
|
||||
assert!(joined.contains(expected), "{expected} is missing from {joined}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_parts_keep_their_results_around_the_length_limit() {
|
||||
let long = "a/".repeat(MAX_NAME_BYTES);
|
||||
assert!(entry_parts(long.as_bytes(), 0).is_err());
|
||||
// Stripped folders do not count toward the length, but are still checked.
|
||||
let fits = format!("{}b", "a/".repeat(MAX_NAME_BYTES / 2));
|
||||
let strip = MAX_NAME_BYTES / 2;
|
||||
assert_eq!(entry_parts(fits.as_bytes(), strip), Ok(Some(vec!["b".to_string()])));
|
||||
assert!(entry_parts(format!("..{}", &fits[1..]).as_bytes(), strip).is_err());
|
||||
assert_eq!(entry_parts(b"./", 0), Ok(None));
|
||||
assert_eq!(entry_parts(b"top/", 1), Ok(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sha256_hex_matches_the_fips_180_example() {
|
||||
// FIPS 180-4 example "abc".
|
||||
|
||||
@@ -4,21 +4,18 @@ use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use craft_xtask::fetch::{ExtractOptions, FetchError, FetchSummary, Pin, Transport, extract, fetch_archive_with, fetch_pinned_with, sha256_hex};
|
||||
use tempfile::TempDir;
|
||||
|
||||
/// A folder under the system temporary folder, removed when dropped.
|
||||
struct Scratch(PathBuf);
|
||||
/// A folder under the system temporary folder, created with a unique name and removed when
|
||||
/// dropped.
|
||||
struct Scratch(PathBuf, TempDir);
|
||||
|
||||
impl Scratch {
|
||||
fn new(label: &str) -> Self {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!("craft-xtask-{label}-{}-{n}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).unwrap();
|
||||
Self(path)
|
||||
let dir = tempfile::Builder::new().prefix(&format!("craft-xtask-{label}-")).tempdir().unwrap();
|
||||
Self(dir.path().to_path_buf(), dir)
|
||||
}
|
||||
|
||||
/// Every name under the folder, sorted, with `/` between folders.
|
||||
@@ -34,23 +31,19 @@ impl Scratch {
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(&self.0, "", &mut out);
|
||||
walk(self.1.path(), "", &mut out);
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the fake server does for one address.
|
||||
enum Reply {
|
||||
Body(Vec<u8>),
|
||||
/// Sends these bytes, then fails as a dropped connection does.
|
||||
Cut(Vec<u8>),
|
||||
/// Sends nothing and refuses the body for its advertised size, as `curl --max-filesize` does.
|
||||
Refused,
|
||||
}
|
||||
|
||||
/// An in-process transport: a table from address to reply, with a count of requests.
|
||||
@@ -77,6 +70,7 @@ impl Transport for Fake {
|
||||
out.write_all(bytes)?;
|
||||
Err(io::Error::new(io::ErrorKind::ConnectionReset, "connection reset"))
|
||||
}
|
||||
Some(Reply::Refused) => Err(io::Error::new(io::ErrorKind::FileTooLarge, "maximum file size exceeded")),
|
||||
None => Err(io::Error::new(io::ErrorKind::NotFound, "404")),
|
||||
}
|
||||
}
|
||||
@@ -164,6 +158,20 @@ fn a_response_of_unknown_length_stops_at_the_limit() {
|
||||
assert!(dir.listing().is_empty(), "{:?}", dir.listing());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_the_transport_refuses_for_its_size_is_too_large() {
|
||||
let dir = Scratch::new("refused");
|
||||
let fake = Fake::default().with(URL, Reply::Refused);
|
||||
let sha = sha256_hex(b"body");
|
||||
|
||||
let err = fetch_pinned_with(&dir.0, &[pin("a.png", &sha)], &fake).unwrap_err();
|
||||
assert!(matches!(&err, FetchError::TooLarge { limit, .. } if limit == "1024 bytes"), "{err}");
|
||||
let archive = Pin { name: "t.tar", url: URL, sha256: &sha, max_bytes: 1024 };
|
||||
let err = fetch_archive_with(&dir.0, &archive, &ExtractOptions::default(), &fake).unwrap_err();
|
||||
assert!(matches!(&err, FetchError::TooLarge { limit, .. } if limit == "1024 bytes"), "{err}");
|
||||
assert!(dir.listing().is_empty(), "{:?}", dir.listing());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_response_of_exactly_the_limit_is_accepted() {
|
||||
let dir = Scratch::new("exact");
|
||||
@@ -222,6 +230,9 @@ fn bad_pins_are_refused_before_any_download() {
|
||||
// A composed `é` and `e` followed by a combining acute accent are one name on macOS.
|
||||
cases.push(vec![pin("\u{e9}.png", &sha), pin("e\u{301}.png", &sha)]);
|
||||
cases.push(vec![pin("\u{e9}/a.png", &sha), pin("E\u{301}/b.png", &sha)]);
|
||||
// `α` with U+0345 and U+0301 in either order is one name once composed.
|
||||
cases.push(vec![pin("\u{3b1}\u{345}\u{301}.png", &sha), pin("\u{3b1}\u{301}\u{345}.png", &sha)]);
|
||||
cases.push(vec![pin("\u{3b1}\u{345}\u{301}/a.png", &sha), pin("\u{3b1}\u{301}\u{345}/b.png", &sha)]);
|
||||
cases.push(vec![Pin { url: "file:///etc/passwd", ..pin("a.png", &sha) }]);
|
||||
cases.push(vec![Pin { url: "http://example.com/a.png", ..pin("a.png", &sha) }]);
|
||||
cases.push(vec![Pin { url: "https:///a.png", ..pin("a.png", &sha) }]);
|
||||
@@ -366,7 +377,7 @@ fn an_archive_with_the_wrong_hash_or_size_writes_nothing() {
|
||||
|
||||
#[test]
|
||||
fn unsafe_archive_entries_write_nothing() {
|
||||
let cases: [&[(&str, u8, &[u8])]; 19] = [
|
||||
let cases: [&[(&str, u8, &[u8])]; 21] = [
|
||||
&[("ok.png", b'0', b"1"), ("foo\\bar.png", b'0', b"2")],
|
||||
&[("ok.png", b'0', b"1"), ("foo//", b'5', b"")],
|
||||
&[("ok.png", b'0', b"1"), ("foo//bar.png", b'0', b"2")],
|
||||
@@ -386,6 +397,8 @@ fn unsafe_archive_entries_write_nothing() {
|
||||
&[("\u{3c3}/a.txt", b'0', b"1"), ("\u{3c2}/b.txt", b'0', b"2")],
|
||||
&[("\u{e9}.txt", b'0', b"1"), ("e\u{301}.txt", b'0', b"2")],
|
||||
&[("e\u{301}/a.txt", b'0', b"1"), ("\u{c9}/b.txt", b'0', b"2")],
|
||||
&[("\u{3b1}\u{345}\u{301}.txt", b'0', b"1"), ("\u{3b1}\u{301}\u{345}.txt", b'0', b"2")],
|
||||
&[("\u{3b1}\u{345}\u{301}/a.txt", b'0', b"1"), ("\u{3b1}\u{301}\u{345}/b.txt", b'0', b"2")],
|
||||
];
|
||||
for entries in cases {
|
||||
let dir = Scratch::new("unsafe");
|
||||
@@ -500,9 +513,13 @@ fn reads_an_archive_made_by_the_system_tar() {
|
||||
let archive = source.0.join("suite.tgz");
|
||||
// COPYFILE_DISABLE keeps macOS tar from adding `._` metadata entries.
|
||||
let made = Command::new("tar").env("COPYFILE_DISABLE", "1").arg("-czf").arg(&archive).arg("-C").arg(&source.0).arg("suite").status();
|
||||
if !matches!(made, Ok(status) if status.success()) {
|
||||
eprintln!("SKIPPED: no system tar ({made:?})");
|
||||
return;
|
||||
match made {
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {
|
||||
eprintln!("SKIPPED: no system tar");
|
||||
return;
|
||||
}
|
||||
Err(e) => panic!("cannot run tar: {e}"),
|
||||
Ok(status) => assert!(status.success(), "tar failed: {status}"),
|
||||
}
|
||||
let bytes = fs::read(&archive).unwrap();
|
||||
|
||||
|
||||
Reference in new issue
Block a user