//! Strict parsing of the SSH `exec` request: `git-upload-pack '/owner/repo.git'`. //! //! No shell is ever involved. The accepted grammar is deliberately tiny: //! one of four service prefixes, one space, then one argument that is either //! single-quoted or a bare token with no whitespace or quoting characters. use forge_git::GitService; #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum ParseError { #[error("unsupported command")] UnsupportedCommand, #[error("malformed repository path")] MalformedPath, } /// Service prefixes accepted by the server. Both the hyphenated form git uses and /// the spaced form `git upload-pack` are allowed. Anything else is rejected. const PREFIXES: &[(&str, GitService)] = &[ ("git-upload-pack ", GitService::UploadPack), ("git-receive-pack ", GitService::ReceivePack), ("git upload-pack ", GitService::UploadPack), ("git receive-pack ", GitService::ReceivePack), ]; /// Returns the service and the repository path with `.git` stripped and the /// leading `/` or `~/` removed. Anything else is an error. pub fn parse_exec(cmd: &str) -> Result<(GitService, String), ParseError> { let (service, rest) = split_service(cmd)?; let raw = unquote_argument(rest)?; let path = normalize_path(raw)?; Ok((service, path)) } /// Exec prefix of the Git LFS authenticate request. pub(crate) const LFS_AUTHENTICATE_PREFIX: &str = "git-lfs-authenticate "; /// Direction of a `git-lfs-authenticate` request. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LfsOperation { Download, Upload, } /// Parses `git-lfs-authenticate '/[.git]' download|upload`. The path follows the /// same rules as `parse_exec`, and the operation must be exactly `download` or `upload`. pub fn parse_lfs_authenticate(cmd: &str) -> Result<(String, LfsOperation), ParseError> { let rest = cmd .strip_prefix(LFS_AUTHENTICATE_PREFIX) .ok_or(ParseError::UnsupportedCommand)?; // The path argument ends at its closing quote, or at the first space when it is bare. let end = if let Some(quoted) = rest.strip_prefix('\'') { quoted.find('\'').ok_or(ParseError::MalformedPath)? + 2 } else { rest.find(' ').ok_or(ParseError::MalformedPath)? }; let (arg, tail) = rest.split_at(end); let operation = match tail { " download" => LfsOperation::Download, " upload" => LfsOperation::Upload, _ => return Err(ParseError::MalformedPath), }; let path = normalize_path(unquote_argument(arg)?)?; Ok((path, operation)) } fn split_service(cmd: &str) -> Result<(GitService, &str), ParseError> { PREFIXES .iter() .find_map(|(prefix, service)| cmd.strip_prefix(prefix).map(|rest| (*service, rest))) .ok_or(ParseError::UnsupportedCommand) } /// Extracts the argument. A quoted argument may contain spaces but no quotes, /// backslashes or control characters. An unquoted argument must contain none of /// whitespace, quotes, backslashes or control characters. fn unquote_argument(rest: &str) -> Result<&str, ParseError> { if let Some(quoted) = rest.strip_prefix('\'') { let inner = quoted.strip_suffix('\'').ok_or(ParseError::MalformedPath)?; if inner .chars() .any(|c| matches!(c, '\'' | '\\') || c.is_control()) { return Err(ParseError::MalformedPath); } return Ok(inner); } if rest.is_empty() || rest .chars() .any(|c| c.is_whitespace() || matches!(c, '\'' | '"' | '\\') || c.is_control()) { return Err(ParseError::MalformedPath); } Ok(rest) } /// Strips one leading `/` or `~/`, then requires exactly `owner/repo` or /// `owner/repo.git`, returning `owner/repo`. fn normalize_path(raw: &str) -> Result { let path = raw.strip_prefix('/').unwrap_or(raw); let path = path.strip_prefix("~/").unwrap_or(path); let segments: Vec<&str> = path.split('/').collect(); let [owner, repo] = segments.as_slice() else { return Err(ParseError::MalformedPath); }; for segment in [owner, repo] { if segment.is_empty() || *segment == ".." || segment.starts_with('-') || segment.starts_with('.') || !segment .bytes() .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) { return Err(ParseError::MalformedPath); } } let repo = repo.strip_suffix(".git").unwrap_or(repo); if repo.is_empty() { return Err(ParseError::MalformedPath); } Ok(format!("{owner}/{repo}")) } #[cfg(test)] mod tests { use super::*; fn ok(cmd: &str) -> (GitService, String) { match parse_exec(cmd) { Ok(v) => v, Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"), } } fn err(cmd: &str) -> ParseError { match parse_exec(cmd) { Ok(v) => panic!("expected {cmd:?} to be rejected, got {v:?}"), Err(e) => e, } } #[test] fn accepts_valid_exec_commands() { // Covers both services, wiki suffix, spaced form, leading slash and // tilde stripping, and unquoted paths. let cases: &[(&str, GitService, &str)] = &[ ( "git-upload-pack '/tahinli/proj.git'", GitService::UploadPack, "tahinli/proj", ), ( "git-receive-pack '/tahinli/proj.git'", GitService::ReceivePack, "tahinli/proj", ), ( "git-receive-pack '/tahinli/proj.wiki.git'", GitService::ReceivePack, "tahinli/proj.wiki", ), ( "git-upload-pack 'tahinli/proj.wiki'", GitService::UploadPack, "tahinli/proj.wiki", ), ( "git upload-pack '/tahinli/proj'", GitService::UploadPack, "tahinli/proj", ), ( "git receive-pack 'tahinli/proj.git'", GitService::ReceivePack, "tahinli/proj", ), ( "git-upload-pack '~/tahinli/proj'", GitService::UploadPack, "tahinli/proj", ), ( "git-upload-pack '/~/tahinli/proj'", GitService::UploadPack, "tahinli/proj", ), ( "git-upload-pack 'tahinli/proj'", GitService::UploadPack, "tahinli/proj", ), ( "git-upload-pack /tahinli/proj.git", GitService::UploadPack, "tahinli/proj", ), ( "git-receive-pack tahinli/proj", GitService::ReceivePack, "tahinli/proj", ), ]; for (cmd, service, path) in cases { assert_eq!(ok(cmd), (*service, path.to_string()), "case {cmd}"); } } #[test] fn rejects_malformed_exec_paths() { // Option, shell and traversal injection, bad quoting, control // characters, wrong segment counts, empty values and stray spaces. let cases: &[&str] = &[ // Only one leading slash is stripped. "git-upload-pack '//tahinli/proj'", // Unquoted paths with a quote, backslash or space. "git-upload-pack a/b c", "git-upload-pack a/b'", "git-upload-pack a\"b/c", "git-upload-pack a\\b/c", // Option injection. "git-upload-pack '--help'", "git-upload-pack '--upload-pack=touch /x'", "git-upload-pack '-x/y'", "git-upload-pack 'a/-b'", // Shell injection. "git-upload-pack 'a/b'; rm -rf /", "git-upload-pack 'a/b' 'c/d'", "git-upload-pack 'a/b$(id)'", "git-upload-pack 'a/b;c'", "git-upload-pack 'a/b|c'", "git-upload-pack 'a/b&c'", "git-upload-pack 'a/b%20c'", "git-upload-pack 'a/é'", "git-upload-pack 'a/b`id`'", "git-upload-pack 'a/b' && id", // Quote, backslash, newline, NUL and control characters inside quotes. "git-upload-pack 'a/b\\c'", "git-upload-pack 'a/b\nc'", "git-upload-pack 'a/b\rc'", "git-upload-pack 'a/b\0c'", "git-upload-pack 'a/b\x07c'", "git-upload-pack 'a/b\x7fc'", "git-upload-pack 'a/b'c'", // Traversal and hidden segments. "git-upload-pack '../x/y'", "git-upload-pack 'a/..'", "git-upload-pack '/a/../b'", "git-upload-pack '.hidden/repo'", "git-upload-pack 'owner/.git'", // Wrong segment count. "git-upload-pack 'a/b/c'", "git-upload-pack 'a'", "git-upload-pack 'a/'", "git-upload-pack '/a/b/'", "git-upload-pack '//'", // Empty values. "git-upload-pack ''", "git-upload-pack '/'", "git-upload-pack '~/'", "git-upload-pack '.git'", "git-upload-pack ", // Extra spaces and trailing garbage. "git-upload-pack '/a/b'", "git-upload-pack '/a/b' ", "git-upload-pack '/a/b", ]; for cmd in cases { assert_eq!(err(cmd), ParseError::MalformedPath, "case {cmd:?}"); } } #[test] fn rejects_unknown_commands() { let cases: &[&str] = &[ "git-upload-archive '/a/b'", "git upload-archive '/a/b'", "ls -la", "", "git-upload-packx '/a/b'", "git-upload-pack'/a/b'", "git-upload-pack", "GIT-UPLOAD-PACK '/a/b'", " git-upload-pack '/a/b'", ]; for cmd in cases { assert_eq!(err(cmd), ParseError::UnsupportedCommand, "case {cmd:?}"); } } fn lfs_ok(cmd: &str) -> (String, LfsOperation) { match parse_lfs_authenticate(cmd) { Ok(v) => v, Err(e) => panic!("expected {cmd:?} to parse, got {e:?}"), } } fn lfs_err(cmd: &str) -> ParseError { match parse_lfs_authenticate(cmd) { Ok(v) => panic!("expected {cmd:?} to be rejected, got {v:?}"), Err(e) => e, } } #[test] fn lfs_accepts_quoted_and_bare_paths() { let cases: &[(&str, &str, LfsOperation)] = &[ ( "git-lfs-authenticate '/tahinli/proj.git' download", "tahinli/proj", LfsOperation::Download, ), ( "git-lfs-authenticate 'tahinli/proj' upload", "tahinli/proj", LfsOperation::Upload, ), ( "git-lfs-authenticate /tahinli/proj.git upload", "tahinli/proj", LfsOperation::Upload, ), ]; for (cmd, path, op) in cases { assert_eq!(lfs_ok(cmd), (path.to_string(), *op), "case {cmd}"); } } #[test] fn lfs_rejects_malformed_commands() { let cases: &[&str] = &[ // Bad operation. "git-lfs-authenticate 'a/b' push", "git-lfs-authenticate 'a/b' ", "git-lfs-authenticate 'a/b' download extra", "git-lfs-authenticate 'a/b'download", "git-lfs-authenticate 'a/b' Download", // Bad paths. "git-lfs-authenticate '--help' download", "git-lfs-authenticate '../x/y' upload", "git-lfs-authenticate 'a/b'; id download", "git-lfs-authenticate 'a/b' 'c' download", "git-lfs-authenticate 'a/b download", "git-lfs-authenticate a/b c download", "git-lfs-authenticate 'a/b/c' download", "git-lfs-authenticate ''", ]; for cmd in cases { assert_eq!(lfs_err(cmd), ParseError::MalformedPath, "case {cmd:?}"); } } #[test] fn lfs_rejects_other_commands() { assert_eq!( lfs_err("git-upload-pack 'a/b' download"), ParseError::UnsupportedCommand ); assert_eq!( lfs_err("git-lfs-authenticate-x 'a/b' download"), ParseError::UnsupportedCommand ); } }