Skip to content

fix(versioning): enforce is_managed_externally on version restore - #44013

Merged
rusackas merged 3 commits into
apache:masterfrom
mikebridge:sc-115616-restore-managed-externally
Sep 9, 2026
Merged

rusackas merged 3 commits into
apache:masterfrom
mikebridge:sc-115616-restore-managed-externally

Conversation

@mikebridge

Copy link
Copy Markdown
Member

SUMMARY

version-history.mdx documents that version restore is withheld from externally managed entities — their source of truth lives outside Superset and would overwrite the restore on the next sync. But that refusal lived only in the browser: BaseRestoreVersionCommand.validate() checked the ENABLE_VERSIONING_CAPTURE gate, existence, and editorship, and never is_managed_externally. So an otherwise-authorized editor could restore an externally managed chart, dashboard, or dataset by calling POST /api/v1/{type}/<uuid>/versions/<version_uuid>/restore directly.

validate() now refuses an externally managed entity after the editorship check, raising the command's forbidden_exc (HTTP 403) — matching the intent of the browser gate and enforcing the documented promise server-side. The 403 carries no body, so it reads the same as a permission denial (a known FAB response_403 limitation); routing to failed_exc/422 to carry an explanatory message would log the refusal as an error via logger.exception, so forbidden_exc is used.

Soft-delete recovery is deliberately left available — it changes visibility, not content, so it doesn't conflict with the external source of truth.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Not applicable — backend authorization fix, no UI.

TESTING INSTRUCTIONS

  • Unit: tests/unit_tests/commands/test_base_restore_version_command.py — parametrized over the three concrete restore commands (chart/dashboard/dataset), asserting each raises its own forbidden_exc for an externally managed entity, with a reverted-fix control (an editable, non-managed entity still validates, so the guard is what rejects the managed case). pytest tests/unit_tests/commands/test_base_restore_version_command.py (6 passed).
  • Integration: tests/integration_tests/charts/version_restore_tests.py::...test_restore_refuses_externally_managed_chart — a real chart marked is_managed_externally=True → the restore endpoint returns 403 and the chart is not mutated.
  • The unit guard was verified to fail across all three commands when the is_managed_externally check is reverted.
  • Changed-file pre-commit (mypy/ruff/ruff-format/pylint) clean.

ADDITIONAL INFORMATION

  • Has associated issue: sc-115616 (Preset-internal)
  • Required feature flags:
  • Changes UI
  • Includes DB Migration
  • Introduces new feature or API
  • Removes existing feature or API

🤖 Generated with Claude Code

sc-115616. version-history.mdx states that version restore is withheld from
externally managed entities (their source of truth lives outside Superset and
would overwrite the restore on the next sync), but the refusal existed only in
the browser — BaseRestoreVersionCommand.validate() checked the capture gate,
existence, and editorship, but never is_managed_externally. An otherwise-
authorized editor could therefore restore an externally managed chart,
dashboard, or dataset by calling the endpoint directly.

validate() now refuses an externally managed entity after the editorship
check, raising the command's forbidden_exc (HTTP 403). The 403 carries no
body, so it is indistinguishable from a permission denial (a known FAB
response_403 limitation); routing to failed_exc/422 to carry a message would
log the refusal as an error, so forbidden_exc is used. Soft-delete recovery is
deliberately left available: it changes visibility, not content.

Tests: parametrized unit tests over the three concrete restore commands
(chart/dashboard/dataset) asserting each raises its own forbidden_exc for an
externally managed entity, with a reverted-fix control (an editable, non-
managed entity still validates — the refusal test passes only because of the
guard); and an integration test on a real chart asserting the restore endpoint
returns 403 and does not mutate the chart. UPDATING.md documents the API
behavior change.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01267VBWbvWTNZUg9GvXKgkC
@codecov

codecov Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.84%. Comparing base (7382ee0) to head (cc6a82a).
⚠️ Report is 10 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #44013      +/-   ##
==========================================
+ Coverage   79.81%   79.84%   +0.02%     
==========================================
  Files        2914     2914              
  Lines      170473   170575     +102     
  Branches    39518    39538      +20     
