Skip to content

[agent] cleanup: Fix proxy security and testing monkeypatch support - #374

Open
google-labs-jules[bot] wants to merge 2 commits into
mainfrom
jules-13424727956599722460-58b60a7c
Open

[agent] cleanup: Fix proxy security and testing monkeypatch support#374
google-labs-jules[bot] wants to merge 2 commits into
mainfrom
jules-13424727956599722460-58b60a7c

Conversation

@google-labs-jules

@google-labs-jules google-labs-jules Bot commented Jun 25, 2026

Copy link
Copy Markdown

Agent Report Summary

  • Branch: jules-13424727956599722460-58b60a7c
  • Diff Summary: Modifies backend/src/agent/security.py to fix IP extraction proxy count boundary logic and fix the function's default parameters for mocking. Modifies multiple tests across test_api_security.py, test_rate_limiter_proxy.py, and test_proxy_security.py to use monkeypatch safely.

Scan Results

  • Misplaced files moved: None
  • Unused files: None
  • Ambiguous files: None

Verification

  • Commands run: cd backend && uv run pytest tests/
  • Verification status: pass
  • Failure conditions encountered: None. All 357 tests pass successfully.

Risk Assessment

  • Risk summary: Low risk. Modifies only security proxy fallback cases and test files to be compliant with standard pytest monkeypatch patterns.
  • Files requiring human review: None.

Machine Metadata

agent: repository_maintenance_agent
branch: jules-13424727956599722460-58b60a7c
verification_status: pass
todo_quality_score: 100
knowledge_base_health_score: 100

PR created automatically by Jules for task 13424727956599722460 started by @MasumRab

Summary by Sourcery

Adjust proxy client IP extraction logic and align rate limiting behavior with trusted proxy configuration, updating tests to safely override proxy settings via pytest monkeypatch.

Bug Fixes:

  • Fix client IP extraction from X-Forwarded-For when trusted proxy count is zero or omitted, ensuring correct fallback to configured TRUSTED_PROXY_COUNT.
  • Correct rate limiting behavior so requests behind a trusted proxy are associated with the real client IP instead of an "unknown" placeholder.

Tests:

  • Update proxy and rate limiter tests to use pytest monkeypatch for TRUSTED_PROXY_COUNT configuration instead of relying on module-level state.
  • Adjust expectations in proxy-related tests to reflect the corrected client IP extraction and rate limiting behavior.

…tMiddleware tests

Refactored `extract_client_ip_from_forwarded` to evaluate `TRUSTED_PROXY_COUNT` dynamically at runtime rather than as a default function argument at import time, preventing issues where tests could not successfully `monkeypatch` the module global.

Additionally, corrected the trusted proxy check to allow `trusted_proxy_count >= 0` rather than `> 0`, so direct proxy simulations (where `TRUSTED_PROXY_COUNT=0` but X-Forwarded-For headers are present) resolve to the rightmost IP instead of falling through to the highly vulnerable leftmost spoofable IP.

Updated multiple `test_proxy_security.py` tests to properly apply `monkeypatch` on the module to control test states accurately. Tests were updated and assert successful operation of the middleware.
@google-labs-jules

Copy link
Copy Markdown
Author

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@trunk-io

trunk-io Bot commented Jun 25, 2026

Copy link
Copy Markdown

Merging to main in this repository is managed by Trunk.

  • To merge this pull request, check the box to the left or comment /trunk merge below.

After your PR is submitted to the merge queue, this comment will be automatically updated with its status. If the PR fails, failure details will also be posted here

@sourcery-ai

sourcery-ai Bot commented Jun 25, 2026

Copy link
Copy Markdown

Reviewer's Guide

Fixes client IP extraction logic in agent security to handle a trusted proxy count of zero correctly and makes the function easier to monkeypatch, while updating proxy-related tests to use pytest’s monkeypatch fixture and align expectations with the corrected behavior.

Flow diagram for updated extract_client_ip_from_forwarded proxy count handling

flowchart TD
    A["Call extract_client_ip_from_forwarded"] --> B{trusted_proxy_count is None}
    B -->|Yes| C["Set trusted_proxy_count = TRUSTED_PROXY_COUNT"]
    B -->|No| D["Use provided trusted_proxy_count"]
    C --> E["Parse forwarded into ips list"]
    D --> E
    E --> F{trusted_proxy_count >= 0}
    F -->|No| G["Fallback: return fallback_ip"]
    F -->|Yes| H["Compute idx = -(trusted_proxy_count + 1)"]
    H --> I{"abs(idx) <= len(ips)"}
    I -->|Yes| J["Return ips[idx] (supports trusted_proxy_count = 0)"]
    I -->|No| G
