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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(openapi): delete the dead bearer→handler auth adapter (#41311)
Xiyuan Chen3d436a7e31e1
diff --git a/api/controllers/openapi/_models.py b/api/controllers/openapi/_models.pyindex c5e8a22d466..530f2afeb0d 100644--- a/api/controllers/openapi/_models.py+++ b/api/controllers/openapi/_models.py@@ -3,7 +3,7 @@from __future__ import annotationsfrom enum import StrEnum-from typing import Any, Final, Literal+from typing import Any, Final, Literal, Selffrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator@@ -51,7 +51,7 @@ class MessageMetadata(BaseModel):class PaginationEnvelope[T](BaseModel):- """Canonical pagination envelope for `/openapi/v1/*` list endpoints."""+ """The one shape every paginated list on this surface answers with."""page: intlimit: int@@ -60,7 +60,7 @@ class PaginationEnvelope[T](BaseModel):data: list[T]@classmethod- def build(cls, *, page: int, limit: int, total: int, items: list[T]) -> PaginationEnvelope[T]:+ def build(cls, *, page: int, limit: int, total: int, items: list[T]) -> Self:return cls(page=page, limit=limit, total=total, has_more=page * limit < total, data=items)@@ -74,20 +74,12 @@ class AppListRow(BaseModel):workspace_name: str | None = None-class AppListResponse(BaseModel):- page: int- limit: int- total: int- has_more: bool- data: list[AppListRow]+class AppListResponse(PaginationEnvelope[AppListRow]):+ pass-class PermittedExternalAppsListResponse(BaseModel):- page: int- limit: int- total: int- has_more: bool- data: list[AppListRow]+class PermittedExternalAppsListResponse(PaginationEnvelope[AppListRow]):+ passclass AppInfo(BaseModel):@@ -109,29 +101,6 @@ class AppDescribeResponse(BaseModel):input_schema: dict[str, Any] | None = Field(default=None)-class ChatMessageResponse(BaseModel):- event: str- task_id: str- id: str- message_id: str- conversation_id: str- mode: str- answer: str- metadata: MessageMetadata = Field(default_factory=MessageMetadata)- created_at: int---class CompletionMessageResponse(BaseModel):- event: str- task_id: str- id: str- message_id: str- mode: str- answer: str- metadata: MessageMetadata = Field(default_factory=MessageMetadata)- created_at: int--class WorkflowRunData(BaseModel):id: strworkflow_id: str@@ -145,13 +114,6 @@ class WorkflowRunData(BaseModel):finished_at: int | None = None-class WorkflowRunResponse(BaseModel):- workflow_run_id: str- task_id: str- mode: Literal["workflow"] = "workflow"- data: WorkflowRunData--class AccountPayload(BaseModel):id: stremail: str@@ -195,12 +157,8 @@ class SessionRow(BaseModel):expires_at: str | None = None-class SessionListResponse(BaseModel):- page: int- limit: int- total: int- has_more: bool- data: list[SessionRow]+class SessionListResponse(PaginationEnvelope[SessionRow]):+ passclass SessionListQuery(BaseModel):@@ -398,12 +356,8 @@ class MemberResponse(BaseModel):avatar: str | None = None-class MemberListResponse(BaseModel):- page: int- limit: int- total: int- has_more: bool- data: list[MemberResponse]+class MemberListResponse(PaginationEnvelope[MemberResponse]):+ passclass MemberListQuery(BaseModel):diff --git a/api/controllers/openapi/apps.py b/api/controllers/openapi/apps.pyindex 5e1abe27b98..2675cac0400 100644--- a/api/controllers/openapi/apps.py+++ b/api/controllers/openapi/apps.py@@ -37,8 +37,6 @@ from models.model import AppModefrom services.account_service import TenantServicefrom services.app_service import AppListParams, AppService-_ALLOWED_DESCRIBE_FIELDS: frozenset[str] = frozenset({"info", "parameters", "input_schema"})-def _is_listable(app: App) -> bool:"""Whether the openapi app face exposes this app (curated, listable types only)."""@@ -155,7 +153,7 @@ class AppListApi(Resource):def get(self, session: Session, *, auth_data: AuthData, query: AppListQuery):workspace_id = query.workspace_id- empty = AppListResponse(page=query.page, limit=query.limit, total=0, has_more=False, data=[])+ empty = AppListResponse.build(page=query.page, limit=query.limit, total=0, items=[])if query.name:try:@@ -205,7 +203,7 @@ class AppListApi(Resource):workspace_id=str(workspace_id),workspace_name=tenant_name,)- env = AppListResponse(page=1, limit=1, total=1, has_more=False, data=[item])+ env = AppListResponse.build(page=1, limit=1, total=1, items=[item])return envparams = AppListParams(@@ -244,11 +242,5 @@ class AppListApi(Resource):if _is_listable(r)]- env = AppListResponse(- page=query.page,- limit=query.limit,- total=pagination.total,- has_more=query.page * query.limit < pagination.total,- data=items,- )+ env = AppListResponse.build(page=query.page, limit=query.limit, total=pagination.total, items=items)return envdiff --git a/api/controllers/openapi/apps_permitted_external.py b/api/controllers/openapi/apps_permitted_external.pyindex a56ab4ae621..284ec0713d9 100644--- a/api/controllers/openapi/apps_permitted_external.py+++ b/api/controllers/openapi/apps_permitted_external.py@@ -52,8 +52,8 @@ class PermittedExternalAppsListApi(Resource):)if not page_result.app_ids:- env = PermittedExternalAppsListResponse(- page=query.page, limit=query.limit, total=page_result.total, has_more=False, data=[]+ env = PermittedExternalAppsListResponse.build(+ page=query.page, limit=query.limit, total=page_result.total, items=[])return env@@ -80,12 +80,8 @@ class PermittedExternalAppsListApi(Resource):workspace_name=tenant.name if tenant else None,))- env = PermittedExternalAppsListResponse(- page=query.page,- limit=query.limit,- total=page_result.total,- has_more=query.page * query.limit < page_result.total,- data=items,+ env = PermittedExternalAppsListResponse.build(+ page=query.page, limit=query.limit, total=page_result.total, items=items)return envdiff --git a/api/controllers/openapi/auth/data.py b/api/controllers/openapi/auth/data.pyindex ab1d311fb06..de6f6eaf0fa 100644--- a/api/controllers/openapi/auth/data.py+++ b/api/controllers/openapi/auth/data.py@@ -42,10 +42,8 @@ class AuthData(BaseModel):required_scope: Scope | None = Nonetoken_type: TokenTypeaccount_id: uuid.UUID | None = None- token_hash: strtoken_id: uuid.UUID | None = Nonescopes: frozenset[Scope]- tenants: dict[str, bool] = Field(default_factory=dict)external_identity: ExternalIdentity | None = Nonepath_params: dict[str, str] = Field(default_factory=dict)diff --git a/api/controllers/openapi/auth/pipeline.py b/api/controllers/openapi/auth/pipeline.pyindex 12c3c9dce6c..bb32927725d 100644--- a/api/controllers/openapi/auth/pipeline.py+++ b/api/controllers/openapi/auth/pipeline.py@@ -75,10 +75,8 @@ class AuthPipeline:data = AuthData(token_type=identity.token_type,account_id=identity.account_id,- token_hash=identity.token_hash,token_id=identity.token_id,scopes=frozenset(identity.scopes),- tenants=dict(identity.verified_tenants),required_scope=scope,allowed_roles=allowed_roles,rbac=rbac,diff --git a/api/controllers/openapi/auth/surface_gate.py b/api/controllers/openapi/auth/surface_gate.pydeleted file mode 100644index f3d2d0735bb..00000000000--- a/api/controllers/openapi/auth/surface_gate.py+++ /dev/null@@ -1,90 +0,0 @@-"""Surface gate.--`@accept_subjects(...)` is the route-level form. `SurfaceCheck` (pipeline-step) is the pipeline-level form. Both delegate to `check_surface` so the-audit emit + canonical-path message are single-sourced.--Subjects come from `libs.oauth_bearer.SubjectType` directly — no parallel-vocabulary. Caller hits the wrong surface → 403 ``wrong_surface`` + audit-``openapi.wrong_surface_denied``.-"""--from __future__ import annotations--from collections.abc import Callable-from functools import wraps-from typing import TypeVar--from flask import request-from werkzeug.exceptions import Forbidden--from controllers.openapi._audit import emit_wrong_surface-from libs.oauth_bearer import SubjectType, try_get_auth_ctx--_CANONICAL_PATH: dict[SubjectType, str] = {- SubjectType.ACCOUNT: "/openapi/v1/apps",- SubjectType.EXTERNAL_SSO: "/openapi/v1/permitted-external-apps",-}--F = TypeVar("F", bound=Callable[..., object])---def check_surface(accepted: frozenset[SubjectType]) -> None:- """Enforce that the resolved subject is in ``accepted``.-- Reads the openapi auth ContextVar via :func:`try_get_auth_ctx`. Raises- ``Forbidden`` with ``wrong_surface`` + canonical-path hint on miss;- emits ``openapi.wrong_surface_denied`` audit. If no auth context is- set the bearer layer didn't run — that's a wiring bug, not a- user-driven failure, so surface it as a ``RuntimeError`` instead of- a silent 403.- """- ctx = try_get_auth_ctx()- if ctx is None:- raise RuntimeError(- "check_surface called without an auth context; stack validate_bearer or BearerCheck above the surface gate"- )-- subject = _coerce_subject_type(getattr(ctx, "subject_type", None))- if subject in accepted:- return-- canonical = _CANONICAL_PATH.get(subject, "/openapi/v1/") if subject else "/openapi/v1/"- emit_wrong_surface(- subject_type=subject.value if subject else None,- attempted_path=request.path,- client_id=getattr(ctx, "client_id", None),- token_id=_stringify(getattr(ctx, "token_id", None)),- )- raise Forbidden(description=f"wrong_surface (canonical: {canonical})")---def accept_subjects(*accepted: SubjectType) -> Callable[[F], F]:- accepted_set: frozenset[SubjectType] = frozenset(accepted)-- def deco(fn: F) -> F:- @wraps(fn)- def wrapper(*args: object, **kwargs: object) -> object:- check_surface(accepted_set)- return fn(*args, **kwargs)-- return wrapper # type: ignore[return-value]-- return deco---def _coerce_subject_type(raw: object) -> SubjectType | None:- match raw:- case None:- return None- case SubjectType():- return raw- case str():- return SubjectType(raw)- return None---def _stringify(value: object) -> str | None:- if value is None:- return None- return str(value)diff --git a/api/controllers/openapi/auth/verify.py b/api/controllers/openapi/auth/verify.pyindex 7420841a8f3..c669bfaecd9 100644--- a/api/controllers/openapi/auth/verify.py+++ b/api/controllers/openapi/auth/verify.py@@ -8,7 +8,7 @@ from controllers.common.rbac import enforce_rbac_checksfrom controllers.openapi.auth.data import AuthData, CallerKindfrom extensions.ext_database import dbfrom libs.oauth_bearer import Scope, TokenType-from services.account_service import AccountService, TenantService+from services.account_service import AccountServicefrom services.enterprise.enterprise_service import EnterpriseService, WebAppAccessMode@@ -77,13 +77,6 @@ def check_app_api_enabled(data: AuthData) -> None:raise Forbidden("service_api_disabled")-def check_app_access(data: AuthData) -> None:- if data.tenant is None:- return- if not TenantService.account_belongs_to_tenant(data.account_id, data.tenant.id, session=db.session()):- raise Forbidden("subject_no_app_access")--_ALLOWED_MODES_BY_TOKEN_TYPE: dict[TokenType, frozenset[WebAppAccessMode]] = {TokenType.OAUTH_ACCOUNT: frozenset({diff --git a/api/controllers/openapi/workspaces.py b/api/controllers/openapi/workspaces.pyindex 6bff0349f78..6053e09bf28 100644--- a/api/controllers/openapi/workspaces.py+++ b/api/controllers/openapi/workspaces.py@@ -163,12 +163,11 @@ class WorkspaceMembersApi(Resource):total = len(members)start = (query.page - 1) * query.limitpage_items = members[start : start + query.limit]- return MemberListResponse(+ return MemberListResponse.build(page=query.page,limit=query.limit,total=total,- has_more=query.page * query.limit < total,- data=[_member_response(m) for m in page_items],+ items=[_member_response(m) for m in page_items],)@auth_router.guard_workspace(diff --git a/api/libs/oauth_bearer.py b/api/libs/oauth_bearer.pyindex 89ede4b8a12..bfd96650b8d 100644--- a/api/libs/oauth_bearer.py+++ b/api/libs/oauth_bearer.py@@ -1,9 +1,4 @@-"""OAuth bearer primitives.--To add a token kind: write a Resolver, add a SubjectType + Accepts member,-append a TokenKind to build_registry, and update _SUBJECT_TO_ACCEPT.-Authenticator + validate_bearer stay untouched.-"""+"""OAuth bearer primitives."""from __future__ import annotations@@ -13,23 +8,19 @@ import loggingimport uuidfrom collections.abc import Callable, Iterablefrom contextvars import ContextVar, Token-from dataclasses import dataclass, field+from dataclasses import dataclassfrom datetime import UTC, datetimefrom enum import StrEnumfrom functools import wraps-from typing import Literal, ParamSpec, Protocol, TypeVar+from typing import Literal, Protocol-from flask import request-from sqlalchemy import select, update+from sqlalchemy import updatefrom sqlalchemy.orm import Session-from werkzeug.exceptions import Forbidden, ServiceUnavailable, Unauthorized+from werkzeug.exceptions import ServiceUnavailablefrom configs import dify_config-from enums import DeploymentEdition-from extensions.ext_database import db-from extensions.ext_redis import redis_clientfrom libs.rate_limit import enforce_bearer_rate_limit-from models import Account, OAuthAccessToken, TenantAccountJoin+from models import OAuthAccessTokenlogger = logging.getLogger(__name__)@@ -53,8 +44,8 @@ class Scope(StrEnum):"""Catalog of bearer scopes recognised by the openapi surface.`FULL` is the catch-all carried by `dfoa_` account tokens — it satisfies- any per-route `require_scope`. `dfoe_` tokens carry the per-feature scopes- (`APPS_RUN`, `APPS_READ_PERMITTED_EXTERNAL`).+ any per-route scope requirement. `dfoe_` tokens carry the per-feature+ scopes (`APPS_RUN`, `APPS_READ_PERMITTED_EXTERNAL`)."""FULL = "full"@@ -65,32 +56,12 @@ class Scope(StrEnum):WORKSPACE_WRITE = "workspace:write"-class Accepts(StrEnum):- """Subject types a route is willing to accept as caller."""-- USER_ACCOUNT = "user_account"- USER_EXT_SSO = "user_ext_sso"---ACCEPT_USER_ANY: frozenset[Accepts] = frozenset({Accepts.USER_ACCOUNT, Accepts.USER_EXT_SSO})-ACCEPT_USER_EXT_SSO: frozenset[Accepts] = frozenset({Accepts.USER_EXT_SSO})--_SUBJECT_TO_ACCEPT: dict[SubjectType, Accepts] = {- SubjectType.ACCOUNT: Accepts.USER_ACCOUNT,- SubjectType.EXTERNAL_SSO: Accepts.USER_EXT_SSO,-}--@dataclass(frozen=True, slots=True)class AuthContext:"""Per-request identity published via :data:`_auth_ctx_var`(see :func:`set_auth_ctx` / :func:`get_auth_ctx`). ``scopes`` /``subject_type`` / ``token_type`` come from the TokenKind, not the DB —corrupt rows can't elevate scope.-- `verified_tenants` is a snapshot of the Layer-0 verdict cache at- authenticate time. Per-request mutations write through to Redis via- `record_layer0_verdict`; this snapshot is not updated in place (frozen)."""subject_type: SubjectType@@ -102,8 +73,6 @@ class AuthContext:token_id: uuid.UUIDtoken_type: TokenTypeexpires_at: datetime | None- token_hash: str- verified_tenants: dict[str, bool] = field(default_factory=dict)_auth_ctx_var: ContextVar[AuthContext] = ContextVar("openapi_auth_ctx")@@ -133,7 +102,6 @@ class ResolvedRow:client_id: str | Nonetoken_id: uuid.UUIDexpires_at: datetime | None- verified_tenants: dict[str, bool] = field(default_factory=dict)def to_cache(self) -> dict:return {@@ -143,7 +111,6 @@ class ResolvedRow:"client_id": self.client_id,"token_id": str(self.token_id),"expires_at": self.expires_at.isoformat() if self.expires_at else None,- "verified_tenants": dict(self.verified_tenants),}@classmethod@@ -155,29 +122,9 @@ class ResolvedRow:client_id=data.get("client_id"),token_id=uuid.UUID(data["token_id"]),expires_at=datetime.fromisoformat(data["expires_at"]) if data["expires_at"] else None,- verified_tenants=_coerce_verified_tenants(data.get("verified_tenants")),)-def _coerce_verified_tenants(raw: object) -> dict[str, bool]:- """Tolerate legacy entries that stored 'ok'/'denied' string verdicts.-- TODO(post-v1.0): remove once the AuthContext cache TTL has fully cycled- on all live deployments (60s TTL → safe to drop one release after rollout).- """- if not isinstance(raw, dict):- return {}- out: dict[str, bool] = {}- for k, v in raw.items():- if isinstance(v, bool):- out[k] = v- elif v == "ok":- out[k] = True- elif v == "denied":- out[k] = False- return out--class Resolver(Protocol):def resolve(self, token_hash: str) -> ResolvedRow | None: # pragma: no cover - contract...@@ -279,9 +226,8 @@ class BearerAuthenticator:def authenticate(self, token: str) -> AuthContext:"""Identity + per-token rate limit (single source).- Both the openapi pipeline (`BearerCheck`) and the decorator- (`validate_bearer`) call this — rate-limit fires exactly once per- request regardless of which path hosts the route.+ The openapi auth pipeline is the only caller, so the rate limit fires+ exactly once per request."""kind = self._registry.find(token)if kind is None:@@ -301,8 +247,6 @@ class BearerAuthenticator:token_id=row.token_id,token_type=kind.token_type,expires_at=row.expires_at,- token_hash=token_hash,- verified_tenants=dict(row.verified_tenants),)@@ -466,92 +410,6 @@ class _VariantResolver:)-# ============================================================================-# Layer 0 — workspace membership cache + helper-# ============================================================================---def record_layer0_verdict(token_hash: str, tenant_id: str, verdict: bool) -> None:- """Merge a Layer-0 membership verdict into the AuthContext cache entry at- `auth:token:{hash}`. No-op if entry missing/expired/invalid — next request- rebuilds via authenticate() and re-runs Layer 0.- """- cache_key = TOKEN_CACHE_KEY_FMT.format(hash=token_hash)- raw = redis_client.get(cache_key)- if raw is None:- return- text = raw.decode() if isinstance(raw, (bytes, bytearray)) else raw- if text == "invalid":- return- try:- data = json.loads(text)- except (ValueError, KeyError):- return- ttl = redis_client.ttl(cache_key)- if ttl <= 0:- return- data.setdefault("verified_tenants", {})[tenant_id] = verdict- redis_client.setex(cache_key, ttl, json.dumps(data))---def check_workspace_membership(- *,- account_id: uuid.UUID | str,- tenant_id: str,- token_hash: str,- membership_cache: dict[str, bool] | None = None,- cached_verdicts: dict[str, bool] | None = None,-) -> None:- """Layer-0 enforcement core. Raises `Forbidden` on deny, returns on allow.-- Shared by the pipeline step (`WorkspaceMembershipCheck`) and the- inline helper (`require_workspace_member`). Caller is responsible for- short-circuiting on EE / SSO subjects before invoking — this function- runs the membership + active-status checks unconditionally.- """- cache = membership_cache if membership_cache is not None else cached_verdicts or {}- cached = cache.get(tenant_id)- if cached is True:- return- if cached is False:- raise Forbidden("workspace_membership_revoked")-- join = db.session.execute(- select(TenantAccountJoin.id).where(- TenantAccountJoin.account_id == account_id,- TenantAccountJoin.tenant_id == tenant_id,- )- ).scalar_one_or_none()- if join is None:- record_layer0_verdict(token_hash, tenant_id, False)- raise Forbidden("workspace_membership_revoked")-- status = db.session.execute(select(Account.status).where(Account.id == account_id)).scalar_one_or_none()- if status != "active":- record_layer0_verdict(token_hash, tenant_id, False)- raise Forbidden("workspace_membership_revoked")-- record_layer0_verdict(token_hash, tenant_id, True)---def require_workspace_member(ctx: AuthContext, tenant_id: str) -> None:- """AuthContext-flavoured wrapper around `check_workspace_membership`.-- No-op on EE (gateway RBAC owns tenant isolation) and for SSO subjects- (no `tenant_account_joins` row by definition).- """- if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE:- return- if ctx.subject_type != SubjectType.ACCOUNT or ctx.account_id is None:- return- check_workspace_membership(- account_id=ctx.account_id,- tenant_id=tenant_id,- token_hash=ctx.token_hash,- membership_cache=ctx.verified_tenants,- )--# ============================================================================# Decorator — route-level bearer gate# ============================================================================@@ -574,10 +432,9 @@ def get_authenticator() -> BearerAuthenticator:def extract_bearer(req) -> str | None:"""Pull the bearer token out of an HTTP request's Authorization header.- Used by both attachment paths (the ``validate_bearer`` decorator and the- openapi ``Pipeline.guard``) so the parsing rule lives in one place. Pipeline- callers extract once at the boundary and pass the token through ``Context``- so steps stay independent of the request object.+ Used by the openapi auth pipeline, which extracts once at the request+ boundary so the parsing rule lives in one place and later steps stay+ independent of the request object."""header = req.headers.get("Authorization", "")scheme, _, value = header.partition(" ")@@ -586,50 +443,6 @@ def extract_bearer(req) -> str | None:return value.strip()-_DP = ParamSpec("_DP")-_DR = TypeVar("_DR")---def validate_bearer(*, accept: frozenset[Accepts]) -> Callable[[Callable[_DP, _DR]], Callable[_DP, _DR]]:- """Opt-in: omitting it leaves the route unauthenticated.-- Resolves user-level OAuth bearers (``dfoa_`` / ``dfoe_``). Legacy- ``app-`` keys belong to ``service_api/wraps.py:validate_app_token``- and are rejected here as the wrong auth scheme for this surface.- """-- def wrap(fn: Callable[_DP, _DR]) -> Callable[_DP, _DR]:- @wraps(fn)- def inner(*args: _DP.args, **kwargs: _DP.kwargs) -> _DR:- token = extract_bearer(request)- if token is None:- raise Unauthorized("missing bearer token")-- if _authenticator is None:- raise ServiceUnavailable("bearer_auth_disabled: set ENABLE_OAUTH_BEARER=true to enable")-- try:- ctx = get_authenticator().authenticate(token)- except InvalidBearerError as e:- raise Unauthorized(str(e))-- if _SUBJECT_TO_ACCEPT[ctx.subject_type] not in accept:- raise Forbidden("token subject type not accepted here")-- # Try/finally pairing — the WSGI worker thread is reused- # across requests, so a leaked ContextVar would publish the- # previous caller's identity to the next request.- reset_token = set_auth_ctx(ctx)- try:- return fn(*args, **kwargs)- finally:- reset_auth_ctx(reset_token)-- return inner-- return wrap--def bearer_feature_required[**P, R](fn: Callable[P, R]) -> Callable[P, R]:"""503 if ENABLE_OAUTH_BEARER is off — minted tokens would be unusablewithout the authenticator, so fail fast instead of approving silently.@@ -644,29 +457,6 @@ def bearer_feature_required[**P, R](fn: Callable[P, R]) -> Callable[P, R]:return inner-def require_scope(scope: Scope) -> Callable:- """Route-level scope gate — must run AFTER validate_bearer so that- the auth ContextVar is set. Raises ``Forbidden('insufficient_scope: <scope>')``- when the bearer lacks both the requested scope and ``Scope.FULL``.- """-- def wrap(fn: Callable) -> Callable:- @wraps(fn)- def inner(*args, **kwargs):- ctx = try_get_auth_ctx()- if ctx is None:- raise RuntimeError(- "require_scope used without validate_bearer; stack @validate_bearer above @require_scope"- )- if Scope.FULL not in ctx.scopes and scope not in ctx.scopes:- raise Forbidden(f"insufficient_scope: {scope}")- return fn(*args, **kwargs)-- return inner-- return wrap--# ============================================================================# Wiring — called once from the app factory# ============================================================================diff --git a/api/services/openapi/license_gate.py b/api/services/openapi/license_gate.pydeleted file mode 100644index 8df92eb344b..00000000000--- a/api/services/openapi/license_gate.py+++ /dev/null@@ -1,53 +0,0 @@-"""License gate for the /openapi/v1/permitted-external-apps* surface.--Enterprise-edition only. Community and Cloud deployments skip the gate entirely —-the EE blueprint chain is what gives CE deploys no callers on this surface-in practice, but the explicit short-circuit avoids any test/fixture that-flips the surface on without flipping the license.--Uses the narrow system license policy shared with Console admission.--Companion to ``controllers.console.wraps.enterprise_license_required`` —-that one is for console (cookie-authed, force-logout 401). This one is-for bearer surface (token-authed, 403 ``license_required``).-"""--from __future__ import annotations--import logging-from collections.abc import Callable-from functools import wraps--from werkzeug.exceptions import Forbidden--from configs import dify_config-from enums import DeploymentEdition-from services.entities.feature_entities import LicenseStatus-from services.system_feature_service import SystemFeatureService--logger = logging.getLogger(__name__)--_VALID_LICENSE_STATUSES: frozenset[LicenseStatus] = frozenset({LicenseStatus.ACTIVE, LicenseStatus.EXPIRING})---def license_required[**P, R](view: Callable[P, R]) -> Callable[P, R]:- """Decorator form. Raises ``Forbidden('license_required')`` when the EE- deployment has no valid license. No-op outside the Enterprise edition.- """-- @wraps(view)- def decorated(*args: P.args, **kwargs: P.kwargs) -> R:- if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.ENTERPRISE and not _is_license_valid():- raise Forbidden(description="license_required")- return view(*args, **kwargs)-- return decorated---def _is_license_valid() -> bool:- try:- license_status = SystemFeatureService.get_license_status()- except Exception:- logger.exception("license_gate: SystemFeatureService.get_license_status failed")- return False- return license_status in _VALID_LICENSE_STATUSESdiff --git a/api/tests/integration_tests/controllers/openapi/test_auth.py b/api/tests/integration_tests/controllers/openapi/test_auth.pydeleted file mode 100644index 956a0904dab..00000000000--- a/api/tests/integration_tests/controllers/openapi/test_auth.py+++ /dev/null@@ -1,128 +0,0 @@-"""Integration tests for the /openapi/v1 bearer auth surface.--Layer 0 (workspace membership), per-token rate limit, and read-scope (`apps:read`)-acceptance/rejection on app-scoped routes.-"""--from __future__ import annotations--from collections.abc import Generator--import pytest-from flask import Flask-from flask.testing import FlaskClient--from enums import DeploymentEdition-from extensions.ext_database import db-from models import App, Tenant---def test_info_accepts_account_bearer_with_apps_read_scope(- test_client: FlaskClient,- app_in_workspace: App,- account_token: str,-) -> None:- res = test_client.get(- f"/openapi/v1/apps/{app_in_workspace.id}/info",- headers={"Authorization": f"Bearer {account_token}"},- )- assert res.status_code == 200- assert res.json["id"] == app_in_workspace.id---def other_workspace_app(flask_app: Flask) -> Generator[App, None, None]:- """A fresh app under a *different* tenant — caller has no membership row."""- with flask_app.app_context():- other_tenant = Tenant(name="other", status="normal")- db.session.add(other_tenant)- db.session.commit()- app = App(- tenant_id=other_tenant.id,- name="b",- mode="chat",- status="normal",- enable_site=True,- enable_api=True,- )- db.session.add(app)- db.session.commit()- yield app- db.session.delete(app)- db.session.delete(other_tenant)- db.session.commit()---def test_layer0_denies_account_bearer_without_membership(- test_client: FlaskClient,- account_token: str,- other_workspace_app: App,-) -> None:- """Account A bearer hitting an app under tenant B — Layer 0 denies on CE."""- res = test_client.get(- f"/openapi/v1/apps/{other_workspace_app.id}/info",- headers={"Authorization": f"Bearer {account_token}"},- )- assert res.status_code == 403- assert res.json.get("message") == "workspace_membership_revoked"---def test_layer0_skipped_for_enterprise_edition(- test_client: FlaskClient,- account_token: str,- other_workspace_app: App,- monkeypatch,-) -> None:- """On EE, Layer 0 short-circuits — gateway RBAC owns tenant isolation.-- /info uses validate_bearer + require_workspace_member inline (no- AppAuthzCheck), so a cross-tenant bearer reaches the app lookup and- gets 200 — gateway is expected to enforce isolation upstream.- """- from configs import dify_config-- # Override the conftest autouse default for this test only.- monkeypatch.setattr(dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.ENTERPRISE)-- res = test_client.get(- f"/openapi/v1/apps/{other_workspace_app.id}/info",- headers={"Authorization": f"Bearer {account_token}"},- )- assert res.status_code == 200- assert res.json.get("message") != "workspace_membership_revoked"---def test_rate_limit_returns_429_after_60_requests(- test_client: FlaskClient,- account_token: str,-) -> None:- """61st sequential GET to /account on the same bearer → 429 with Retry-After."""- headers = {"Authorization": f"Bearer {account_token}"}- for i in range(60):- r = test_client.get("/openapi/v1/account", headers=headers)- assert r.status_code == 200, f"unexpected fail at i={i}"-- r = test_client.get("/openapi/v1/account", headers=headers)- assert r.status_code == 429- assert r.headers.get("Retry-After"), "Retry-After header missing"- assert int(r.headers["Retry-After"]) >= 1- body = r.json or {}- assert body.get("error") == "rate_limited"- assert isinstance(body.get("retry_after_ms"), int)- assert body["retry_after_ms"] >= 1000---def test_rate_limit_bucket_shared_across_surfaces(- test_client: FlaskClient,- app_in_workspace: App,- account_token: str,-) -> None:- """30 calls to /account + 30 calls to /apps/<id>/info on same token → 61st 429s."""- headers = {"Authorization": f"Bearer {account_token}"}- for _ in range(30):- assert test_client.get("/openapi/v1/account", headers=headers).status_code == 200- for _ in range(30):- assert test_client.get(f"/openapi/v1/apps/{app_in_workspace.id}/info", headers=headers).status_code == 200-- r = test_client.get("/openapi/v1/account", headers=headers)- assert r.status_code == 429diff --git a/api/tests/test_containers_integration_tests/controllers/openapi/conftest.py b/api/tests/test_containers_integration_tests/controllers/openapi/conftest.pyindex 2047ee765d1..1b7894bcb8a 100644--- a/api/tests/test_containers_integration_tests/controllers/openapi/conftest.py+++ b/api/tests/test_containers_integration_tests/controllers/openapi/conftest.py@@ -82,7 +82,6 @@ def auth_for(return AuthData(token_type=TokenType.OAUTH_ACCOUNT,account_id=uuid.UUID(str(account.id)),- token_hash="integration-test",token_id=token_id,scopes=frozenset({Scope.FULL}),caller=account,diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_composition.py b/api/tests/unit_tests/controllers/openapi/auth/test_composition.pyindex d61a38848f0..e77bb15c9cc 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_composition.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_composition.py@@ -157,7 +157,6 @@ def _selected_webapp_steps(*, scope, app_access_mode):)data = AuthData(token_type=TokenType.OAUTH_ACCOUNT,- token_hash="x",scopes=frozenset({scope}) if scope is not None else frozenset(),app_access_mode=app_access_mode,)diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_conditions.py b/api/tests/unit_tests/controllers/openapi/auth/test_conditions.pyindex 59776892903..8c3f1bc20ed 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_conditions.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_conditions.py@@ -1,3 +1,4 @@+import uuidfrom unittest.mock import patchfrom controllers.common.rbac import PlainApp, RBACCheck@@ -27,6 +28,9 @@ from models.account import TenantAccountRolefrom services.enterprise.enterprise_service import WebAppAccessModefrom tests.unit_tests.config_override import config_overrides_context+PROBE_ID = uuid.uuid4()+OTHER_ID = uuid.uuid4()+def _ctx(token_type=TokenType.OAUTH_ACCOUNT, path_params=None, **kwargs):return RequestContext(@@ -37,7 +41,7 @@ def _ctx(token_type=TokenType.OAUTH_ACCOUNT, path_params=None, **kwargs):def _data(**kwargs):- defaults: dict = {"token_type": TokenType.OAUTH_ACCOUNT, "token_hash": "x", "scopes": frozenset()}+ defaults: dict = {"token_type": TokenType.OAUTH_ACCOUNT, "scopes": frozenset()}defaults.update(kwargs)return AuthData(**defaults)@@ -89,9 +93,9 @@ def test_data_cond_returns_false_when_data_none():def test_data_cond_evaluates_when_data_present():- c = data_cond(lambda data: data.token_hash == "secret")- assert c(_ctx(), _data(token_hash="secret")) is True- assert c(_ctx(), _data(token_hash="other")) is False+ c = data_cond(lambda data: data.token_id == PROBE_ID)+ assert c(_ctx(), _data(token_id=PROBE_ID)) is True+ assert c(_ctx(), _data(token_id=OTHER_ID)) is Falsedef test_config_cond_ignores_ctx_and_data():diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_data.py b/api/tests/unit_tests/controllers/openapi/auth/test_data.pyindex e5171e64303..73aed7bd615 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_data.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_data.py@@ -39,7 +39,6 @@ def test_request_context_scope_optional():def test_auth_data_is_mutable():data = AuthData(token_type=TokenType.OAUTH_ACCOUNT,- token_hash="abc",scopes=frozenset({Scope.FULL}),)data.token_type = TokenType.OAUTH_EXTERNAL_SSO@@ -49,7 +48,6 @@ def test_auth_data_is_mutable():def test_auth_data_path_params_defaults_empty():data = AuthData(token_type=TokenType.OAUTH_ACCOUNT,- token_hash="abc",scopes=frozenset(),)assert data.path_params == {}@@ -58,7 +56,6 @@ def test_auth_data_path_params_defaults_empty():def test_auth_data_account_id_optional():data = AuthData(token_type=TokenType.OAUTH_EXTERNAL_SSO,- token_hash="abc",scopes=frozenset({Scope.APPS_RUN}),external_identity=ExternalIdentity(email="[email protected]"),)@@ -69,25 +66,14 @@ def test_auth_data_external_identity_none_for_account():data = AuthData(token_type=TokenType.OAUTH_ACCOUNT,account_id=uuid.uuid4(),- token_hash="abc",scopes=frozenset({Scope.FULL}),)assert data.external_identity is None-def test_auth_data_tenants_default_empty():- data = AuthData(- token_type=TokenType.OAUTH_ACCOUNT,- token_hash="abc",- scopes=frozenset(),- )- assert data.tenants == {}--def test_auth_data_token_id_optional():data = AuthData(token_type=TokenType.OAUTH_ACCOUNT,- token_hash="abc",scopes=frozenset(),)assert data.token_id is None@@ -119,7 +105,6 @@ def test_request_context_allowed_roles_set():def test_auth_data_allowed_roles_default_none():data = AuthData(token_type=TokenType.OAUTH_ACCOUNT,- token_hash="abc",scopes=frozenset(),)assert data.allowed_roles is None@@ -131,7 +116,6 @@ def test_auth_data_allowed_roles_set():roles = frozenset({TenantAccountRole.ADMIN})data = AuthData(token_type=TokenType.OAUTH_ACCOUNT,- token_hash="abc",scopes=frozenset(),allowed_roles=roles,)@@ -141,7 +125,6 @@ def test_auth_data_allowed_roles_set():def test_auth_data_tenant_role_default_none():data = AuthData(token_type=TokenType.OAUTH_ACCOUNT,- token_hash="abc",scopes=frozenset(),)assert data.tenant_role is None@@ -152,7 +135,6 @@ def test_auth_data_tenant_role_set():data = AuthData(token_type=TokenType.OAUTH_ACCOUNT,- token_hash="abc",scopes=frozenset(),tenant_role=TenantAccountRole.ADMIN,)diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_flow.py b/api/tests/unit_tests/controllers/openapi/auth/test_flow.pyindex 3ea7ac2b125..1c87c3b6450 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_flow.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_flow.py@@ -11,7 +11,7 @@ def _ctx():def _data():- return AuthData(token_type=TokenType.OAUTH_ACCOUNT, token_hash="x", scopes=frozenset())+ return AuthData(token_type=TokenType.OAUTH_ACCOUNT, scopes=frozenset())def test_applies_returns_true_when_condition_true():diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_pipeline.py b/api/tests/unit_tests/controllers/openapi/auth/test_pipeline.pyindex f483c80eb38..fc215fa4dd1 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_pipeline.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_pipeline.py@@ -16,20 +16,16 @@ def _make_identity(token_type=TokenType.OAUTH_ACCOUNT,account_id=None,scopes=None,- token_hash="testhash",subject_email=None,subject_issuer=None,- verified_tenants=None,token_id=None,):identity = MagicMock()identity.token_type = token_typeidentity.account_id = account_id or uuid.uuid4()identity.scopes = scopes or frozenset({Scope.FULL})- identity.token_hash = token_hashidentity.subject_email = subject_emailidentity.subject_issuer = subject_issuer- identity.verified_tenants = verified_tenants or {}identity.token_id = token_id or uuid.uuid4()return identitydiff --git a/api/tests/unit_tests/controllers/openapi/auth/test_prepare.py b/api/tests/unit_tests/controllers/openapi/auth/test_prepare.pyindex a9ae90a3463..fa844520e3e 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_prepare.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_prepare.py@@ -33,7 +33,6 @@ ACCOUNT_ID = "00000000-0000-0000-0000-000000000003"def _make_auth_data(**kwargs: object) -> AuthData:return AuthData(token_type=kwargs.pop("token_type", TokenType.OAUTH_ACCOUNT),- token_hash=kwargs.pop("token_hash", "testhash"),scopes=kwargs.pop("scopes", frozenset()),**kwargs,)diff --git a/api/tests/unit_tests/controllers/openapi/auth/test_verify.py b/api/tests/unit_tests/controllers/openapi/auth/test_verify.pyindex 89c38c59e4d..baad1264abf 100644--- a/api/tests/unit_tests/controllers/openapi/auth/test_verify.py+++ b/api/tests/unit_tests/controllers/openapi/auth/test_verify.py@@ -10,7 +10,6 @@ from controllers.common.rbac import PlainApp, RBACCheckfrom controllers.openapi.auth.data import AuthDatafrom controllers.openapi.auth.verify import (check_acl,- check_app_access,check_app_api_enabled,check_private_app_permission,check_rbac_permission,@@ -32,7 +31,7 @@ def _rbac_config(config_overrides: Callable[..., None]) -> None:def _data(**kwargs) -> AuthData:- defaults: dict = {"token_type": TokenType.OAUTH_ACCOUNT, "token_hash": "hash", "scopes": frozenset({Scope.FULL})}+ defaults: dict = {"token_type": TokenType.OAUTH_ACCOUNT, "scopes": frozenset({Scope.FULL})}defaults.update(kwargs)return AuthData(**defaults)@@ -63,27 +62,6 @@ def test_check_workspace_member_passes_when_role_present():check_workspace_member(_data(tenant_role=TenantAccountRole.NORMAL))-def test_check_app_access_passes_when_tenant_none():- check_app_access(_data(tenant=None))---def test_check_app_access_passes_when_member():- tenant = Tenant(name="Test Tenant")- tenant.id = "t1"- data = _data(account_id=uuid.uuid4(), tenant=tenant)- with patch("controllers.openapi.auth.verify.TenantService.account_belongs_to_tenant", return_value=True):- check_app_access(data)---def test_check_app_access_raises_when_not_member():- tenant = Tenant(name="Test Tenant")- tenant.id = "t1"- data = _data(account_id=uuid.uuid4(), tenant=tenant)- with patch("controllers.openapi.auth.verify.TenantService.account_belongs_to_tenant", return_value=False):- with pytest.raises(Forbidden, match="subject_no_app_access"):- check_app_access(data)--# --- check_rbac_permission ---_RBAC_REQ = RBACCheck(RBACPermission.APP_VIEW_LAYOUT, PlainApp())diff --git a/api/tests/unit_tests/controllers/openapi/conftest.py b/api/tests/unit_tests/controllers/openapi/conftest.pyindex 6d17dcaa39c..f77e35a3b7f 100644--- a/api/tests/unit_tests/controllers/openapi/conftest.py+++ b/api/tests/unit_tests/controllers/openapi/conftest.py@@ -28,7 +28,6 @@ def _stub_execute(kwargs["auth_data"] = AuthData(token_type=TokenType.OAUTH_ACCOUNT,account_id=uuid.uuid4(),- token_hash="test",token_id=uuid.uuid4(),scopes=frozenset({Scope.FULL}),required_scope=scope,diff --git a/api/tests/unit_tests/controllers/openapi/test_app_run_streaming.py b/api/tests/unit_tests/controllers/openapi/test_app_run_streaming.pyindex 7672e6414fd..88af3d3ff8f 100644--- a/api/tests/unit_tests/controllers/openapi/test_app_run_streaming.py+++ b/api/tests/unit_tests/controllers/openapi/test_app_run_streaming.py@@ -109,7 +109,6 @@ def test_stop_task_calls_queue_manager_and_graph_engine(app: Flask, bypass_pipelauth_data = AuthData.model_construct(token_type=TokenType.OAUTH_ACCOUNT,account_id=uuid.UUID(_TEST_ACCOUNT_ID),- token_hash="test",scopes=frozenset({Scope.FULL}),app=_make_app(),caller=_make_account(),diff --git a/api/tests/unit_tests/controllers/openapi/test_human_input_form.py b/api/tests/unit_tests/controllers/openapi/test_human_input_form.pyindex 28947c69b35..97590ad6dfe 100644--- a/api/tests/unit_tests/controllers/openapi/test_human_input_form.py+++ b/api/tests/unit_tests/controllers/openapi/test_human_input_form.py@@ -26,7 +26,6 @@ def _make_auth_data(app_model, caller, caller_kind):return AuthData.model_construct(token_type=TokenType.OAUTH_ACCOUNT,account_id=uuid.uuid4(),- token_hash="test",scopes=frozenset({Scope.FULL}),app=app_model,caller=caller,diff --git a/api/tests/unit_tests/controllers/openapi/test_pagination_envelope.py b/api/tests/unit_tests/controllers/openapi/test_pagination_envelope.pydeleted file mode 100644index 7b84911d788..00000000000--- a/api/tests/unit_tests/controllers/openapi/test_pagination_envelope.py+++ /dev/null@@ -1,134 +0,0 @@-"""Unit tests for PaginationEnvelope generic Pydantic model."""--from __future__ import annotations--from pydantic import BaseModel--from controllers.openapi._models import PaginationEnvelope---class _Row(BaseModel):- id: str- name: str---def test_envelope_basic_fields():- env = PaginationEnvelope[_Row](page=1, limit=20, total=42, has_more=True, data=[_Row(id="a", name="A")])- dumped = env.model_dump(mode="json")- assert dumped == {- "page": 1,- "limit": 20,- "total": 42,- "has_more": True,- "data": [{"id": "a", "name": "A"}],- }---def test_envelope_empty_data_no_more():- env = PaginationEnvelope[_Row](page=1, limit=20, total=0, has_more=False, data=[])- assert env.model_dump(mode="json")["data"] == []- assert env.model_dump(mode="json")["has_more"] is False---def test_envelope_has_more_true_when_total_exceeds_page_window():- env = PaginationEnvelope[_Row].build(page=1, limit=20, total=42, items=[_Row(id="a", name="A")])- assert env.has_more is True---def test_envelope_has_more_false_when_total_within_page_window():- env = PaginationEnvelope[_Row].build(page=2, limit=20, total=22, items=[_Row(id="a", name="A")])- assert env.has_more is False---def test_envelope_has_more_false_for_last_page():- env = PaginationEnvelope[_Row].build(page=3, limit=20, total=42, items=[_Row(id="a", name="A")])- assert env.has_more is False---def test_max_page_limit_is_200():- from controllers.openapi._models import MAX_PAGE_LIMIT-- assert MAX_PAGE_LIMIT == 200---def test_envelope_uses_pep695_generics():- """Verify the class uses PEP 695 native generic syntax (not legacy Generic[T])."""- from controllers.openapi._models import PaginationEnvelope-- # PEP 695 syntax populates __type_params__; the legacy Generic[T] form does not.- assert PaginationEnvelope.__type_params__, "expected PEP 695 native generic syntax"-- fields = PaginationEnvelope.model_fields- assert {"page", "limit", "total", "has_more", "data"} <= set(fields)---def test_app_info_response_dump_matches_spec():- from controllers.openapi._models import AppInfo-- obj = AppInfo(- id="app1",- name="X",- description="d",- mode="chat",- )- assert obj.model_dump(mode="json") == {- "id": "app1",- "name": "X",- "description": "d",- "mode": "chat",- }---def test_app_describe_response_nests_info_and_parameters():- from controllers.openapi._models import AppDescribeInfo, AppDescribeResponse-- info = AppDescribeInfo(- id="app1",- name="X",- mode="chat",- description=None,- updated_at="2026-05-05T00:00:00+00:00",- service_api_enabled=True,- )- obj = AppDescribeResponse(info=info, parameters={"opening_statement": None})- dumped = obj.model_dump(mode="json")- assert dumped["info"]["service_api_enabled"] is True- assert dumped["parameters"]["opening_statement"] is None---def test_response_models_dump_per_mode():- from controllers.openapi._models import (- ChatMessageResponse,- CompletionMessageResponse,- WorkflowRunData,- WorkflowRunResponse,- )-- chat = ChatMessageResponse(- event="message",- task_id="t1",- id="m1",- message_id="m1",- conversation_id="c1",- mode="chat",- answer="hi",- created_at=0,- )- assert chat.model_dump(mode="json")["mode"] == "chat"- wf = WorkflowRunResponse(- workflow_run_id="r1",- task_id="t1",- data=WorkflowRunData(id="r1", workflow_id="w1", status="succeeded"),- )- assert wf.model_dump(mode="json")["data"]["status"] == "succeeded"- assert wf.model_dump(mode="json")["mode"] == "workflow"- comp = CompletionMessageResponse(- event="message",- task_id="t2",- id="m2",- message_id="m2",- mode="completion",- answer="ok",- created_at=0,- )- assert comp.model_dump(mode="json")["mode"] == "completion"diff --git a/api/tests/unit_tests/controllers/openapi/test_workflow_events_openapi.py b/api/tests/unit_tests/controllers/openapi/test_workflow_events_openapi.pyindex 2e6af990003..7f906826403 100644--- a/api/tests/unit_tests/controllers/openapi/test_workflow_events_openapi.py+++ b/api/tests/unit_tests/controllers/openapi/test_workflow_events_openapi.py@@ -31,7 +31,6 @@ def _make_auth_data(app_model, caller, caller_kind):return AuthData.model_construct(token_type=TokenType.OAUTH_ACCOUNT,account_id=uuid.uuid4(),- token_hash="test",scopes=frozenset({Scope.FULL}),app=app_model,caller=caller,diff --git a/api/tests/unit_tests/controllers/openapi/test_workspaces_members.py b/api/tests/unit_tests/controllers/openapi/test_workspaces_members.pyindex 02398cbd2ad..9b998edff57 100644--- a/api/tests/unit_tests/controllers/openapi/test_workspaces_members.py+++ b/api/tests/unit_tests/controllers/openapi/test_workspaces_members.py@@ -9,7 +9,7 @@ Coverage:Auth-pipeline plumbing is bypassed via the `bypass_pipeline` fixture fromconftest.py; the bearer identity is seeded into the openapi auth ContextVar-via `_seed` (the slot `validate_bearer` publishes). Tests that exercise+via `_seed`. Tests that exerciseendpoint *bodies* skip the single `guard_workspace` decorator via``__wrapped__`` — membership and role enforcement live in the auth pipelineand are covered in `auth/test_prepare.py` and `auth/test_verify.py`.@@ -113,8 +113,6 @@ def _auth_ctx(account_id: uuid.UUID | None = None) -> AuthContext:token_id=uuid.uuid4(),token_type=TokenType.OAUTH_ACCOUNT,expires_at=datetime.now(UTC),- token_hash="h",- verified_tenants={},)@@ -125,7 +123,6 @@ def _auth_data(account_id: uuid.UUID) -> AuthData:return AuthData(token_type=TokenType.OAUTH_ACCOUNT,account_id=account_id,- token_hash="testhash",scopes=frozenset({Scope.FULL}),)diff --git a/api/tests/unit_tests/libs/test_oauth_bearer_layer0_cache.py b/api/tests/unit_tests/libs/test_oauth_bearer_layer0_cache.pydeleted file mode 100644index 0023f17119e..00000000000--- a/api/tests/unit_tests/libs/test_oauth_bearer_layer0_cache.py+++ /dev/null@@ -1,94 +0,0 @@-"""Unit tests for record_layer0_verdict — merge L0 verdict into AuthContext cache."""--from __future__ import annotations--import json-from unittest.mock import MagicMock, patch--import pytest--from libs.oauth_bearer import record_layer0_verdict---def mock_redis():- return MagicMock()---@patch("libs.oauth_bearer.redis_client")-def test_no_op_when_cache_entry_missing(mock_redis):- mock_redis.get.return_value = None- record_layer0_verdict("h1", "t1", True)- mock_redis.setex.assert_not_called()---@patch("libs.oauth_bearer.redis_client")-def test_no_op_when_cache_entry_invalid_marker(mock_redis):- mock_redis.get.return_value = b"invalid"- record_layer0_verdict("h1", "t1", True)- mock_redis.setex.assert_not_called()---@patch("libs.oauth_bearer.redis_client")-def test_no_op_when_json_malformed(mock_redis):- mock_redis.get.return_value = b"not json"- record_layer0_verdict("h1", "t1", True)- mock_redis.setex.assert_not_called()---@patch("libs.oauth_bearer.redis_client")-def test_no_op_when_ttl_expired(mock_redis):- mock_redis.get.return_value = json.dumps(- {- "subject_email": "e",- "subject_issuer": None,- "account_id": None,- "token_id": "tid",- "expires_at": None,- }- ).encode()- mock_redis.ttl.return_value = -1- record_layer0_verdict("h1", "t1", True)- mock_redis.setex.assert_not_called()---@patch("libs.oauth_bearer.redis_client")-def test_merges_new_tenant_verdict(mock_redis):- mock_redis.get.return_value = json.dumps(- {- "subject_email": "e",- "subject_issuer": None,- "account_id": None,- "token_id": "tid",- "expires_at": None,- "verified_tenants": {"t0": True},- }- ).encode()- mock_redis.ttl.return_value = 42-- record_layer0_verdict("h1", "t1", False)-- mock_redis.setex.assert_called_once()- args = mock_redis.setex.call_args- assert args.args[0] == "auth:token:h1"- assert args.args[1] == 42 # remaining TTL preserved- written = json.loads(args.args[2])- assert written["verified_tenants"] == {"t0": True, "t1": False}---@patch("libs.oauth_bearer.redis_client")-def test_merges_when_field_absent_from_legacy_entry(mock_redis):- """Backward compat: legacy cache entry without verified_tenants field."""- mock_redis.get.return_value = json.dumps(- {- "subject_email": "e",- "subject_issuer": None,- "account_id": None,- "token_id": "tid",- "expires_at": None,- }- ).encode()- mock_redis.ttl.return_value = 42- record_layer0_verdict("h1", "t1", True)- written = json.loads(mock_redis.setex.call_args.args[2])- assert written["verified_tenants"] == {"t1": True}diff --git a/api/tests/unit_tests/libs/test_oauth_bearer_require_scope.py b/api/tests/unit_tests/libs/test_oauth_bearer_require_scope.pydeleted file mode 100644index e8204a6e2e0..00000000000--- a/api/tests/unit_tests/libs/test_oauth_bearer_require_scope.py+++ /dev/null@@ -1,98 +0,0 @@-"""require_scope is a route-level gate run after validate_bearer.-Tests use a fake auth_ctx published via the openapi auth ContextVar (no-authenticator wiring needed). The `_publish_auth_ctx` helper guarantees-the ContextVar is reset between tests so worker-thread reuse can't leak-identity into the next test.-"""--from __future__ import annotations--import uuid-from collections.abc import Iterator-from contextlib import contextmanager--import pytest-from flask import Flask-from werkzeug.exceptions import Forbidden--from libs.oauth_bearer import (- AuthContext,- Scope,- SubjectType,- TokenType,- require_scope,- reset_auth_ctx,- set_auth_ctx,-)---@contextmanager-def _publish_auth_ctx(ctx: AuthContext) -> Iterator[None]:- token = set_auth_ctx(ctx)- try:- yield- finally:- reset_auth_ctx(token)---def app() -> Flask:- app = Flask(__name__)- app.config["TESTING"] = True- return app---def _ctx(scopes) -> AuthContext:- return AuthContext(- subject_type=SubjectType.ACCOUNT,- subject_email="[email protected]",- subject_issuer="dify:account",- account_id=uuid.uuid4(),- client_id="difyctl",- scopes=scopes,- token_id=uuid.uuid4(),- token_type=TokenType.OAUTH_ACCOUNT,- expires_at=None,- token_hash="h1",- verified_tenants={},- )---def test_require_scope_allows_when_scope_present(app: Flask):- @require_scope("apps:read")- def view():- return "ok"-- with app.test_request_context(), _publish_auth_ctx(_ctx(frozenset({"apps:read"}))):- assert view() == "ok"---def test_require_scope_rejects_when_scope_missing(app: Flask):- @require_scope("apps:write")- def view():- return "ok"-- with app.test_request_context(), _publish_auth_ctx(_ctx(frozenset({"apps:read"}))):- with pytest.raises(Forbidden) as exc:- view()- assert "insufficient_scope: apps:write" in str(exc.value.description)---def test_require_scope_full_passes_any_check(app: Flask):- @require_scope("apps:write")- def view():- return "ok"-- with app.test_request_context(), _publish_auth_ctx(_ctx(frozenset({Scope.FULL}))):- assert view() == "ok"---def test_require_scope_without_validate_bearer_raises_runtime_error(app: Flask):- @require_scope("apps:read")- def view():- return "ok"-- with app.test_request_context():- # No auth ContextVar published — validate_bearer was forgotten.- with pytest.raises(RuntimeError, match="stack @validate_bearer above @require_scope"):- view()diff --git a/api/tests/unit_tests/libs/test_workspace_member_helper.py b/api/tests/unit_tests/libs/test_workspace_member_helper.pydeleted file mode 100644index af9acd9cf62..00000000000--- a/api/tests/unit_tests/libs/test_workspace_member_helper.py+++ /dev/null@@ -1,202 +0,0 @@-"""SQLite-backed unit tests for workspace membership enforcement."""--from __future__ import annotations--import uuid-from collections.abc import Iterator-from dataclasses import dataclass-from unittest.mock import Mock--import pytest-from sqlalchemy import event-from sqlalchemy.orm import Session-from werkzeug.exceptions import Forbidden--from enums import DeploymentEdition-from libs import oauth_bearer-from libs.oauth_bearer import AuthContext, Scope, SubjectType, TokenType, require_workspace_member-from models.account import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole-from tests.unit_tests.config_override import apply_config_overrides-from tests.unit_tests.model_factories import make_account--pytestmark = pytest.mark.usefixtures("community_edition")---@dataclass(frozen=True)-class Database:- """Real ORM binding and executed-statement log for one isolated test."""-- session: Session- statements: list[str]---def database(sqlite_session: Session, monkeypatch: pytest.MonkeyPatch) -> Iterator[Database]:- statements: list[str] = []-- def record_statement(_connection, _cursor, statement, _parameters, _context, _executemany) -> None:- statements.append(statement)-- engine = sqlite_session.get_bind()- event.listen(engine, "before_cursor_execute", record_statement)- binding = Database(session=sqlite_session, statements=statements)- monkeypatch.setattr(oauth_bearer, "db", binding)- try:- yield binding- finally:- event.remove(engine, "before_cursor_execute", record_statement)---def community_edition(monkeypatch: pytest.MonkeyPatch) -> None:- apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)---def _ctx(- verified: dict[str, bool] | None = None,- *,- account_id: uuid.UUID | None = None,- account: bool = True,-) -> AuthContext:- return AuthContext(- subject_type=SubjectType.ACCOUNT if account else SubjectType.EXTERNAL_SSO,- subject_email="[email protected]",- subject_issuer=None,- account_id=account_id or (uuid.uuid4() if account else None),- client_id="difyctl",- scopes=frozenset({Scope.FULL}),- token_id=uuid.uuid4(),- token_type=TokenType.OAUTH_ACCOUNT if account else TokenType.OAUTH_EXTERNAL_SSO,- expires_at=None,- token_hash="h1",- verified_tenants=dict(verified or {}),- )---def _persist_membership(- session: Session,- *,- account_id: uuid.UUID,- tenant_id: str,- status: AccountStatus = AccountStatus.ACTIVE,-) -> None:- account = _account(account_id, status=status)- tenant = Tenant(name=f"Tenant {tenant_id}")- tenant.id = tenant_id- membership = TenantAccountJoin(- tenant_id=tenant_id,- account_id=account_id.hex,- role=TenantAccountRole.NORMAL,- )- session.add_all([account, tenant, membership])- session.commit()---def _account(account_id: uuid.UUID, *, status: AccountStatus = AccountStatus.ACTIVE) -> Account:- # SQLite's StringUUID adapter binds UUID objects as compact hex, while- # PostgreSQL binds their dashed string form. Persist the SQLite-bound form- # so the production query can keep accepting the AuthContext UUID object.- return make_account(- account_id=account_id.hex, name="Workspace member", email=f"{account_id}@example.com", status=status- )---def test_skips_for_enterprise_edition(database: Database, monkeypatch: pytest.MonkeyPatch) -> None:- apply_config_overrides(monkeypatch, DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- before = len(database.statements)-- require_workspace_member(_ctx(), "tenant-1")-- assert len(database.statements) == before---def test_skips_for_external_sso(database: Database) -> None:- before = len(database.statements)-- require_workspace_member(_ctx(account=False), "tenant-1")-- assert len(database.statements) == before---def test_uses_cached_allow_without_database_access(database: Database) -> None:- before = len(database.statements)-- require_workspace_member(_ctx({"tenant-1": True}), "tenant-1")-- assert len(database.statements) == before---def test_uses_cached_denial_without_database_access(database: Database) -> None:- before = len(database.statements)-- with pytest.raises(Forbidden, match="workspace_membership_revoked"):- require_workspace_member(_ctx({"tenant-1": False}), "tenant-1")-- assert len(database.statements) == before--[email protected]("database")-def test_denies_when_membership_is_absent(- monkeypatch: pytest.MonkeyPatch,-) -> None:- record_verdict = Mock()- monkeypatch.setattr(oauth_bearer, "record_layer0_verdict", record_verdict)-- with pytest.raises(Forbidden, match="workspace_membership_revoked"):- require_workspace_member(_ctx(), "tenant-1")-- record_verdict.assert_called_once_with("h1", "tenant-1", False)---def test_denies_membership_from_another_tenant(- database: Database,- monkeypatch: pytest.MonkeyPatch,-) -> None:- account_id = uuid.uuid4()- requested_tenant_member_id = uuid.uuid4()- status_decoy_id = uuid.uuid4()- _persist_membership(database.session, account_id=account_id, tenant_id="tenant-2")- _persist_membership(database.session, account_id=requested_tenant_member_id, tenant_id="tenant-1")- database.session.add(_account(status_decoy_id, status=AccountStatus.BANNED))- database.session.commit()- record_verdict = Mock()- monkeypatch.setattr(oauth_bearer, "record_layer0_verdict", record_verdict)-- with pytest.raises(Forbidden, match="workspace_membership_revoked"):- require_workspace_member(_ctx(account_id=account_id), "tenant-1")-- record_verdict.assert_called_once_with("h1", "tenant-1", False)---def test_denies_when_account_is_inactive(- database: Database,- monkeypatch: pytest.MonkeyPatch,-) -> None:- account_id = uuid.uuid4()- _persist_membership(- database.session,- account_id=account_id,- tenant_id="tenant-1",- status=AccountStatus.BANNED,- )- record_verdict = Mock()- monkeypatch.setattr(oauth_bearer, "record_layer0_verdict", record_verdict)-- with pytest.raises(Forbidden, match="workspace_membership_revoked"):- require_workspace_member(_ctx(account_id=account_id), "tenant-1")-- record_verdict.assert_called_once_with("h1", "tenant-1", False)---def test_allows_active_member_and_records_verdict(- database: Database,- monkeypatch: pytest.MonkeyPatch,-) -> None:- account_id = uuid.uuid4()- _persist_membership(database.session, account_id=account_id, tenant_id="tenant-1")- record_verdict = Mock()- monkeypatch.setattr(oauth_bearer, "record_layer0_verdict", record_verdict)-- require_workspace_member(_ctx(account_id=account_id), "tenant-1")-- record_verdict.assert_called_once_with("h1", "tenant-1", True)diff --git a/api/tests/unit_tests/services/openapi/test_mint_policy.py b/api/tests/unit_tests/services/openapi/test_mint_policy.pyindex e3bf6cd9d0e..c3df657ed4c 100644--- a/api/tests/unit_tests/services/openapi/test_mint_policy.py+++ b/api/tests/unit_tests/services/openapi/test_mint_policy.py@@ -10,7 +10,6 @@ from __future__ import annotationsimport pytest-from enums import DeploymentEditionfrom libs.oauth_bearer import MINTABLE_PROFILES, Scope, SubjectTypefrom services.openapi.mint_policy import MintPolicyViolation, validate_mint_policy@@ -73,50 +72,3 @@ def test_message_carries_both_drift_reasons():msg = str(exc.value)assert "prefix" in msgassert "scopes" in msg---def test_license_required_decorator_skips_on_ce(config_overrides):- from services.openapi.license_gate import license_required-- @license_required- def view():- return "ok"-- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)- assert view() == "ok"---def test_license_required_decorator_403_on_invalid_ee_license(config_overrides):- from unittest.mock import patch-- from werkzeug.exceptions import Forbidden-- from services.openapi.license_gate import license_required-- @license_required- def view():- return "ok"-- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- with (- patch("services.openapi.license_gate._is_license_valid", return_value=False),- ):- with pytest.raises(Forbidden) as exc:- view()- assert "license_required" in exc.value.description---def test_license_required_decorator_passes_on_valid_ee_license(config_overrides):- from unittest.mock import patch-- from services.openapi.license_gate import license_required-- @license_required- def view():- return "ok"-- config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)- with (- patch("services.openapi.license_gate._is_license_valid", return_value=True),- ):- assert view() == "ok"