==========================================
+ Hits       136066   136189     +123     
+ Misses      31885    31871      -14     
+ Partials     2522     2515       -7     
Flag Coverage Δ
hive 37.61% <0.00%> (-0.02%) ⬇️
mysql 57.36% <100.00%> (+0.04%) ⬆️
postgres 57.39% <100.00%> (+0.04%) ⬆️
presto 39.49% <0.00%> (-0.02%) ⬇️
python 84.24% <100.00%> (+0.04%) ⬆️
sqlite 57.09% <100.00%> (+0.03%) ⬆️
unit 75.32% <100.00%> (+0.11%) ⬆️

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.

Coordinator/independent review of apache#44013 (sc-115616): the forbidden_exc
ClassVar docstring said it covers only the editorship denial; it now also
covers the externally-managed refusal (both HTTP 403). Also note in the chart
restore integration test that chart is the representative real-model case and
the dashboard/dataset commands inherit the guard from the shared base (pinned
across all three by the parametrized unit test).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01267VBWbvWTNZUg9GvXKgkC
@mikebridge
mikebridge marked this pull request as ready for review September 8, 2026 17:25
@mikebridge

Copy link
Copy Markdown
Member Author

@aminghadersohi — ready for review when you have a moment. Small authz fix: version restore was withheld from externally managed entities only in the browser, so an otherwise-authorized editor could restore one via a direct API call (and have it overwritten on the next external sync). BaseRestoreVersionCommand.validate() now refuses managed-externally entities with 403 after the editorship check; soft-delete recovery is deliberately left available. Parametrized unit tests over all three concrete commands + a real-chart integration test (403, no mutation). A cross-model pass confirmed the gate is complete; the same gap on the ordinary PUT/update commands is tracked separately as sc-120011.

@netlify

netlify Bot commented Sep 8, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 17d5bcd
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6aa044ffc1cda20008029d2f
😎 Deploy Preview https://deploy-preview-44013--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.

@aminghadersohi
aminghadersohi self-requested a review September 8, 2026 17:46

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

Reviewed at head 17d5bcd099b8c3c1ebc20240ed2c07328f213976.

The production change is two lines at superset/commands/version_restore.py:160-161, appended to validate() after the existing raise_for_editorship call at :150. I verified the -3 lines are the docstring rewrite at :67-70 only — nothing was removed from the authorization path. The change is strictly additive: no path is more permissive after it than before.

I focused on the two ways a base-class gate like this usually goes wrong. Both come back clean.

The gate is complete across all three subclasses

A check in a base class only holds if every subclass inherits it, and a partial gate on an authorization control is worse than none because it reads as enforced. Enumerated at head, BaseRestoreVersionCommand has exactly three subclasses — RestoreChartVersionCommand, RestoreDashboardVersionCommand, RestoreDatasetVersionCommand. All three are pure ClassVar declarations; none overrides validate() or run(), so none can skip the check.

Ordering is also guaranteed rather than conventional: run() (:79) has _do_restore() as its only body, and _do_restore() calls self.validate() as its first statement (:91) before resolve_version or restore_version are reached.

On other entry points: restore_version is reached only through restore_version_endpoint (superset/versioning/api_helpers.py:362), which the three API handlers delegate to, and each passes its command class. The backward-compat VersionDAO.restore_version façade (superset/daos/version.py:78) would bypass the command, but it has no callers anywhere in superset/ — no route, task, CLI, or import path reaches it. I found no restore entry point that bypasses the check.

is_managed_externally is universal and cannot be NULL

The bare attribute access with no getattr default would be an AttributeError — a 500 on a restore that should have succeeded — if any reachable model lacked the column. All three do have it:

  • superset/models/slice.py:144 (Slice)
  • superset/models/dashboard.py:207 (Dashboard)
  • superset/connectors/sqla/models.py:232 (BaseDatasource, which SqlaTable inherits)

All three are plain Column(Boolean, nullable=False, default=False) — not hybrids or properties.

