Skip to content

fix(security): stop Gerrit suggestions from writing into .git - #3960

Closed
TianHengZhuang wants to merge 1 commit into
The-PR-Agent:mainfrom
TianHengZhuang:fix/gerrit-suggestion-git-metadata
Closed

TianHengZhuang wants to merge 1 commit into
The-PR-Agent:mainfrom
TianHengZhuang:fix/gerrit-suggestion-git-metadata

Conversation

@TianHengZhuang

Copy link
Copy Markdown
Contributor

Fixes #3914.

resolve() follows symlinks, so a tracked symlink inside the checkout made the containment check pass: (repo_root / evil_link).resolve() lands on repo_root/.git/hooks/pre-commit, which is still under repo_root, so relative_to() was happy. add_suggestion then rewrote that path before the diff() call a few lines later read the tree, which turns a code suggestion into a write into git's own metadata.

Two checks now sit next to the existing relative_to, in the same try so the one except ValueError still reports and skips:

  • the un-resolved path must not be a symlink
  • the resolved path must not have .git among its parts

The second one covers the case the first misses: a symlinked directory (gitdir -> .git) whose final component is an ordinary file, which resolves into .git without the requested path itself being a symlink. A symlink that resolves inside the checkout and outside .git still works, which is what the existing symlink tests in this file rely on.

Tests in tests/unittest/test_gerrit_provider.py:

  • test_publish_code_suggestions_refuses_paths_that_reach_into_git, parametrised over link.py (symlink to .git/config) and gitdir/config (through a symlinked directory). Both assert add_suggestion was never called and that .git/config is byte-identical afterwards.
  • test_publish_code_suggestions_still_applies_a_regular_file guards the other direction, so the new rejection cannot swallow ordinary suggestions.

No conflict with #3876 as far as I can tell: that one edits add_suggestion, this edits its caller and leaves the function alone. Happy to rebase if you would rather see them land in the other order.

ruff check clean. pytest tests/unittest/test_gerrit_provider.py -k publish_code_suggestions passes. Seven other tests in that file compare newline-sensitive bytes and fail on a Windows checkout (b'app.py\r\n' != b'app.py\n'), which is unrelated to this change and does not happen on CI.

publish_code_suggestions checks containment with
(repo_root / relevant_file).resolve().relative_to(repo_root), but resolve()
follows symlinks, so a tracked symlink that points into .git/ still looks
contained. add_suggestion then rewrites whatever it points at -- the
obvious target being .git/hooks/pre-commit -- before the git diff a few
lines later reads it.

Reject a symlink outright, and reject any path that resolves through a
.git directory, in the same try/except that already drops traversal.

Fixes The-PR-Agent#3914
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Prevent Gerrit suggestions from modifying Git metadata

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Reject Gerrit suggestion paths that are symlinks or resolve into .git, preventing metadata
 writes.
• Test both symlink attack paths and confirm regular-file suggestions still apply.
Diagram

graph TD
  A["Gerrit suggestion"] --> B{"Final symlink?"} -- "No" --> C["Resolve path"] --> D{"Contained outside .git?"} -- "Yes" --> F["Apply suggestion"] --> G["Generate patch"]
  B -- "Yes" --> E["Skip suggestion"]
  D -- "No" --> E
Loading
High-Level Assessment

Keep validation at the suggestion caller, before add_suggestion writes. Rejecting every path with a symlinked parent would also block safe in-checkout paths; checking the resolved destination protects .git while preserving those paths.

Files changed (2) +60 / -1

Bug fix (1) +10 / -1
gerrit_provider.pyBlock suggestion paths that reach Git metadata +10/-1

Block suggestion paths that reach Git metadata

• The suggestion publisher rejects a final-component symlink and any resolved path containing '.git' before applying a suggestion. These checks use the existing skip-on-invalid-path handling.

pr_agent/git_providers/gerrit_provider.py

Tests (1) +50 / -0
test_gerrit_provider.pyCover unsafe symlink paths and regular suggestions +50/-0

Cover unsafe symlink paths and regular suggestions

• Adds cases for a file symlink and a symlinked directory targeting '.git/config', asserting neither applies a suggestion or changes the config. A regular-file case confirms accepted suggestions still reach 'add_suggestion'.

