Skip to content

Fix: add SSRF guard for agent test_db_connection endpoint - #14860

Merged
KevinHuSh merged 4 commits into
infiniflow:mainfrom
dale053:fix/ssrf-test-db-connection-14858
May 18, 2026
Merged

KevinHuSh merged 4 commits into
infiniflow:mainfrom
dale053:fix/ssrf-test-db-connection-14858

Conversation

@dale053

@dale053 dale053 commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Closes #14858

The test_db_connection endpoint in the agent API accepts a user-supplied host and connects to it directly via database drivers (MySQL/PostgreSQL) without any validation. This allows an attacker to probe internal network addresses (e.g. 127.0.0.1, 10.x.x.x, link-local, etc.) through the server — a classic Server-Side Request Forgery (SSRF) vulnerability.

This PR adds an SSRF guard that resolves the host and rejects any address that is not globally routable before the database connection is attempted.

Changes:

  • common/ssrf_guard.py — Added assert_host_is_safe(), a host-level counterpart of the existing assert_url_is_safe(), designed for non-HTTP protocols (database drivers) where there is no URL to parse.
  • api/apps/restful_apis/agent_api.py — Call assert_host_is_safe(req["host"]) at the top of test_db_connection so that non-public hosts are rejected early with a clear error message.

Fixes #14858

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: b739b9a9-47d0-4806-a8b0-9e61fa20e050

📥 Commits

Reviewing files that changed from the base of the PR and between d55c2c5 and 4294ce3.

📒 Files selected for processing (1)
  • api/apps/restful_apis/agent_api.py

📝 Walkthrough

Walkthrough

A new host-level SSRF guard validates hostnames resolve to globally routable IPs and the test_db_connection endpoint now calls it, returning errors on invalid or unresolvable hosts and using the validated safe_host for all DB connection paths.

Changes

SSRF host validation for database connection endpoint

Layer / File(s) Summary
test_db_connection endpoint protection
api/apps/restful_apis/agent_api.py
Import assert_host_is_safe; wrap validation in try/except to return get_data_error_result on ValueError or OSError DNS failures; store validated safe_host and use it for MySQL/MariaDB, OceanBase, Postgres, MSSQL (ODBC SERVER=), IBM DB2 (HOSTNAME and logs), and Trino DBAPI connection calls.

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped through DNS and socket threads,
Nibbled at names where danger treads,
I swapped the host for one that's safe,
Kept pry-hops out of server's place,
Carrot in paw, I guard the nets.

🚥 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 clearly and concisely describes the main change: adding an SSRF guard to protect the agent test_db_connection endpoint, which directly addresses the core security vulnerability fixed in this PR.
Description check ✅ Passed The description fully addresses the required template sections: it explains the SSRF vulnerability being fixed, clearly states the type of change (Bug Fix), provides specific file-level changes, and references the related issue #14858.
Linked Issues check ✅ Passed All coding requirements from issue #14858 are met: host validation via assert_host_is_safe() is implemented before connections, rejects non-globally-routable addresses, applies to all seven database driver branches (MySQL, MariaDB, OceanBase, PostgreSQL, MSSQL, IBM DB2, Trino), and provides appropriate error handling.
Out of Scope Changes check ✅ Passed All changes remain narrowly focused on the SSRF vulnerability remediation: the new assert_host_is_safe() function in common/ssrf_guard.py and its application in agent_api.py's test_db_connection endpoint are directly aligned with issue #14858 objectives with no extraneous modifications.

✏️ 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: 1

🧹 Nitpick comments (1)
api/apps/restful_apis/agent_api.py (1)

711-714: ⚡ Quick win

Use get_data_error_result for client validation errors.

server_error_response reports a server-side failure, but a ValueError from assert_host_is_safe is a request-validation failure (4xx-style). Elsewhere in this file, ValueError from validators is consistently surfaced via get_data_error_result (e.g. lines 514-515, 938-939). Recommend aligning with that pattern (already folded into the diff above).

🤖 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 `@api/apps/restful_apis/agent_api.py` around lines 711 - 714, The code treats a
validation failure from assert_host_is_safe as a server error; change the
exception handling to return a client validation response by calling
get_data_error_result with the exception message instead of
server_error_response. Locate the try/except around
assert_host_is_safe(req["host"]) and replace the except block to return
get_data_error_result(str(exc)) so it matches the existing pattern used
elsewhere in this file (see other ValueError handlers like the ones around lines
where get_data_error_result is used).
🤖 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 `@api/apps/restful_apis/agent_api.py`:
- Around line 711-714: The call to assert_host_is_safe currently discards the
validated IP, allowing a TOCTOU DNS-rebind when later passing req["host"] to DB
drivers; change the code to capture the return value (e.g., safe_host =
assert_host_is_safe(req["host"])) and then use safe_host in all subsequent
connection calls instead of req["host"] (apply to
MySQLDatabase/PostgresqlDatabase constructors, pyodbc.connect, ibm_db.connect,
trino.dbapi.connect and the oceanbase/postgres/mssql (SERVER=...)/IBM DB2
(HOSTNAME=...) branches). If hostname preservation is required for TLS/SNI, wrap
the connect call with pin_dns(req["host"], safe_host) instead; ensure you still
call assert_host_is_safe and use its returned IP in the connect logic or the
pin_dns context.

---

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 711-714: The code treats a validation failure from
assert_host_is_safe as a server error; change the exception handling to return a
client validation response by calling get_data_error_result with the exception
message instead of server_error_response. Locate the try/except around
assert_host_is_safe(req["host"]) and replace the except block to return
get_data_error_result(str(exc)) so it matches the existing pattern used
elsewhere in this file (see other ValueError handlers like the ones around lines
where get_data_error_result is used).
🪄 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: d7916d9f-0173-4b83-abcf-96964219b045

📥 Commits

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

📒 Files selected for processing (2)
  • api/apps/restful_apis/agent_api.py
  • common/ssrf_guard.py

Comment thread api/apps/restful_apis/agent_api.py Resolved

@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: 1

🤖 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 `@api/apps/restful_apis/agent_api.py`:
- Around line 711-714: Catch both ValueError and OSError/socket.gaierror from
assert_host_is_safe and treat them as user/data errors by returning
get_data_error_result; additionally add a logging.warning entry when a host is
rejected that records the offending req["host"] and the requesting tenant/user
(pull from req or request context) so rejections are auditable, and if desired
log the full exception at debug level but do not surface resolver details in the
returned get_data_error_result; update the try/except around assert_host_is_safe
to reflect these changes and avoid letting resolver errors bubble up to
server_error_response.
🪄 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: cbca43ff-2ebc-4e14-939e-da0ac9f339fd

📥 Commits

Reviewing files that changed from the base of the PR and between e04a2a0 and d133c8a.

📒 Files selected for processing (1)
  • api/apps/restful_apis/agent_api.py

Comment thread api/apps/restful_apis/agent_api.py Resolved
@dale053

dale053 commented May 14, 2026

Copy link
Copy Markdown
Contributor Author

Hi , @JinHai-CN
When you have a chance, Could you please review this PR?
Thank you for your time

@JinHai-CN JinHai-CN added the ci Continue Integration label May 15, 2026
@codecov

codecov Bot commented May 15, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (86bcf97) to head (4294ce3).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14860   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ 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 15, 2026

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN
Thank you for your time.
All checks have passed! could you please review this PR?

@KevinHuSh
KevinHuSh merged commit fe82a96 into infiniflow:main May 18, 2026
1 check passed
yuzhichang added a commit that referenced this pull request Jun 28, 2026
### What problem does this PR solve?

Closes #15608.

The ExeSQL agent tool (`agent/tools/exesql.py`) opens database
connections to a node-author-controlled host/port with no SSRF
validation. The sibling `test_db_connection` endpoint already validates
the host via `common.ssrf_guard.assert_host_is_safe` (added by PR
#14860), but the tool that actually performs the connection at agent run
time was left unguarded — so the guard is bypassed simply by running the
agent. An agent author can point the host at `127.0.0.1`,
`169.254.169.254` (cloud metadata), or any internal RFC1918 host/port,
turning ExeSQL into an internal port-scanner / metadata-fetch primitive.

### Fix

Mirror the accepted endpoint guard: validate (and resolve) the host
once, before the `db_type` dispatch, and connect to the validated public
IP so a later DNS change cannot rebind the host to an internal address.

- Add `from common.ssrf_guard import assert_host_is_safe`.
- `safe_host = assert_host_is_safe(self._param.host)` before the
dispatch (rejects loopback, link-local/metadata, RFC1918, and
unresolvable hosts).
- Substitute the validated IP into all 6 driver branches: mysql/mariadb,
oceanbase, postgres, mssql, trino, IBM DB2.

Adds `test/unit_test/agent/tools/test_exesql_ssrf.py` covering loopback,
link-local/metadata, RFC1918, and empty-host rejection (before any
connection), plus an allowed host dialing the validated IP.

### Validation

- `python3 -m py_compile agent/tools/exesql.py`
- `ruff check agent/tools/exesql.py
test/unit_test/agent/tools/test_exesql_ssrf.py`
- `pytest test/unit_test/agent/tools/test_exesql_ssrf.py` — 5 passed

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)

---------

Co-authored-by: Zhichang Yu <[email protected]>
yuzhichang added a commit that referenced this pull request Jun 29, 2026
### What problem does this PR solve?

Closes #15608.

The ExeSQL agent tool (`agent/tools/exesql.py`) opens database
connections to a node-author-controlled host/port with no SSRF
validation. The sibling `test_db_connection` endpoint already validates
the host via `common.ssrf_guard.assert_host_is_safe` (added by PR
#14860), but the tool that actually performs the connection at agent run
time was left unguarded — so the guard is bypassed simply by running the
agent. An agent author can point the host at `127.0.0.1`,
`169.254.169.254` (cloud metadata), or any internal RFC1918 host/port,
turning ExeSQL into an internal port-scanner / metadata-fetch primitive.

### Fix

Mirror the accepted endpoint guard: validate (and resolve) the host
once, before the `db_type` dispatch, and connect to the validated public
IP so a later DNS change cannot rebind the host to an internal address.

- Add `from common.ssrf_guard import assert_host_is_safe`.
- `safe_host = assert_host_is_safe(self._param.host)` before the
dispatch (rejects loopback, link-local/metadata, RFC1918, and
unresolvable hosts).
- Substitute the validated IP into all 6 driver branches: mysql/mariadb,
oceanbase, postgres, mssql, trino, IBM DB2.

Adds `test/unit_test/agent/tools/test_exesql_ssrf.py` covering loopback,
link-local/metadata, RFC1918, and empty-host rejection (before any
connection), plus an allowed host dialing the validated IP.

### Validation

- `python3 -m py_compile agent/tools/exesql.py`
- `ruff check agent/tools/exesql.py
test/unit_test/agent/tools/test_exesql_ssrf.py`
- `pytest test/unit_test/agent/tools/test_exesql_ssrf.py` — 5 passed

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)

---------

Co-authored-by: Zhichang Yu <[email protected]>
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:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: SRF via /agents/test_db_connection — no host/port validation allows internal network scanning

3 participants