Skip to content

fix: return 401 instead of 500 for an unauthenticated Azure DevOps webhook - #2703

Merged
IsmaelMartinez merged 4 commits into
The-PR-Agent:mainfrom
dwin-gharibi:fix/azure-webhook-missing-credentials
Aug 20, 2026
Merged

IsmaelMartinez merged 4 commits into
The-PR-Agent:mainfrom
dwin-gharibi:fix/azure-webhook-missing-credentials

Conversation

@dwin-gharibi

Copy link
Copy Markdown
Contributor

Closes #2702.

Description

Requests with no Authorization header produce an unhandled AttributeError and a 500, with no WWW-Authenticate challenge and a stack trace in the logs.

Root cause

security = HTTPBasic(auto_error=False) (pr_agent/servers/azuredevops_server_webhook.py:33) suppresses FastAPI's own 401, so credentials is None when the header is absent and credentials.username raises at line 86.

This is not an authentication bypass — the request is still rejected, it just fails with the wrong status and no challenge header.

The fix

Reject a None credentials object with the same 401 the wrong-password branch already returns.

Behaviour change

Before no Authorization header → 500, WWW-Authenticate: None
After no Authorization header → 401, WWW-Authenticate: 'Basic'; correct and wrong credentials behave exactly as before (200 / 401)

Verified against the real authorize dependency through a FastAPI TestClient.

Files changed

pr_agent/servers/azuredevops_server_webhook.py | 7 +++++++
 1 file changed, 7 insertions(+)

Testing

  • pytest tests/unittest — 1748 passed, 1 skipped, 1 xfailed (unchanged from main)
  • CI pipeline reproduced locally exactly as .github/workflows/build-and-test.yaml runs it:
    docker build -f docker/Dockerfile --target test .
    docker run --rm <image> pytest -v tests/unittest
    
    → 1748 passed, 1 skipped, 1 xfailed on python:3.12.13-slim
  • Targeted regression check for this defect: reproduced on main, no longer reproducible on this branch
  • ruff — no new findings vs main; isort — clean

Risk / compatibility

No change to accepted or rejected credentials — only to the unauthenticated case's status code.

Checklist

  • Focused on a single fix
  • Existing tests pass
  • No new dependencies
  • No user-facing configuration changes
  • Reviewed by a maintainer

Copilot AI lite review requested due to automatic review settings August 17, 2026 17:31

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@qodo-code-review

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Fix Azure DevOps webhook unauthenticated requests to return 401

🐞 Bug fix 🕐 10-20 Minutes

Grey Divider

AI Description

• Return 401 + Basic challenge when Azure DevOps webhook lacks an Authorization header.
• Prevent AttributeError by explicitly rejecting missing HTTPBasic credentials.
• Preserve existing behavior for correct vs incorrect credentials.
Diagram

graph TD
ADO{{"Azure DevOps"}} --> API["FastAPI webhook endpoint"] --> AUTH["authorize() dependency"] --> DEC{"Credentials present?"}
DEC -->|"no"| R401["401 + WWW-Authenticate: Basic"]
DEC -->|"yes"| CHECK["Validate username/password"] --> OK["Handle webhook"] --> AGENT["PRAgent processing"]
CHECK -->|"invalid"| R401
subgraph Legend
direction LR
_ext{{"External"}} ~~~ _api["API/Component"] ~~~ _dec{"Decision"}
end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use HTTPBasic(auto_error=True) and rely on FastAPI’s built-in 401
  • ➕ FastAPI automatically emits a standard 401 challenge when the header is missing
  • ➕ Less custom branching inside authorize()
  • ➖ Conflicts with the current design that keeps auth optional when webhook credentials aren’t configured
  • ➖ Would require conditional wiring (different dependency) to preserve current behavior when WEBHOOK_* are unset
2. Custom authentication dependency (no HTTPBasic)
  • ➕ Full control over parsing headers and consistent error responses across providers
  • ➖ More code and more security-sensitive parsing logic to maintain
  • ➖ Harder to keep aligned with framework behavior and best practices

Recommendation: The chosen fix (explicitly rejecting credentials=None when webhook credentials are configured) is the best trade-off: it preserves the existing “auth optional if not configured” behavior while restoring correct 401 + WWW-Authenticate semantics and avoiding unhandled exceptions.

Files changed (1) +7 / -0

Bug fix (1) +7 / -0
azuredevops_server_webhook.pyHandle missing Basic auth credentials with a proper 401 challenge +7/-0

Handle missing Basic auth credentials with a proper 401 challenge

• Adds an explicit guard for the case where HTTPBasic returns None credentials (missing Authorization header). When webhook credentials are configured, the server now raises a 401 with a WWW-Authenticate: Basic header instead of crashing with an AttributeError.

pr_agent/servers/azuredevops_server_webhook.py

@dwin-gharibi

Copy link
Copy Markdown
Contributor Author

@naorpeled

@dwin-gharibi
dwin-gharibi force-pushed the fix/azure-webhook-missing-credentials branch from 512d7c8 to d9dce47 Compare August 19, 2026 11:49
@github-actions github-actions Bot added the bug label Aug 19, 2026
@qodo-code-review

qodo-code-review Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. authorize uses single quotes ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The added detail and headers string literals use single quotes instead of the required double
quotes.
Code

pr_agent/servers/azuredevops_server_webhook.py[R89-90]

+            detail='Missing credentials.',
+            headers={'WWW-Authenticate': 'Basic'},
Relevance

●●● Strong

Recent accepted quote-style fixes outweigh one rejected broad style suggestion.

PR-#2584
PR-#2406
PR-#2598

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694657 requires double quotes for Python string literals. The added exception
fields use 'Missing credentials.', 'WWW-Authenticate', and 'Basic'.

Rule 2694657: Use double quotes for all Python string literals
pr_agent/servers/azuredevops_server_webhook.py[89-90]

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 newly added Python string literals use single quotes, contrary to the required quoting convention.

## Issue Context
Change `detail`, `WWW-Authenticate`, and `Basic` to double-quoted literals without altering behavior.

## Fix Focus Areas
- pr_agent/servers/azuredevops_server_webhook.py[89-90]

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



Informational

2. Test docstring lacks imperative phrasing ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The new test docstring begins with the descriptive phrase HTTPBasic(auto_error=False) yields
rather than an imperative verb.
Code

tests/unittest/test_azure_devops_webhook_auth.py[R25-26]

+    """HTTPBasic(auto_error=False) yields None when the header is absent, so the
+    dependency must reject it rather than dereference None and return a 500."""
Relevance

● Weak

Recent test docstring imperative-style request was explicitly rejected.

PR-#2661

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 2694688 requires new function docstrings to begin in imperative mood. This
docstring instead starts with a declarative description of HTTPBasic behavior.

Rule 2694688: Docstrings and comments must use imperative phrasing
tests/unittest/test_azure_devops_webhook_auth.py[25-26]

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 function docstring uses descriptive phrasing instead of the required imperative mood.

## Issue Context
Rewrite the opening so it begins with an imperative verb while preserving the explanation of the regression scenario.

## Fix Focus Areas
- tests/unittest/test_azure_devops_webhook_auth.py[25-26]

ⓘ 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): 34 rules
Review mode: ⏭️ Skipped: The latest push only changes quote style and rewords a test docstring; it has no semantic or behavioral effect.

Grey Divider

Tip of the day
💡 Did you know, you can copy the agent prompt from any finding and feed it to your IDE agent

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown
Contributor

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

@IsmaelMartinez IsmaelMartinez self-assigned this Aug 20, 2026
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.

An unauthenticated webhook request returns 500 instead of 401

3 participants