mirror of
https://github.com/langgenius/dify.git
synced 2026-05-09 04:36:31 +08:00
Type and lint pass over the openapi controllers, auth pipeline, and
oauth bearer/device-flow plumbing. Down from 36 pyright errors and 16
ruff errors to 0/0; 93 openapi unit tests pass.
Logic fixes:
- libs/oauth_bearer.py: drop private-naming on the friend-API methods
consumed by _VariantResolver (cache_get / cache_set_positive /
cache_set_negative / hard_expire / session_factory). They were always
cross-class accessors — leading underscore was misleading. Add public
registry property on BearerAuthenticator. _hard_expire row_id widened
to UUID | str (matches the StringUUID column type).
- libs/oauth_bearer.py: type validate_bearer / bearer_feature_required
with ParamSpec / PEP-695 so wrapped routes preserve their signature.
- libs/rate_limit.py: same — typed rate_limit decorator.
- services/oauth_device_flow.py: mint_oauth_token / _upsert accept
Session | scoped_session (Flask-SQLAlchemy proxy). Guard row-is-None
after upsert.
- controllers/openapi/{chat,completion,workflow}_messages.py: tuple-vs-
Mapping shape narrowing on AppGenerateService.generate return —
production returns Mapping, tests mock as (body, status). Validate
through Pydantic Response model in both shapes.
- controllers/openapi/oauth_device.py: replace flask_restx.reqparse (banned)
with Pydantic Request/Query models — DeviceCodeRequest, DevicePollRequest,
DeviceLookupQuery, DeviceMutateRequest. Two PEP-695 generic helpers
(_validate_json / _validate_query) translate ValidationError to BadRequest.
- controllers/openapi/auth/strategies.py: Protocol param-name match
(subject_type), Optional narrowing on app/tenant/account_id/subject_email.
- controllers/openapi/auth/steps.py: subject_type-is-None guard before
mounter dispatch.
- core/app/apps/workflow/generate_task_pipeline.py + models/workflow.py:
add WorkflowAppLogCreatedFrom.OPENAPI + matching match-case branch.
Fixes match-exhaustiveness and possibly-unbound created_from.
- libs/device_flow_security.py: pyright ignore on flask after_request
hook (registered by the framework, pyright sees as unused).
- services/oauth_device_flow.py: rename Exceptions to *Error suffix
(StateNotFoundError / InvalidTransitionError / UserCodeExhaustedError);
same for libs/oauth_bearer.py (InvalidBearerError / TokenExpiredError).
Update all callers across openapi controllers.
- controllers/openapi/{oauth_device,oauth_device_sso}.py +
services/oauth_device_flow.py: switch logger.error in except blocks
to logger.exception (TRY400) — keeps the traceback for ops.
- configs/feature/__init__.py: OPENAPI_KNOWN_CLIENT_IDS computed_field
needs an @property alongside for pyright to see it as a value, not a
method. Matches the existing line-451 pattern.
Plus ruff format + import-sort across the openapi tree (pure formatting).
135 lines
4.3 KiB
Python
135 lines
4.3 KiB
Python
"""User-scoped identity + session endpoints under /openapi/v1/account."""
|
|
|
|
import builtins
|
|
|
|
import pytest
|
|
from flask import Flask
|
|
from flask.views import MethodView
|
|
|
|
from controllers.openapi import bp as openapi_bp
|
|
from controllers.openapi.account import (
|
|
AccountApi,
|
|
AccountSessionByIdApi,
|
|
AccountSessionsApi,
|
|
AccountSessionsSelfApi,
|
|
)
|
|
|
|
if not hasattr(builtins, "MethodView"):
|
|
builtins.MethodView = MethodView # type: ignore[attr-defined]
|
|
|
|
|
|
@pytest.fixture
|
|
def openapi_app() -> Flask:
|
|
app = Flask(__name__)
|
|
app.config["TESTING"] = True
|
|
app.register_blueprint(openapi_bp)
|
|
return app
|
|
|
|
|
|
def _rule(app: Flask, path: str):
|
|
return next(r for r in app.url_map.iter_rules() if r.rule == path)
|
|
|
|
|
|
def test_account_route_registered(openapi_app: Flask):
|
|
rules = {r.rule for r in openapi_app.url_map.iter_rules()}
|
|
assert "/openapi/v1/account" in rules
|
|
|
|
|
|
def test_account_dispatches_to_class(openapi_app: Flask):
|
|
rule = _rule(openapi_app, "/openapi/v1/account")
|
|
assert openapi_app.view_functions[rule.endpoint].view_class is AccountApi
|
|
|
|
|
|
def test_account_sessions_self_route_registered(openapi_app: Flask):
|
|
rules = {r.rule for r in openapi_app.url_map.iter_rules()}
|
|
assert "/openapi/v1/account/sessions/self" in rules
|
|
|
|
|
|
def test_sessions_self_dispatches_to_class(openapi_app: Flask):
|
|
rule = _rule(openapi_app, "/openapi/v1/account/sessions/self")
|
|
assert openapi_app.view_functions[rule.endpoint].view_class is AccountSessionsSelfApi
|
|
|
|
|
|
def test_account_methods(openapi_app: Flask):
|
|
rule = _rule(openapi_app, "/openapi/v1/account")
|
|
assert "GET" in rule.methods
|
|
|
|
|
|
def test_sessions_self_methods(openapi_app: Flask):
|
|
rule = _rule(openapi_app, "/openapi/v1/account/sessions/self")
|
|
assert "DELETE" in rule.methods
|
|
|
|
|
|
def test_sessions_list_route_registered(openapi_app: Flask):
|
|
rules = {r.rule for r in openapi_app.url_map.iter_rules()}
|
|
assert "/openapi/v1/account/sessions" in rules
|
|
|
|
|
|
def test_sessions_list_dispatches_to_sessions_api(openapi_app: Flask):
|
|
rule = _rule(openapi_app, "/openapi/v1/account/sessions")
|
|
assert openapi_app.view_functions[rule.endpoint].view_class is AccountSessionsApi
|
|
assert "GET" in rule.methods
|
|
|
|
|
|
def test_session_by_id_route_registered(openapi_app: Flask):
|
|
rules = {r.rule for r in openapi_app.url_map.iter_rules()}
|
|
assert "/openapi/v1/account/sessions/<string:session_id>" in rules
|
|
|
|
|
|
def test_session_by_id_dispatches_to_correct_class(openapi_app: Flask):
|
|
rule = _rule(openapi_app, "/openapi/v1/account/sessions/<string:session_id>")
|
|
assert openapi_app.view_functions[rule.endpoint].view_class is AccountSessionByIdApi
|
|
assert "DELETE" in rule.methods
|
|
|
|
|
|
def test_subject_match_for_account_filters_by_account_id():
|
|
"""Account subject scopes queries via account_id."""
|
|
import uuid as _uuid
|
|
|
|
from controllers.openapi.account import _subject_match
|
|
from libs.oauth_bearer import AuthContext, SubjectType
|
|
|
|
aid = _uuid.uuid4()
|
|
ctx = AuthContext(
|
|
subject_type=SubjectType.ACCOUNT,
|
|
subject_email="user@example.com",
|
|
subject_issuer="dify:account",
|
|
account_id=aid,
|
|
scopes=frozenset({"full"}),
|
|
token_id=_uuid.uuid4(),
|
|
source="oauth_account",
|
|
expires_at=None,
|
|
)
|
|
clauses = _subject_match(ctx)
|
|
# One predicate, on account_id
|
|
assert len(clauses) == 1
|
|
assert "account_id" in str(clauses[0])
|
|
|
|
|
|
def test_subject_match_for_external_sso_filters_by_email_and_issuer():
|
|
"""External SSO subject scopes via (subject_email, subject_issuer)
|
|
AND account_id IS NULL — so a same-email account row from a
|
|
federated tenant cannot be revoked through an SSO bearer.
|
|
"""
|
|
import uuid as _uuid
|
|
|
|
from controllers.openapi.account import _subject_match
|
|
from libs.oauth_bearer import AuthContext, SubjectType
|
|
|
|
ctx = AuthContext(
|
|
subject_type=SubjectType.EXTERNAL_SSO,
|
|
subject_email="sso@partner.com",
|
|
subject_issuer="https://idp.partner.com",
|
|
account_id=None,
|
|
scopes=frozenset({"apps:run"}),
|
|
token_id=_uuid.uuid4(),
|
|
source="oauth_external_sso",
|
|
expires_at=None,
|
|
)
|
|
clauses = _subject_match(ctx)
|
|
assert len(clauses) == 3
|
|
rendered = " ".join(str(c) for c in clauses)
|
|
assert "subject_email" in rendered
|
|
assert "subject_issuer" in rendered
|
|
assert "account_id IS NULL" in rendered
|