forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.7 MiBeb7e617Tahinli1 month ago137 commits

lfs_pointer.rs147 lines, 4.8 KiBHistoryRawDownload
1//! Parser for Git LFS pointer files (spec v1, https://github.com/git-lfs/git-lfs/blob/main/docs/spec.md).
2//! A pointer is a small text blob:
3//!
4//! ```text
5//! version https://git-lfs.github.com/spec/v1
6//! oid sha256:<64 lowercase hex>
7//! size <decimal bytes>
8//! ```
9//!
10//! Extra `key value` lines are allowed. The parser is pure and accepts nothing else.
11
12use crate::lfs::is_valid_oid;
13
14/// Pointer files are about 130 bytes. Anything larger is never treated as a pointer.
15pub const MAX_POINTER_BYTES: usize = 1024;
16
17const VERSION_LINE: &str = "version https://git-lfs.github.com/spec/v1";
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Pointer {
21 /// The SHA-256 of the object, lowercase hex, without the `sha256:` prefix.
22 pub oid: String,
23 /// Object size in bytes.
24 pub size: u64,
25}
26
27/// Returns the pointer described by `data`, or `None` when `data` is not a valid pointer.
28pub fn parse(data: &[u8]) -> Option<Pointer> {
29 if data.len() > MAX_POINTER_BYTES {
30 return None;
31 }
32 let text = std::str::from_utf8(data).ok()?;
33 let mut lines = text.strip_suffix('\n').unwrap_or(text).split('\n');
34 if lines.next()? != VERSION_LINE {
35 return None;
36 }
37
38 let mut oid = None;
39 let mut size = None;
40 for line in lines {
41 let (key, value) = line.split_once(' ')?;
42 match key {
43 "oid" => {
44 let hex = value.strip_prefix("sha256:")?;
45 if oid.is_some() || !is_valid_oid(hex) {
46 return None;
47 }
48 oid = Some(hex.to_owned());
49 }
50 "size" => {
51 if size.is_some() || value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit())
52 {
53 return None;
54 }
55 size = Some(value.parse::<u64>().ok()?);
56 }
57 // Other keys (such as `ext-0-...`) are allowed and ignored.
58 _ => {}
59 }
60 }
61 Some(Pointer {
62 oid: oid?,
63 size: size?,
64 })
65}
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70
71 const OID: &str = "4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393";
72
73 fn pointer(oid: &str, size: &str) -> String {
74 format!("{VERSION_LINE}\noid sha256:{oid}\nsize {size}\n")
75 }
76
77 #[test]
78 fn rejects_malformed_pointers() {
79 let no_size = format!("{VERSION_LINE}\noid sha256:{OID}\n");
80 let no_oid = format!("{VERSION_LINE}\nsize 1\n");
81 let twice = format!("{VERSION_LINE}\noid sha256:{OID}\noid sha256:{OID}\nsize 1\n");
82 let big = format!("{VERSION_LINE}\n{}", "x".repeat(MAX_POINTER_BYTES));
83 let cases: Vec<(&str, Vec<u8>)> = vec![
84 (
85 "other version url",
86 format!("version https://example.com/spec/v1\noid sha256:{OID}\nsize 1\n")
87 .into_bytes(),
88 ),
89 (
90 "version with trailing space",
91 format!("{VERSION_LINE} \noid sha256:{OID}\nsize 1\n").into_bytes(),
92 ),
93 (
94 "uppercase oid",
95 pointer(&OID.to_uppercase(), "1").into_bytes(),
96 ),
97 ("short oid", pointer(&OID[..63], "1").into_bytes()),
98 ("long oid", pointer(&format!("{OID}0"), "1").into_bytes()),
99 (
100 "md5 oid",
101 format!("{VERSION_LINE}\noid md5:{OID}\nsize 1\n").into_bytes(),
102 ),
103 ("empty size", pointer(OID, "").into_bytes()),
104 ("negative size", pointer(OID, "-1").into_bytes()),
105 ("fractional size", pointer(OID, "1.5").into_bytes()),
106 ("hex size", pointer(OID, "0x10").into_bytes()),
107 (
108 "size overflows u64",
109 pointer(OID, "99999999999999999999999").into_bytes(),
110 ),
111 ("no size line", no_size.into_bytes()),
112 ("no oid line", no_oid.into_bytes()),
113 ("duplicate oid line", twice.into_bytes()),
114 ("oversized", big.into_bytes()),
115 ("non-utf8", vec![0xff, 0xfe, 0x00]),
116 ("empty", Vec::new()),
117 ("plain text", b"hello\nworld\n".to_vec()),
118 ];
119 for (name, bytes) in cases {
120 assert_eq!(parse(&bytes), None, "case {name}");
121 }
122 }
123
124 #[test]
125 fn parses_a_standard_pointer() {
126 let got = parse(pointer(OID, "12345").as_bytes());
127 assert_eq!(
128 got,
129 Some(Pointer {
130 oid: OID.to_owned(),
131 size: 12345
132 })
133 );
134 }
135
136 #[test]
137 fn accepts_missing_trailing_newline_and_extra_keys() {
138 let text = format!("{VERSION_LINE}\next-0-x sha256:abc\noid sha256:{OID}\nsize 0");
139 assert_eq!(
140 parse(text.as_bytes()),
141 Some(Pointer {
142 oid: OID.to_owned(),
143 size: 0
144 })
145 );
146 }
147}