Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/git/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, `<name>\t<url> (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 `<redacted>`, and so is every query value (`?private_token=<redacted>`, keeping the parameter names) and a non-empty fragment (`#<redacted>`). 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://<redacted>`. 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 `<redacted>`, 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 `<redacted>`, and so is every query value (`?private_token=<redacted>`, keeping the parameter names) and a non-empty fragment (`#<redacted>`). 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://<redacted>`. 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 `<redacted>`; 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 `<redacted>`, 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

Expand Down
48 changes: 32 additions & 16 deletions src/git/src/mcp_server_git/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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<transport>[A-Za-z][A-Za-z0-9+.-]*)::")

# One line of `git remote -v`: `<name>\t<url> (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<name>[^\t]*)\t(?P<url>.*) \((?P<direction>fetch|push)\)"
r"(?P<filter> \[.*\])?$"
# 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 `<name>\t` on a line of `git remote -v`: `<url> (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<url>.*) \((?P<direction>fetch|push)\)(?P<filter> \[.*\])?$"
)

# Schemes whose username is an account name rather than a secret, so it is kept
Expand Down Expand Up @@ -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://<redacted>`. A remote-helper address (`<transport>::<url>`) 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:
Expand Down Expand Up @@ -1322,28 +1328,38 @@ 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(
"A configured remote URL contains a newline, so the remotes cannot "
"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)


Expand Down
73 changes: 69 additions & 4 deletions src/git/tests/test_remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,12 @@ async def test_not_a_repository(tmp_path: Path):
("file://u:p@host/srv/r?x", "file://<redacted>@host/srv/r?x"),
# A password holding a line separator other than '\n'.
("https://u:s3cret\u2028tok@example.com/r", "https://<redacted>@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", "<redacted>"),
("d\thttps://alice:token@example.com/r.git", "<redacted>"),
("x https://example.com/r.git", "<redacted>"),
("https:: https://alice:token@example.com/r", "https::<redacted>"),
],
)
def test_redact_url(url: str, expected: str):
Expand All @@ -183,14 +189,16 @@ def test_unparseable_line_is_withheld(repo: git.Repo):
# `git remote -v` always prints `<name>\t<url> (<direction>)`. 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) == (
"<redacted>\n<redacted>\n<redacted>\nup\thttps://example.com/r (push)"
Expand Down Expand Up @@ -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=<redacted> (fetch)\n"
"origin\thttps://git.example.com/g/r.git#<redacted> (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://<redacted>@srv.example.com/org/r.git (fetch)\n"
"c\td\thttps://<redacted>@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<redacted> (fetch)\nlead\t<redacted> (push)")
assert "REPOTOKEN" not in result["content"][0]["text"]


def test_longest_configured_name_is_matched(repo: git.Repo):
# With remotes `c` and `c<TAB>d` both configured, a line starting
# `c<TAB>d<TAB>` 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://<redacted>@example.com/r (fetch)\n"
"c\td\thttps://<redacted>@example.com/r (push)\n"
"<redacted>"
)