Skip to main content

ferro_cargo_registry_server/
name.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Cargo crate name validator.
3//!
4//! Reference: `doc.rust-lang.org/cargo/reference/manifest.html#the-name-field`
5//! and the registry API under "Crate name restrictions".
6//!
7//! Rules:
8//! - 1–64 characters inclusive.
9//! - First character must be an ASCII letter.
10//! - Remaining characters must be ASCII alphanumeric, `-`, or `_`.
11//! - Case-insensitive comparisons (the index uses lowercased names),
12//!   though the canonical form from the manifest is preserved verbatim.
13
14use crate::error::CargoError;
15
16/// Maximum crate name length enforced by crates.io (registry spec).
17pub const MAX_NAME_LEN: usize = 64;
18
19/// Returns true if `name` satisfies the Cargo crate-name rules.
20#[must_use]
21pub fn is_valid_name(name: &str) -> bool {
22    if name.is_empty() || name.len() > MAX_NAME_LEN {
23        return false;
24    }
25    let mut chars = name.chars();
26    let Some(first) = chars.next() else {
27        return false;
28    };
29    if !first.is_ascii_alphabetic() {
30        return false;
31    }
32    chars.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
33}
34
35/// Validate a crate name, returning a typed error on rejection.
36///
37/// # Errors
38/// Returns [`CargoError::InvalidName`] when the name does not satisfy
39/// [`is_valid_name`].
40pub fn validate_name(name: &str) -> Result<(), CargoError> {
41    if is_valid_name(name) {
42        Ok(())
43    } else {
44        Err(CargoError::InvalidName(name.to_owned()))
45    }
46}
47
48/// Canonicalize a crate name to its storage / index key.
49///
50/// Cargo treats crate names case-insensitively and considers `-` and `_`
51/// interchangeable for *uniqueness* (a registry must not host both
52/// `foo-bar` and `foo_bar`). The canonical key therefore lowercases the
53/// name and folds `-` to `_`. This is the key under which records are
54/// stored and the form the sparse-index path is derived from, so a
55/// mixed-case publish (`MyCrate`) is retrievable at the lowercase path
56/// (`my/cr/mycrate`) cargo actually requests.
57///
58/// The original display case is preserved separately in the
59/// [`IndexEntry::name`](crate::index::IndexEntry) field.
60#[must_use]
61pub fn canonical_name(name: &str) -> String {
62    name.to_ascii_lowercase().replace('-', "_")
63}
64
65/// Whether two crate names collide under cargo's uniqueness rules
66/// (case-insensitive, `-`/`_`-insensitive).
67#[must_use]
68pub fn names_collide(a: &str, b: &str) -> bool {
69    canonical_name(a) == canonical_name(b)
70}
71
72/// Compute the sparse-index path for `name`.
73///
74/// Reference: `doc.rust-lang.org/cargo/reference/registries.html#index-format`.
75///
76/// Layout rules:
77/// - 1-char names → `1/{name}`
78/// - 2-char names → `2/{name}`
79/// - 3-char names → `3/{first-char}/{name}`
80/// - 4+-char names → `{first-two}/{second-two}/{name}`
81///
82/// All prefixes are lowercased; the stored filename preserves the
83/// original case because Cargo's `cksum` input uses the canonical name.
84#[must_use]
85pub fn index_path(name: &str) -> String {
86    let lower = name.to_ascii_lowercase();
87    match lower.len() {
88        0 => String::new(),
89        1 => format!("1/{lower}"),
90        2 => format!("2/{lower}"),
91        3 => format!("3/{}/{}", &lower[0..1], lower),
92        _ => format!("{}/{}/{}", &lower[0..2], &lower[2..4], lower),
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::{index_path, is_valid_name, validate_name};
99
100    #[test]
101    fn valid_crate_names() {
102        assert!(is_valid_name("serde"));
103        assert!(is_valid_name("tokio"));
104        assert!(is_valid_name("abc-def"));
105        assert!(is_valid_name("abc_def"));
106        assert!(is_valid_name("A")); // single letter, 1 char.
107    }
108
109    #[test]
110    fn invalid_crate_names() {
111        assert!(!is_valid_name(""));
112        assert!(!is_valid_name("-foo"));
113        assert!(!is_valid_name("1abc"));
114        assert!(!is_valid_name("foo bar"));
115        assert!(!is_valid_name(&"a".repeat(65)));
116    }
117
118    /// Boundary: the length check is `name.len() > MAX_NAME_LEN`, so a
119    /// name of *exactly* `MAX_NAME_LEN` (64) is valid and 65 is not. This
120    /// kills the `>` → `>=` mutant (which would reject the 64-char name).
121    #[test]
122    fn name_length_boundary_is_inclusive_at_max() {
123        use super::MAX_NAME_LEN;
124        let at_max = "a".repeat(MAX_NAME_LEN);
125        assert_eq!(at_max.len(), 64);
126        assert!(is_valid_name(&at_max), "64-char name must be valid");
127        let over_max = "a".repeat(MAX_NAME_LEN + 1);
128        assert!(!is_valid_name(&over_max), "65-char name must be invalid");
129    }
130
131    /// The `0`-length arm of `index_path` returns the empty string — a
132    /// canonical layout that no other arm produces. Deleting the arm would
133    /// route an empty name through the `_` arm and slice-panic, so an
134    /// explicit assertion pins the empty result.
135    #[test]
136    fn index_path_empty_name_is_empty_string() {
137        assert_eq!(index_path(""), "");
138    }
139
140    #[test]
141    fn validate_surface_error() {
142        let e = validate_name("").unwrap_err();
143        assert!(matches!(e, crate::error::CargoError::InvalidName(_)));
144    }
145
146    #[test]
147    fn index_path_layout_by_length() {
148        assert_eq!(index_path("a"), "1/a");
149        assert_eq!(index_path("ab"), "2/ab");
150        assert_eq!(index_path("abc"), "3/a/abc");
151        assert_eq!(index_path("serde"), "se/rd/serde");
152        // 4-char boundary.
153        assert_eq!(index_path("tokio"), "to/ki/tokio");
154        assert_eq!(index_path("abcd"), "ab/cd/abcd");
155    }
156
157    #[test]
158    fn index_path_lowercases() {
159        assert_eq!(index_path("Serde"), "se/rd/serde");
160        assert_eq!(index_path("AB"), "2/ab");
161    }
162
163    /// F5: the canonical key lowercases and folds `-`→`_` so cargo's
164    /// uniqueness rules are honoured.
165    #[test]
166    fn canonical_name_folds_case_and_hyphen() {
167        use super::{canonical_name, names_collide};
168        assert_eq!(canonical_name("MyCrate"), "mycrate");
169        assert_eq!(canonical_name("Foo-Bar"), "foo_bar");
170        assert_eq!(canonical_name("foo_bar"), "foo_bar");
171        assert!(names_collide("foo-bar", "foo_bar"));
172        assert!(names_collide("Foo", "foo"));
173        assert!(names_collide("My-Crate", "my_crate"));
174        assert!(!names_collide("foo", "bar"));
175    }
176}