Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(api): authorize task cancellation by dataset access (#19359)

Harsh Kashyap19ec6245c4fa
diff --git a/api/apps/restful_apis/task_api.py b/api/apps/restful_apis/task_api.py
index 3688e71bc8..1e016a4396 100644
--- a/api/apps/restful_apis/task_api.py
+++ b/api/apps/restful_apis/task_api.py
@@ -16,7 +16,7 @@
import logging
from datetime import datetime
-from api.apps import login_required
+from api.apps import current_user, login_required
from api.db.services.task_service import TaskService, CANVAS_DEBUG_DOC_ID, GRAPH_RAPTOR_FAKE_DOC_ID
from api.utils.api_utils import (
get_json_result,
@@ -55,6 +55,29 @@ async def _cancel_task(task_id):
Sets a Redis cancel flag, updates the task progress to -1 (cancelled),
and marks the associated document's run status as CANCEL if applicable.
"""
+ exists, task = TaskService.get_by_id(task_id)
+ if not exists:
+ return get_json_result(data=True)
+
+ # Cancelling flips the document to CANCEL and sets the worker cancel flag,
+ # so the caller must be able to access the dataset that owns the document -
+ # otherwise any logged-in user could stop another tenant's parsing tasks by
+ # guessing a task id. Tasks bound to fake doc ids (canvas debug,
+ # graph/raptor) carry no resolvable document and are cancelled through the
+ # kb-scoped flows instead.
+ doc_id = task.doc_id
+ doc = None
+ if doc_id and doc_id not in (CANVAS_DEBUG_DOC_ID, GRAPH_RAPTOR_FAKE_DOC_ID):
+ from api.db.services.document_service import DocumentService
+
+ # DocumentService.accessible fails closed when the document no longer
+ # resolves, so a task whose document is gone cannot be cancelled cross
+ # tenant.
+ if not DocumentService.accessible(doc_id, current_user.id):
+ logging.warning("task cancel denied: task_id=%s user_id=%s", task_id, current_user.id)
+ return get_json_result(data=False, code=RetCode.AUTHENTICATION_ERROR, message="no authorization")
+ _, doc = DocumentService.get_by_id(doc_id)
+
try:
REDIS_CONN.set(f"{task_id}-cancel", "x")
except Exception as e:
@@ -64,10 +87,6 @@ async def _cancel_task(task_id):
message="Failed to stop task",
)
- exists, task = TaskService.get_by_id(task_id)
- if not exists:
- return get_json_result(data=True)
-
# Append a cancellation message so the user can see it in progress_msg.
try:
cancel_msg = f"\n{datetime.now().strftime('%H:%M:%S')} Task stopped by user."
@@ -81,20 +100,16 @@ async def _cancel_task(task_id):
logging.warning("Failed to update task %s progress after cancellation: %s", task_id, str(e))
# If the task belongs to a document, also mark the document's run status as
- # cancelled so that the UI reflects the state correctly.
+ # cancelled so that the UI reflects the state correctly. Reuses the document
+ # resolved during the authorization check above.
try:
- from api.db.services.document_service import DocumentService
-
- doc_id = task.doc_id
- if doc_id and doc_id not in (CANVAS_DEBUG_DOC_ID, GRAPH_RAPTOR_FAKE_DOC_ID):
- _, doc = DocumentService.get_by_id(doc_id)
- if doc and str(doc.run) in (TaskStatus.RUNNING.value, TaskStatus.SCHEDULE.value):
- cancel_doc_msg = f"\n{datetime.now().strftime('%H:%M:%S')} Task stopped by user."
- DocumentService.update_by_id(
- doc_id,
- {"run": TaskStatus.CANCEL.value, "progress": 0, "progress_msg": (doc.progress_msg or "") + cancel_doc_msg},
- )
- logging.debug("Appended cancellation marker to progress_msg on task cancel: task_id=%s doc_id=%s", task_id, doc_id)
+ if doc is not None and str(doc.run) in (TaskStatus.RUNNING.value, TaskStatus.SCHEDULE.value):
+ cancel_doc_msg = f"\n{datetime.now().strftime('%H:%M:%S')} Task stopped by user."
+ DocumentService.update_by_id(
+ doc_id,
+ {"run": TaskStatus.CANCEL.value, "progress": 0, "progress_msg": (doc.progress_msg or "") + cancel_doc_msg},
+ )
+ logging.debug("Appended cancellation marker to progress_msg on task cancel: task_id=%s doc_id=%s", task_id, doc_id)
except Exception as e:
logging.warning("Failed to update document run status for task %s: %s", task_id, str(e))
diff --git a/test/unit_test/api/apps/restful_apis/test_task_cancel_authz_unit.py b/test/unit_test/api/apps/restful_apis/test_task_cancel_authz_unit.py
new file mode 100644
index 0000000000..50cfe994c6
--- /dev/null
+++ b/test/unit_test/api/apps/restful_apis/test_task_cancel_authz_unit.py
@@ -0,0 +1,266 @@
+#
+# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+#
+# Licensed 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.
+#
+"""Authorization tests for POST /tasks/<task_id>/cancel and PATCH /tasks/<task_id>.
+
+Cancelling a task flips its document to CANCEL and sets the Redis cancel
+flag, so the route must verify the caller can access the dataset that owns
+the task's document. These tests stub the HTTP layer and services and drive
+the real handler.
+"""
+
+import asyncio
+import importlib.util
+import sys
+from pathlib import Path
+from types import ModuleType, SimpleNamespace
+
+import pytest
+
+
+class _DummyManager:
+ def route(self, *_args, **_kwargs):
+ def decorator(func):
+ return func
+
+ return decorator
+
+
+def _run(coro):
+ return asyncio.run(coro)
+
+
+REDIS_SETS: list = []
+REQUEST_JSON: dict = {"action": "stop"}
+
+
+def _load_module(monkeypatch, *, accessible_kb_ids):
+ repo_root = Path(__file__).resolve().parents[5]
+
+ quart_mod = ModuleType("quart")
+ monkeypatch.setitem(sys.modules, "quart", quart_mod)
+
+ api_pkg = ModuleType("api")
+ api_pkg.__path__ = [str(repo_root / "api")]
+ monkeypatch.setitem(sys.modules, "api", api_pkg)
+
+ apps_mod = ModuleType("api.apps")
+ apps_mod.__path__ = [str(repo_root / "api" / "apps")]
+ apps_mod.current_user = SimpleNamespace(id="user-a")
+ apps_mod.login_required = lambda func: func
+ monkeypatch.setitem(sys.modules, "api.apps", apps_mod)
+ api_pkg.apps = apps_mod
+
+ api_utils_mod = ModuleType("api.utils.api_utils")
+
+ def get_json_result(data=None, message="success", code=0):
+ return {"code": code, "data": data, "message": message}
+
+ async def get_request_json():
+ return REQUEST_JSON
+
+ def validate_request(*_keys):
+ def _decorator(func):
+ async def _wrapper(*args, **kwargs):
+ return await func(*args, **kwargs)
+
+ return _wrapper
+
+ return _decorator
+
+ api_utils_mod.get_json_result = get_json_result
+ api_utils_mod.get_request_json = get_request_json
+ api_utils_mod.validate_request = validate_request
+ monkeypatch.setitem(sys.modules, "api.utils.api_utils", api_utils_mod)
+
+ constants_mod = ModuleType("common.constants")
+
+ class RetCode:
+ ARGUMENT_ERROR = 101
+ DATA_ERROR = 102
+ AUTHENTICATION_ERROR = 109
+ CONNECTION_ERROR = 503
+
+ class _Status:
+ def __init__(self, v):
+ self.value = v
+
+ class TaskStatus:
+ RUNNING = _Status("1")
+ SCHEDULE = _Status("0")
+ CANCEL = _Status("4")
+
+ constants_mod.RetCode = RetCode
+ constants_mod.TaskStatus = TaskStatus
+ monkeypatch.setitem(sys.modules, "common.constants", constants_mod)
+
+ redis_mod = ModuleType("rag.utils.redis_conn")
+
+ class _Redis:
+ @staticmethod
+ def set(key, value):
+ REDIS_SETS.append(key)
+
+ redis_mod.REDIS_CONN = _Redis
+ monkeypatch.setitem(sys.modules, "rag.utils.redis_conn", redis_mod)
+
+ # TaskService stub: task-1 -> doc-1 -> kb-mine; task-2 -> doc-2 -> kb-theirs
+ task_svc_mod = ModuleType("api.db.services.task_service")
+
+ class _UpdateChain:
+ def where(self, *a):
+ return self
+
+ def execute(self):
+ return 1
+
+ class _TaskModel:
+ id = "task-id"
+ progress_msg = ""
+ progress = 0
+
+ @staticmethod
+ def update(**_kw):
+ return _UpdateChain()
+
+ class _TaskService:
+ model = _TaskModel
+
+ @staticmethod
+ def get_by_id(task_id):
+ if task_id == "task-1":
+ return True, SimpleNamespace(id="task-1", doc_id="doc-1")
+ if task_id == "task-2":
+ return True, SimpleNamespace(id="task-2", doc_id="doc-2")
+ if task_id == "task-3":
+ return True, SimpleNamespace(id="task-3", doc_id="dataflow_x")
+ if task_id == "task-4":
+ return True, SimpleNamespace(id="task-4", doc_id="doc-gone")
+ return False, None
+
+ task_svc_mod.TaskService = _TaskService
+ task_svc_mod.CANVAS_DEBUG_DOC_ID = "dataflow_x"
+ task_svc_mod.GRAPH_RAPTOR_FAKE_DOC_ID = "graph_raptor_x"
+ monkeypatch.setitem(sys.modules, "api.db.services.task_service", task_svc_mod)
+
+ doc_svc_mod = ModuleType("api.db.services.document_service")
+
+ class _DocumentService:
+ @staticmethod
+ def get_by_id(doc_id):
+ if doc_id == "doc-1":
+ return True, SimpleNamespace(id="doc-1", kb_id="kb-mine", run="1", progress_msg="")
+ if doc_id == "doc-2":
+ return True, SimpleNamespace(id="doc-2", kb_id="kb-theirs", run="1", progress_msg="")
+ return False, None
+
+ @staticmethod
+ def accessible(doc_id, user_id):
+ ok, doc = _DocumentService.get_by_id(doc_id)
+ if not ok:
+ return False
+ return doc.kb_id in accessible_kb_ids
+
+ @staticmethod
+ def update_by_id(_id, _data):
+ return 1
+
+ doc_svc_mod.DocumentService = _DocumentService
+ monkeypatch.setitem(sys.modules, "api.db.services.document_service", doc_svc_mod)
+
+ kb_svc_mod = ModuleType("api.db.services.knowledgebase_service")
+
+ class _KnowledgebaseService:
+ @staticmethod
+ def accessible(kb_id, user_id):
+ return kb_id in accessible_kb_ids
+
+ kb_svc_mod.KnowledgebaseService = _KnowledgebaseService
+ monkeypatch.setitem(sys.modules, "api.db.services.knowledgebase_service", kb_svc_mod)
+
+ for mod_name in list(sys.modules.keys()):
+ if mod_name.startswith("api.apps.restful_apis.task_api"):
+ del sys.modules[mod_name]
+
+ module_name = "api.apps.restful_apis.task_api"
+ module_path = repo_root / "api" / "apps" / "restful_apis" / "task_api.py"
+ spec = importlib.util.spec_from_file_location(module_name, module_path)
+ module = importlib.util.module_from_spec(spec)
+ module.manager = _DummyManager()
+ monkeypatch.setitem(sys.modules, module_name, module)
+ spec.loader.exec_module(module)
+ return module
+
+
[email protected](autouse=True)
+def _clean_redis_log():
+ REDIS_SETS.clear()
+
+
+def test_cancel_own_task_succeeds(monkeypatch):
+ module = _load_module(monkeypatch, accessible_kb_ids={"kb-mine"})
+ res = _run(module.cancel_task("task-1"))
+ assert res["code"] == 0, res
+ assert "task-1-cancel" in REDIS_SETS
+
+
+def test_cancel_other_tenants_task_denied(monkeypatch):
+ module = _load_module(monkeypatch, accessible_kb_ids={"kb-mine"})
+ res = _run(module.cancel_task("task-2"))
+ assert res["code"] != 0, f"cross-tenant cancel must be denied, got {res}"
+ assert "task-2-cancel" not in REDIS_SETS, "cancel flag was set for another tenant's task"
+
+
+def test_patch_stop_entry_point_enforces_same_authz(monkeypatch):
+ module = _load_module(monkeypatch, accessible_kb_ids={"kb-mine"})
+ REQUEST_JSON["action"] = "stop"
+ res = _run(module.patch_task("task-2"))
+ assert res["code"] != 0, f"cross-tenant PATCH stop must be denied, got {res}"
+ assert "task-2-cancel" not in REDIS_SETS
+ res = _run(module.patch_task("task-1"))
+ assert res["code"] == 0, res
+ assert "task-1-cancel" in REDIS_SETS
+
+
+def test_patch_rejects_unknown_action(monkeypatch):
+ module = _load_module(monkeypatch, accessible_kb_ids={"kb-mine"})
+ REQUEST_JSON["action"] = "restart"
+ res = _run(module.patch_task("task-1"))
+ assert res["code"] != 0
+ assert "task-1-cancel" not in REDIS_SETS
+
+
+def test_fake_doc_id_tasks_still_cancel(monkeypatch):
+ # Canvas-debug / graph-raptor tasks carry fake doc ids and are cancelled
+ # through the kb-scoped flows; the authz change must not break them.
+ module = _load_module(monkeypatch, accessible_kb_ids=set())
+ res = _run(module.cancel_task("task-3"))
+ assert res["code"] == 0, res
+ assert "task-3-cancel" in REDIS_SETS
+
+
+def test_task_with_unresolved_document_is_denied(monkeypatch):
+ # accessible() fails closed: a task whose document no longer resolves
+ # cannot be cancelled cross tenant.
+ module = _load_module(monkeypatch, accessible_kb_ids={"kb-mine"})
+ res = _run(module.cancel_task("task-4"))
+ assert res["code"] != 0, f"unresolved document must fail closed, got {res}"
+ assert "task-4-cancel" not in REDIS_SETS