Repository navigation
fix: block SSRF in misc_utils.download_img for OAuth avatars - #14868
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
💤 Files with no reviewable changes (1)
📝 WalkthroughWalkthrough
ChangesSSRF-Protected Image Download
Sequence Diagram(s)sequenceDiagram
participant Caller
participant download_img
participant common.ssrf_guard.assert_url_is_safe
participant common.pin_dns_global
participant httpx.AsyncClient
Caller->>download_img: fetch(url)
download_img->>common.ssrf_guard.assert_url_is_safe: validate URL
alt URL rejected
download_img-->>Caller: "" (failure)
else URL ok
download_img->>common.pin_dns_global: pin DNS for host
download_img->>httpx.AsyncClient: stream GET (follow_redirects=False)
httpx.AsyncClient-->>download_img: response (200 or redirect)
loop redirects (<= _OAUTH_AVATAR_MAX_REDIRECTS)
alt redirect status ∈ {301,302,303,307,308}
download_img->>common.ssrf_guard.assert_url_is_safe: validate Location
download_img->>common.pin_dns_global: pin DNS for new host
download_img->>httpx.AsyncClient: stream GET next URL
end
end
alt final 200 and within byte limit
download_img->>download_img: encode bytes -> data: URI
download_img-->>Caller: data URI
else failure (non-200 / oversized / missing Location / exception / timeout)
download_img-->>Caller: "" (failure)
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@common/misc_utils.py`:
- Around line 90-99: The code currently returns empty string silently in three
cases (missing Location header during a redirect, non-200 response, and
redirect-hop exhaustion in the redirect loop around response handling); add
logging in those branches so failures are visible. Update the branches around
the response handling (referencing response, current_url, redirect_hops, and
_REDIRECT_STATUS) to call the module logger (e.g., logger or
logging.getLogger(__name__)) and emit an appropriate message including
current_url, response.status_code (when present), and redirect_hops before
returning "" so each rejection path is distinguishable in logs.
- Around line 77-101: The streaming GET should be bounded by a total wall-clock
deadline: wrap the async streaming block (the async with httpx.AsyncClient(...)
as client: and its inner async with client.stream("GET", current_url,
headers=headers or None) as response: plus the async for chunk in
response.aiter_bytes() loop) in asyncio.wait_for(..., timeout=request_timeout)
so the entire fetch/stream cannot hang beyond request_timeout; preserve existing
handling of redirects (redirect_hops, current_url) and status checks
(response.status_code in _REDIRECT_STATUS, != 200) and use the same
request_timeout variable when calling asyncio.wait_for.
In `@test/unit_test/common/test_misc_utils.py`:
- Around line 106-118: Add tests exercising redirect-chain SSRF: create a mocked
HTTP redirect (30x) from a safe URL to a loopback address and assert
download_img returns "" (e.g., new test name test_redirect_to_loopback_blocked),
and create a mock redirect chain that exceeds the max hops to assert
download_img returns "" (e.g., test_redirect_too_many_hops_blocked). Use the
same download_img helper used in existing tests and arrange mocked responses so
the initial URL is allowed but the Location header points to
"http://127.0.0.1/..." or "http://169.254.169.254/..." for the first test, and
for the second test follow redirects beyond the configured hop limit to trigger
the max-hop rejection, then assert result == "" in both tests.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 76ad6b9f-441d-43f7-b2f8-210af6f008d1
📒 Files selected for processing (2)
common/misc_utils.pytest/unit_test/common/test_misc_utils.py
There was a problem hiding this comment.
🧹 Nitpick comments (1)
common/misc_utils.py (1)
74-74: ⚡ Quick winUse the module-level
loggerconsistently instead of rootlogging.Line 31 introduces
logger = logging.getLogger(__name__), and most new warnings (lines 97, 106, 135, 154) correctly use it, but lines 74, 116, and 143 fall back tologging.warning(...). That routes those messages through the root logger, dropping the module name from the log record and bypassing any per‑module level/handler config — making the very rejection paths the past review asked to be observable harder to filter on.♻️ Proposed fix
@@ line 74 - logging.warning("download_img rejected URL (SSRF guard): %s", exc) + logger.warning("download_img rejected URL (SSRF guard): %s", exc) @@ line 116 - if len(body) + len(chunk) > _OAUTH_AVATAR_MAX_BYTES: - logging.warning( - "download_img response exceeded max size (%s bytes); URL rejected", - _OAUTH_AVATAR_MAX_BYTES, - ) + if len(body) + len(chunk) > _OAUTH_AVATAR_MAX_BYTES: + logger.warning( + "download_img response exceeded max size: url=%r max_bytes=%s", + current_url, + _OAUTH_AVATAR_MAX_BYTES, + ) @@ line 143 - except Exception as exc: - logging.warning("download_img request failed: %s", exc) + except Exception as exc: + logger.warning( + "download_img request failed: url=%r redirect_hops=%s err=%s", + current_url, + redirect_hops, + exc, + ) return ""As per coding guidelines,
**/*.py: Add logging for new flows.Also applies to: 116-116, 143-143
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@common/misc_utils.py` at line 74, The rejection-path log calls in common/misc_utils.py are using the root logger (logging.warning) instead of the module-level logger; update the three occurrences in the download image/path-related code to call logger.warning(...) so they use the existing module logger (logger = logging.getLogger(__name__)) declared earlier (replace the calls at the locations that correspond to the download_img flow and the other two warning sites referenced in the review). Ensure the message and exception parameter remain unchanged when switching to logger.warning to preserve semantics.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@common/misc_utils.py`:
- Line 74: The rejection-path log calls in common/misc_utils.py are using the
root logger (logging.warning) instead of the module-level logger; update the
three occurrences in the download image/path-related code to call
logger.warning(...) so they use the existing module logger (logger =
logging.getLogger(__name__)) declared earlier (replace the calls at the
locations that correspond to the download_img flow and the other two warning
sites referenced in the review). Ensure the message and exception parameter
remain unchanged when switching to logger.warning to preserve semantics.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 70593b1b-670c-4f58-95a6-b0e19c071b4b
📒 Files selected for processing (2)
common/misc_utils.pytest/unit_test/common/test_misc_utils.py
|
Hi, @wangq8 |
|
Hi, @KevinHuSh |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14868 +/- ##
==========================================
- Coverage 95.59% 93.12% -2.47%
==========================================
Files 10 10
Lines 703 713 +10
Branches 112 116 +4
==========================================
- Hits 672 664 -8
- Misses 21 29 +8
- Partials 10 20 +10 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
Hi, @KevinHuSh |
What problem does this PR solve?
Closes #14865
download_imgincommon/misc_utils.pyis used for OAuth avatar URLs. The previous implementation calledasync_requestfromcommon.http_client, which followed redirects without re-validating each hop and did not apply the same SSRF protections as this path needs. That made it possible to reach non-public or disallowed targets (for example via redirects or unsafe URLs) when fetching avatars.This change replaces that flow with an explicit, bounded fetch: each URL (including every redirect target) is checked with
common.ssrf_guard.assert_url_is_safe, DNS is pinned withpin_dns_global,httpxstreams the body withfollow_redirects=Falseand a manual redirect loop (capped byRAGFLOW_OAUTH_AVATAR_MAX_REDIRECTS), and total response size is capped (RAGFLOW_OAUTH_AVATAR_MAX_BYTES). Timeouts, proxy, and user agent align withHTTP_CLIENT_*env vars without importinghttp_client, so lightweight tests stay simple.Unit tests cover empty/None URLs, loopback, cloud metadata-style addresses, and disallowed schemes so SSRF regressions are caught early.
Type of change