tests/unittest/test_gerrit_provider.py

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (1) 📎 Requirement gaps (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Git metadata can still be rewritten on Mac 🐞 Bug ⛨ Security
Description
publish_code_suggestions compares resolved path components to the case-sensitive string .git. On
a case-insensitive macOS filesystem, .GIT/config can refer to .git/config while retaining the
requested spelling in the path, so the check passes and add_suggestion opens the metadata file for
writing.
Code

pr_agent/git_providers/gerrit_provider.py[R460-461]

+                if ".git" in target_path.parts:
+                    raise ValueError("resolves into .git")
Evidence
The added check requires an exact .git component match; a path that passes it is handed to a
function that opens the resolved target for writing.

pr_agent/git_providers/gerrit_provider.py[452-462]
pr_agent/git_providers/gerrit_provider.py[468-472]
pr_agent/git_providers/gerrit_provider.py[178-190]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The exact `.git` component comparison can miss differently cased paths to Git metadata on case-insensitive filesystems.
## Fix Focus Areas
- pr_agent/git_providers/gerrit_provider.py[459-462]
- tests/unittest/test_gerrit_provider.py[121-140]
## Recommended Fix
Compare path components using case-insensitive normalization where the filesystem treats names case-insensitively. Add a test that verifies a differently cased spelling of `.git/config` cannot reach `add_suggestion`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. New security comment starts descriptively 📘 Rule violation ⚙ Maintainability
Description
The comment above requested_path.is_symlink() begins with resolve() follows symlinks and
narrates what add_suggestion() would do instead of using imperative phrasing. Its opening sentence
spans the symlink and metadata cases, leaving a later editor of either guard with a descriptive
instruction.
Code

pr_agent/git_providers/gerrit_provider.py[R453-455]

+                # resolve() follows symlinks, so a tracked symlink into .git/ would still look
+                # contained and add_suggestion() would then rewrite git's own metadata (for
+                # example .git/hooks/pre-commit) before the diff below reads it. Refuse a
Evidence
The checklist requires comments describing code behavior to use imperative phrasing. The added
comment opens with resolve() follows symlinks and continues by describing what add_suggestion()
would do.

Rule 2694688: Docstrings and comments must use imperative phrasing
pr_agent/git_providers/gerrit_provider.py[453-456]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new security comment opens with narrative phrasing rather than an imperative instruction.

## Fix Focus Areas
- pr_agent/git_providers/gerrit_provider.py[453-456]

## Recommended Fix
Rephrase the comment to instruct readers to reject symlinked paths and paths resolving into `.git`, while retaining the explanation of the risk.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Some checkouts reject every suggestion 🐞 Bug ≡ Correctness
Description
publish_code_suggestions searches every component of the absolute target_path for .git,
including components above repo_root. If the temporary checkout is created beneath a parent
directory named .git, even an ordinary file such as app.py is skipped.
Code

pr_agent/git_providers/gerrit_provider.py[R460-461]

+                if ".git" in target_path.parts:
+                    raise ValueError("resolves into .git")
Evidence
prepare_repo creates the checkout under the temporary directory location, while the new check
inspects absolute path parts rather than parts relative to that checkout.

pr_agent/git_providers/gerrit_provider.py[109-126]
pr_agent/git_providers/gerrit_provider.py[444-465]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Checking all absolute path components rejects ordinary suggestions when a checkout has a `.git` directory among its ancestors.
## Fix Focus Areas
- pr_agent/git_providers/gerrit_provider.py[459-462]
- tests/unittest/test_gerrit_provider.py[143-159]
## Recommended Fix
First establish that the resolved target is inside `repo_root`, then check only its checkout-relative components for `.git`. Test an ordinary suggestion in a checkout nested beneath a directory named `.git`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Grey Divider

Context sources
✅ Compliance rules (platform): 31 rules
Review mode: Auto: ⚖️ Balanced: Security-sensitive path validation warrants a complete careful review.
ⓘ  1 issues published inline · 3 in summary

Grey Divider

Tip of the day
💡 Did you know, you can add REVIEW.md to your repo root and Qodo follows it on every PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment on lines +460 to +461
if ".git" in target_path.parts:
raise ValueError("resolves into .git")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

1. Git metadata can still be rewritten on mac 🐞 Bug ⛨ Security

publish_code_suggestions compares resolved path components to the case-sensitive string .git. On
a case-insensitive macOS filesystem, .GIT/config can refer to .git/config while retaining the
requested spelling in the path, so the check passes and add_suggestion opens the metadata file for
writing.
Agent Prompt
## Issue description
The exact `.git` component comparison can miss differently cased paths to Git metadata on case-insensitive filesystems.
## Fix Focus Areas
- pr_agent/git_providers/gerrit_provider.py[459-462]
- tests/unittest/test_gerrit_provider.py[121-140]
## Recommended Fix
Compare path components using case-insensitive normalization where the filesystem treats names case-insensitively. Add a test that verifies a differently cased spelling of `.git/config` cannot reach `add_suggestion`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

Thanks for the careful write-up and the directory-symlink test, which is a good case to cover. #3915 was opened a day earlier for #3914 with the same guard, so I'm closing this as a duplicate to keep the work in one place. Both versions still let .GIT/config through on a case-insensitive filesystem, as Qodo flagged here; that fix is being handled on #3915.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Gerrit /improve: don't follow symlinks when applying a suggestion

2 participants