The NULL-falsiness concern doesn't apply either. nullable=False makes NULL unstorable, and the migration that introduced the column (2022-01-19_07-34_5fd49410a97a_add_columns_for_external_management.py) used server_default=sa.false(), so legacy rows were backfilled to False rather than left NULL. There is no cohort of rows for which this gate silently does nothing.

Tests

The unit tests are parametrized over the three concrete commands rather than testing the base in isolation, which is exactly the right shape — a base-only test would still pass if a subclass overrode validate(). The integration test asserts both the 403 and that the entity was not mutated.

I reverted only the two production lines and re-ran: the three test_validate_refuses_externally_managed_entity cases fail (one per subclass, DID NOT RAISE {Chart,Dashboard,Dataset}ForbiddenError) while the three non-managed control cases still pass. The tests genuinely pin this change.

Soft-delete scoping is sound

UPDATING.md excludes soft-delete recovery as "changes visibility, not content." Confirmed: BaseRestoreCommand.run() (superset/commands/restore.py) calls model.restore(), which is SoftDeleteMixin.restore() at superset/models/helpers.py:1421 — it sets deleted_at = None and nothing else. It cannot restore content, so the same gate doesn't belong there.


One comment-accuracy nit (non-blocking)

The inline comment at :158-159 says the 403 "carries no body." In FAB 5.2.2, BaseApi.response_403 returns self.response(403, **{"message": "Forbidden"}) — there is a body.

The security property you're relying on still holds, so this isn't a behavior problem: response_403(self) takes no message argument, so the body is fixed and non-customizable, and the externally-managed refusal is byte-identical to the editorship denial. Nothing is disclosed. But since this comment is asserting a security property, it'd be worth matching the wording to reality — something like "carries a fixed body with no reason detail, so it reads the same as a permission denial." The non-disclosure design itself is the right call and worth keeping.

One question, not a defect

A fully-authorized editor now gets an opaque 403 they cannot distinguish from a permissions problem — no indication that the refusal is about external management rather than their own access. That's a real UX cost, and you've knowingly traded it for non-disclosure, which is a defensible trade. Is that the intended end state, or would you want a distinguishable error here eventually? I'm not asserting the current choice is wrong; the UPDATING.md line does document the behavior change on a public endpoint, and for a two-line authz fix that seems proportionate.

Also noting for context, not as something for this PR: you flagged that the equivalent gap on the ordinary PUT/update commands is tracked as sc-120011. That matches what I see — is_managed_externally appears in superset/commands/chart/update.py:130 and create.py:99 only for the parent dashboard check, not as a guard on the updated entity itself. Correctly out of scope here.

Verification notes

  • RAN: tests/unit_tests/commands/test_base_restore_version_command.py — 6 passed at head; 3 failed / 3 passed against the reverted check.
  • INSPECTED (not run): the integration test — it errors in my environment on example-data fixture setup, an environment limitation rather than a test defect. CI covers it (test-postgres, test-mysql, test-sqlite all green at head).
  • CI at head: zero failure, zero timed_out. Most cancelled entries are a superseded run (34256991557, 17:26Z) replaced by a later run (34257056xxx, 17:39Z) where each leg resolved to success or, for the frontend legs, correctly skipped — this PR touches no frontend files. The one leg cancelled without a later counterpart is playwright-tests-experimental, an experimental frontend job. Note that gh pr checks buckets cancelled into its failure column, which misreads this.

Nothing blocking from me. The gate is complete, the attribute is universal, the NULL path is closed, and the tests pin it across all three subclasses.

🤖 Automated review. I'm an external reviewer on this repo, so this is a comment rather than an approval.

…y guard

Amin review of apache#44013: the comment said the 403 "carries no body," but FAB
5.2.2's response_403 returns a fixed ``{"message": "Forbidden"}`` body. The
security property is unchanged — the body is fixed and identical to the
editorship denial, so the refusal discloses nothing — but the comment now
states that accurately (fixed body, no reason detail, indistinguishable from a
permission denial) rather than claiming an empty body. Comment only.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01267VBWbvWTNZUg9GvXKgkC
@mikebridge

Copy link
Copy Markdown
Member Author

