← Back to Pull requests

fix(python): resolve and pin webhook endpoints against SSRF #4376

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Oct 20, 2026 08:28 UTC
Author

Related Issue


Part of #3516. The issue stays open until every language is fixed; this PR covers the two Python packages that send webhooks (agent-mesh and agent-os).

Problem & Solution


Problem: The .NET WebhookApprover (#3363) already resolves the endpoint host at request time, rejects any record in a blocked range, pins the socket to the validated address through ConnectCallback, and disables proxies. The Python senders did not. HttpAdvisory, VersionedWebhookApproval and the deprecated WebhookApproval in agent-mesh checked the host against three literal strings once, at construction, then handed the URL to the default urllib opener, which resolves the name itself, follows redirects and honours proxy variables. WebhookNotifier and WebhookApprovalBackend in agent-os had no URL check at all. On main, _validate_webhook_url accepts http://127.0.0.1/, localhost, 127.0.0.1.nip.io, [fd00:ec2::254] (the bracketed entry never matches because urlparse strips the brackets), 169.254.169.254. (trailing dot) and 2130706433 (decimal IPv4). A DNS answer that changes between validation and connect also reaches the internal destination.

Solution: Add WebhookEndpointGuard to both packages, mirroring the .NET fix.

  • At construction it rejects non-http(s) schemes, blocked host names and their subdomains (localhost, metadata.google and its .internal form, case and trailing-dot normalised), and literal addresses in loopback, private, link-local, shared, multicast, reserved, benchmark and documentation ranges for IPv4 and IPv6. IPv4-mapped and IPv4-compatible forms are unwrapped. inet_aton spellings (decimal, hex, short forms) are parsed with getaddrinfo(AI_NUMERICHOST), which never touches DNS.

  • At connect time it resolves the host itself, refuses the request when any record is internal, and opens the socket to the validated address. The client never resolves the name a second time, so rebinding between validation and connect cannot steer the request. TLS still verifies the certificate against the host name.

  • The opener carries no redirect, proxy or file handler: a 3xx is an error, proxy variables are ignored, only http and https work.

  • Operators who need an internal receiver pass endpoint_guard=WebhookEndpointGuard.allowing(["10.0.0.0/8"]). The default allows nothing internal. The resolver is injectable so tests run without network.
  • The guard is wired into HttpAdvisory, VersionedWebhookApproval and WebhookApproval (agent-mesh) and WebhookNotifier and WebhookApprovalBackend (agent-os). The module ships in both packages because neither can import the other's development checkout; a test in each keeps the two copies identical.

    Behaviour change to note: constructing any of these five classes with a loopback or private URL now raises ValueError. Local-development setups that post to 127.0.0.1 must pass endpoint_guard=WebhookEndpointGuard.allowing([...]). Both package CHANGELOGs record this.

    Impact on Your Work


    Closes the Python half of a cross-SDK SSRF gap. A governance deployment that accepts an approval or advisory webhook URL from configuration could be steered to loopback, RFC1918 or cloud-metadata addresses through a rebinding host name, a redirect, or an unusual address spelling, and the approval flow would then produce an ALLOW from an attacker-reachable receiver. After this change the Python packages hold the same line as .NET.

    Timeline


    None

    Alternatives Considered


  • Extend the existing literal-string check with more strings. Rejected: it cannot cover DNS rebinding, redirects or proxy routing, which are the exploited paths.

  • Validate once at request time and let urllib connect. Rejected: the client resolves the name again, so a rebinding name still wins the race. Pinning the validated address is the only way to close it.

  • Put the guard in agent-governance-toolkit-core and import it from both packages. Rejected for this PR: neither package can import the other's development checkout today, and pip install -e .[dev] on main is unresolvable (agentmesh-platform[dev] pins agentrust-trace<0.6 while core 5.0.0 pins <0.3), so a shared dependency would block the fix. A test in each package asserts the two copies stay byte-identical; moving to a shared module can follow once the dependency pins are untangled.
  • Type of Change


  • Bug fix (non-breaking change that fixes an issue)

  • New feature (non-breaking change that adds functionality)

  • Breaking change (fix or feature that would cause existing functionality to change)

  • Documentation update

  • Maintenance (dependency updates, CI/CD, refactoring)

  • Security fix
  • Package(s) Affected


    Core & runtime:
  • agent-governance-toolkit-core

  • agent-primitives

  • agent-os

  • agent-mesh

  • agent-runtime

  • agent-sre

  • agent-compliance
  • Governance & security:

  • agent-mcp-governance

  • agent-rag-governance

  • agent-sandbox

  • agent-discovery

  • agt-policies

  • policy-engine
  • Platform & tooling:

  • agent-hypervisor

  • agent-lightning

  • agent-marketplace

  • agent-governance-toolkit-cli

  • agent-governance-toolkit-integrations

  • agent-governance-toolkit-protocols

  • agentmesh-integrations (framework integrations)
  • CLI plugins:

  • agent-governance CLI plugins (copilot-cli / claude-code / opencode / antigravity-cli)
  • Shared / other:

  • schemas

  • action (GitHub Action)

  • examples

  • docs / root (.cspell-repo-terms.txt)
  • Testing

    Unit Testing


    New files:
  • agent-governance-python/agent-mesh/tests/test_webhook_guard.py: 110 tests.

  • agent-governance-python/agent-os/tests/test_webhook_guard.py: 53 tests.
  • They cover each attack case with injected DNS answers (loopback, private, link-local, metadata, IPv4-mapped IPv6, decimal and hex IPv4, localhost, trailing dot, bracketed IPv6, subdomains of blocked names), a loopback server that proves the socket is pinned to the validated address and that a 3xx is refused, a patched connect that records the pinned target for the rebinding case, proxy-variable ignoring, scheme rejection, the allowing([...]) escape hatch, and a byte-identity check between the two package copies.

    Adjusted existing tests: agent-mesh test_advisory.py and test_approval_strict.py (tests that post to 127.0.0.1:1 now allow-list that address; tests that mocked urllib.request.urlopen mock the guard instead); agent-os test_webhooks.py (same adjustment).

    Against main's source both new files fail at collection with ImportError: cannot import name 'webhook_guard', and main's _validate_webhook_url accepts http://127.0.0.1/, localhost, 127.0.0.1.nip.io, [fd00:ec2::254], 169.254.169.254. and 2130706433.

    Manual Testing


    Environment: Python 3.12.3, pytest 9.1.1, PYTHONPATH=src. pip install -e .[dev] is unresolvable on main today (agentmesh-platform[dev] pins agentrust-trace<0.6; agent-governance-toolkit-core 5.0.0 pins <0.3), so venvs were built with uv venv plus --no-deps and the test dependencies.

    New and touched suites on the branch:

    cd agent-governance-python/agent-mesh
    PYTHONPATH=src pytest tests/test_webhook_guard.py                       # 110 passed
    PYTHONPATH=src pytest tests/test_advisory.py tests/test_approval.py tests/test_approval_webhook.py \
      tests/test_transport_wiring.py tests/test_approval_strict.py tests/test_approval_bridge.py   # 104 passed
    cd ../agent-os
    PYTHONPATH=src pytest tests/test_webhook_guard.py                       # 53 passed
    PYTHONPATH=src pytest tests/test_webhooks.py tests/test_escalation.py \
      tests/test_escalation_and_reversibility.py                             # 62 passed
    

    Full suites, same venv, main vs branch:

  • agent-mesh: 45 failed / 3973 passed on main vs 45 failed / 4163 passed on branch. Identical failure set (otel, websockets, trace_sink, server PermissionError: missing optional dependencies and subprocess spawn in the sandbox).

  • agent-os: 26 failed + 15 collection errors / 2739 passed on main vs 26 failed + 15 errors / 2794 passed on branch. Identical set (agent_control_specification Rust SDK not built, redis, subprocess sandbox, CLI validate).
  • An independent second pass rebuilt the environments (agent-os with the native ACS SDK built with maturin, as CI does) and re-ran on a detached origin/main worktree and on the branch:

  • main with the new test files copied in: both test_webhook_guard.py files fail at collection with ImportError.

  • branch, agent-mesh: test_webhook_guard.py + test_advisory.py + test_approval_strict.py: 175 passed. Full tests/: 2 failed, 4618 passed, 81 skipped. The 2 failures are tests/test_server.py::TestMainModule::test_unknown_component_exits and ::test_no_args_exits (PermissionError: [Errno 13] Permission denied: 'python', subprocess spawn in the sandbox), reproduced identically on origin/main.

  • branch, agent-os: test_webhook_guard.py + test_webhooks.py: 73 passed. Full tests/: 3 failed, 3327 passed, 57 skipped. The 3 failures are tests/test_new_features_batch2.py::TestSandboxProvider::test_subprocess_echo/_timeout/_failure, same subprocess sandbox issue, reproduced identically on origin/main.
  • Lint and checks:

    ruff check src/ --select E,F,W --ignore E501     # clean for both packages and both new test files
    python3 scripts/check_license_headers.py          # all 4 new .py files carry the header; same 42 pre-existing lines flagged on main and branch, no new misses
    python3 -I scripts/ci/changed_lines.py --base origin/main --extensions ".md,.txt,.rst,.py,.ts,.js,.go,.rs,.cs,.yml,.yaml" --mode added-lines --output ci-diff/added.txt   # 1791 added lines
    npx --yes cspell@8.17.3 --config .cspell.json --no-progress ci-diff/added.txt   # Issues found: 0
    

    Eight terms added to .cspell-repo-terms.txt in sorted position: setsockopt, functools, gaierror, getaddrinfo, getproxies, IPPROTO, NODELAY, NUMERICHOST.

    Checklist


  • I have linked a related issue above, or completed "Problem & Solution", "Impact on Your Work", and "Alternatives Considered"

  • My code follows the project style guidelines (ruff check)

  • I have added tests that prove my fix/feature works

  • All new and existing tests pass (pytest)

  • I have updated documentation as needed

  • I have signed the Microsoft CLA
  • Attribution & Prior Art


  • This contribution does not contain code copied or derived from other projects without attribution

  • Any external projects that inspired this design are credited in code comments or documentation

  • If this PR implements functionality similar to an existing open-source project, I have listed it below
  • Prior art / related projects (if any):
    The design mirrors this repository's own .NET WebhookApprover (#3363): request-time resolution, deny-set check on every record, pinned connect, no proxy.

    AI Assistance


  • I can explain every meaningful change in this PR: what it does, why, and what tradeoffs were considered

  • I have run tests and verification appropriate for this change

  • No part of this PR was autonomously submitted by an AI agent without my review

  • I have not used AI to generate review comments on others' PRs
  • If AI tools materially shaped this change, briefly note what was used:
    Claude Code drafted the fix and tests under my direction; an independent verification pass re-ran the tests on main and on the branch and probed bypasses, and I reviewed the result.

    IP, Patents, and Licensing


  • This contribution does not implement patent-pending or patent-encumbered techniques

  • This contribution does not require an NDA or licensing agreement to understand or use

  • Any AI tools used have terms compatible with the MIT License
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: prayagupa Review duration: 48201m
    All Vouch review confidence checks passed
    Residual risk 0.33 = Change Risk (0.59) × (1 − Review Confidence (0.45)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.59 · 650 lines diff across 8 files
    0.59
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    44%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #4376"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 44.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 59% (MEDIUM) · Higher = larger blast radius
    59%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 44.7% · Lower = rushed or shallow review
    44.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 32.6% · Safe to merge
    32.6%