diff --git a/src/git/README.md b/src/git/README.md index ccff61aa5e..2c06687721 100644 --- a/src/git/README.md +++ b/src/git/README.md @@ -113,7 +113,7 @@ Please note that mcp-server-git is currently in early development. The functiona - Inputs: - `repo_path` (string): Path to the Git repository. - Returns: One line per remote and direction, `\t (fetch)` or `(push)` (a partial clone's fetch line ends with its filter, such as ` [blob:none]`), or `No remotes configured` - - A credential embedded in a URL is never returned: the whole userinfo of a URL such as `https://user:token@host/...` or `https://token@host/...` is shown as ``, and so is every query value (`?private_token=`, keeping the parameter names) and a non-empty fragment (`#`). An SSH username (`ssh://git@host/...`) is kept, since it names an account rather than authenticating one; a password after it is redacted. A remote-helper address (`https::https://user:token@host/...`) has its inner URL redacted the same way. A URL where a `?` or `#` comes before the userinfo's `@` (`https://host?t=a@b`) cannot be split safely, so it is shown as `https://`. A token carried as a path segment (`https://host/token/SECRET/r.git`) is not redacted, since it cannot be told apart from a repository name. scp-style addresses (`git@host:path`) and local paths are shown as configured, and a `file://` URL keeps its `?` and `#` parts, which belong to a local file name. A line that cannot be parsed is shown as ``, and if a configured remote URL (or `insteadOf` rewrite) contains a newline, which git itself refuses, the tool returns an error instead of a listing. + - A credential embedded in a URL is never returned: the whole userinfo of a URL such as `https://user:token@host/...` or `https://token@host/...` is shown as ``, and so is every query value (`?private_token=`, keeping the parameter names) and a non-empty fragment (`#`). An SSH username (`ssh://git@host/...`) is kept, since it names an account rather than authenticating one; a password after it is redacted. A remote-helper address (`https::https://user:token@host/...`) has its inner URL redacted the same way. A URL where a `?` or `#` comes before the userinfo's `@` (`https://host?t=a@b`) cannot be split safely, so it is shown as `https://`. A token carried as a path segment (`https://host/token/SECRET/r.git`) is not redacted, since it cannot be told apart from a repository name. A value that holds a URL anywhere but at its start (` https://user:token@host/...`, with leading whitespace) cannot be split safely, so it is shown as ``; a remote name holding a tab is matched against the configured names, so the URL after it is still redacted. scp-style addresses (`git@host:path`) and local paths are shown as configured, and a `file://` URL keeps its `?` and `#` parts, which belong to a local file name. A line that cannot be parsed is shown as ``, and if a configured remote URL (or `insteadOf` rewrite) contains a newline, which git itself refuses, the tool returns an error instead of a listing. ### Protocol versions diff --git a/src/git/src/mcp_server_git/server.py b/src/git/src/mcp_server_git/server.py index 9aea4cfb3c..29329ab240 100644 --- a/src/git/src/mcp_server_git/server.py +++ b/src/git/src/mcp_server_git/server.py @@ -1204,13 +1204,18 @@ def git_branch( # after the `::` is a URL of its own, and is redacted as one. _REMOTE_HELPER = re.compile(r"^(?P[A-Za-z][A-Za-z0-9+.-]*)::") -# One line of `git remote -v`: `\t (fetch|push)`, and on a -# partial clone's fetch line the promisor filter after it (` [blob:none]`). -# `.` matches everything but '\n', so a URL holding another line separator -# (U+2028, say) stays whole. -_REMOTE_LINE = re.compile( - r"^(?P[^\t]*)\t(?P.*) \((?Pfetch|push)\)" - r"(?P \[.*\])?$" +# A scheme followed by `://` anywhere in a value. A value holding one that +# `_URL_SCHEME` does not find at its start (after a space or a tab, say) holds +# a URL that cannot be split from what precedes it. +_EMBEDDED_URL = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://") + +# What follows `\t` on a line of `git remote -v`: ` (fetch|push)`, +# and on a partial clone's fetch line the promisor filter after it +# (` [blob:none]`). `.` matches everything but '\n', so a URL holding another +# line separator (U+2028, say) stays whole. The name is not matched here: it +# may hold a tab itself, so it is taken from the configured names instead. +_REMOTE_ENTRY = re.compile( + r"^(?P.*) \((?Pfetch|push)\)(?P \[.*\])?$" ) # Schemes whose username is an account name rather than a secret, so it is kept @@ -1260,15 +1265,16 @@ def redact_url(url: str) -> str: kept: a token there cannot be told apart from a repository name. A URL whose userinfo would hold a '?' or '#' cannot be split safely and is shown as `scheme://`. A remote-helper address (`::`) has its inner URL redacted. - An scp-like address (`git@host:path`) or a local path is not a URL and is - returned as is. + A value holding `scheme://` anywhere but at its start (` https://...`) + cannot be split safely either, and is withheld whole. An scp-like address + (`git@host:path`) or a local path is not a URL and is returned as is. """ helper = _REMOTE_HELPER.match(url) if helper is not None: return url[: helper.end()] + redact_url(url[helper.end() :]) authority = _URL_SCHEME.match(url) if authority is None: - return url + return REDACTED if _EMBEDDED_URL.search(url) else url scheme = authority["scheme"] match = _URL_USERINFO.match(url) if match is None: @@ -1322,6 +1328,13 @@ def git_remote(repo: git.Repo) -> str: '\\n' alone, the only separator git prints, not on every separator `str.splitlines` knows, which would cut a URL holding U+2028 in two. A URL holding a newline itself is refused (`_remote_url_has_newline`). + + A remote name may hold a tab, so the tab that ends it is not the first one + on the line. Each line's name is the longest configured name (from + `git remote`, one per line: git allows no newline in a name) that the line + starts with, followed by a tab. Whatever a shorter name would have left in + the URL column is then left to `redact_url`, which withholds a value with + a URL that does not start it. """ if _remote_url_has_newline(repo): raise ValueError( @@ -1329,21 +1342,24 @@ def git_remote(repo: git.Repo) -> str: "be listed without risking a credential in it; git refuses such " "URLs as well" ) + names = sorted( + filter(None, _git_text(repo, "remote").split("\n")), key=len, reverse=True + ) output = _git_text(repo, "remote", "-v").rstrip("\n") if not output: return "No remotes configured" lines = [] for line in output.split("\n"): - match = _REMOTE_LINE.match(line) - if match is None: + name = next((n for n in names if line.startswith(n + "\t")), None) + match = None if name is None else _REMOTE_ENTRY.match(line[len(name) + 1 :]) + if name is None or match is None: # Not a line in the shape `git remote -v` prints (a URL holding a - # newline, say): it cannot be parsed, so none of it is returned. + # newline, say, or a name not configured): it cannot be parsed, + # so none of it is returned. lines.append(REDACTED) continue url = redact_url(match["url"]) - lines.append( - f"{match['name']}\t{url} ({match['direction']}){match['filter'] or ''}" - ) + lines.append(f"{name}\t{url} ({match['direction']}){match['filter'] or ''}") return "\n".join(lines) diff --git a/src/git/tests/test_remote.py b/src/git/tests/test_remote.py index f887cfa56c..e2ee26d3a4 100644 --- a/src/git/tests/test_remote.py +++ b/src/git/tests/test_remote.py @@ -173,6 +173,12 @@ async def test_not_a_repository(tmp_path: Path): ("file://u:p@host/srv/r?x", "file://@host/srv/r?x"), # A password holding a line separator other than '\n'. ("https://u:s3cret\u2028tok@example.com/r", "https://@example.com/r"), + # A value holding a URL that does not start it cannot be split safely, + # so it is withheld whole. + (" https://bob:token@example.com/r.git", ""), + ("d\thttps://alice:token@example.com/r.git", ""), + ("x https://example.com/r.git", ""), + ("https:: https://alice:token@example.com/r", "https::"), ], ) def test_redact_url(url: str, expected: str): @@ -183,14 +189,16 @@ def test_unparseable_line_is_withheld(repo: git.Repo): # `git remote -v` always prints `\t ()`. A line in # any other shape (a URL holding a raw newline is split across two) cannot # be parsed, so none of it is returned. - with mock.patch.object( - server, - "_git_text", - return_value=( + outputs = { + ("remote",): "origin\nup\n", + ("remote", "-v"): ( "origin\thttps://u:pa\nss@example.com/r (fetch)\n" "origin\tno-direction\n" "up\thttps://example.com/r (push)\n" ), + } + with mock.patch.object( + server, "_git_text", side_effect=lambda _repo, *args: outputs[args] ): assert git_remote(repo) == ( "\n\n\nup\thttps://example.com/r (push)" @@ -261,3 +269,60 @@ async def test_query_and_fragment_credentials_are_redacted_over_the_wire( "origin\thttps://git.example.com/g/r.git?private_token= (fetch)\n" "origin\thttps://git.example.com/g/r.git# (push)" ) + + +async def test_tab_in_remote_name_keeps_the_url_whole( + tmp_path: Path, repo: git.Repo, monkeypatch: pytest.MonkeyPatch +): + # A remote name may hold a tab, which `git remote -v` prints as is before + # the tab that ends the name. The name is matched against the configured + # names, so the URL after it, rewritten by a credential-bearing `insteadOf` + # in the user's global config, is still redacted. + global_config = tmp_path / "global.gitconfig" + global_config.write_text( + '[url "https://alice:HOSTTOKEN@srv.example.com/"]\n' + "\tinsteadOf = https://srv.example.com/\n", + encoding="utf-8", + ) + monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(global_config)) + repo.git.config("remote.c\td.url", "https://srv.example.com/org/r.git") + result = await call_remote(None, repo) + assert result == text_result( + "c\td\thttps://@srv.example.com/org/r.git (fetch)\n" + "c\td\thttps://@srv.example.com/org/r.git (push)" + ) + assert "HOSTTOKEN" not in result["content"][0]["text"] + + +async def test_url_not_starting_with_its_scheme_is_withheld(repo: git.Repo): + # A configured value with leading whitespace is printed as is by git; the + # URL inside it does not start the value, so it is withheld whole. + repo.git.config("remote.lead.url", " https://bob:REPOTOKEN@example.com/r.git") + result = await call_remote(None, repo) + assert result == text_result("lead\t (fetch)\nlead\t (push)") + assert "REPOTOKEN" not in result["content"][0]["text"] + + +def test_longest_configured_name_is_matched(repo: git.Repo): + # With remotes `c` and `cd` both configured, a line starting + # `cd` is read as the longer name, and whichever remote it came + # from, a URL left holding a tab and another URL is withheld. + outputs = { + ("remote",): "c\nc\td\n", + ("remote", "-v"): ( + "c\td\thttps://u:p@example.com/r (fetch)\n" + "c\td\thttps://u:p@example.com/r (push)\n" + "unknown\thttps://u:p@example.com/r (fetch)\n" + ), + } + with ( + mock.patch.object(server, "_remote_url_has_newline", return_value=False), + mock.patch.object( + server, "_git_text", side_effect=lambda _repo, *args: outputs[args] + ), + ): + assert git_remote(repo) == ( + "c\td\thttps://@example.com/r (fetch)\n" + "c\td\thttps://@example.com/r (push)\n" + "" + )