Skip to main content

grit_lib/check_ref_format/
mod.rs

1//! Ref-name validation — `git check-ref-format` rules.
2//!
3//! This module implements the same validation logic as
4//! `git check_refname_format()` in `git/refs.c`, including the
5//! `--allow-onelevel`, `--refspec-pattern`, and `--normalize` options.
6//!
7//! # Rules
8//!
9//! A ref name is valid when:
10//!
11//! 1. No path component begins with `.`
12//! 2. No `..` anywhere
13//! 3. No ASCII control characters (< 0x20 or DEL 0x7f)
14//! 4. No space, `~`, `^`, `:`, `?`, `[`, `\`
15//! 5. No trailing `/`
16//! 6. No path component ends with `.lock`
17//! 7. No `@{`
18//! 8. Cannot be exactly `@`
19//! 9. No consecutive slashes `//` (unless `--normalize` collapses them)
20//! 10. No leading `/` (unless `--normalize` strips it)
21//! 11. No trailing `.`
22//! 12. Must have at least two slash-separated components (unless
23//!     `--allow-onelevel`)
24
25mod ref_name;
26
27pub use ref_name::{RefName, RefNamePolicy, RefNameRef};
28
29use std::borrow::Cow;
30
31use crate::git_path::normalize_path_copy;
32
33use thiserror::Error;
34
35/// Errors returned by ref-name validation and [`RefName::parse`].
36#[derive(Debug, Error, PartialEq, Eq)]
37#[non_exhaustive]
38pub enum RefNameError {
39    /// The ref name is empty.
40    #[error("ref name is empty")]
41    Empty,
42    /// The ref name is exactly `@`.
43    #[error("ref name is a lone '@'")]
44    LoneAt,
45    /// A component starts with `.`.
46    #[error("ref name component starts with '.'")]
47    ComponentStartsDot,
48    /// The ref name contains `..`.
49    #[error("ref name contains '..'")]
50    DoubleDot,
51    /// An illegal character was found (control chars, space, `~`, `^`, `:`, `?`, `[`, `\\`).
52    #[error("ref name contains an illegal character")]
53    IllegalChar,
54    /// The ref name contains `@{{`.
55    #[error("ref name contains '@{{'")]
56    AtBrace,
57    /// The ref name contains `*` but `--refspec-pattern` was not set, or
58    /// contains more than one `*` with `--refspec-pattern`.
59    #[error("ref name contains invalid use of '*'")]
60    InvalidWildcard,
61    /// A path component ends with `.lock`.
62    #[error("ref name component ends with '.lock'")]
63    DotLock,
64    /// The ref name ends with `/`.
65    #[error("ref name ends with '/'")]
66    TrailingSlash,
67    /// The ref name starts with `/` (after normalization).
68    #[error("ref name starts with '/'")]
69    LeadingSlash,
70    /// The ref name ends with `.`.
71    #[error("ref name ends with '.'")]
72    TrailingDot,
73    /// The ref name has only one component and `--allow-onelevel` was not set.
74    #[error("ref name has only one component (needs --allow-onelevel)")]
75    OneLevel,
76    /// The branch short name is reserved (e.g. `HEAD`).
77    #[error("branch name is reserved")]
78    ReservedBranchName,
79    /// Branch short names must not begin with `-` (matches Git's `check_branch_ref`).
80    #[error("branch name must not start with '-'")]
81    BranchStartsWithDash,
82    /// The ref name has zero-length components (consecutive slashes) that
83    /// cannot be normalized away.
84    #[error("ref name contains consecutive slashes")]
85    ConsecutiveSlashes,
86    /// [`RefNameRef::parse`] was called with normalization that would change the input.
87    #[error("ref name requires normalization; use RefName::parse")]
88    NormalizationRequired,
89    /// The name is not safe to store as a ref.
90    #[error("ref name is not storable")]
91    NotStorable,
92    /// The name is not safe to map under ref storage.
93    #[error("ref name is not safe for the filesystem")]
94    UnsafeForFilesystem,
95    /// The name is not valid on a fetch/upload-pack advertisement.
96    #[error("ref name is not a valid advertised ref")]
97    NotAdvertisedFetchRef,
98    /// The name would be rejected by receive-pack.
99    #[error("ref name is not valid for receive-pack")]
100    ReceivePackRefused,
101}
102
103/// Low-level format flags (`git check-ref-format` options).
104#[derive(Debug, Clone, Default)]
105pub(crate) struct RefFormatOptions {
106    pub allow_onelevel: bool,
107    pub refspec_pattern: bool,
108    pub normalize: bool,
109}
110
111/// Validate `refname` according to Git ref-name rules.
112///
113/// Returns `Ok(normalized)` where `normalized` is:
114/// - the ref name itself when `opts.normalize` is `false`, or
115/// - the ref name with leading `/` stripped and consecutive slashes
116///   collapsed when `opts.normalize` is `true`.
117///
118/// Returns `Err` when the ref name is invalid.
119pub(crate) fn check_refname_format(
120    refname: &str,
121    opts: &RefFormatOptions,
122) -> Result<String, RefNameError> {
123    check_refname_format_borrowed(refname, opts).map(Cow::into_owned)
124}
125
126/// Validate a ref name without copying it unless normalization is requested.
127///
128/// Returns a borrowed `refname` or the normalized name, with the same errors as
129/// [`check_refname_format`] for the supplied `opts`.
130pub(crate) fn check_refname_format_borrowed<'a>(
131    refname: &'a str,
132    opts: &RefFormatOptions,
133) -> Result<Cow<'a, str>, RefNameError> {
134    if refname.is_empty() {
135        return Err(RefNameError::Empty);
136    }
137
138    // Apply normalization (collapse leading/consecutive slashes) when requested.
139    let normalized = if opts.normalize {
140        Cow::Owned(collapse_slashes(refname))
141    } else {
142        Cow::Borrowed(refname)
143    };
144
145    let name: &str = &normalized;
146
147    if name.is_empty() {
148        return Err(RefNameError::Empty);
149    }
150
151    // Lone '@' is always invalid.
152    if name == "@" {
153        return Err(RefNameError::LoneAt);
154    }
155
156    // Leading '/' is invalid (even after normalization collapse_slashes strips
157    // a leading slash, so if it's still here it means the whole name was just
158    // slashes → empty after stripping, caught above).
159    // Actually collapse_slashes keeps one leading slash if there is content
160    // after it — in non-normalize mode we reject it directly.
161    if !opts.normalize && name.starts_with('/') {
162        return Err(RefNameError::LeadingSlash);
163    }
164
165    // Trailing '/' is always invalid (even after normalize it would be gone
166    // because there's no component after it).
167    if name.ends_with('/') {
168        return Err(RefNameError::TrailingSlash);
169    }
170
171    // Trailing '.' is always invalid.
172    if name.ends_with('.') {
173        return Err(RefNameError::TrailingDot);
174    }
175
176    // Walk through the name byte-by-byte, tracking component starts.
177    let bytes = name.as_bytes();
178    let mut component_start = 0usize;
179    let mut component_count = 0usize;
180    let mut last = b'\0';
181    let mut wildcard_used = false;
182
183    let mut i = 0usize;
184    while i < bytes.len() {
185        let ch = bytes[i];
186
187        match ch {
188            b'/' => {
189                // End of a component.
190                let comp_len = i - component_start;
191                if comp_len == 0 {
192                    // Consecutive or leading slash (shouldn't happen after
193                    // normalization, but catch it in non-normalize mode).
194                    return Err(RefNameError::ConsecutiveSlashes);
195                }
196                // Validate the finished component.
197                validate_component(&bytes[component_start..i], &mut wildcard_used, opts)?;
198                component_count += 1;
199                component_start = i + 1;
200                last = ch;
201                i += 1;
202                continue;
203            }
204            b'.' if last == b'.' => {
205                return Err(RefNameError::DoubleDot);
206            }
207            b'{' if last == b'@' => {
208                return Err(RefNameError::AtBrace);
209            }
210            b'*' => {
211                if !opts.refspec_pattern {
212                    return Err(RefNameError::InvalidWildcard);
213                }
214                if wildcard_used {
215                    return Err(RefNameError::InvalidWildcard);
216                }
217                wildcard_used = true;
218            }
219            // Control characters (< 0x20 or DEL 0x7f) and forbidden chars.
220            0x00..=0x1f | 0x7f | b' ' | b'~' | b'^' | b':' | b'?' | b'[' | b'\\' => {
221                return Err(RefNameError::IllegalChar);
222            }
223            _ => {}
224        }
225
226        last = ch;
227        i += 1;
228    }
229
230    // Validate the last component (from component_start to end).
231    let last_comp = &bytes[component_start..];
232    if last_comp.is_empty() {
233        // Name ended with '/' — already checked above, but be safe.
234        return Err(RefNameError::TrailingSlash);
235    }
236    validate_component(last_comp, &mut wildcard_used, opts)?;
237    component_count += 1;
238
239    // At least two components required unless --allow-onelevel.
240    if !opts.allow_onelevel && component_count < 2 {
241        return Err(RefNameError::OneLevel);
242    }
243
244    Ok(normalized)
245}
246
247/// Validate a single path component (the bytes between `/` separators, or the
248/// entire name when there are no slashes).
249///
250/// Rules checked here:
251/// - Must not start with `.`
252/// - Must not end with `.lock`
253fn validate_component(
254    comp: &[u8],
255    _wildcard_used: &mut bool,
256    _opts: &RefFormatOptions,
257) -> Result<(), RefNameError> {
258    if comp.is_empty() {
259        return Err(RefNameError::ConsecutiveSlashes);
260    }
261
262    // Component must not start with '.'.
263    if comp[0] == b'.' {
264        return Err(RefNameError::ComponentStartsDot);
265    }
266
267    // Component must not end with ".lock".
268    const LOCK_SUFFIX: &[u8] = b".lock";
269    if comp.len() >= LOCK_SUFFIX.len() && comp.ends_with(LOCK_SUFFIX) {
270        return Err(RefNameError::DotLock);
271    }
272
273    Ok(())
274}
275
276/// Whether `refname` is safe to map to a path under ref storage.
277///
278/// Matches Git's `refname_is_safe()` in `refs.c`: refs under `refs/` must not
279/// escape that prefix via `.` / `..` components; root-style names must be
280/// uppercase ASCII letters and underscores only (e.g. `HEAD`).
281#[must_use]
282pub(crate) fn refname_is_safe(refname: &str) -> bool {
283    if let Some(rest) = refname.strip_prefix("refs/") {
284        if rest.is_empty() || rest.starts_with('/') || rest.ends_with('/') {
285            return false;
286        }
287        return normalize_path_copy(rest)
288            .ok()
289            .is_some_and(|normalized| normalized == rest);
290    }
291
292    if refname.is_empty() {
293        return false;
294    }
295    refname.bytes().all(|b| b.is_ascii_uppercase() || b == b'_')
296}
297
298pub(crate) use ref_name::{is_storable_ref_name, is_valid_fetch_advertised_ref};
299
300/// Strip a leading `/` and collapse consecutive interior slashes to one.
301///
302/// This collapses runs of `/` the same way `git check-ref-format` does.
303pub fn collapse_slashes(refname: &str) -> String {
304    let mut result = String::with_capacity(refname.len());
305    let mut prev = b'/';
306
307    for ch in refname.bytes() {
308        if prev == b'/' && ch == b'/' {
309            // Skip consecutive slashes (including a leading one when prev
310            // was initialized to '/').
311            continue;
312        }
313        result.push(ch as char);
314        prev = ch;
315    }
316
317    result
318}
319
320pub(crate) fn is_valid_advertised_symref_target(name: &str) -> bool {
321    RefNameRef::parse(name, &RefNamePolicy::symref_target()).is_ok()
322}
323
324#[cfg(test)]
325mod tests {
326    #[test]
327    fn validation_borrows_names_when_normalization_is_disabled() {
328        let name = "refs/heads/topic";
329        assert!(matches!(
330            super::check_refname_format_borrowed(name, &super::RefFormatOptions::default()),
331            Ok(std::borrow::Cow::Borrowed(value)) if value == name
332        ));
333        let opts = super::RefFormatOptions {
334            normalize: true,
335            ..Default::default()
336        };
337        assert!(matches!(
338            super::check_refname_format_borrowed("/refs//heads/topic", &opts),
339            Ok(std::borrow::Cow::Owned(value)) if value == name
340        ));
341    }
342
343    use super::*;
344
345    fn opts_default() -> RefFormatOptions {
346        RefFormatOptions::default()
347    }
348
349    fn opts_onelevel() -> RefFormatOptions {
350        RefFormatOptions {
351            allow_onelevel: true,
352            ..Default::default()
353        }
354    }
355
356    fn opts_refspec() -> RefFormatOptions {
357        RefFormatOptions {
358            refspec_pattern: true,
359            ..Default::default()
360        }
361    }
362
363    fn opts_normalize() -> RefFormatOptions {
364        RefFormatOptions {
365            normalize: true,
366            ..Default::default()
367        }
368    }
369
370    fn valid(refname: &str, opts: &RefFormatOptions) {
371        assert!(
372            check_refname_format(refname, opts).is_ok(),
373            "expected '{refname}' to be valid with opts={opts:?}"
374        );
375    }
376
377    fn invalid(refname: &str, opts: &RefFormatOptions) {
378        assert!(
379            check_refname_format(refname, opts).is_err(),
380            "expected '{refname}' to be invalid with opts={opts:?}"
381        );
382    }
383
384    #[test]
385    fn empty_is_invalid() {
386        invalid("", &opts_default());
387        invalid("", &opts_onelevel());
388    }
389
390    #[test]
391    fn basic_valid() {
392        valid("foo/bar/baz", &opts_default());
393        valid("refs/heads/main", &opts_default());
394    }
395
396    #[test]
397    fn one_level_requires_flag() {
398        invalid("foo", &opts_default());
399        valid("foo", &opts_onelevel());
400    }
401
402    #[test]
403    fn double_dot_invalid() {
404        invalid("heads/foo..bar", &opts_default());
405    }
406
407    #[test]
408    fn trailing_dot_invalid() {
409        invalid("refs/heads/foo.", &opts_default());
410        invalid("heads/foo.", &opts_default());
411    }
412
413    #[test]
414    fn component_starts_with_dot() {
415        invalid("./foo", &opts_default());
416        invalid(".refs/foo", &opts_default());
417        invalid("foo/./bar", &opts_default());
418    }
419
420    #[test]
421    fn dot_lock_invalid() {
422        invalid("heads/foo.lock", &opts_default());
423        invalid("foo.lock/bar", &opts_default());
424    }
425
426    #[test]
427    fn at_brace_invalid() {
428        invalid("heads/v@{ation", &opts_default());
429    }
430
431    #[test]
432    fn lone_at_invalid() {
433        invalid("@", &opts_default());
434        invalid("@", &opts_onelevel());
435    }
436
437    #[test]
438    fn wildcard_requires_flag() {
439        invalid("foo/*", &opts_default());
440        valid(
441            "foo/*",
442            &RefFormatOptions {
443                refspec_pattern: true,
444                allow_onelevel: false,
445                normalize: false,
446            },
447        );
448    }
449
450    #[test]
451    fn double_wildcard_invalid() {
452        invalid("foo/*/*", &opts_refspec());
453    }
454
455    #[test]
456    fn control_chars_invalid() {
457        invalid("heads/foo\x01", &opts_default());
458        invalid("heads/foo\x7f", &opts_default());
459    }
460
461    #[test]
462    fn forbidden_chars_invalid() {
463        invalid("heads/foo?bar", &opts_default());
464        invalid("heads/foo bar", &opts_default());
465        invalid("heads/foo~bar", &opts_default());
466        invalid("heads/foo^bar", &opts_default());
467        invalid("heads/foo:bar", &opts_default());
468        invalid("heads/foo[bar", &opts_default());
469        invalid("heads/foo\\bar", &opts_default());
470    }
471
472    #[test]
473    fn normalize_collapses_slashes() {
474        let result = check_refname_format("refs///heads/foo", &opts_normalize());
475        assert!(result.is_ok());
476        assert_eq!(result.unwrap(), "refs/heads/foo");
477    }
478
479    #[test]
480    fn normalize_strips_leading_slash() {
481        let result = check_refname_format("/heads/foo", &opts_normalize());
482        assert!(result.is_ok());
483        assert_eq!(result.unwrap(), "heads/foo");
484    }
485
486    #[test]
487    fn leading_slash_without_normalize() {
488        invalid("/heads/foo", &opts_default());
489    }
490
491    #[test]
492    fn foo_dot_slash_bar_valid() {
493        // "foo./bar" is valid — the dot is not at the start of a component
494        // and doesn't form ".lock".
495        valid("foo./bar", &opts_default());
496    }
497
498    #[test]
499    fn utf8_allowed() {
500        // Non-ASCII bytes that are valid UTF-8 are allowed.
501        valid("heads/fu\u{00DF}", &opts_default());
502    }
503
504    #[test]
505    fn refname_is_safe_rejects_traversal_under_refs() {
506        assert!(!refname_is_safe("refs/heads/../../config"));
507        assert!(!refname_is_safe("refs/foo/../../bar"));
508        assert!(!refname_is_safe("refs/foo/../bar"));
509        assert!(refname_is_safe("refs/heads/main"));
510        assert!(refname_is_safe("HEAD"));
511    }
512
513    #[test]
514    fn receive_pack_refname_ok_rejects_funny_refs() {
515        use super::ref_name::receive_pack_refname_ok;
516        assert!(!receive_pack_refname_ok("refs/heads/../../config", true));
517        assert!(!receive_pack_refname_ok("refs/heads/../../config", false));
518        assert!(!receive_pack_refname_ok("heads/main", false));
519        assert!(receive_pack_refname_ok("refs/heads/main", false));
520        assert!(receive_pack_refname_ok("refs/tags/v1", true));
521    }
522
523    #[test]
524    fn fetch_advertised_ref_rejects_traversal_and_illegal() {
525        assert!(is_valid_fetch_advertised_ref("refs/heads/main"));
526        assert!(is_valid_fetch_advertised_ref("refs/tags/v1.0"));
527        assert!(!is_valid_fetch_advertised_ref("refs/heads/../../../config"));
528        assert!(!is_valid_fetch_advertised_ref("heads/main"));
529        assert!(!is_valid_fetch_advertised_ref("refs/heads/foo..bar"));
530    }
531
532    #[test]
533    fn symref_target_rejects_traversal() {
534        assert!(is_valid_advertised_symref_target("refs/heads/main"));
535        assert!(!is_valid_advertised_symref_target(
536            "refs/heads/../../../config"
537        ));
538    }
539
540    #[test]
541    fn validate_branch_short_name_issue_927() {
542        let invalid = ["bad name", "x..y", "a~b", "a.lock", "HEAD", "a:b", "a*b"];
543        for name in invalid {
544            assert!(
545                RefName::branch(name).is_err(),
546                "expected branch name {name:?} to be rejected"
547            );
548        }
549        assert!(RefName::branch("main").is_ok());
550        assert!(RefName::branch("feature/foo").is_ok());
551        assert!(RefName::branch("@").is_ok());
552        assert!(RefName::branch("-").is_err());
553        assert!(RefName::branch("-topic").is_err());
554    }
555
556    #[test]
557    fn validate_tag_short_name_issue_927() {
558        let invalid = ["bad name", "a..b", "x.lock"];
559        for name in invalid {
560            assert!(
561                RefName::tag(name).is_err(),
562                "expected tag name {name:?} to be rejected"
563            );
564        }
565        assert!(RefName::tag("v1.0").is_ok());
566        assert!(RefName::tag("@").is_ok());
567        assert!(RefName::tag("HEAD").is_ok());
568    }
569}