forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

cargo.rs313 lines, 12.9 KiBHistoryRawDownload
1//! Cargo registry rules, pure and without IO: crate and version names, the publish body, the
2//! index line written for each version, the index file path of a crate, and the README and
3//! repository link found in a `.crate` file. The wire formats follow the Cargo book's registry
4//! chapters: the publish body, the index format (version 2) and the sparse index layout.
5
6use std::io::Read;
7
8use flate2::read::GzDecoder;
9use serde_json::{Map, Value, json};
10
11use crate::error::{Error, Result};
12
13/// Longest crate name, in characters.
14pub const MAX_NAME_CHARS: usize = 64;
15/// Largest README read out of a `.crate` file, in bytes.
16pub const MAX_README_BYTES: u64 = 256 * 1024;
17
18/// Checks a crate name and returns its lowercase key. The key names the index file, so it is
19/// what routes and storage use; the name as published is kept for display and the index.
20pub fn crate_name_key(name: &str) -> Result<String> {
21 let starts_alpha = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic());
22 let chars_ok = name
23 .chars()
24 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
25 if !starts_alpha || !chars_ok || name.len() > MAX_NAME_CHARS {
26 return Err(Error::InvalidName(format!(
27 "`{name}` is not a valid crate name: start with a letter, then letters, digits, `-` or `_`, at most {MAX_NAME_CHARS} characters"
28 )));
29 }
30 Ok(name.to_ascii_lowercase())
31}
32
33/// The sparse index path of a crate key, relative to the index URL (`1/a`, `2/ab`, `3/a/abc`,
34/// `ab/cd/abcdef`). The key is ASCII, checked by [`crate_name_key`].
35pub fn index_path(key: &str) -> String {
36 match key.len() {
37 1 => format!("1/{key}"),
38 2 => format!("2/{key}"),
39 3 => format!("3/{}/{key}", &key[..1]),
40 _ => format!("{}/{}/{key}", &key[..2], &key[2..4]),
41 }
42}
43
44/// Parses a version as semver. Cargo versions are semver, with build metadata kept as written.
45pub fn parse_version(version: &str) -> Result<semver::Version> {
46 semver::Version::parse(version)
47 .map_err(|e| Error::Invalid(format!("`{version}` is not a valid version: {e}")))
48}
49
50/// A publish body split into its parts. The metadata is the JSON document, the crate the
51/// gzipped tarball whose sha256 the index records.
52pub struct Publish<'a> {
53 pub metadata: Value,
54 pub crate_file: &'a [u8],
55}
56
57/// Splits a publish body: a little-endian u32 length and the JSON metadata, then a little-endian
58/// u32 length and the `.crate` bytes. Both lengths must match the body exactly.
59pub fn parse_publish(body: &[u8]) -> Result<Publish<'_>> {
60 let (json_len, rest) = take_len(body)?;
61 if json_len > rest.len() {
62 return Err(Error::Invalid(
63 "publish body is shorter than its metadata length".into(),
64 ));
65 }
66 let (json_bytes, rest) = rest.split_at(json_len);
67 let metadata: Value = serde_json::from_slice(json_bytes)
68 .map_err(|e| Error::Invalid(format!("publish metadata is not JSON: {e}")))?;
69 if !metadata.is_object() {
70 return Err(Error::Invalid(
71 "publish metadata must be a JSON object".into(),
72 ));
73 }
74 let (crate_len, rest) = take_len(rest)?;
75 if crate_len != rest.len() {
76 return Err(Error::Invalid(
77 "crate length does not match the body".into(),
78 ));
79 }
80 Ok(Publish {
81 metadata,
82 crate_file: rest,
83 })
84}
85
86fn take_len(bytes: &[u8]) -> Result<(usize, &[u8])> {
87 let Some((head, rest)) = bytes.split_first_chunk::<4>().map(|(h, r)| (*h, r)) else {
88 return Err(Error::Invalid("publish body is truncated".into()));
89 };
90 let len = usize::try_from(u32::from_le_bytes(head))
91 .map_err(|_| Error::Invalid("length does not fit".into()))?;
92 Ok((len, rest))
93}
94
95/// Text field of the metadata, or `None` when absent or not a string.
96pub fn meta_str<'a>(meta: &'a Value, key: &str) -> Option<&'a str> {
97 meta.get(key).and_then(Value::as_str)
98}
99
100/// The dependencies of an index line, from the publish metadata. A renamed dependency
101/// (`explicit_name_in_toml`) is listed under its local name, with the real crate in `package`.
102pub fn index_deps(meta: &Value) -> Vec<Value> {
103 let deps = meta.get("deps").and_then(Value::as_array);
104 deps.map_or_else(Vec::new, |list| {
105 list.iter()
106 .map(|dep| {
107 let crate_name = meta_str(dep, "name").unwrap_or_default();
108 let renamed = meta_str(dep, "explicit_name_in_toml");
109 json!({
110 "name": renamed.unwrap_or(crate_name),
111 "req": dep.get("version_req").cloned().unwrap_or(Value::Null),
112 "features": dep.get("features").cloned().unwrap_or_else(|| json!([])),
113 "optional": dep.get("optional").and_then(Value::as_bool).unwrap_or(false),
114 "default_features": dep.get("default_features").and_then(Value::as_bool).unwrap_or(true),
115 "target": dep.get("target").cloned().unwrap_or(Value::Null),
116 "kind": dep.get("kind").and_then(Value::as_str).unwrap_or("normal"),
117 "registry": dep.get("registry").cloned().unwrap_or(Value::Null),
118 "package": renamed.map(|_| crate_name),
119 })
120 })
121 .collect()
122 })
123}
124
125/// The index line of one version (format version 2). Features that use the `dep:` or `?`
126/// syntax go to `features2`, as the format requires; the rest stay in `features`.
127pub fn index_line(meta: &Value, checksum: &str) -> Result<Value> {
128 let name =
129 meta_str(meta, "name").ok_or_else(|| Error::Invalid("metadata has no name".into()))?;
130 let vers =
131 meta_str(meta, "vers").ok_or_else(|| Error::Invalid("metadata has no vers".into()))?;
132 let mut features = Map::new();
133 let mut features2 = Map::new();
134 if let Some(declared) = meta.get("features").and_then(Value::as_object) {
135 for (feature, members) in declared {
136 let modern = members.as_array().is_some_and(|list| {
137 list.iter()
138 .filter_map(Value::as_str)
139 .any(|m| m.starts_with("dep:") || m.contains('?'))
140 });
141 if modern {
142 features2.insert(feature.clone(), members.clone());
143 } else {
144 features.insert(feature.clone(), members.clone());
145 }
146 }
147 }
148 let mut line = json!({
149 "name": name,
150 "vers": vers,
151 "deps": index_deps(meta),
152 "cksum": checksum,
153 "features": features,
154 "yanked": false,
155 "links": meta.get("links").cloned().unwrap_or(Value::Null),
156 "v": 2,
157 });
158 if !features2.is_empty() {
159 line["features2"] = Value::Object(features2);
160 }
161 if let Some(rust_version) = meta_str(meta, "rust_version") {
162 line["rust_version"] = json!(rust_version);
163 }
164 Ok(line)
165}
166
167/// The `(owner, repo)` a `repository` URL names on this forge, when it points at a repo under
168/// `base_url` (for example `https://git.tahinli.com/`). Any other URL links nothing.
169pub fn repo_link(repository: &str, base_url: &str) -> Option<(String, String)> {
170 let base = base_url.trim_end_matches('/');
171 let rest = repository.trim().strip_prefix(base)?.strip_prefix('/')?;
172 let rest = rest.trim_end_matches('/');
173 let rest = rest.strip_suffix(".git").unwrap_or(rest);
174 let mut parts = rest.split('/');
175 let owner = parts.next().filter(|s| !s.is_empty())?;
176 let repo = parts.next().filter(|s| !s.is_empty())?;
177 if parts.next().is_some() {
178 return None;
179 }
180 Some((owner.to_owned(), repo.to_owned()))
181}
182
183/// The README of a `.crate` file: the first `README*` file at the top of the package directory
184/// (`<name>-<version>/README.md`). Read at most [`MAX_README_BYTES`] bytes. Returns `None` when
185/// the archive is not a gzipped tarball or has no README.
186pub fn crate_readme(crate_file: &[u8]) -> Option<String> {
187 const MAX_INFLATED_SCAN_BYTES: u64 = 256 * 1024 * 1024;
188 // A small upload can inflate without end; past this much the README search gives up.
189 let inflated = GzDecoder::new(crate_file).take(MAX_INFLATED_SCAN_BYTES);
190 let mut archive = tar::Archive::new(inflated);
191 let entries = archive.entries().ok()?;
192 for entry in entries {
193 let entry = entry.ok()?;
194 let path = entry.path().ok()?.into_owned();
195 let mut parts = path.components();
196 parts.next()?;
197 let file = parts.next()?;
198 let is_top = parts.next().is_none();
199 let file_name = file.as_os_str().to_string_lossy().to_ascii_lowercase();
200 if is_top && file_name.starts_with("readme") && entry.header().entry_type().is_file() {
201 let mut bytes = Vec::new();
202 entry.take(MAX_README_BYTES).read_to_end(&mut bytes).ok()?;
203 return Some(String::from_utf8_lossy(&bytes).into_owned());
204 }
205 }
206 None
207}
208
209#[cfg(test)]
210mod tests {
211 use super::*;
212
213 #[test]
214 fn names_follow_crate_rules_and_lowercase() {
215 assert_eq!(crate_name_key("Serde_json").unwrap(), "serde_json");
216 assert!(crate_name_key("").is_err());
217 assert!(crate_name_key("1abc").is_err());
218 assert!(crate_name_key("a b").is_err());
219 assert!(crate_name_key("a.b").is_err());
220 assert!(crate_name_key(&"a".repeat(65)).is_err());
221 assert!(crate_name_key(&"a".repeat(64)).is_ok());
222 }
223
224 #[test]
225 fn index_paths_match_the_sparse_layout() {
226 assert_eq!(index_path("a"), "1/a");
227 assert_eq!(index_path("ab"), "2/ab");
228 assert_eq!(index_path("abc"), "3/a/abc");
229 assert_eq!(index_path("serde"), "se/rd/serde");
230 }
231
232 #[test]
233 fn publish_body_round_trips_and_rejects_bad_lengths() {
234 let meta = br#"{"name":"demo","vers":"0.1.0"}"#;
235 let krate = b"gz-bytes";
236 let mut body = Vec::new();
237 body.extend_from_slice(&(meta.len() as u32).to_le_bytes());
238 body.extend_from_slice(meta);
239 body.extend_from_slice(&(krate.len() as u32).to_le_bytes());
240 body.extend_from_slice(krate);
241 let parsed = parse_publish(&body).unwrap();
242 assert_eq!(parsed.metadata["name"], "demo");
243 assert_eq!(parsed.crate_file, krate);
244
245 let mut short = body.clone();
246 short.pop();
247 assert!(parse_publish(&short).is_err());
248 assert!(parse_publish(&body[..3]).is_err());
249 }
250
251 #[test]
252 fn index_line_renames_deps_and_splits_features() {
253 let meta = json!({
254 "name": "demo", "vers": "0.2.0", "links": null, "rust_version": "1.80",
255 "deps": [
256 {"name": "serde", "version_req": "^1", "features": ["derive"], "optional": false,
257 "default_features": true, "target": null, "kind": "normal", "registry": null,
258 "explicit_name_in_toml": null},
259 {"name": "tokio", "version_req": "1", "features": [], "optional": true,
260 "default_features": false, "target": null, "kind": "dev", "registry": null,
261 "explicit_name_in_toml": "rt"}
262 ],
263 "features": {"default": ["serde"], "net": ["dep:tokio"]}
264 });
265 let line = index_line(&meta, "abc").unwrap();
266 assert_eq!(line["cksum"], "abc");
267 assert_eq!(line["yanked"], false);
268 assert_eq!(line["v"], 2);
269 assert_eq!(line["rust_version"], "1.80");
270 assert_eq!(line["deps"][1]["name"], "rt");
271 assert_eq!(line["deps"][1]["package"], "tokio");
272 assert_eq!(line["deps"][0]["package"], Value::Null);
273 assert_eq!(line["features"]["default"], json!(["serde"]));
274 assert_eq!(line["features2"]["net"], json!(["dep:tokio"]));
275 }
276
277 #[test]
278 fn repository_links_only_forge_repos() {
279 let base = "https://git.tahinli.com/";
280 assert_eq!(
281 repo_link("https://git.tahinli.com/tahinli/forge.git", base),
282 Some(("tahinli".into(), "forge".into()))
283 );
284 assert_eq!(repo_link("https://github.com/tahinli/forge", base), None);
285 assert_eq!(repo_link("https://git.tahinli.com/tahinli", base), None);
286 assert_eq!(repo_link("https://git.tahinli.com/a/b/c", base), None);
287 }
288
289 #[test]
290 fn readme_is_read_from_the_package_directory() {
291 let mut tar_bytes = Vec::new();
292 {
293 let mut builder = tar::Builder::new(&mut tar_bytes);
294 let body = b"# Demo\n\nHello.";
295 let mut header = tar::Header::new_gnu();
296 header.set_size(body.len() as u64);
297 header.set_mode(0o644);
298 header.set_cksum();
299 builder
300 .append_data(&mut header, "demo-0.1.0/README.md", &body[..])
301 .unwrap();
302 builder.finish().unwrap();
303 }
304 let mut gz = Vec::new();
305 {
306 let mut enc = flate2::write::GzEncoder::new(&mut gz, flate2::Compression::fast());
307 std::io::Write::write_all(&mut enc, &tar_bytes).unwrap();
308 enc.finish().unwrap();
309 }
310 assert_eq!(crate_readme(&gz).as_deref(), Some("# Demo\n\nHello."));
311 assert_eq!(crate_readme(b"not gzip"), None);
312 }
313}