@aminghadersohi thanks — good catches. Addressed in cc6a82a:

  • Corrected the comment: FAB's response_403 does return a fixed {"message": "Forbidden"} body; reworded to say it carries a fixed body with no reason detail (identical to the editorship denial), so the refusal discloses nothing but reads the same as a permission denial.

On your question about the opaque 403 for a fully-authorized editor: that's the intended end state for this change. The non-disclosure is deliberate (a managed-externally refusal shouldn't be more informative than a permission denial), and keeping it as the shared forbidden_exc avoids a distinct exception + endpoint mapping for what sc-115616 scoped as the minimal server-side gate. A distinguishable, documented error (e.g. a 409/422 with a 'managed externally' reason) is a reasonable future enhancement if operators need to tell the two apart — happy to file it as a follow-up if you think it's worth surfacing to API clients.

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

Round 2, re-reviewed at head cc6a82ada3741d25590e732bba5a3a08a0445594. Delta since my round-1 review (5146206213 @ 17d5bcd099b8) is one commit, cc6a82ada3 — comment-only: superset/commands/version_restore.py, 4 insertions / 2 deletions, no other file touched. The gate itself (:162-163) is byte-identical to what I reviewed last round; only its preceding comment block changed. Nothing in this delta touches the analysis I did in round 1, so I'm not re-deriving it.

The corrected 403-body wording is accurate, and it states the right reason

This is the one thing I needed to judge, and I checked the prose rather than the commit subject.

The new text at :157-161 reads: "Raised as forbidden_exc (HTTP 403); FAB's response_403 returns a fixed {"message": "Forbidden"} body with no reason detail, identical to the editorship denial above, so the refusal discloses nothing but also can't be distinguished from a permission denial."

Verified against the installed library and this head:

  • FAB 5.2.2 BaseApi.response_403 is return self.response(403, **{"message": "Forbidden"}) — the literal body quoted in the comment is exact.
  • restore_version_endpoint calls api.response_403() with no arguments at superset/versioning/api_helpers.py:393, and both denials raise the same forbidden_exc class (:152 for editorship, :163 for managed-externally). So the two responses aren't merely similar — they are produced by the same call site from the same exception type, and are byte-identical.

That last point is why I'd call this more than a softening of the old claim. "Identical to the editorship denial above" is the load-bearing fact, and it's the stronger one: the reason detail is destroyed at the raise, not at the response. Even if response_403 did accept a message, no reason could reach the client without an endpoint change. The comment now says something a future reader can actually rely on, which was my whole reason for filing the nit. Good fix.

(For the record, the response_403(self) signature takes no message parameter either — so the "fixed" claim holds twice over. Noting it as corroboration, not as a further request.)

New at this head: the exception survives the transaction wrapper

I flagged "HTTP 403" as an assertion worth confirming end-to-end, since run() wraps _do_restore() in @transaction(on_error=partial(on_error, reraise=self.failed_exc)) and transaction catches except Exception broadly (superset/utils/decorators.py:274). A broad catch between a security raise and the response boundary is the usual way a control like this quietly becomes a no-op.

It doesn't happen here. on_error's catches keeps its default (SQLAlchemyError,) (decorators.py:223) because the command overrides only reraise; a ForbiddenError is not a SQLAlchemyError, so it falls to else: raise ex at :243 and propagates unchanged. I confirmed all three triplets are mutually disjoint — for chart, dashboard and dataset, forbidden_exc is not a subclass of SQLAlchemyError, not_found_exc or failed_exc — so the earlier except command_cls.not_found_exc at api_helpers.py:390 can't shadow it either. The 403 claim holds end-to-end. The db.session.rollback() at :275 runs first, which is the right order and matches your integration test's no-mutation assertion.

My round-1 open question is answered — closing it

You addressed the opaque-403 UX question in your PR comment: it's the intended end state, non-disclosure is deliberate, and keeping the shared forbidden_exc avoids a distinct exception plus endpoint mapping for what sc-115616 scoped as the minimal server-side gate. That's a reasonable call and it was always yours to make — I raised it as a question, not a defect, and I'm satisfied. No need to file the 409/422 follow-up on my account; if operators do ask to tell the two apart, the comment now documents the constraint clearly enough that whoever picks it up will know what they're changing.

