Skip to content

fix(database): don't reattach stored connection details when the effective destination changes - #44003

Merged
rusackas merged 4 commits into
masterfrom
fix/database-connection-identity-check
Sep 8, 2026
Merged

rusackas merged 4 commits into
masterfrom
fix/database-connection-identity-check

Conversation

@rusackas

@rusackas rusackas commented Sep 8, 2026

Copy link
Copy Markdown
Member

SUMMARY

test_connection, validate_parameters, database update, and database import all decide whether to reattach a stored connection secret (password, encrypted_extra, or SSH tunnel credential) by comparing one visible field against its masked/stored form, without checking whether other request-controlled fields also feed into the actual connection destination.

extra.engine_params (in particular engine_params.connect_args.host/.port) is merged into the DBAPI connect kwargs by SQLAlchemy and can override the host/port carried in the URI itself. The SSH tunnel's server_address/server_port can change independently of the URI. For database update, the URI's own host/port can change directly while its password segment stays masked, with nothing comparing it against the stored host first.

This PR adds an identity check across all four paths (mirroring the check #43393 already added for database import's URI-host case, extended to also cover extra.engine_params, and applied fresh to database update, which had none before) and refuses to reattach a stored secret unless a fresh credential is supplied for a destination that changed. Shared comparison logic lives in superset/commands/database/utils.py. Also scopes DatabaseDAO.get_database_by_name to the same DatabaseFilter object-visibility boundary find_by_id/get_connection already use for this resource.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A — backend-only change, no UI impact.

TESTING INSTRUCTIONS

Regression tests added per site (extra.engine_params variant, SSH-tunnel-endpoint variant, and for database update also the plain URI-host variant). Each was verified to fail without its corresponding fix and pass with it. pytest tests/unit_tests/commands/databases/ tests/unit_tests/databases/ tests/unit_tests/daos/ — 521 passed. Legitimate flows (unchanged destination, or a deliberate move with a freshly supplied credential) are covered and unaffected.

ADDITIONAL INFORMATION

  • Has associated issue
  • Required feature flags
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
  • Confirm DB Migration upgrade and downgrade tested
  • Introduces new feature or API
  • Removes existing feature or API

…ctive destination changes

test_connection, validate_parameters, database update, and database
import all decide whether to reattach a stored secret (password,
encrypted_extra, or SSH tunnel credential) by comparing one visible
field against its masked/stored form, without checking whether other
request-controlled fields also feed into the actual connection
destination:

- extra.engine_params (in particular engine_params.connect_args.host/
  .port) is merged into the DBAPI connect() kwargs by SQLAlchemy and
  can override the host/port carried in the URI itself.
- The SSH tunnel server_address/server_port can change independently
  of the URI.
- (update only) the URI's own host/port can change directly while its
  password segment is left masked, with nothing comparing it against
  the stored host first.

A principal who can reach one of these endpoints for a given database
can redirect its real stored credential to a destination they control.
For the update path this is a persistent change: the real credential
is sent to the new destination on the *next* use of the database by
anyone, not just the requester.

Also scopes DatabaseDAO.get_database_by_name to the same DatabaseFilter
object-visibility boundary find_by_id/get_connection already apply to
this resource; it was previously an unfiltered lookup.

Shared comparison logic factored into
superset/commands/database/utils.py (engine_params_changed,
ssh_tunnel_endpoint_changed, ssh_tunnel_rebind_unsafe,
uri_identity_changed) and reused across all four call sites, extending
the identity-check policy PR #43393 established for database import's
URI-host case to also cover extra.engine_params, and applying an
equivalent check to database update, which previously had none.

Regression tests added per site (engine_params variant, SSH-tunnel-
endpoint variant, and for update also the plain URI-host variant),
each verified to fail without its corresponding fix and pass with it.
Legitimate flows (unchanged destination, or a deliberate move with a
freshly supplied credential) are covered and unaffected.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@bito-code-review

bito-code-review Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #1c94ef

Actionable Suggestions - 0
Additional Suggestions - 7
  • superset/commands/database/update.py - 1
    • CWE-200: Secret Rebind Gap · Line 228-232
      The docstring (lines 197-205) claims to protect the stored encrypted_extra credential, but this check only inspects the URI password. When the destination changes and a fresh URI password is supplied, the stored `encrypted_extra` secret (preserved via `masked_encrypted_extra` → `unmask_encrypted_extra` in `run()`) silently rides along to the new host. Add a guard for `masked_encrypted_extra` when `connection_identity_changed`. ([CWE-200](https://cwe.mitre.org/data/definitions/200.html))
  • superset/commands/database/utils.py - 1
    • Over-broad engine_params compare · Line 79-88
      `engine_params_changed` compares the whole `engine_params` dict, but `_check_no_unsafe_secret_rebind` (update.py:223-232) treats any difference as a destination change. On a normal edit the frontend submits the stored URI with a masked password (SqlAlchemyForm.tsx:79), so changing only non-identity keys (e.g. `pool_size`, `connect_args` ssl options) raises `DatabaseUpdateUnsafeRebindError` even though the host/port is unchanged. Compare only the identity-relevant `connect_args` host/port keys.
  • superset/commands/database/test_connection.py - 1
    • Over-broad rebind guard · Line 91-95
      `engine_params_changed` compares the entire `engine_params` dict, so editing any non-destination param (e.g. `connect_args.ssl`, `pool_size`) sets `_identity_changed=True` and raises `DatabaseTestConnectionUnsafeRebindError`, blocking test-connection for an existing DB even though host/port are unchanged. Consider comparing only destination-affecting keys (host/port) so legitimate engine_param edits still test successfully.
  • superset/daos/database.py - 1
    • Duplicate base-filter logic · Line 195-197
      This manually reimplements `_apply_base_filter` (base.py:284-293), which already builds `cls.base_filter(cls.id_column_name, SQLAInterface(...)).apply(query, None)` using `DatabaseDAO.base_filter`. Reuse `DatabaseDAO._apply_base_filter(query)` so the visibility boundary stays in one place and can't diverge if the base filter logic changes.
  • superset/commands/database/importers/v1/utils.py - 1
    • Over-broad engine_params check · Line 58-61
      `engine_params_changed` compares the entire `engine_params` dict, so any benign change (e.g. `connect_args.sslmode`, timeouts) is treated as a destination change and forces re-entering credentials via `_refuse_stored_secret_reuse`. Consider comparing only destination-affecting keys (host/port) to avoid blocking legitimate imports.
  • superset/commands/database/validate.py - 1
    • Over-broad identity flag · Line 154-159
      `identity_changed` is a single OR of `engine_params_changed` and `ssh_tunnel_endpoint_changed`, but it gates the SSH tunnel password unmask at line 154-159. If a user changes only `extra.engine_params` (and the URI also changes, so line 130 doesn't raise), the unchanged tunnel's stored password is no longer rehydrated and the connection test spuriously fails with a masked password. Gate each unmask on its own check.
  • superset/commands/database/exceptions.py - 1
    • Misattributed error field · Line 63-63
      `DatabaseUpdateUnsafeRebindError` hardcodes `field_name="sqlalchemy_uri"`, but `update.py::_check_no_unsafe_secret_rebind` also raises it when only the SSH tunnel endpoint changes. The 422 from `normalized_messages()` is then attributed to `sqlalchemy_uri` even though that field is unchanged, misleading the client. Consider making `field_name` a parameter and passing `"ssh_tunnel"` for the tunnel branch.
Review Details
  • Files reviewed - 10 · Commit Range: 87a5280..87a5280
    • superset/commands/database/exceptions.py
    • superset/commands/database/importers/v1/utils.py
    • superset/commands/database/test_connection.py
    • superset/commands/database/update.py
    • superset/commands/database/utils.py
    • superset/commands/database/validate.py
    • superset/daos/database.py
    • tests/unit_tests/commands/databases/update_test.py
    • tests/unit_tests/commands/databases/validate_test.py
    • tests/unit_tests/databases/commands/importers/v1/import_test.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@rusackas rusackas changed the title fix(database): don't reattach stored connection secrets when the effective destination changes fix(database): don't reattach stored connection details when the effective destination changes Sep 8, 2026
Comment thread superset/commands/database/update.py Outdated
Comment on lines +228 to +232
if connection_identity_changed and submitted_password in (
None,
PASSWORD_MASK,
):
raise DatabaseInvalidError(exceptions=[DatabaseUpdateUnsafeRebindError()])

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.

Suggestion: A destination change is accepted only when the URI contains a real password, so fresh masked_encrypted_extra credentials are rejected for engines storing authentication outside the URI. [api mismatch]

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/commands/database/update.py
**Line:** 228:232
**Comment:**
	*Api Mismatch: A destination change is accepted only when the URI contains a real password, so fresh `masked_encrypted_extra` credentials are rejected for engines storing authentication outside the URI.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct catch, this and sha174n's more detailed suggestion on the same lines are the same underlying gap. Fixed in 72ccf98 (see reply on that thread for detail).

@bito-code-review

Copy link
Copy Markdown
Contributor

The flagged issue is correct. The current implementation of _check_no_unsafe_secret_rebind in superset/commands/database/update.py only checks for PASSWORD_MASK or None in the sqlalchemy_uri password field when a destination change is detected. It fails to account for cases where the password might be stored in encrypted_extra (which is common for engines that store authentication outside the URI).

To resolve this, you should update the check to also verify if encrypted_extra is being reused (i.e., remains masked) when a destination change occurs.

Would you like me to fetch all other comments on this PR to validate and implement fixes for them as well?

superset/commands/database/update.py

if connection_identity_changed and (
            submitted_password in (None, PASSWORD_MASK)
            or self._properties.get("encrypted_extra") == PASSWORD_MASK
        ):
            raise DatabaseInvalidError(exceptions=[DatabaseUpdateUnsafeRebindError()])

@codecov

codecov Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.81633% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.82%. Comparing base (7382ee0) to head (527bef3).
⚠️ Report is 4 commits behind head on master.

Files with missing lines Patch % Lines
superset/commands/database/update.py 88.46% 2 Missing and 1 partial ⚠️
superset/commands/database/test_connection.py 85.71% 1 Missing and 1 partial ⚠️
superset/commands/database/utils.py 93.75% 2 Missing ⚠️
superset/commands/database/validate.py 80.00% 0 Missing and 2 partials ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master   #44003   +/-   ##
=======================================
  Coverage   79.81%   79.82%           
=======================================
  Files        2914     2914           
  Lines      170473   170549   +76     
  Branches    39518    39530   +12     
=======================================
+ Hits       136066   136143   +77     
- Misses      31885    31886    +1     
+ Partials     2522     2520    -2     
Flag Coverage Δ
hive 37.62% <23.46%> (-0.01%) ⬇️
mysql 57.33% <65.30%> (+0.01%) ⬆️
postgres 57.36% <65.30%> (+<0.01%) ⬆️
presto 39.50% <23.46%> (-0.02%) ⬇️
python 84.21% <90.81%> (+0.01%) ⬆️
sqlite 57.06% <55.10%> (+<0.01%) ⬆️
unit 75.22% <87.75%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 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.

Comment thread superset/commands/database/update.py Resolved
rusackas and others added 2 commits September 8, 2026 09:05
- Reuse DatabaseDAO._apply_base_filter in get_database_by_name instead
  of reimplementing the base_filter application inline, so the
  visibility boundary can't diverge if that logic changes.
- Refine the encrypted_extra reuse check in update.py (building on the
  applied suggestion from this thread): check model.password is not
  None rather than re-parsing the masked URI to determine whether this
  engine even has a URI password, and exclude an empty ("{}")
  encrypted_extra from being treated as a stored secret to protect.
- Parameterize field_name on DatabaseUpdateUnsafeRebindError so the SSH
  tunnel branch attributes its 422 to ssh_tunnel instead of
  sqlalchemy_uri.
- Fix a bug shared by test_connection.py and validate.py: the SSH
  tunnel password unmask was gated on the combined identity-changed
  flag (engine_params OR ssh tunnel endpoint), so an unrelated
  engine_params edit would spuriously withhold a legitimate,
  unchanged SSH tunnel's stored password. Gate the tunnel unmask on
  its own endpoint-changed check instead, independent of engine_params
  (matching how update.py already gates its SSH tunnel check
  independently of the URI/engine_params check).

Regression tests added for all of the above; each verified to fail
without its corresponding fix and pass with it.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@rusackas

rusackas commented Sep 8, 2026

Copy link
Copy Markdown
Member Author

Went through Bito's additional suggestions and sha174n's inline review, pushed a follow-up commit (72ccf98) addressing what checked out:

Taken:

  • The encrypted_extra reuse gap in update.py (Bito's CWE-200 finding, sha174n's more detailed version with a suggestion block) — real gap, took sha174n's fix with two refinements (check model.password is not None instead of re-deriving via the masked URI, and exclude an empty "{}" encrypted_extra from being treated as a stored secret).
  • daos/database.py's duplicate base-filter logic — DatabaseDAO._apply_base_filter exists upstream now (landed after this branch was first opened), swapped the manual reimplementation for it.
  • The SSH tunnel gating bug flagged on validate.py — real, and it turned out to also exist in test_connection.py (same pattern, just not flagged there). Both now gate the tunnel's own password unmask on whether the tunnel endpoint itself changed, not the combined identity flag, so an unrelated engine_params edit no longer spuriously breaks a legitimate tunneled connection test.
  • The field_name misattribution on DatabaseUpdateUnsafeRebindError — parameterized it so the SSH-tunnel-only rebind case attributes its 422 correctly.

Not taken: the three "narrow engine_params comparison to host/port only" suggestions (update.py, test_connection.py, importers/v1/utils.py). The false-positive concern is real, but the fix as proposed is a regression risk as-is — Postgres has hostaddr as a second way to redirect the destination independent of host, and I haven't audited whether an equivalent exists across the other engine specs this code touches. Narrowing the comparison without that audit could reopen the exact bug this PR closes for some driver. Left the conservative whole-dict comparison in place; the usability cost seems like a reasonable follow-up issue for someone to do that audit properly rather than something to rush into a security-relevant PR.

Regression tests added for everything taken above, each verified to fail without its fix and pass with it.

@netlify

netlify Bot commented Sep 8, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 527bef3
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6aa040d1bf90a700082bb6ac
😎 Deploy Preview https://deploy-preview-44003--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@sha174n sha174n 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.

LGTM. The destination-change checks now cover the URI password, encrypted_extra, and the SSH tunnel per-secret, so a stored secret is no longer reattached onto a changed destination when only one of them is refreshed — and engines that keep credentials entirely in encrypted_extra (no URI password) can still make legitimate destination changes. Test coverage matches each path, including the encrypted_extra-only and fresh-URI-password-with-masked-encrypted_extra cases. Thanks for the quick turnaround.

@rusackas
rusackas merged commit 33c6df7 into master Sep 8, 2026
75 checks passed
@rusackas
rusackas deleted the fix/database-connection-identity-check branch September 8, 2026 18:02
@bito-code-review

Copy link
Copy Markdown
Contributor

Bito Automatic Review Skipped – PR Already Merged

Bito scheduled an automatic review for this pull request, but the review was skipped because this PR was merged before the review could be run.
No action is needed if you didn't intend to review it. To get a review, you can type /review in a comment and save it

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants