forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiB2e29cbcTahinli6 hours ago333 commits

parse.rs351 lines, 10.9 KiBHistoryRawDownload
1use forge_git::GitService;
2
3#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
4pub enum ParseError {
5 #[error("unsupported command")]
6 UnsupportedCommand,
7 #[error("malformed repository path")]
8 MalformedPath,
9}
10
11const PREFIXES: &[(&str, GitService)] = &[
12 ("git-upload-pack ", GitService::UploadPack),
13 ("git-receive-pack ", GitService::ReceivePack),
14 ("git upload-pack ", GitService::UploadPack),
15 ("git receive-pack ", GitService::ReceivePack),
16];
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct RepoPath {
20 pub owner: String,
21 pub name: String,
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub(crate) enum ExecCommand {
26 Git(GitService, RepoPath),
27 LfsAuthenticate(RepoPath, LfsOperation),
28}
29
30pub(crate) fn parse_command(cmd: &str) -> Result<ExecCommand, ParseError> {
31 if cmd.starts_with(LFS_AUTHENTICATE_PREFIX) {
32 let (path, operation) = parse_lfs_authenticate(cmd)?;
33 return Ok(ExecCommand::LfsAuthenticate(path, operation));
34 }
35 let (service, path) = parse_exec(cmd)?;
36 Ok(ExecCommand::Git(service, path))
37}
38
39fn parse_exec(cmd: &str) -> Result<(GitService, RepoPath), ParseError> {
40 let (service, rest) = split_service(cmd)?;
41 let raw = unquote_argument(rest)?;
42 let path = normalize_path(raw)?;
43 Ok((service, path))
44}
45
46const LFS_AUTHENTICATE_PREFIX: &str = "git-lfs-authenticate ";
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum LfsOperation {
50 Download,
51 Upload,
52}
53
54fn parse_lfs_authenticate(cmd: &str) -> Result<(RepoPath, LfsOperation), ParseError> {
55 let rest = cmd
56 .strip_prefix(LFS_AUTHENTICATE_PREFIX)
57 .ok_or(ParseError::UnsupportedCommand)?;
58 let (arg, op) = rest.rsplit_once(' ').ok_or(ParseError::MalformedPath)?;
59 let operation = match op {
60 "download" => LfsOperation::Download,
61 "upload" => LfsOperation::Upload,
62 _ => return Err(ParseError::MalformedPath),
63 };
64 let path = normalize_path(unquote_argument(arg)?)?;
65 Ok((path, operation))
66}
67
68fn split_service(cmd: &str) -> Result<(GitService, &str), ParseError> {
69 PREFIXES
70 .iter()
71 .find_map(|(prefix, service)| cmd.strip_prefix(prefix).map(|rest| (*service, rest)))
72 .ok_or(ParseError::UnsupportedCommand)
73}
74
75fn unquote_argument(rest: &str) -> Result<&str, ParseError> {
76 if let Some(quoted) = rest.strip_prefix('\'') {
77 let inner = quoted.strip_suffix('\'').ok_or(ParseError::MalformedPath)?;
78 if inner
79 .chars()
80 .any(|c| matches!(c, '\'' | '\\') || c.is_control())
81 {
82 return Err(ParseError::MalformedPath);
83 }
84 return Ok(inner);
85 }
86 if rest.is_empty()
87 || rest
88 .chars()
89 .any(|c| c.is_whitespace() || matches!(c, '\'' | '"' | '\\') || c.is_control())
90 {
91 return Err(ParseError::MalformedPath);
92 }
93 Ok(rest)
94}
95
96fn normalize_path(raw: &str) -> Result<RepoPath, ParseError> {
97 let path = raw.strip_prefix('/').unwrap_or(raw);
98 let path = path.strip_prefix("~/").unwrap_or(path);
99
100 let segments: Vec<&str> = path.split('/').collect();
101 let [owner, repo] = segments.as_slice() else {
102 return Err(ParseError::MalformedPath);
103 };
104 for segment in [owner, repo] {
105 if segment.is_empty()
106 || *segment == ".."
107 || segment.starts_with('-')
108 || segment.starts_with('.')
109 || !segment
110 .bytes()
111 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
112 {
113 return Err(ParseError::MalformedPath);
114 }
115 }
116
117 let repo = repo.strip_suffix(".git").unwrap_or(repo);
118 if repo.is_empty() {
119 return Err(ParseError::MalformedPath);
120 }
121 Ok(RepoPath {
122 owner: owner.to_string(),
123 name: repo.to_string(),
124 })
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130
131 fn ok(cmd: &str) -> (GitService, String) {
132 match parse_exec(cmd) {
133 Ok((service, path)) => (service, format!("{}/{}", path.owner, path.name)),
134 Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"),
135 }
136 }
137
138 fn err(cmd: &str) -> ParseError {
139 match parse_exec(cmd) {
140 Ok(v) => panic!("expected {cmd:?} to be rejected, got {v:?}"),
141 Err(e) => e,
142 }
143 }
144
145 #[test]
146 fn accepts_valid_exec_commands() {
147 let cases: &[(&str, GitService, &str)] = &[
148 (
149 "git-upload-pack '/tahinli/proj.git'",
150 GitService::UploadPack,
151 "tahinli/proj",
152 ),
153 (
154 "git-receive-pack '/tahinli/proj.git'",
155 GitService::ReceivePack,
156 "tahinli/proj",
157 ),
158 (
159 "git-receive-pack '/tahinli/proj.wiki.git'",
160 GitService::ReceivePack,
161 "tahinli/proj.wiki",
162 ),
163 (
164 "git-upload-pack 'tahinli/proj.wiki'",
165 GitService::UploadPack,
166 "tahinli/proj.wiki",
167 ),
168 (
169 "git upload-pack '/tahinli/proj'",
170 GitService::UploadPack,
171 "tahinli/proj",
172 ),
173 (
174 "git receive-pack 'tahinli/proj.git'",
175 GitService::ReceivePack,
176 "tahinli/proj",
177 ),
178 (
179 "git-upload-pack '~/tahinli/proj'",
180 GitService::UploadPack,
181 "tahinli/proj",
182 ),
183 (
184 "git-upload-pack '/~/tahinli/proj'",
185 GitService::UploadPack,
186 "tahinli/proj",
187 ),
188 (
189 "git-upload-pack 'tahinli/proj'",
190 GitService::UploadPack,
191 "tahinli/proj",
192 ),
193 (
194 "git-upload-pack /tahinli/proj.git",
195 GitService::UploadPack,
196 "tahinli/proj",
197 ),
198 (
199 "git-receive-pack tahinli/proj",
200 GitService::ReceivePack,
201 "tahinli/proj",
202 ),
203 ];
204 for (cmd, service, path) in cases {
205 assert_eq!(ok(cmd), (*service, path.to_string()), "case {cmd}");
206 }
207 }
208
209 #[test]
210 fn rejects_malformed_exec_paths() {
211 let cases: &[&str] = &[
212 "git-upload-pack '//tahinli/proj'",
213 "git-upload-pack a/b c",
214 "git-upload-pack a/b'",
215 "git-upload-pack a\"b/c",
216 "git-upload-pack a\\b/c",
217 "git-upload-pack '--help'",
218 "git-upload-pack '--upload-pack=touch /x'",
219 "git-upload-pack '-x/y'",
220 "git-upload-pack 'a/-b'",
221 "git-upload-pack 'a/b'; rm -rf /",
222 "git-upload-pack 'a/b' 'c/d'",
223 "git-upload-pack 'a/b$(id)'",
224 "git-upload-pack 'a/b;c'",
225 "git-upload-pack 'a/b|c'",
226 "git-upload-pack 'a/b&c'",
227 "git-upload-pack 'a/b%20c'",
228 "git-upload-pack 'a/é'",
229 "git-upload-pack 'a/b`id`'",
230 "git-upload-pack 'a/b' && id",
231 "git-upload-pack 'a/b\\c'",
232 "git-upload-pack 'a/b\nc'",
233 "git-upload-pack 'a/b\rc'",
234 "git-upload-pack 'a/b\0c'",
235 "git-upload-pack 'a/b\x07c'",
236 "git-upload-pack 'a/b\x7fc'",
237 "git-upload-pack 'a/b'c'",
238 "git-upload-pack '../x/y'",
239 "git-upload-pack 'a/..'",
240 "git-upload-pack '/a/../b'",
241 "git-upload-pack '.hidden/repo'",
242 "git-upload-pack 'owner/.git'",
243 "git-upload-pack 'a/b/c'",
244 "git-upload-pack 'a'",
245 "git-upload-pack 'a/'",
246 "git-upload-pack '/a/b/'",
247 "git-upload-pack '//'",
248 "git-upload-pack ''",
249 "git-upload-pack '/'",
250 "git-upload-pack '~/'",
251 "git-upload-pack '.git'",
252 "git-upload-pack ",
253 "git-upload-pack '/a/b'",
254 "git-upload-pack '/a/b' ",
255 "git-upload-pack '/a/b",
256 ];
257 for cmd in cases {
258 assert_eq!(err(cmd), ParseError::MalformedPath, "case {cmd:?}");
259 }
260 }
261
262 #[test]
263 fn rejects_unknown_commands() {
264 let cases: &[&str] = &[
265 "git-upload-archive '/a/b'",
266 "git upload-archive '/a/b'",
267 "ls -la",
268 "",
269 "git-upload-packx '/a/b'",
270 "git-upload-pack'/a/b'",
271 "git-upload-pack",
272 "GIT-UPLOAD-PACK '/a/b'",
273 " git-upload-pack '/a/b'",
274 ];
275 for cmd in cases {
276 assert_eq!(err(cmd), ParseError::UnsupportedCommand, "case {cmd:?}");
277 }
278 }
279
280 fn lfs_ok(cmd: &str) -> (String, LfsOperation) {
281 match parse_lfs_authenticate(cmd) {
282 Ok((path, operation)) => (format!("{}/{}", path.owner, path.name), operation),
283 Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"),
284 }
285 }
286
287 fn lfs_err(cmd: &str) -> ParseError {
288 match parse_lfs_authenticate(cmd) {
289 Ok(v) => panic!("expected {cmd:?} to be rejected, got {v:?}"),
290 Err(e) => e,
291 }
292 }
293
294 #[test]
295 fn lfs_accepts_quoted_and_bare_paths() {
296 let cases: &[(&str, &str, LfsOperation)] = &[
297 (
298 "git-lfs-authenticate '/tahinli/proj.git' download",
299 "tahinli/proj",
300 LfsOperation::Download,
301 ),
302 (
303 "git-lfs-authenticate 'tahinli/proj' upload",
304 "tahinli/proj",
305 LfsOperation::Upload,
306 ),
307 (
308 "git-lfs-authenticate /tahinli/proj.git upload",
309 "tahinli/proj",
310 LfsOperation::Upload,
311 ),
312 ];
313 for (cmd, path, op) in cases {
314 assert_eq!(lfs_ok(cmd), (path.to_string(), *op), "case {cmd}");
315 }
316 }
317
318 #[test]
319 fn lfs_rejects_malformed_commands() {
320 let cases: &[&str] = &[
321 "git-lfs-authenticate 'a/b' push",
322 "git-lfs-authenticate 'a/b' ",
323 "git-lfs-authenticate 'a/b' download extra",
324 "git-lfs-authenticate 'a/b'download",
325 "git-lfs-authenticate 'a/b' Download",
326 "git-lfs-authenticate '--help' download",
327 "git-lfs-authenticate '../x/y' upload",
328 "git-lfs-authenticate 'a/b'; id download",
329 "git-lfs-authenticate 'a/b' 'c' download",
330 "git-lfs-authenticate 'a/b download",
331 "git-lfs-authenticate a/b c download",
332 "git-lfs-authenticate 'a/b/c' download",
333 "git-lfs-authenticate ''",
334 ];
335 for cmd in cases {
336 assert_eq!(lfs_err(cmd), ParseError::MalformedPath, "case {cmd:?}");
337 }
338 }
339
340 #[test]
341 fn lfs_rejects_other_commands() {
342 assert_eq!(
343 lfs_err("git-upload-pack 'a/b' download"),
344 ParseError::UnsupportedCommand
345 );
346 assert_eq!(
347 lfs_err("git-lfs-authenticate-x 'a/b' download"),
348 ParseError::UnsupportedCommand
349 );
350 }
351}