forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.4 MiBe587be7Tahinli11 hours ago323 commits

parse.rs370 lines, 12.4 KiBHistoryRawDownload
1//! Strict parsing of the SSH `exec` request: `git-upload-pack '/owner/repo.git'`.
2//!
3//! No shell is ever involved. The accepted grammar is deliberately tiny:
4//! one of four service prefixes, one space, then one argument that is either
5//! single-quoted or a bare token with no whitespace or quoting characters.
6
7use forge_git::GitService;
8
9#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
10pub enum ParseError {
11 #[error("unsupported command")]
12 UnsupportedCommand,
13 #[error("malformed repository path")]
14 MalformedPath,
15}
16
17/// Service prefixes accepted by the server. Both the hyphenated form git uses and
18/// the spaced form `git upload-pack` are allowed. Anything else is rejected.
19const PREFIXES: &[(&str, GitService)] = &[
20 ("git-upload-pack ", GitService::UploadPack),
21 ("git-receive-pack ", GitService::ReceivePack),
22 ("git upload-pack ", GitService::UploadPack),
23 ("git receive-pack ", GitService::ReceivePack),
24];
25
26/// Owner and repository name with `.git` stripped and the leading `/` or `~/` removed.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct RepoPath {
29 pub owner: String,
30 pub name: String,
31}
32
33/// Returns the service and the repository path. Anything else is an error.
34pub(crate) fn parse_exec(cmd: &str) -> Result<(GitService, RepoPath), ParseError> {
35 let (service, rest) = split_service(cmd)?;
36 let raw = unquote_argument(rest)?;
37 let path = normalize_path(raw)?;
38 Ok((service, path))
39}
40
41/// Exec prefix of the Git LFS authenticate request.
42pub(crate) const LFS_AUTHENTICATE_PREFIX: &str = "git-lfs-authenticate ";
43
44/// Direction of a `git-lfs-authenticate` request.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum LfsOperation {
47 Download,
48 Upload,
49}
50
51/// Parses `git-lfs-authenticate '<owner>/<repo>[.git]' download|upload`. The path follows the
52/// same rules as `parse_exec`, and the operation must be exactly `download` or `upload`.
53pub(crate) fn parse_lfs_authenticate(cmd: &str) -> Result<(RepoPath, LfsOperation), ParseError> {
54 let rest = cmd
55 .strip_prefix(LFS_AUTHENTICATE_PREFIX)
56 .ok_or(ParseError::UnsupportedCommand)?;
57 let (arg, op) = rest.rsplit_once(' ').ok_or(ParseError::MalformedPath)?;
58 let operation = match op {
59 "download" => LfsOperation::Download,
60 "upload" => LfsOperation::Upload,
61 _ => return Err(ParseError::MalformedPath),
62 };
63 let path = normalize_path(unquote_argument(arg)?)?;
64 Ok((path, operation))
65}
66
67fn split_service(cmd: &str) -> Result<(GitService, &str), ParseError> {
68 PREFIXES
69 .iter()
70 .find_map(|(prefix, service)| cmd.strip_prefix(prefix).map(|rest| (*service, rest)))
71 .ok_or(ParseError::UnsupportedCommand)
72}
73
74/// Extracts the argument. A quoted argument may contain spaces but no quotes,
75/// backslashes or control characters. An unquoted argument must contain none of
76/// whitespace, quotes, backslashes or control characters.
77fn unquote_argument(rest: &str) -> Result<&str, ParseError> {
78 if let Some(quoted) = rest.strip_prefix('\'') {
79 let inner = quoted.strip_suffix('\'').ok_or(ParseError::MalformedPath)?;
80 if inner
81 .chars()
82 .any(|c| matches!(c, '\'' | '\\') || c.is_control())
83 {
84 return Err(ParseError::MalformedPath);
85 }
86 return Ok(inner);
87 }
88 if rest.is_empty()
89 || rest
90 .chars()
91 .any(|c| c.is_whitespace() || matches!(c, '\'' | '"' | '\\') || c.is_control())
92 {
93 return Err(ParseError::MalformedPath);
94 }
95 Ok(rest)
96}
97
98/// Strips one leading `/` or `~/`, then requires exactly `owner/repo` or
99/// `owner/repo.git`.
100fn normalize_path(raw: &str) -> Result<RepoPath, ParseError> {
101 let path = raw.strip_prefix('/').unwrap_or(raw);
102 let path = path.strip_prefix("~/").unwrap_or(path);
103
104 let segments: Vec<&str> = path.split('/').collect();
105 let [owner, repo] = segments.as_slice() else {
106 return Err(ParseError::MalformedPath);
107 };
108 for segment in [owner, repo] {
109 if segment.is_empty()
110 || *segment == ".."
111 || segment.starts_with('-')
112 || segment.starts_with('.')
113 || !segment
114 .bytes()
115 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
116 {
117 return Err(ParseError::MalformedPath);
118 }
119 }
120
121 let repo = repo.strip_suffix(".git").unwrap_or(repo);
122 if repo.is_empty() {
123 return Err(ParseError::MalformedPath);
124 }
125 Ok(RepoPath {
126 owner: owner.to_string(),
127 name: repo.to_string(),
128 })
129}
130
131#[cfg(test)]
132mod tests {
133 use super::*;
134
135 fn ok(cmd: &str) -> (GitService, String) {
136 match parse_exec(cmd) {
137 Ok((service, path)) => (service, format!("{}/{}", path.owner, path.name)),
138 Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"),
139 }
140 }
141
142 fn err(cmd: &str) -> ParseError {
143 match parse_exec(cmd) {
144 Ok(v) => panic!("expected {cmd:?} to be rejected, got {v:?}"),
145 Err(e) => e,
146 }
147 }
148
149 #[test]
150 fn accepts_valid_exec_commands() {
151 // Covers both services, wiki suffix, spaced form, leading slash and
152 // tilde stripping, and unquoted paths.
153 let cases: &[(&str, GitService, &str)] = &[
154 (
155 "git-upload-pack '/tahinli/proj.git'",
156 GitService::UploadPack,
157 "tahinli/proj",
158 ),
159 (
160 "git-receive-pack '/tahinli/proj.git'",
161 GitService::ReceivePack,
162 "tahinli/proj",
163 ),
164 (
165 "git-receive-pack '/tahinli/proj.wiki.git'",
166 GitService::ReceivePack,
167 "tahinli/proj.wiki",
168 ),
169 (
170 "git-upload-pack 'tahinli/proj.wiki'",
171 GitService::UploadPack,
172 "tahinli/proj.wiki",
173 ),
174 (
175 "git upload-pack '/tahinli/proj'",
176 GitService::UploadPack,
177 "tahinli/proj",
178 ),
179 (
180 "git receive-pack 'tahinli/proj.git'",
181 GitService::ReceivePack,
182 "tahinli/proj",
183 ),
184 (
185 "git-upload-pack '~/tahinli/proj'",
186 GitService::UploadPack,
187 "tahinli/proj",
188 ),
189 (
190 "git-upload-pack '/~/tahinli/proj'",
191 GitService::UploadPack,
192 "tahinli/proj",
193 ),
194 (
195 "git-upload-pack 'tahinli/proj'",
196 GitService::UploadPack,
197 "tahinli/proj",
198 ),
199 (
200 "git-upload-pack /tahinli/proj.git",
201 GitService::UploadPack,
202 "tahinli/proj",
203 ),
204 (
205 "git-receive-pack tahinli/proj",
206 GitService::ReceivePack,
207 "tahinli/proj",
208 ),
209 ];
210 for (cmd, service, path) in cases {
211 assert_eq!(ok(cmd), (*service, path.to_string()), "case {cmd}");
212 }
213 }
214
215 #[test]
216 fn rejects_malformed_exec_paths() {
217 // Option, shell and traversal injection, bad quoting, control
218 // characters, wrong segment counts, empty values and stray spaces.
219 let cases: &[&str] = &[
220 // Only one leading slash is stripped.
221 "git-upload-pack '//tahinli/proj'",
222 // Unquoted paths with a quote, backslash or space.
223 "git-upload-pack a/b c",
224 "git-upload-pack a/b'",
225 "git-upload-pack a\"b/c",
226 "git-upload-pack a\\b/c",
227 // Option injection.
228 "git-upload-pack '--help'",
229 "git-upload-pack '--upload-pack=touch /x'",
230 "git-upload-pack '-x/y'",
231 "git-upload-pack 'a/-b'",
232 // Shell injection.
233 "git-upload-pack 'a/b'; rm -rf /",
234 "git-upload-pack 'a/b' 'c/d'",
235 "git-upload-pack 'a/b$(id)'",
236 "git-upload-pack 'a/b;c'",
237 "git-upload-pack 'a/b|c'",
238 "git-upload-pack 'a/b&c'",
239 "git-upload-pack 'a/b%20c'",
240 "git-upload-pack 'a/é'",
241 "git-upload-pack 'a/b`id`'",
242 "git-upload-pack 'a/b' && id",
243 // Quote, backslash, newline, NUL and control characters inside quotes.
244 "git-upload-pack 'a/b\\c'",
245 "git-upload-pack 'a/b\nc'",
246 "git-upload-pack 'a/b\rc'",
247 "git-upload-pack 'a/b\0c'",
248 "git-upload-pack 'a/b\x07c'",
249 "git-upload-pack 'a/b\x7fc'",
250 "git-upload-pack 'a/b'c'",
251 // Traversal and hidden segments.
252 "git-upload-pack '../x/y'",
253 "git-upload-pack 'a/..'",
254 "git-upload-pack '/a/../b'",
255 "git-upload-pack '.hidden/repo'",
256 "git-upload-pack 'owner/.git'",
257 // Wrong segment count.
258 "git-upload-pack 'a/b/c'",
259 "git-upload-pack 'a'",
260 "git-upload-pack 'a/'",
261 "git-upload-pack '/a/b/'",
262 "git-upload-pack '//'",
263 // Empty values.
264 "git-upload-pack ''",
265 "git-upload-pack '/'",
266 "git-upload-pack '~/'",
267 "git-upload-pack '.git'",
268 "git-upload-pack ",
269 // Extra spaces and trailing garbage.
270 "git-upload-pack '/a/b'",
271 "git-upload-pack '/a/b' ",
272 "git-upload-pack '/a/b",
273 ];
274 for cmd in cases {
275 assert_eq!(err(cmd), ParseError::MalformedPath, "case {cmd:?}");
276 }
277 }
278
279 #[test]
280 fn rejects_unknown_commands() {
281 let cases: &[&str] = &[
282 "git-upload-archive '/a/b'",
283 "git upload-archive '/a/b'",
284 "ls -la",
285 "",
286 "git-upload-packx '/a/b'",
287 "git-upload-pack'/a/b'",
288 "git-upload-pack",
289 "GIT-UPLOAD-PACK '/a/b'",
290 " git-upload-pack '/a/b'",
291 ];
292 for cmd in cases {
293 assert_eq!(err(cmd), ParseError::UnsupportedCommand, "case {cmd:?}");
294 }
295 }
296
297 fn lfs_ok(cmd: &str) -> (String, LfsOperation) {
298 match parse_lfs_authenticate(cmd) {
299 Ok((path, operation)) => (format!("{}/{}", path.owner, path.name), operation),
300 Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"),
301 }
302 }
303
304 fn lfs_err(cmd: &str) -> ParseError {
305 match parse_lfs_authenticate(cmd) {
306 Ok(v) => panic!("expected {cmd:?} to be rejected, got {v:?}"),
307 Err(e) => e,
308 }
309 }
310
311 #[test]
312 fn lfs_accepts_quoted_and_bare_paths() {
313 let cases: &[(&str, &str, LfsOperation)] = &[
314 (
315 "git-lfs-authenticate '/tahinli/proj.git' download",
316 "tahinli/proj",
317 LfsOperation::Download,
318 ),
319 (
320 "git-lfs-authenticate 'tahinli/proj' upload",
321 "tahinli/proj",
322 LfsOperation::Upload,
323 ),
324 (
325 "git-lfs-authenticate /tahinli/proj.git upload",
326 "tahinli/proj",
327 LfsOperation::Upload,
328 ),
329 ];
330 for (cmd, path, op) in cases {
331 assert_eq!(lfs_ok(cmd), (path.to_string(), *op), "case {cmd}");
332 }
333 }
334
335 #[test]
336 fn lfs_rejects_malformed_commands() {
337 let cases: &[&str] = &[
338 // Bad operation.
339 "git-lfs-authenticate 'a/b' push",
340 "git-lfs-authenticate 'a/b' ",
341 "git-lfs-authenticate 'a/b' download extra",
342 "git-lfs-authenticate 'a/b'download",
343 "git-lfs-authenticate 'a/b' Download",
344 // Bad paths.
345 "git-lfs-authenticate '--help' download",
346 "git-lfs-authenticate '../x/y' upload",
347 "git-lfs-authenticate 'a/b'; id download",
348 "git-lfs-authenticate 'a/b' 'c' download",
349 "git-lfs-authenticate 'a/b download",
350 "git-lfs-authenticate a/b c download",
351 "git-lfs-authenticate 'a/b/c' download",
352 "git-lfs-authenticate ''",
353 ];
354 for cmd in cases {
355 assert_eq!(lfs_err(cmd), ParseError::MalformedPath, "case {cmd:?}");
356 }
357 }
358
359 #[test]
360 fn lfs_rejects_other_commands() {
361 assert_eq!(
362 lfs_err("git-upload-pack 'a/b' download"),
363 ParseError::UnsupportedCommand
364 );
365 assert_eq!(
366 lfs_err("git-lfs-authenticate-x 'a/b' download"),
367 ParseError::UnsupportedCommand
368 );
369 }
370}