Skip to content

fix: per-request settings clone in bitbucket-server & azuredevops webhooks (#2345) - #2351

Merged
naorpeled merged 2 commits into
The-PR-Agent:mainfrom
alonz101:AlonZ/fix-repo-settings-state-leak
Aug 8, 2026
Merged

naorpeled merged 2 commits into
The-PR-Agent:mainfrom
alonz101:AlonZ/fix-repo-settings-state-leak

Conversation

@alonz101

@alonz101 alonz101 commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

User description

Summary

Fixes #2345 — apply_repo_settings() leaking .pr_agent.toml state across PRs from different repositories.

Root cause

global_settings is a module-level Dynaconf singleton. apply_repo_settings() mutates it without resetting between requests, so settings loaded for one repo persist into subsequent reviews of unrelated repos in the same long-lived webhook process.

Fix

5 of 7 webhook servers already isolate per-request settings with context["settings"] = copy.deepcopy(global_settings) (github_app, gitlab_webhook, gitea_app, bitbucket_app, gerrit_server). This PR aligns the last 2 (bitbucket_server_webhook, azuredevops_server_webhook) with that existing pattern. get_settings() already prefers context["settings"] over global_settings, so the per-request clone is sufficient.

Tests

tests/unittest/test_apply_repo_settings.py covers:

  • Repo settings get applied within a request
  • Repo A's [pr_reviewer] extra_instructions don't leak into a subsequent Repo B request that has no .pr_agent.toml
  • Repo A's unknown section (e.g. [my_custom_repo_section]) doesn't leak either

Test plan

  • PYTHONPATH=. .venv/bin/pytest tests/unittest/test_apply_repo_settings.py -v (3 passed)
  • PYTHONPATH=. .venv/bin/pytest tests/unittest -q (297 passed, no regressions)
  • pre-commit run --files <changed> (clean)

PR Type

Bug fix, Tests


Description

  • Fix .pr_agent.toml state leaking across PRs from different repositories

  • Add context["settings"] = copy.deepcopy(global_settings) per-request isolation to bitbucket_server_webhook and azuredevops_server_webhook handlers

  • Add regression tests covering settings isolation, unknown section leaks, and TOML application

  • Minor whitespace/formatting cleanup in both webhook server files


Diagram Walkthrough

flowchart LR
  A["Incoming Webhook Request"]
  B["bitbucket_server_webhook\nhandle_webhook()"]
  C["azuredevops_server_webhook\nhandle_webhook()"]
  D["context['settings'] =\ncopy.deepcopy(global_settings)"]
  E["apply_repo_settings()\nmutates context['settings']"]
  F["global_settings\n(module-level singleton)\nremains clean"]
  G["Next request gets\nfresh settings clone"]

  A -- "POST /webhook" --> B
  A -- "POST /" --> C
  B -- "per-request clone" --> D
  C -- "per-request clone" --> D
  D -- "isolated mutation" --> E
  F -- "deep copy source" --> D
  E -- "request ends" --> F
  F -- "next request" --> G
Loading

File Walkthrough

Relevant files
Bug fix
azuredevops_server_webhook.py
Add per-request settings clone to Azure DevOps webhook handler

pr_agent/servers/azuredevops_server_webhook.py

  • Added import copy and imported context from starlette_context and
    global_settings from config_loader
  • Added context["settings"] = copy.deepcopy(global_settings) at the
    start of handle_webhook() to isolate per-request settings
  • Minor whitespace cleanup (trailing spaces removed in several
    functions)
+7/-4     
bitbucket_server_webhook.py
Add per-request settings clone to Bitbucket Server webhook handler

pr_agent/servers/bitbucket_server_webhook.py

  • Added import copy and imported context from starlette_context and
    global_settings from config_loader
  • Added context["settings"] = copy.deepcopy(global_settings) at the
    start of handle_webhook() to isolate per-request settings
  • Minor whitespace cleanup (trailing spaces removed in several
    functions)
  • Reformatted a long import line for BitbucketServerProvider
+12/-8   
Tests
test_apply_repo_settings.py
Add regression tests for cross-repo settings isolation     

tests/unittest/test_apply_repo_settings.py

  • New test file with FakeGitProvider stub and fresh_global_settings
    fixture
  • test_repo_settings_from_toml_are_applied: verifies TOML settings are
    applied within a request context
  • test_repo_without_toml_does_not_inherit_previous_repo_settings:
    verifies repo A's settings don't leak into repo B with no
    .pr_agent.toml
  • test_unknown_section_does_not_leak_to_next_repo: verifies
    custom/unknown TOML sections don't persist across requests
+121/-0 

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

qodo-free-for-open-source-projects Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Fix settings state leak by cloning per-request settings in ADO/Bitbucket webhooks

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Prevent .pr_agent.toml settings from leaking across repos in long-lived webhook servers
• Clone global_settings into context["settings"] per request for Bitbucket Server and Azure
 DevOps Server
• Add regression tests covering known and unknown repo TOML sections
Diagram

graph TD
  ADO["Azure DevOps Server webhook"] --> CTX["starlette_context (request)"] --> GS["get_settings()"] --> ARS["apply_repo_settings()"]
  BB["Bitbucket Server webhook"] --> CTX
  GLOB[("global_settings singleton")] --> ADO
  GLOB --> BB
  ARS --> CTX
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Centralize settings cloning in middleware
  • ➕ Eliminates the risk of forgetting to clone in future webhook servers/routes
  • ➕ Keeps request lifecycle concerns in one place
  • ➖ Requires careful ordering with other middleware that may read settings
  • ➖ Slightly broader refactor than the current targeted fix
2. Make apply_repo_settings() pure (return a new settings object)
  • ➕ Avoids mutation-based state leaks by design
  • ➕ Easier to reason about and test without context globals
  • ➖ Larger refactor touching many call sites expecting implicit global behavior
  • ➖ Potential compatibility risk with existing settings access patterns
3. Reset global_settings after each request
  • ➕ Avoids needing per-request cloning at each entrypoint
  • ➕ Keeps current APIs mostly intact
  • ➖ Hard to guarantee cleanup on exceptions/background tasks
  • ➖ Still couples correctness to request teardown behavior

Recommendation: The chosen approach (per-request deepcopy into context[&#x27;settings&#x27;]) is the best near-term fix: it matches the existing pattern used by other servers, is minimally invasive, and leverages get_settings() already preferring the request-scoped settings. If this issue has recurred across servers, consider a follow-up to move the clone into a shared middleware/util to make it impossible to miss in new handlers.

Files changed (3) +140 / -12

Bug fix (2) +19 / -12
azuredevops_server_webhook.pySeed per-request settings clone for Azure DevOps Server webhooks +7/-4

Seed per-request settings clone for Azure DevOps Server webhooks

• Imports 'copy' and 'context', and sets 'context['settings'] = deepcopy(global_settings)' at the start of webhook handling. This prevents '.pr_agent.toml' settings loaded for one repo from persisting into subsequent requests handled by the same long-lived process.

pr_agent/servers/azuredevops_server_webhook.py

bitbucket_server_webhook.pySeed per-request settings clone for Bitbucket Server webhooks +12/-8

Seed per-request settings clone for Bitbucket Server webhooks

• Adds per-request settings isolation by cloning 'global_settings' into 'starlette_context' before reading other settings and applying repo TOML. Includes minor formatting adjustments without behavioral impact beyond the settings scoping fix.

pr_agent/servers/bitbucket_server_webhook.py

Tests (1) +121 / -0
test_apply_repo_settings.pyAdd regression tests for cross-repo settings leakage +121/-0

Add regression tests for cross-repo settings leakage

• Introduces unit tests that simulate two sequential request contexts to ensure repo A settings do not leak into repo B when repo B has no '.pr_agent.toml'. Also validates that unknown TOML sections introduced by a repo are confined to the request-scoped settings clone.

tests/unittest/test_apply_repo_settings.py

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

qodo-free-for-open-source-projects Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

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

Grey Divider


Remediation recommended

1. Clone before signature check 🐞 Bug ➹ Performance
Description
In bitbucket_server_webhook.handle_webhook(), the code deep-copies the full Dynaconf settings into
request context before verifying the webhook signature, so even requests that will be rejected incur
the deepcopy overhead. This introduces avoidable CPU/memory work on unauthenticated traffic and can
amplify resource pressure under load.
Code

pr_agent/servers/bitbucket_server_webhook.py[R134-137]

async def handle_webhook(background_tasks: BackgroundTasks, request: Request):
  log_context = {"server_type": "bitbucket_server"}
  data = await request.json()
+    context["settings"] = copy.deepcopy(global_settings)
Evidence
The Bitbucket Server webhook handler clones settings immediately after parsing JSON and before
reading/verifying the signature; since get_settings() returns context["settings"] when present,
the expensive clone can be deferred until after signature verification while preserving request
isolation for subsequent apply_repo_settings() calls.

pr_agent/servers/bitbucket_server_webhook.py[133-149]
pr_agent/config_loader.py[47-60]

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

## Issue description
`context["settings"] = copy.deepcopy(global_settings)` is executed before the optional Bitbucket Server webhook signature verification. This means invalid/unauthenticated requests still pay the full settings clone cost.
## Issue Context
`get_settings()` prefers `context["settings"]`, so the clone should still be created before any code path that mutates settings (e.g., `apply_repo_settings(pr_url)`), but it can be deferred until after signature verification and the connection-test early return.
## Fix Focus Areas
- pr_agent/servers/bitbucket_server_webhook.py[134-149]

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


Grey Divider

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

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Previous review results

Review updated until commit 981e2a3 ⚖️ Balanced

Results up to commit c4e868c


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


Remediation recommended
1. Clone before signature check 🐞 Bug ➹ Performance
Description
In bitbucket_server_webhook.handle_webhook(), the code deep-copies the full Dynaconf settings into
request context before verifying the webhook signature, so even requests that will be rejected incur
the deepcopy overhead. This introduces avoidable CPU/memory work on unauthenticated traffic and can
amplify resource pressure under load.
Code

pr_agent/servers/bitbucket_server_webhook.py[R134-137]

async def handle_webhook(background_tasks: BackgroundTasks, request: Request):
   log_context = {"server_type": "bitbucket_server"}
   data = await request.json()
+    context["settings"] = copy.deepcopy(global_settings)
Evidence
The Bitbucket Server webhook handler clones settings immediately after parsing JSON and before
reading/verifying the signature; since get_settings() returns context["settings"] when present,
the expensive clone can be deferred until after signature verification while preserving request
isolation for subsequent apply_repo_settings() calls.

pr_agent/servers/bitbucket_server_webhook.py[133-149]
pr_agent/config_loader.py[47-60]

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

## Issue description
`context["settings"] = copy.deepcopy(global_settings)` is executed before the optional Bitbucket Server webhook signature verification. This means invalid/unauthenticated requests still pay the full settings clone cost.
## Issue Context
`get_settings()` prefers `context["settings"]`, so the clone should still be created before any code path that mutates settings (e.g., `apply_repo_settings(pr_url)`), but it can be deferred until after signature verification and the connection-test early return.
## Fix Focus Areas
- pr_agent/servers/bitbucket_server_webhook.py[134-149]

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


Context used
Results up to commit fc8ab42


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


Remediation recommended
1. Clone before signature check 🐞 Bug ➹ Performance
Description
In bitbucket_server_webhook.handle_webhook(), the code deep-copies the full Dynaconf settings into
request context before verifying the webhook signature, so even requests that will be rejected incur
the deepcopy overhead. This introduces avoidable CPU/memory work on unauthenticated traffic and can
amplify resource pressure under load.
Code

pr_agent/servers/bitbucket_server_webhook.py[R134-137]

async def handle_webhook(background_tasks: BackgroundTasks, request: Request):
    log_context = {"server_type": "bitbucket_server"}
    data = await request.json()
+    context["settings"] = copy.deepcopy(global_settings)
Evidence
The Bitbucket Server webhook handler clones settings immediately after parsing JSON and before
reading/verifying the signature; since get_settings() returns context["settings"] when present,
the expensive clone can be deferred until after signature verification while preserving request
isolation for subsequent apply_repo_settings() calls.

pr_agent/servers/bitbucket_server_webhook.py[133-149]
pr_agent/config_loader.py[47-60]

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

## Issue description
`context["settings"] = copy.deepcopy(global_settings)` is executed before the optional Bitbucket Server webhook signature verification. This means invalid/unauthenticated requests still pay the full settings clone cost.

## Issue Context
`get_settings()` prefers `context["settings"]`, so the clone should still be created before any code path that mutates settings (e.g., `apply_repo_settings(pr_url)`), but it can be deferred until after signature verification and the connection-test early return.

## Fix Focus Areas
- pr_agent/servers/bitbucket_server_webhook.py[134-149]

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


Context used
Results up to commit fc8ab42


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Great, no issues found!

Qodo reviewed your code and found no material issues that require review
Qodo Logo

@alonz101

Copy link
Copy Markdown
Contributor Author

PR Description updated to latest commit (fc8ab42)

@alonz101

Copy link
Copy Markdown
Contributor Author

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2345 - Partially compliant

Compliant requirements:

  • apply_repo_settings() no longer leaks state across repos — per-request clone isolates mutations
  • Settings from repo A do not persist when repo B has no .pr_agent.toml
  • Unknown/custom sections from one repo do not leak to the next repo
  • bitbucket_server_webhook and azuredevops_server_webhook now set context["settings"] = copy.deepcopy(global_settings) per request, matching the other 5 webhook servers
  • Regression tests covering all three scenarios are added
  • Full existing unit test suite passes (297 passed per PR description)

Non-compliant requirements:

  • Per-section merge carrying over stale keys when repo B does have a .pr_agent.toml (partial overlap case) is not explicitly tested or addressed — the fix only isolates via the per-request clone, which handles the empty-toml case but the partial-overlap scenario within a single request is still present in apply_repo_settings() logic itself

Requires further human verification:

  • Confirm that the other 5 webhook servers (github_app, gitlab_webhook, gitea_app, bitbucket_app, gerrit_server) already set context["settings"] before apply_repo_settings() is called, so no similar leak exists there
  • Verify that background tasks dispatched via background_tasks.add_task(...) correctly inherit the context["settings"] set before the task is enqueued (starlette-context behavior with BackgroundTasks)
⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Context not propagated to BackgroundTask

context["settings"] is set in the request handler, but the actual work is dispatched via background_tasks.add_task(handle_request_azure, data, log_context). Starlette's BackgroundTasks run after the response is sent and outside the request context, so starlette_context's context object (which is request-scoped) may not be accessible in the background task. If the context is not available, get_settings() will fall back to global_settings, defeating the isolation. The same pattern exists in bitbucket_server_webhook.py. This should be verified against how the other 5 webhook servers handle this (they may pass the cloned settings explicitly or use a different dispatch mechanism).

context["settings"] = copy.deepcopy(global_settings)
# get_logger().info(json.dumps(data))

background_tasks.add_task(handle_request_azure, data, log_context)
Context not propagated to BackgroundTask

Same issue as in azuredevops_server_webhook.py: context["settings"] is set before background_tasks.add_task(...) is called, but background tasks in Starlette run outside the request lifecycle. If starlette_context does not propagate the context to background tasks, the per-request clone will not be visible inside the task, and get_settings() will fall back to the shared global_settings singleton — leaving the state-leak bug unfixed at runtime despite the tests passing (tests use request_cycle_context which does propagate correctly).

context["settings"] = copy.deepcopy(global_settings)
get_logger().info(json.dumps(data))

webhook_secret = get_settings().get("BITBUCKET_SERVER.WEBHOOK_SECRET", None)

@alonz101

alonz101 commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor Author

PR Code Suggestions ✨

CategorySuggestion                                                                                                                                    Impact
Possible issue
Pass settings clone explicitly to background task

The context["settings"] is set in the request handler but the actual processing
happens in a background task. Since starlette_context is request-scoped, the context
(and thus the settings clone) may not be available when the background task runs
after the request completes. The deep copy of settings should be passed explicitly
as a parameter to the background task function to ensure isolation.

pr_agent/servers/azuredevops_server_webhook.py [180]

-background_tasks.add_task(handle_request_azure, data, log_context)
+settings_copy = copy.deepcopy(global_settings)
+context["settings"] = settings_copy
+background_tasks.add_task(handle_request_azure, data, log_context, settings_copy)
Suggestion importance[1-10]: 7

__

Why: This is a valid concern: starlette_context is request-scoped and may not persist into background tasks after the request completes. Passing the settings_copy explicitly to handle_request_azure would ensure the settings are available during background processing. However, the improved_code changes the function signature of handle_request_azure which isn't shown in the diff, and the actual behavior depends on how starlette_context handles background tasks in this specific setup.

Medium

@alonz101

Copy link
Copy Markdown
Contributor Author

Looked into the BackgroundTask concern — false positive

The auto /review worried that context["settings"] might not survive into background_tasks.add_task(...)
because Starlette runs background tasks "after the response." Tested it with the same pattern this PR uses:

@app.post("/webhook")                             
async def handle_webhook(background_tasks: BackgroundTasks, request: Request):
    data = await request.json()                                                                                 
    context["settings"] = f"clone-for-{data['repo']}"
    background_tasks.add_task(check, data["repo"])                                                              
                                                                                                                
Two sequential requests:                          
request 'A' → context['settings'] = 'clone-for-A'  ✅                                                           
request 'B' → context['settings'] = 'clone-for-B'  ✅
                                                     
starlette_context uses a ContextVar and the middleware wraps the request with with request_cycle_context(...).  
Starlette's BackgroundTask is awaited inside Response.__call__, before the middleware's with block exits — so   
background tasks see the per-request clone, not the global singleton. Same reason the 5 existing webhook servers
 using this pattern work fine.  

No code change needed.

@tomaszharatynowiczABS

Copy link
Copy Markdown

Hey @alonz101 — just flagging that #2346 also targets issue #2345, but at the config-loader layer rather than per-webhook. Different trade-off:

Posting on both so maintainers see the full picture and can pick whichever shape fits the project better. No competitive intent — leak is annoying either way it gets fixed.

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

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit fc8ab42

…hooks (The-PR-Agent#2345)

apply_repo_settings() mutates the module-level global_settings singleton.
In long-lived webhook servers, .pr_agent.toml from a previously-reviewed
repo leaked into PRs from other repos. 5 of 7 servers already cloned
global_settings into context["settings"] per request - this aligns the
last 2.

Adds regression tests including the unknown-section case.
@naorpeled
naorpeled force-pushed the AlonZ/fix-repo-settings-state-leak branch from fc8ab42 to c4e868c Compare August 8, 2026 17:14
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit c4e868c

Address Qodo review on The-PR-Agent#2351: move the per-request context['settings'] clone
below the webhook signature verification and connection-test early return, so
rejected/unauthenticated requests don't pay the deepcopy cost. The clone still
precedes apply_repo_settings() (which mutates get_settings()), preserving
per-request isolation. Azure DevOps already gates auth via a route dependency,
so its clone is already post-auth and unchanged.

Co-authored-by: alonz101 <alonz101@users.noreply.github.com>
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 981e2a3

@naorpeled
naorpeled merged commit 89cb6dd into The-PR-Agent:main Aug 8, 2026
4 checks passed
@naorpeled

Copy link
Copy Markdown
Member

Thanks @alonz101 !!

naorpeled added a commit to tharatynowicz/pr-agent that referenced this pull request Aug 8, 2026
…nt#2345)

Complements the per-request settings clone merged in The-PR-Agent#2351. That fix isolates
every webhook server; this one covers callers that run many PRs in one process
WITHOUT a per-request clone — notably github_polling — where a previous repo's
.pr_agent.toml would otherwise persist in the shared global_settings when the
next repo has no config file (the loader early-exits on empty repo settings).

Approach: note_repo_setting_override() records the pre-override value of each
key a repo/extra .pr_agent.toml writes; reset_repo_settings_overrides(), called
at the top of apply_repo_settings(), reverts exactly those keys. Only
repo-settings-managed keys are touched, so runtime/base config set outside the
merge (config.extra_config_url, config.is_auto_command, ...) is preserved.

Details:
- Record/revert go through get_settings(), so a per-request context['settings']
  clone is handled as well as global_settings.
- Revert rebuilds each affected section once: Dynaconf's unset() cannot drop a
  nested key, and the rebuild preserves sibling keys not in the ledger.
- set_claude_model() also rewrites config.model_weak / config.fallback_models;
  those are recorded too so the claude shorthand doesn't leak derived keys.
- Record/revert are guarded by an RLock.

Tests: tests/unittest/test_apply_repo_settings.py keeps the clone-based cases
from The-PR-Agent#2351 and adds a class covering the no-clone path: leak reverted, runtime
flags preserved, non-repo config preserved, revert targets the effective
settings object, and no claude-shorthand model-key leak. Full unit suite: 1732
passed.

Co-authored-by: Tomasz Haratynowicz <75249676+tharatynowicz@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

apply_repo_settings() leaks .pr_agent.toml state across PRs from different repositories

3 participants