codeant-ai-for-open-source[bot] commented on code in PR #42469: URL: https://github.com/apache/superset/pull/42469#discussion_r3673647341
########## superset/commands/version_restore.py: ########## @@ -0,0 +1,152 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""Shared base for the per-entity restore-version commands. + +The three concrete commands (:mod:`superset.commands.chart.restore_version`, +:mod:`superset.commands.dashboard.restore_version`, +:mod:`superset.commands.dataset.restore_version`) differ only in: + +* the model class they operate on +* the per-entity ``NotFoundError`` / ``ForbiddenError`` / ``UpdateFailedError`` + triplet they raise + +Everything else — capture gate, lookup, editorship check, version-uuid +resolution, action-kind stamping, restore dispatch, transactional +boundary — lives here. Subclasses are pure declarations: the base builds +the ``@transaction`` wrapper at call time from the ``failed_exc`` +ClassVar (mirroring ``BaseRestoreCommand``), so a new entity rollout +cannot forget the decorator. +""" + +from __future__ import annotations + +from functools import partial +from typing import Any, ClassVar +from uuid import UUID + +from superset import security_manager +from superset.commands.base import BaseCommand +from superset.exceptions import SupersetSecurityException +from superset.extensions import db +from superset.utils.decorators import on_error, transaction +from superset.versioning.queries import find_active_by_uuid, resolve_version +from superset.versioning.restore import restore_version, RestoreResult +from superset.versioning.utils import capture_enabled + + +class BaseRestoreVersionCommand(BaseCommand): + """Workflow for a non-destructive version restore on one entity. + + Subclasses declare the model class plus the three entity-specific + exception ClassVars; the base owns the workflow and the transactional + boundary. + """ + + #: Subclass overrides — the versioned model class (``Slice`` / + #: ``Dashboard`` / ``SqlaTable``). + model_cls: ClassVar[type] + + #: Subclass overrides — exception classes raised on the matching + #: failure modes. ``not_found_exc`` covers "no such entity", + #: "version_uuid not on this entity", and "capture disabled" (the + #: route is inert under the kill-switch); the API handler maps each + #: to HTTP 404. ``forbidden_exc`` covers the row-level editorship + #: denial (HTTP 403). ``failed_exc`` wraps unexpected failures inside + #: the transaction (HTTP 422). + not_found_exc: ClassVar[type[Exception]] + forbidden_exc: ClassVar[type[Exception]] + failed_exc: ClassVar[type[Exception]] + + def __init__(self, entity_uuid: UUID, version_uuid: UUID) -> None: + self._uuid = entity_uuid + self._version_uuid = version_uuid + + def run(self) -> RestoreResult: + # Build the transactional wrapper at call time so ``on_error`` can + # reference ``self.failed_exc`` — a per-subclass ClassVar that + # isn't available when this method is defined on the base (same + # pattern and rationale as ``BaseRestoreCommand.run``). + @transaction(on_error=partial(on_error, reraise=self.failed_exc)) + def _perform() -> RestoreResult: + return self._do_restore() + + return _perform() + + def _do_restore(self) -> RestoreResult: + entity = self.validate() + resolved = resolve_version( + self.model_cls, self._uuid, self._version_uuid, entity=entity + ) + if resolved is None: + raise self.not_found_exc() + version_number, transaction_id = resolved Review Comment: **Suggestion:** The target version is resolved without locking or validating the entity's current version, then the revert is applied using the potentially stale `entity` instance. If another request edits the entity after `resolve_version()` but before `restore_version()`, this restore can overwrite that newer update. Lock the live row for the restore transaction and/or re-check its current transaction/version immediately before applying the revert, aborting when it has changed. [race condition] <details> <summary><b>Severity Level:</b> Critical 🚨</summary> ```mdx - ❌ Chart restores can silently overwrite newer chart edits. - ❌ Dashboard restores can overwrite newer dashboard changes. - ❌ Dataset restores can overwrite newer fields, columns, or metrics. - ⚠️ Concurrent edits are especially realistic through collaborative UI/API usage. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=5b3b41f1dd444c46adf67366ebcb8b93&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=5b3b41f1dd444c46adf67366ebcb8b93&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/commands/version_restore.py **Line:** 91:96 **Comment:** *Race Condition: The target version is resolved without locking or validating the entity's current version, then the revert is applied using the potentially stale `entity` instance. If another request edits the entity after `resolve_version()` but before `restore_version()`, this restore can overwrite that newer update. Lock the live row for the restore transaction and/or re-check its current transaction/version immediately before applying the revert, aborting when it has changed. 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 ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42469&comment_hash=39c30d5c4a9d1eb6f73976a86fd865391de16344bcf61c96781d7c6b7c12387d&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42469&comment_hash=39c30d5c4a9d1eb6f73976a86fd865391de16344bcf61c96781d7c6b7c12387d&reaction=dislike'>👎</a> -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
