Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(api): enforce RAG draft variable access boundaries (#40745)

WH-209962a544a14670
diff --git a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_draft_variable.py b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_draft_variable.py
index b7d470ca13e..b272506052d 100644
--- a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_draft_variable.py
+++ b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_draft_variable.py
@@ -8,7 +8,6 @@ from flask import Response
from flask_restx import Resource, marshal, marshal_with
from pydantic import BaseModel, Field
from sqlalchemy.orm import sessionmaker
-from werkzeug.exceptions import Forbidden
from controllers.common.errors import InvalidArgumentError, NotFoundError
from controllers.common.schema import query_params_from_model, register_schema_models
@@ -19,12 +18,22 @@ from controllers.console.app.error import (
from controllers.console.app.workflow_draft_variable import (
_WORKFLOW_DRAFT_VARIABLE_FIELDS, # type: ignore[private-usage]
EnvironmentVariableListResponse,
+ ensure_variable_access,
workflow_draft_variable_list_model,
workflow_draft_variable_list_without_value_model,
workflow_draft_variable_model,
)
from controllers.console.datasets.wraps import get_rag_pipeline
-from controllers.console.wraps import account_initialization_required, model_validate, setup_required, with_current_user
+from controllers.console.wraps import (
+ RBACPermission,
+ RBACResourceScope,
+ account_initialization_required,
+ edit_permission_required,
+ model_validate,
+ rbac_permission_required,
+ setup_required,
+ with_current_user,
+)
from core.app.file_access import DatabaseFileAccessController
from core.workflow.llm_environment_variable import LLMEnvironmentVariable, environment_variable_value_type
from core.workflow.variable_prefixes import CONVERSATION_VARIABLE_NODE_ID, SYSTEM_VARIABLE_NODE_ID
@@ -62,21 +71,21 @@ def _api_prerequisite[T, **P, R](
It ensures the following conditions are satisfied:
- - Dify has been property setup.
+ - Dify has been properly set up.
- The request user has logged in and initialized.
- - The requested app is a workflow or a chat flow.
- - The request user has the edit permission for the app.
+ - The requested RAG pipeline belongs to the current tenant.
+ - The request user has legacy edit permission or Dataset edit RBAC access.
"""
@setup_required
@login_required
@account_initialization_required
@get_rag_pipeline
+ @edit_permission_required
+ @rbac_permission_required(RBACResourceScope.DATASET, RBACPermission.DATASET_EDIT)
@with_current_user
@wraps(f)
def wrapper(self: T, current_user: Account, *args: P.args, **kwargs: P.kwargs) -> R | Response:
- if not current_user.has_edit_permission:
- raise Forbidden()
return f(self, current_user, *args, **kwargs)
return wrapper
@@ -180,16 +189,17 @@ class RagPipelineVariableApi(Resource):
@console_ns.response(200, "Variable retrieved successfully", workflow_draft_variable_model)
@_api_prerequisite
@marshal_with(workflow_draft_variable_model)
- def get(self, _current_user: Account, pipeline: Pipeline, variable_id: UUID):
+ def get(self, current_user: Account, pipeline: Pipeline, variable_id: UUID):
draft_var_srv = WorkflowDraftVariableService(
session=db.session(),
)
variable_id_str = str(variable_id)
- variable = draft_var_srv.get_variable(variable_id=variable_id_str)
- if variable is None:
- raise NotFoundError(description=f"variable not found, id={variable_id_str}")
- if variable.app_id != pipeline.id:
- raise NotFoundError(description=f"variable not found, id={variable_id_str}")
+ variable = ensure_variable_access(
+ variable=draft_var_srv.get_variable(variable_id=variable_id_str),
+ app_id=pipeline.id,
+ variable_id=variable_id_str,
+ current_user_id=current_user.id,
+ )
return variable
@console_ns.response(200, "Variable updated successfully", workflow_draft_variable_model)
@@ -200,7 +210,7 @@ class RagPipelineVariableApi(Resource):
def patch(
self,
req_data: WorkflowDraftVariablePatchPayload,
- _current_user: Account,
+ current_user: Account,
pipeline: Pipeline,
variable_id: UUID,
):
@@ -231,11 +241,12 @@ class RagPipelineVariableApi(Resource):
args = req_data.model_dump(exclude_none=True)
variable_id_str = str(variable_id)
- variable = draft_var_srv.get_variable(variable_id=variable_id_str)
- if variable is None:
- raise NotFoundError(description=f"variable not found, id={variable_id_str}")
- if variable.app_id != pipeline.id:
- raise NotFoundError(description=f"variable not found, id={variable_id_str}")
+ variable = ensure_variable_access(
+ variable=draft_var_srv.get_variable(variable_id=variable_id_str),
+ app_id=pipeline.id,
+ variable_id=variable_id_str,
+ current_user_id=current_user.id,
+ )
new_name = args.get(self._PATCH_NAME_FIELD, None)
raw_value = args.get(self._PATCH_VALUE_FIELD, None)
@@ -272,16 +283,17 @@ class RagPipelineVariableApi(Resource):
@console_ns.response(204, "Variable deleted successfully")
@_api_prerequisite
- def delete(self, _current_user: Account, pipeline: Pipeline, variable_id: UUID):
+ def delete(self, current_user: Account, pipeline: Pipeline, variable_id: UUID):
draft_var_srv = WorkflowDraftVariableService(
session=db.session(),
)
variable_id_str = str(variable_id)
- variable = draft_var_srv.get_variable(variable_id=variable_id_str)
- if variable is None:
- raise NotFoundError(description=f"variable not found, id={variable_id_str}")
- if variable.app_id != pipeline.id:
- raise NotFoundError(description=f"variable not found, id={variable_id_str}")
+ variable = ensure_variable_access(
+ variable=draft_var_srv.get_variable(variable_id=variable_id_str),
+ app_id=pipeline.id,
+ variable_id=variable_id_str,
+ current_user_id=current_user.id,
+ )
draft_var_srv.delete_variable(variable)
db.session.commit()
return Response("", 204)
@@ -292,7 +304,7 @@ class RagPipelineVariableResetApi(Resource):
@console_ns.response(200, "Variable reset successfully", workflow_draft_variable_model)
@console_ns.response(204, "Variable reset (no content)")
@_api_prerequisite
- def put(self, _current_user: Account, pipeline: Pipeline, variable_id: UUID):
+ def put(self, current_user: Account, pipeline: Pipeline, variable_id: UUID):
draft_var_srv = WorkflowDraftVariableService(
session=db.session(),
)
@@ -304,11 +316,12 @@ class RagPipelineVariableResetApi(Resource):
f"Draft workflow not found, pipeline_id={pipeline.id}",
)
variable_id_str = str(variable_id)
- variable = draft_var_srv.get_variable(variable_id=variable_id_str)
- if variable is None:
- raise NotFoundError(description=f"variable not found, id={variable_id_str}")
- if variable.app_id != pipeline.id:
- raise NotFoundError(description=f"variable not found, id={variable_id_str}")
+ variable = ensure_variable_access(
+ variable=draft_var_srv.get_variable(variable_id=variable_id_str),
+ app_id=pipeline.id,
+ variable_id=variable_id_str,
+ current_user_id=current_user.id,
+ )
resetted = draft_var_srv.reset_variable(draft_workflow, variable)
db.session.commit()
diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_draft_variable.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_draft_variable.py
index a000a6a6ed5..2c8ee4da25d 100644
--- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_draft_variable.py
+++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_draft_variable.py
@@ -1,4 +1,5 @@
-from inspect import unwrap
+from collections.abc import Callable
+from inspect import getclosurevars, unwrap
from unittest.mock import MagicMock, patch
import pytest
@@ -17,6 +18,7 @@ from controllers.console.datasets.rag_pipeline.rag_pipeline_draft_variable impor
RagPipelineVariableResetApi,
WorkflowDraftVariablePatchPayload,
)
+from controllers.console.wraps import RBACPermission, RBACResourceScope
from core.workflow.llm_environment_variable import LLMEnvironmentVariable
from core.workflow.variable_prefixes import SYSTEM_VARIABLE_NODE_ID
from graphon.variables.types import SegmentType
@@ -44,6 +46,17 @@ def restx_config(app):
return patch.dict(app.config, {"RESTX_MASK_HEADER": "X-Fields"})
+def test_rag_draft_variable_routes_require_dataset_edit_permission() -> None:
+ route = RagPipelineVariableApi.get
+ legacy_gate = unwrap(route, stop=lambda decorator: "edit_permission_required" in decorator.__code__.co_qualname)
+ rbac_gate = unwrap(route, stop=lambda decorator: "scene" in getclosurevars(decorator).nonlocals)
+
+ assert "edit_permission_required" in legacy_gate.__code__.co_qualname
+ permissions = getclosurevars(rbac_gate).nonlocals
+ assert permissions["resource_type"] == RBACResourceScope.DATASET
+ assert permissions["scene"] == RBACPermission.DATASET_EDIT
+
+
class TestRagPipelineVariableCollectionApi:
def test_get_variables_success(self, app: Flask, fake_db, editor_user, restx_config):
api = RagPipelineVariableCollectionApi()
@@ -183,7 +196,7 @@ class TestRagPipelineVariableApi:
method = unwrap(api.patch)
pipeline = MagicMock(id="p1", tenant_id="t1")
- variable = MagicMock(app_id="p1", value_type=SegmentType.FILE)
+ variable = MagicMock(app_id="p1", user_id="account-1", value_type=SegmentType.FILE)
srv = MagicMock()
srv.get_variable.return_value = variable
@@ -207,7 +220,7 @@ class TestRagPipelineVariableApi:
method = unwrap(api.delete)
pipeline = MagicMock(id="p1")
- variable = MagicMock(app_id="p1")
+ variable = MagicMock(app_id="p1", user_id="account-1")
srv = MagicMock()
srv.get_variable.return_value = variable
@@ -225,6 +238,61 @@ class TestRagPipelineVariableApi:
assert result.status_code == 204
+ ("api_type", "method", "payload"),
+ [
+ (RagPipelineVariableApi, RagPipelineVariableApi.get, None),
+ (
+ RagPipelineVariableApi,
+ RagPipelineVariableApi.patch,
+ WorkflowDraftVariablePatchPayload(name="new name"),
+ ),
+ (RagPipelineVariableApi, RagPipelineVariableApi.delete, None),
+ (RagPipelineVariableResetApi, RagPipelineVariableResetApi.put, None),
+ ],
+)
+def test_direct_variable_access_rejects_different_user(
+ app: Flask,
+ fake_db: MagicMock,
+ editor_user: Account,
+ api_type: type[RagPipelineVariableApi] | type[RagPipelineVariableResetApi],
+ method: Callable[..., object],
+ payload: WorkflowDraftVariablePatchPayload | None,
+) -> None:
+ api = api_type()
+ method = unwrap(method)
+ pipeline = MagicMock(id="p1", tenant_id="t1")
+ variable = MagicMock(app_id="p1", user_id="account-2")
+ draft_service = MagicMock()
+ draft_service.get_variable.return_value = variable
+ rag_service = MagicMock()
+ rag_service.get_draft_workflow.return_value = MagicMock()
+ if payload is not None:
+ call_args = (api, payload, editor_user, pipeline, "v1")
+ else:
+ call_args = (api, editor_user, pipeline, "v1")
+
+ with (
+ app.test_request_context("/"),
+ patch("controllers.console.datasets.rag_pipeline.rag_pipeline_draft_variable.db", fake_db),
+ patch(
+ "controllers.console.datasets.rag_pipeline.rag_pipeline_draft_variable.RagPipelineService",
+ return_value=rag_service,
+ ),
+ patch(
+ "controllers.console.datasets.rag_pipeline.rag_pipeline_draft_variable.WorkflowDraftVariableService",
+ return_value=draft_service,
+ ),
+ pytest.raises(NotFoundError),
+ ):
+ method(*call_args)
+
+ draft_service.update_variable.assert_not_called()
+ draft_service.delete_variable.assert_not_called()
+ draft_service.reset_variable.assert_not_called()
+ fake_db.session.commit.assert_not_called()
+
+
class TestRagPipelineVariableResetApi:
def test_reset_variable_success(self, app: Flask, fake_db, editor_user):
api = RagPipelineVariableResetApi()
@@ -232,7 +300,7 @@ class TestRagPipelineVariableResetApi:
pipeline = MagicMock(id="p1")
workflow = MagicMock()
- variable = MagicMock(app_id="p1")
+ variable = MagicMock(app_id="p1", user_id="account-1")
srv = MagicMock()
srv.get_variable.return_value = variable