Loading

File-Level Changes

Change Details Files
Adjust client IP extraction from X-Forwarded-For to handle trusted proxy count defaults and zero-value correctly.
  • Change extract_client_ip_from_forwarded trusted_proxy_count parameter to accept None and resolve to TRUSTED_PROXY_COUNT at runtime for easier monkeypatching.
  • Add runtime defaulting of trusted_proxy_count when None to preserve existing configuration behavior.
  • Relax trusted_proxy_count boundary check from > 0 to >= 0 so that a zero trusted proxy count selects the last IP instead of falling back.
  • Clarify inline comments for index calculation when trusted_proxy_count is zero or positive.
backend/src/agent/security.py
Update proxy and rate-limiter tests to safely monkeypatch TRUSTED_PROXY_COUNT and match the fixed IP extraction behavior.
  • Inject pytest monkeypatch fixture into async and sync tests that rely on TRUSTED_PROXY_COUNT.
  • Use monkeypatch.setattr to override agent.security.TRUSTED_PROXY_COUNT in each test instead of relying on global state or import-time configuration.
  • Adjust expected stored client IP in rate limiter proxy logic test from "unknown" to "127.0.0.1" to reflect corrected sanitization and extraction.
  • Ensure all proxy security, rate-limiter, and API security tests validate behavior with explicit trusted proxy counts.
backend/tests/test_proxy_security.py
backend/tests/agent/test_rate_limiter_proxy.py
backend/tests/agent/test_api_security.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sonarqubecloud

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • In extract_client_ip_from_forwarded, consider explicitly validating that trusted_proxy_count is non-negative (or documenting behavior for negative values) before using it, so misconfigurations don't silently change IP extraction behavior.
  • In test_rate_limiter_proxy_logic, the assertion changed to expect "127.0.0.1" but the preceding comment still refers to sanitizing invalid IPs to "unknown"; update the comment to match the current behavior to avoid confusion.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `extract_client_ip_from_forwarded`, consider explicitly validating that `trusted_proxy_count` is non-negative (or documenting behavior for negative values) before using it, so misconfigurations don't silently change IP extraction behavior.
- In `test_rate_limiter_proxy_logic`, the assertion changed to expect `"127.0.0.1"` but the preceding comment still refers to sanitizing invalid IPs to `"unknown"`; update the comment to match the current behavior to avoid confusion.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Copy Markdown
Owner

Jules Session Analysis: This PR has merge conflicts. Recommended fix: git fetch origin && git rebase origin/main. Resolve conflicts and push. Let me know if you need help!

@google-labs-jules

Copy link
Copy Markdown
Author

Jules Session Analysis: This PR has merge conflicts. Recommended fix: git fetch origin && git rebase origin/main. Resolve conflicts and push. Let me know if you need help!

I have successfully merged origin/main into this branch, resolved the merge conflicts (specifically within the test files we updated during this session to correctly mock the globally evaluated proxy configuration parameters), and pushed the updated commits. All 359 tests are now passing successfully.

…tMiddleware tests

Refactored `extract_client_ip_from_forwarded` to evaluate `TRUSTED_PROXY_COUNT` dynamically at runtime rather than as a default function argument at import time, preventing issues where tests could not successfully `monkeypatch` the module global.

Additionally, corrected the trusted proxy check to allow `trusted_proxy_count >= 0` rather than `> 0`, so direct proxy simulations (where `TRUSTED_PROXY_COUNT=0` but X-Forwarded-For headers are present) resolve to the rightmost IP instead of falling through to the highly vulnerable leftmost spoofable IP.

Updated multiple `test_proxy_security.py` tests to properly apply `monkeypatch` on the module to control test states accurately. Resolved upstream merge conflicts and re-verified all tests pass.
@vercel

vercel Bot commented Jul 30, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
gemini-fullstack-langgraph-quickstart Ready Ready Preview Jul 30, 2026 6:17pm

@sonarqubecloud

Copy link
Copy Markdown

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.

1 participant