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