Skip to content

fix: block SSRF in misc_utils.download_img for OAuth avatars - #14868

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
dale053:fix/14865-ssrf-oauth-avatar-url
May 22, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
dale053:fix/14865-ssrf-oauth-avatar-url

Conversation

@dale053

@dale053 dale053 commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Closes #14865

download_img in common/misc_utils.py is used for OAuth avatar URLs. The previous implementation called async_request from common.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 with pin_dns_global, httpx streams the body with follow_redirects=False and a manual redirect loop (capped by RAGFLOW_OAUTH_AVATAR_MAX_REDIRECTS), and total response size is capped (RAGFLOW_OAUTH_AVATAR_MAX_BYTES). Timeouts, proxy, and user agent align with HTTP_CLIENT_* env vars without importing http_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

  • Bug Fix (non-breaking change which fixes an issue)

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels May 12, 2026
@coderabbitai

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9edc78cf-8e2f-4c2f-bce3-92b05e5cd74a

📥 Commits

Reviewing files that changed from the base of the PR and between e47bbc3 and e83bca0.

📒 Files selected for processing (1)
  • test/unit_test/common/test_misc_utils.py
💤 Files with no reviewable changes (1)
  • test/unit_test/common/test_misc_utils.py

📝 Walkthrough

Walkthrough

download_img is rewritten to securely fetch OAuth avatar images using httpx with per-hop SSRF validation and DNS pinning, bounded redirect following, streamed response reading with a byte limit and timeout, and base64 data: URI encoding; tests were extended with SSRF-blocking regression cases.

Changes

SSRF-Protected Image Download

Layer / File(s) Summary
Download implementation with SSRF protection, redirect handling, and streaming
common/misc_utils.py
Adds urljoin import and module constants. Rewrites download_img to validate initial and redirect URLs via common.ssrf_guard.assert_url_is_safe, pin DNS per hop with pin_dns_global, perform httpx streaming with follow_redirects=False, follow only {301,302,303,307,308} redirect codes resolving Location via urljoin, enforce a maximum total byte budget while reading chunks, require a final 200 status, and return a base64 data: URI (default image/jpeg) or "" on failures (validation, timeout, request exceptions, non-200 final status, missing Location, redirect/size/time limits).
Security regression tests for SSRF-protected download
test/unit_test/common/test_misc_utils.py
Adds asyncio import and in-file async/httpx stubs to avoid real network calls. Refactors TestDownloadImg to call download_img via asyncio.run(...) and expands tests with SSRF-blocking assertions for empty/None URLs, loopback (127.0.0.1), metadata IP (169.254.169.254), disallowed file:// scheme, redirect-to-loopback, and excessive redirect hops.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested labels

size:M

Poem

🐰 I hopped through redirects, checked each host,
Pinned DNS threads tight so no secrets were lost,
I streamed tiny bytes, kept the timeout set,
Encoded a smile, but leaked nothing yet —
A careful little rabbit, guarding the nest.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: block SSRF in misc_utils.download_img for OAuth avatars' directly describes the main change: adding SSRF protections to the download_img function for OAuth avatar fetching.
Description check ✅ Passed The description covers the required template sections: it explains the problem (SSRF vulnerability in download_img), identifies the issue being closed (#14865), and correctly marks this as a Bug Fix.
Linked Issues check ✅ Passed The PR implementation meets the core coding requirements from #14865: URL validation via ssrf_guard.assert_url_is_safe, DNS pinning, manual redirect handling with bounded hops, response size enforcement, and comprehensive SSRF regression test coverage.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the SSRF fix: reimplementation of download_img with security controls and corresponding test expansions covering SSRF scenarios. No unrelated modifications are present.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5e46457 and 9b6ef11.

📒 Files selected for processing (2)
  • common/misc_utils.py
  • test/unit_test/common/test_misc_utils.py

Comment thread common/misc_utils.py Resolved
Comment thread common/misc_utils.py Resolved
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels May 13, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
common/misc_utils.py (1)

74-74: ⚡ Quick win

Use the module-level logger consistently instead of root logging.

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 to logging.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

📥 Commits

Reviewing files that changed from the base of the PR and between 9b6ef11 and f413c11.

📒 Files selected for processing (2)
  • common/misc_utils.py
  • test/unit_test/common/test_misc_utils.py

@dale053

dale053 commented May 13, 2026

Copy link
Copy Markdown
Contributor Author

Hi, @wangq8
Could you please review this PR?

@dale053

dale053 commented May 20, 2026

Copy link
Copy Markdown
Contributor Author

Hi, @KevinHuSh
When you have a moment, could you please review this PR?

@KevinHuSh KevinHuSh added the ci Continue Integration label May 21, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft May 21, 2026 07:19
@KevinHuSh
KevinHuSh marked this pull request as ready for review May 21, 2026 07:19
@codecov

codecov Bot commented May 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (5e46457) to head (e83bca0).
⚠️ Report is 150 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@dale053

dale053 commented May 22, 2026

Copy link
Copy Markdown
Contributor Author

Hi, @KevinHuSh
All checks have passed ! Could you please review this PR?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: SSRF via unvalidated avatar URL fetch during OAuth registration leaks internal service data

3 participants