fix(api): prevent cookies from shadowing admin API keys (#39872)

Signed-off-by: kenwoodjw <blackxin55+@gmail.com>
This commit is contained in:
kenwoodjw
2026-08-02 02:43:29 +00:00
committed by GitHub
parent b6824334cf
commit a42d486bc0
4 changed files with 86 additions and 24 deletions
@@ -3,8 +3,9 @@ from typing import cast
from unittest import mock
import pytest
from flask import Response
from flask import Flask, Response, request
from constants import COOKIE_NAME_ACCESS_TOKEN
from core.logging.context import clear_request_context, get_identity_context
from extensions import ext_login
from extensions.ext_login import unauthorized_handler
@@ -74,3 +75,31 @@ def test_on_user_logged_in_logs_unsupported_user_type(caplog: pytest.LogCaptureF
assert get_identity_context() == ("", "", "")
assert "Failed to set logging identity context" in caplog.text
def test_admin_api_key_header_takes_precedence_over_console_cookie(monkeypatch: pytest.MonkeyPatch) -> None:
app = Flask(__name__)
session = mock.Mock(spec=ext_login.Session)
tenant = mock.Mock(spec=ext_login.Tenant)
tenant_account_join = mock.Mock(spec=ext_login.TenantAccountJoin)
account = mock.Mock(spec=ext_login.Account)
session.execute.return_value.one_or_none.return_value = (tenant, tenant_account_join)
session.scalar.return_value = account
monkeypatch.setattr(ext_login.dify_config, "ADMIN_API_KEY_ENABLE", True)
monkeypatch.setattr(ext_login.dify_config, "ADMIN_API_KEY", "admin-key")
monkeypatch.setattr(ext_login.dify_config, "CONSOLE_WEB_URL", "http://console.example.com")
monkeypatch.setattr(ext_login.dify_config, "CONSOLE_API_URL", "http://api.example.com")
monkeypatch.setattr(ext_login.dify_config, "COOKIE_DOMAIN", "")
with app.test_request_context(
"/console/api/test",
headers={
"Authorization": "Bearer admin-key",
"Cookie": f"{COOKIE_NAME_ACCESS_TOKEN}=console-session",
"X-WORKSPACE-ID": "workspace-id",
},
):
result = ext_login._load_user_from_request(request, session)
assert result is account
account.set_current_tenant_with_session.assert_called_once_with(tenant, session=session)
+18
View File
@@ -92,3 +92,21 @@ def test_non_whitelisted_path_requires_csrf():
with pytest.raises(Unauthorized):
token.check_csrf_token(request, "account-1")
def test_admin_api_key_header_bypasses_csrf_when_console_cookie_is_present(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(token.dify_config, "ADMIN_API_KEY_ENABLE", True)
monkeypatch.setattr(token.dify_config, "ADMIN_API_KEY", "admin-key")
monkeypatch.setattr(token.dify_config, "CONSOLE_WEB_URL", "http://console.example.com")
monkeypatch.setattr(token.dify_config, "CONSOLE_API_URL", "http://api.example.com")
monkeypatch.setattr(token.dify_config, "COOKIE_DOMAIN", "")
request = cast(
Request,
MockRequest(
headers={"Authorization": "Bearer admin-key"},
cookies={COOKIE_NAME_ACCESS_TOKEN: "console-session"},
args={},
),
)
token.check_csrf_token(request, "account-1")