Verification notes

  • RAN: tests/unit_tests/commands/test_base_restore_version_command.py — 6 passed at this head. py_compile clean (the comment carries non-ASCII em-dashes). I did not repeat last round's revert experiment; the delta is comment-only and the tests are unchanged.
  • INSPECTED: the integration test — still not runnable in my environment (example-data fixture setup), as last round. CI covers it.
  • CI at this head: fully settled and non-failing on both surfaces. statusCheckRollup returns 75 legs — 74 CheckRun (62 success / 9 skipped / 3 neutral, all COMPLETED) plus 1 StatusContext, netlify/superset-docs-preview/deploy-preview = SUCCESS. Deduping check-runs to newest-per-name across all pages gives 60 distinct legs: 48 success / 9 skipped / 3 neutral. Zero failure, zero cancelled, zero timed_out, nothing pending — cleaner than round 1, which had a genuinely cancelled playwright-tests-experimental leg with no counterpart. 🎪 Sync PR to desired state completed success at 20:40:50Z. mergeable=true; mergeable_state=blocked reflects REVIEW_REQUIRED only.

Nothing blocking. The correction is accurate and the question is closed; from my side this is done.

🤖 Automated review. I'm an external reviewer on this repo, so this is a comment rather than an approval.

mikebridge added a commit to mikebridge/superset that referenced this pull request Sep 8, 2026
…date

An entity with is_managed_externally set has its source of truth outside
Superset; the browser hides the edit affordances, but the refusal was
browser-only — an otherwise-authorized editor could mutate the entity via
PUT /api/v1/{chart,dashboard,dataset}/<id> directly and have the change
overwritten on the next external sync. This is the update-path counterpart
of the matching gate apache#44013 adds to version restore.

Add a shared raise_if_managed_externally helper (commands/utils.py) and
call it from all three UpdateCommand.validate() implementations, after the
editorship check, raising each entity's editorship-denial exception so the
403 response body is identical to a permission denial and discloses
nothing new. Two derived-state save paths are deliberately exempt: the
chart query-context-only save (report workers) and the dashboard
colors-sync command (fired in the background while a dashboard is merely
viewed).

sc-120011

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JRLEJS4mUqKBoPjSjviKUW
@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #6ff2e8

Actionable Suggestions - 0
Review Details
  • Files reviewed - 3 · Commit Range: 49f2d83..cc6a82a
    • superset/commands/version_restore.py
    • tests/integration_tests/charts/version_restore_tests.py
    • tests/unit_tests/commands/test_base_restore_version_command.py
  • Files skipped - 1
    • UPDATING.md - Reason: Filter setting
  • 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 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, approving! aminghadersohi's two-round review is thorough as usual: confirmed the gate can't be bypassed by any of the three subclasses or the legacy DAO facade, confirmed is_managed_externally can't be NULL on any of the three models, reverted the fix to confirm the tests actually pin it, and traced the exception through the @transaction wrapper to confirm it isn't swallowed. Real fix for a real gap, nice work.

@rusackas
rusackas merged commit fc110d8 into apache:master Sep 9, 2026
75 checks passed
mikebridge added a commit to mikebridge/superset that referenced this pull request Sep 11, 2026
…date

An entity with is_managed_externally set has its source of truth outside
Superset; the browser hides the edit affordances, but the refusal was
browser-only — an otherwise-authorized editor could mutate the entity via
PUT /api/v1/{chart,dashboard,dataset}/<id> directly and have the change
overwritten on the next external sync. This is the update-path counterpart
of the matching gate apache#44013 adds to version restore.

Add a shared raise_if_managed_externally helper (commands/utils.py) and
call it from all three UpdateCommand.validate() implementations, after the
editorship check, raising each entity's editorship-denial exception so the
403 response body is identical to a permission denial and discloses
nothing new. Two derived-state save paths are deliberately exempt: the
chart query-context-only save (report workers) and the dashboard
colors-sync command (fired in the background while a dashboard is merely
viewed).

sc-120011

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JRLEJS4mUqKBoPjSjviKUW
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants