Repository navigation
fix(guardrails): route custom-code http_request() through SSRF validation #32870
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
138 changes: 138 additions & 0 deletions
138
tests/test_litellm/proxy/guardrails/test_custom_code_primitives.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| import socket | ||
|
|
||
| import pytest | ||
|
|
||
| from litellm.litellm_core_utils import url_utils | ||
| from litellm.proxy.guardrails.guardrail_hooks.custom_code import primitives | ||
|
|
||
|
|
||
| def _mock_dns(monkeypatch, ip: str): | ||
| def fake_getaddrinfo(host, port, *args, **kwargs): | ||
| return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port or 80))] | ||
|
|
||
| monkeypatch.setattr(url_utils.socket, "getaddrinfo", fake_getaddrinfo) | ||
|
|
||
|
|
||
| class _FakeResponse: | ||
| def __init__(self, status_code=200, json_body=None, location=None): | ||
| self.status_code = status_code | ||
| self._json = json_body if json_body is not None else {"ok": True} | ||
| self.headers = {"location": location} if location else {} | ||
| self.is_redirect = 300 <= status_code < 400 | ||
|
|
||
| def json(self): | ||
| return self._json | ||
|
|
||
| @property | ||
| def text(self): | ||
| return str(self._json) | ||
|
|
||
|
|
||
| class _FakeRawClient: | ||
| def __init__(self, response=None): | ||
| self.response = response or _FakeResponse() | ||
| self.calls = [] | ||
|
|
||
| async def request(self, method, url, headers=None, **kwargs): | ||
| self.calls.append({"method": method, "url": url, "headers": headers or {}}) | ||
| return self.response | ||
|
|
||
|
|
||
| class _FakeHandler: | ||
| def __init__(self, raw_client): | ||
| self.client = raw_client | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_http_request_blocks_cloud_metadata(monkeypatch): | ||
| """Regression for the guardrail SSRF: http_request() must run the URL | ||
| through validate_url() so the AWS/GCP/Azure metadata IP is rejected and | ||
| no outbound request is ever issued.""" | ||
| _mock_dns(monkeypatch, "169.254.169.254") | ||
|
|
||
| raw_client = _FakeRawClient() | ||
| monkeypatch.setattr( | ||
| primitives, "get_async_httpx_client", lambda **kw: _FakeHandler(raw_client) | ||
| ) | ||
|
|
||
| result = await primitives.http_request( | ||
| "http://169.254.169.254/latest/meta-data/iam/security-credentials/" | ||
| ) | ||
|
|
||
| assert result["success"] is False | ||
| assert "SSRF" in result["error"] | ||
| assert raw_client.calls == [] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_http_request_blocks_private_ip(monkeypatch): | ||
| _mock_dns(monkeypatch, "127.0.0.1") | ||
|
|
||
| raw_client = _FakeRawClient() | ||
| monkeypatch.setattr( | ||
| primitives, "get_async_httpx_client", lambda **kw: _FakeHandler(raw_client) | ||
| ) | ||
|
|
||
| result = await primitives.http_request("http://localhost:6379/", method="POST") | ||
|
|
||
| assert result["success"] is False | ||
| assert "SSRF" in result["error"] | ||
| assert raw_client.calls == [] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_http_request_does_not_follow_redirect_to_private(monkeypatch): | ||
| """A public host that 302-redirects to a private target must be blocked at | ||
| the redirect hop rather than followed into the internal network.""" | ||
|
|
||
| def fake_getaddrinfo(host, port, *args, **kwargs): | ||
| ip = "93.184.216.34" if host == "public.example" else "127.0.0.1" | ||
| return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port or 80))] | ||
|
|
||
| monkeypatch.setattr(url_utils.socket, "getaddrinfo", fake_getaddrinfo) | ||
|
|
||
| raw_client = _FakeRawClient( | ||
| response=_FakeResponse(status_code=302, location="http://internal.example/") | ||
| ) | ||
| monkeypatch.setattr( | ||
| primitives, "get_async_httpx_client", lambda **kw: _FakeHandler(raw_client) | ||
| ) | ||
|
|
||
| result = await primitives.http_request("http://public.example/start") | ||
|
|
||
| assert result["success"] is False | ||
| assert "SSRF" in result["error"] | ||
| # Only the first (public) hop was attempted; the private redirect target was | ||
| # rejected before a second request went out. | ||
| assert len(raw_client.calls) == 1 | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_http_request_allows_public_host(monkeypatch): | ||
| """The happy path still works: a public host resolves, the validated request | ||
| is issued to the resolved IP with the original Host header preserved.""" | ||
| _mock_dns(monkeypatch, "93.184.216.34") | ||
|
|
||
| raw_client = _FakeRawClient( | ||
| response=_FakeResponse(status_code=200, json_body={"verdict": "clean"}) | ||
| ) | ||
| monkeypatch.setattr( | ||
| primitives, "get_async_httpx_client", lambda **kw: _FakeHandler(raw_client) | ||
| ) | ||
|
|
||
| result = await primitives.http_request( | ||
| "http://api.example.com/moderate", | ||
| method="POST", | ||
| body={"text": "hello"}, | ||
| ) | ||
|
|
||
| assert result["success"] is True | ||
| assert result["status_code"] == 200 | ||
| assert result["body"] == {"verdict": "clean"} | ||
| assert len(raw_client.calls) == 1 | ||
| call = raw_client.calls[0] | ||
| assert call["method"] == "POST" | ||
| # HTTP target is rewritten to the validated IP; the original hostname rides | ||
| # in the Host header to defeat DNS rebinding. | ||
| assert "93.184.216.34" in call["url"] | ||
| assert call["headers"].get("Host") == "api.example.com" |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
async_safe_requestuses the originalmethodon every hop in the redirect loop. For 301/302/303 responses, RFC 7231 mandates that POST (and other unsafe methods) be reissued as GET to the redirect target; only 307/308 should preserve the method. The old code delegated to httpx withfollow_redirects=True, which handled this automatically. Callers that POST to a URL returning a 301/302/303 will now send POST to the redirect target instead of GET, which can result in 405 errors or unintended double-POSTs against external APIs. Consider addingif response.status_code in (301, 302, 303) and method != "GET": method = "GET"; kwargs.pop("json", None); kwargs.pop("data", None)before advancingurl.