chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
@@ -0,0 +1,253 @@
|
||||
"""Transport-boundary tests for account invitation activation."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from pytest_mock import MockerFixture
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
from werkzeug.exceptions import UnprocessableEntity
|
||||
|
||||
from controllers.console.auth.activate import ActivateApi, ActivateCheckApi
|
||||
from controllers.console.auth.error import InvitationAccountMismatchError as InvitationAccountMismatchHTTPError
|
||||
from controllers.console.error import (
|
||||
AccountInFreezeError,
|
||||
AlreadyActivateError,
|
||||
)
|
||||
from controllers.console.error import (
|
||||
EmailDomainSuspendedError as EmailDomainSuspendedHTTPError,
|
||||
)
|
||||
from enums import DeploymentEdition
|
||||
from extensions.ext_application_services import build_application_services
|
||||
from extensions.ext_redis import RedisClientWrapper
|
||||
from libs.login import AccountWithTenant
|
||||
from models.account import Account
|
||||
from services.account_activation_service import AccountActivationService
|
||||
from services.account_errors import AccountEmailDomainSuspendedError as EmailDomainSuspendedRegistrationError
|
||||
from services.account_errors import FrozenAccountError, InvalidInvitationError, InvitationAccountMismatchError
|
||||
from services.entities.account_activation_entities import (
|
||||
ActivationCheckData,
|
||||
ActivationCheckResult,
|
||||
ActivationCommand,
|
||||
InvitationLookup,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app() -> Flask:
|
||||
app = Flask(__name__)
|
||||
app.config["TESTING"] = True
|
||||
return app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def activation_service(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
redis_transport: tuple[RedisClientWrapper, MagicMock],
|
||||
mocker: MockerFixture,
|
||||
) -> AccountActivationService:
|
||||
service = build_application_services(
|
||||
database_client=sqlite_session_factory,
|
||||
deployment_edition=DeploymentEdition.COMMUNITY,
|
||||
initialization_password="",
|
||||
redis=redis_transport[0],
|
||||
).accounts.activation
|
||||
mocker.patch.object(service, "check")
|
||||
mocker.patch.object(service, "activate")
|
||||
return service
|
||||
|
||||
|
||||
def _services(service: AccountActivationService) -> SimpleNamespace:
|
||||
return SimpleNamespace(accounts=SimpleNamespace(activation=service))
|
||||
|
||||
|
||||
class TestActivateCheckApi:
|
||||
def test_serializes_valid_invitation(
|
||||
self,
|
||||
app: Flask,
|
||||
activation_service: AccountActivationService,
|
||||
) -> None:
|
||||
activation_service.check.return_value = ActivationCheckResult(
|
||||
is_valid=True,
|
||||
data=ActivationCheckData(
|
||||
workspace_name="Test Workspace",
|
||||
workspace_id="workspace-123",
|
||||
email="invitee@example.com",
|
||||
account_status="pending",
|
||||
requires_setup=True,
|
||||
),
|
||||
)
|
||||
with (
|
||||
app.test_request_context(
|
||||
"/activate/check?workspace_id=workspace-123&email=invitee@example.com&token=valid-token"
|
||||
),
|
||||
patch(
|
||||
"controllers.console.auth.activate.application_services",
|
||||
return_value=_services(activation_service),
|
||||
),
|
||||
):
|
||||
response = ActivateCheckApi().get()
|
||||
|
||||
assert response == {
|
||||
"is_valid": True,
|
||||
"data": {
|
||||
"workspace_name": "Test Workspace",
|
||||
"workspace_id": "workspace-123",
|
||||
"email": "invitee@example.com",
|
||||
"account_status": "pending",
|
||||
"requires_setup": True,
|
||||
},
|
||||
}
|
||||
activation_service.check.assert_called_once_with(
|
||||
InvitationLookup(
|
||||
workspace_id="workspace-123",
|
||||
email="invitee@example.com",
|
||||
token="valid-token",
|
||||
),
|
||||
)
|
||||
|
||||
def test_omits_data_for_invalid_invitation(self, app: Flask, activation_service: AccountActivationService) -> None:
|
||||
activation_service.check.return_value = ActivationCheckResult(is_valid=False)
|
||||
|
||||
with (
|
||||
app.test_request_context("/activate/check?token=invalid-token"),
|
||||
patch(
|
||||
"controllers.console.auth.activate.application_services",
|
||||
return_value=_services(activation_service),
|
||||
),
|
||||
):
|
||||
response = ActivateCheckApi().get()
|
||||
|
||||
assert response == {"is_valid": False}
|
||||
|
||||
def test_rejects_request_without_token(self, app: Flask, activation_service: AccountActivationService) -> None:
|
||||
"""`token` is required, so a tokenless query must not reach the application service."""
|
||||
with (
|
||||
app.test_request_context("/activate/check?workspace_id=workspace-123"),
|
||||
patch(
|
||||
"controllers.console.auth.activate.application_services",
|
||||
return_value=_services(activation_service),
|
||||
),
|
||||
pytest.raises(UnprocessableEntity),
|
||||
):
|
||||
ActivateCheckApi().get()
|
||||
|
||||
activation_service.check.assert_not_called()
|
||||
|
||||
|
||||
class TestActivateApi:
|
||||
def test_passes_parsed_command_to_application_service(
|
||||
self,
|
||||
app: Flask,
|
||||
activation_service: AccountActivationService,
|
||||
) -> None:
|
||||
payload = {
|
||||
"workspace_id": "workspace-123",
|
||||
"email": "Invitee@Example.com",
|
||||
"token": "valid-token",
|
||||
"name": "John Doe",
|
||||
"interface_language": "en-US",
|
||||
"timezone": "UTC",
|
||||
}
|
||||
account = Account(name="User", email="user@example.com")
|
||||
account.id = "account-123"
|
||||
with (
|
||||
app.test_request_context("/activate", method="POST", json=payload),
|
||||
patch(
|
||||
"controllers.console.auth.activate.application_services",
|
||||
return_value=_services(activation_service),
|
||||
),
|
||||
patch("controllers.console.auth.activate.extract_access_token", return_value="access-token"),
|
||||
patch(
|
||||
"controllers.console.auth.activate.current_account_with_tenant",
|
||||
return_value=AccountWithTenant(
|
||||
account=account,
|
||||
tenant_id="workspace-123",
|
||||
),
|
||||
),
|
||||
):
|
||||
response = ActivateApi().post()
|
||||
|
||||
assert response == {"result": "success"}
|
||||
activation_service.activate.assert_called_once_with(
|
||||
ActivationCommand(
|
||||
invitation=InvitationLookup(
|
||||
workspace_id="workspace-123",
|
||||
email="Invitee@Example.com",
|
||||
token="valid-token",
|
||||
),
|
||||
name="John Doe",
|
||||
interface_language="en-US",
|
||||
timezone="UTC",
|
||||
),
|
||||
authenticated_account_id="account-123",
|
||||
)
|
||||
|
||||
def test_passes_no_authenticated_account_for_token_only_activation(
|
||||
self,
|
||||
app: Flask,
|
||||
activation_service: AccountActivationService,
|
||||
) -> None:
|
||||
with (
|
||||
app.test_request_context("/activate", method="POST", json={"token": "valid-token"}),
|
||||
patch(
|
||||
"controllers.console.auth.activate.application_services",
|
||||
return_value=_services(activation_service),
|
||||
),
|
||||
patch("controllers.console.auth.activate.extract_access_token", return_value=None),
|
||||
patch("controllers.console.auth.activate.current_account_with_tenant") as resolve_account,
|
||||
):
|
||||
response = ActivateApi().post()
|
||||
|
||||
assert response == {"result": "success"}
|
||||
activation_service.activate.assert_called_once_with(
|
||||
ActivationCommand(invitation=InvitationLookup(workspace_id=None, email=None, token="valid-token")),
|
||||
authenticated_account_id=None,
|
||||
)
|
||||
resolve_account.assert_not_called()
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("service_error", "http_error"),
|
||||
[
|
||||
(InvalidInvitationError(), AlreadyActivateError),
|
||||
(InvitationAccountMismatchError(), InvitationAccountMismatchHTTPError),
|
||||
(FrozenAccountError(), AccountInFreezeError),
|
||||
(EmailDomainSuspendedRegistrationError(), EmailDomainSuspendedHTTPError),
|
||||
],
|
||||
)
|
||||
def test_translates_application_errors(
|
||||
self,
|
||||
app: Flask,
|
||||
activation_service: AccountActivationService,
|
||||
service_error: Exception,
|
||||
http_error: type[Exception],
|
||||
) -> None:
|
||||
activation_service.activate.side_effect = service_error
|
||||
|
||||
with (
|
||||
app.test_request_context("/activate", method="POST", json={"token": "invalid-token"}),
|
||||
patch(
|
||||
"controllers.console.auth.activate.application_services",
|
||||
return_value=_services(activation_service),
|
||||
),
|
||||
patch("controllers.console.auth.activate.extract_access_token", return_value=None),
|
||||
pytest.raises(http_error),
|
||||
):
|
||||
ActivateApi().post()
|
||||
|
||||
def test_rejects_request_without_token(self, app: Flask, activation_service: AccountActivationService) -> None:
|
||||
"""`token` is required, so a tokenless payload must not resolve the session or reach the service."""
|
||||
with (
|
||||
app.test_request_context("/activate", method="POST", json={"workspace_id": "workspace-123"}),
|
||||
patch(
|
||||
"controllers.console.auth.activate.application_services",
|
||||
return_value=_services(activation_service),
|
||||
),
|
||||
patch("controllers.console.auth.activate.extract_access_token") as extract_token,
|
||||
pytest.raises(UnprocessableEntity),
|
||||
):
|
||||
ActivateApi().post()
|
||||
|
||||
extract_token.assert_not_called()
|
||||
activation_service.activate.assert_not_called()
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from inspect import unwrap
|
||||
from unittest.mock import create_autospec, patch
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from controllers.console.auth.data_source_bearer_auth import (
|
||||
ApiKeyAuthBindingPayload,
|
||||
ApiKeyAuthDataSource,
|
||||
ApiKeyAuthDataSourceBinding,
|
||||
ApiKeyAuthDataSourceBindingDelete,
|
||||
)
|
||||
from controllers.console.auth.error import (
|
||||
DataSourceApiKeyAuthCredentialsRejectedRequestError,
|
||||
DataSourceApiKeyAuthProviderNotSupportedError,
|
||||
DataSourceApiKeyAuthProviderUnavailableRequestError,
|
||||
InvalidDataSourceApiKeyAuthCredentialsRequestError,
|
||||
)
|
||||
from libs.exception import BaseHTTPException
|
||||
from machinery.context import RequestContext
|
||||
from services.auth.errors import (
|
||||
DataSourceApiKeyAuthCredentialValidationError,
|
||||
DataSourceApiKeyAuthProviderUnavailableError,
|
||||
InvalidDataSourceApiKeyAuthCredentialsError,
|
||||
UnsupportedDataSourceApiKeyAuthProviderError,
|
||||
)
|
||||
from services.data_source.auth.api_key_service import DataSourceApiKeyAuthService
|
||||
from services.data_source.entities.api_key_auth import (
|
||||
DataSourceApiKeyAuthBindingCreate,
|
||||
DataSourceApiKeyAuthBindingRecord,
|
||||
DataSourceApiKeyAuthCredentials,
|
||||
)
|
||||
|
||||
|
||||
def _request_context() -> RequestContext:
|
||||
return RequestContext(
|
||||
request_id="request-1",
|
||||
trace_id="trace-1",
|
||||
account_id="account-1",
|
||||
active_workspace_id="tenant-1",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _DataSources:
|
||||
api_key_auth: DataSourceApiKeyAuthService
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _ApplicationServices:
|
||||
data_sources: _DataSources
|
||||
|
||||
|
||||
def _application_services(service: DataSourceApiKeyAuthService) -> _ApplicationServices:
|
||||
return _ApplicationServices(data_sources=_DataSources(api_key_auth=service))
|
||||
|
||||
|
||||
def test_list_data_source_auth_passes_context_and_serializes_application_result() -> None:
|
||||
api = ApiKeyAuthDataSource()
|
||||
method = unwrap(api.get)
|
||||
request_context = _request_context()
|
||||
service = create_autospec(DataSourceApiKeyAuthService, instance=True, spec_set=True)
|
||||
service.list_bindings.return_value = (
|
||||
DataSourceApiKeyAuthBindingRecord(
|
||||
id="binding-1",
|
||||
category="api_key",
|
||||
provider="custom",
|
||||
disabled=False,
|
||||
created_at=datetime(2026, 1, 1, tzinfo=UTC),
|
||||
updated_at=datetime(2026, 1, 2, tzinfo=UTC),
|
||||
),
|
||||
)
|
||||
|
||||
with patch(
|
||||
"controllers.console.auth.data_source_bearer_auth.application_services",
|
||||
return_value=_application_services(service),
|
||||
):
|
||||
result = method(api, request_context)
|
||||
|
||||
service.list_bindings.assert_called_once_with(request_context)
|
||||
assert result == {
|
||||
"sources": [
|
||||
{
|
||||
"id": "binding-1",
|
||||
"category": "api_key",
|
||||
"provider": "custom",
|
||||
"disabled": False,
|
||||
"created_at": 1767225600,
|
||||
"updated_at": 1767312000,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def test_create_data_source_auth_binding_passes_context_and_command() -> None:
|
||||
api = ApiKeyAuthDataSourceBinding()
|
||||
method = unwrap(api.post)
|
||||
payload = {
|
||||
"category": "api_key",
|
||||
"provider": "custom",
|
||||
"credentials": {
|
||||
"auth_type": "api_key",
|
||||
"config": {"api_key": "secret", "base_url": "https://example.com"},
|
||||
},
|
||||
}
|
||||
request_context = _request_context()
|
||||
req_data = ApiKeyAuthBindingPayload.model_validate(payload)
|
||||
service = create_autospec(DataSourceApiKeyAuthService, instance=True, spec_set=True)
|
||||
|
||||
with patch(
|
||||
"controllers.console.auth.data_source_bearer_auth.application_services",
|
||||
return_value=_application_services(service),
|
||||
):
|
||||
result, status = method(api, req_data, request_context)
|
||||
|
||||
service.create_binding.assert_called_once_with(
|
||||
request_context,
|
||||
DataSourceApiKeyAuthBindingCreate(
|
||||
category="api_key",
|
||||
provider="custom",
|
||||
credentials=DataSourceApiKeyAuthCredentials(
|
||||
"api_key",
|
||||
"secret",
|
||||
{"base_url": "https://example.com"},
|
||||
),
|
||||
),
|
||||
)
|
||||
assert result == {"result": "success"}
|
||||
assert status == 200
|
||||
|
||||
|
||||
def test_create_data_source_auth_binding_maps_unsupported_provider_to_bad_request() -> None:
|
||||
api = ApiKeyAuthDataSourceBinding()
|
||||
method = unwrap(api.post)
|
||||
request_context = _request_context()
|
||||
req_data = ApiKeyAuthBindingPayload(
|
||||
category="api_key",
|
||||
provider="unsupported",
|
||||
credentials={"auth_type": "api_key", "config": {"api_key": "secret"}},
|
||||
)
|
||||
service = create_autospec(DataSourceApiKeyAuthService, instance=True, spec_set=True)
|
||||
service.create_binding.side_effect = UnsupportedDataSourceApiKeyAuthProviderError(req_data.provider)
|
||||
|
||||
with (
|
||||
patch(
|
||||
"controllers.console.auth.data_source_bearer_auth.application_services",
|
||||
return_value=_application_services(service),
|
||||
),
|
||||
pytest.raises(DataSourceApiKeyAuthProviderNotSupportedError) as exc_info,
|
||||
):
|
||||
method(api, req_data, request_context)
|
||||
|
||||
assert exc_info.value.code == 400
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("service_error", "request_error", "expected_status"),
|
||||
[
|
||||
(
|
||||
InvalidDataSourceApiKeyAuthCredentialsError("Invalid auth type"),
|
||||
InvalidDataSourceApiKeyAuthCredentialsRequestError,
|
||||
400,
|
||||
),
|
||||
(
|
||||
DataSourceApiKeyAuthCredentialValidationError("Credentials rejected"),
|
||||
DataSourceApiKeyAuthCredentialsRejectedRequestError,
|
||||
400,
|
||||
),
|
||||
(
|
||||
DataSourceApiKeyAuthProviderUnavailableError("firecrawl"),
|
||||
DataSourceApiKeyAuthProviderUnavailableRequestError,
|
||||
502,
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_create_data_source_auth_binding_maps_domain_errors(
|
||||
service_error: Exception,
|
||||
request_error: type[BaseHTTPException],
|
||||
expected_status: int,
|
||||
) -> None:
|
||||
api = ApiKeyAuthDataSourceBinding()
|
||||
method = unwrap(api.post)
|
||||
request_context = _request_context()
|
||||
req_data = ApiKeyAuthBindingPayload(
|
||||
category="api_key",
|
||||
provider="firecrawl",
|
||||
credentials={"auth_type": "bearer", "config": {"api_key": "secret"}},
|
||||
)
|
||||
service = create_autospec(DataSourceApiKeyAuthService, instance=True, spec_set=True)
|
||||
service.create_binding.side_effect = service_error
|
||||
|
||||
with (
|
||||
patch(
|
||||
"controllers.console.auth.data_source_bearer_auth.application_services",
|
||||
return_value=_application_services(service),
|
||||
),
|
||||
pytest.raises(request_error) as exc_info,
|
||||
):
|
||||
method(api, req_data, request_context)
|
||||
|
||||
assert exc_info.value.code == expected_status
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
[
|
||||
{"category": "", "provider": "firecrawl", "credentials": {"auth_type": "bearer", "config": {"api_key": "key"}}},
|
||||
{"category": "api_key", "provider": "", "credentials": {"auth_type": "bearer", "config": {"api_key": "key"}}},
|
||||
{"category": "api_key", "provider": "firecrawl", "credentials": {"config": {"api_key": "key"}}},
|
||||
{"category": "api_key", "provider": "firecrawl", "credentials": {"auth_type": "bearer", "config": {}}},
|
||||
{"category": "api_key", "provider": "firecrawl", "credentials": {"auth_type": "bearer", "config": "invalid"}},
|
||||
],
|
||||
)
|
||||
def test_api_key_auth_binding_payload_rejects_invalid_structure(payload: dict[str, object]) -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
ApiKeyAuthBindingPayload.model_validate(payload)
|
||||
|
||||
|
||||
def test_delete_data_source_auth_binding_passes_context_and_binding_id() -> None:
|
||||
api = ApiKeyAuthDataSourceBindingDelete()
|
||||
method = unwrap(api.delete)
|
||||
request_context = _request_context()
|
||||
binding_id = UUID("31a00aeb-0865-4dd2-952a-5e0de34c57cc")
|
||||
service = create_autospec(DataSourceApiKeyAuthService, instance=True, spec_set=True)
|
||||
|
||||
with patch(
|
||||
"controllers.console.auth.data_source_bearer_auth.application_services",
|
||||
return_value=_application_services(service),
|
||||
):
|
||||
result, status = method(api, request_context, binding_id)
|
||||
|
||||
service.delete_binding.assert_called_once_with(request_context, str(binding_id))
|
||||
assert result == ""
|
||||
assert status == 204
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
from http import HTTPStatus
|
||||
from inspect import unwrap
|
||||
from unittest.mock import MagicMock, create_autospec, patch
|
||||
from uuid import UUID
|
||||
|
||||
from flask import Flask, Response
|
||||
|
||||
from controllers.console.auth.data_source_oauth import (
|
||||
OAuthDataSource,
|
||||
OAuthDataSourceBinding,
|
||||
OAuthDataSourceCallback,
|
||||
OAuthDataSourceSync,
|
||||
)
|
||||
from extensions.ext_application_services import ApplicationServices
|
||||
from machinery.context import RequestContext
|
||||
from services.data_source.entities.oauth import DataSourceOAuthCallback
|
||||
from services.data_source.oauth_service import (
|
||||
DataSourceOAuthError,
|
||||
InvalidDataSourceOAuthCodeError,
|
||||
InvalidDataSourceOAuthProviderError,
|
||||
)
|
||||
from tests.helpers.unit.config_override import config_overrides_context
|
||||
|
||||
|
||||
def _request_context() -> RequestContext:
|
||||
return RequestContext(
|
||||
request_id="request-1",
|
||||
trace_id=None,
|
||||
account_id="account-1",
|
||||
active_workspace_id="workspace-1",
|
||||
)
|
||||
|
||||
|
||||
def _services(service: MagicMock) -> MagicMock:
|
||||
services = create_autospec(ApplicationServices, instance=True, spec_set=True)
|
||||
services.data_sources.resolve_oauth.return_value = service
|
||||
return services
|
||||
|
||||
|
||||
def test_get_delegates_to_application_service_and_serializes_response() -> None:
|
||||
service = MagicMock()
|
||||
service.start_authorization.return_value = "https://notion.example/authorize"
|
||||
context = _request_context()
|
||||
|
||||
with patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=_services(service),
|
||||
):
|
||||
result = unwrap(OAuthDataSource.get)(OAuthDataSource(), context, "notion")
|
||||
|
||||
assert result == ({"data": "https://notion.example/authorize"}, HTTPStatus.OK)
|
||||
service.start_authorization.assert_called_once_with(context)
|
||||
|
||||
|
||||
def test_get_maps_unknown_provider_to_bad_request() -> None:
|
||||
service = MagicMock()
|
||||
services = _services(service)
|
||||
services.data_sources.resolve_oauth.side_effect = InvalidDataSourceOAuthProviderError
|
||||
|
||||
with patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=services,
|
||||
):
|
||||
result = unwrap(OAuthDataSource.get)(OAuthDataSource(), _request_context(), "unknown")
|
||||
|
||||
assert result == ({"error": "Invalid provider"}, HTTPStatus.BAD_REQUEST)
|
||||
|
||||
|
||||
def test_callback_parses_query_and_returns_flask_redirect() -> None:
|
||||
app = Flask(__name__)
|
||||
service = MagicMock()
|
||||
service.complete_callback.return_value = DataSourceOAuthCallback(provider="notion", code="code-1", error=None)
|
||||
|
||||
with (
|
||||
app.test_request_context("/?code=code-1"),
|
||||
config_overrides_context(CONSOLE_WEB_URL="https://console.example/root?lang=en#top"),
|
||||
patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=_services(service),
|
||||
),
|
||||
):
|
||||
response = OAuthDataSourceCallback().get("notion")
|
||||
|
||||
assert isinstance(response, Response)
|
||||
assert response.status_code == HTTPStatus.FOUND
|
||||
assert response.location == "https://console.example/root?lang=en&type=notion&code=code-1#top"
|
||||
service.complete_callback.assert_called_once_with(code="code-1", error=None)
|
||||
|
||||
|
||||
def test_binding_parses_query_and_delegates_with_request_context() -> None:
|
||||
app = Flask(__name__)
|
||||
service = MagicMock()
|
||||
context = _request_context()
|
||||
|
||||
with (
|
||||
app.test_request_context("/?code=code-1"),
|
||||
patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=_services(service),
|
||||
),
|
||||
):
|
||||
result = unwrap(OAuthDataSourceBinding.get)(OAuthDataSourceBinding(), context, "notion")
|
||||
|
||||
assert result == ({"result": "success"}, HTTPStatus.OK)
|
||||
service.bind.assert_called_once_with(context, code="code-1")
|
||||
|
||||
|
||||
def test_binding_maps_invalid_code_to_bad_request() -> None:
|
||||
app = Flask(__name__)
|
||||
service = MagicMock()
|
||||
|
||||
with (
|
||||
app.test_request_context("/?code="),
|
||||
patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=_services(service),
|
||||
),
|
||||
):
|
||||
result = unwrap(OAuthDataSourceBinding.get)(OAuthDataSourceBinding(), _request_context(), "notion")
|
||||
|
||||
assert result == ({"error": "Invalid code"}, HTTPStatus.BAD_REQUEST)
|
||||
service.bind.assert_not_called()
|
||||
|
||||
|
||||
def test_binding_maps_application_code_error_to_bad_request() -> None:
|
||||
app = Flask(__name__)
|
||||
service = MagicMock()
|
||||
service.bind.side_effect = InvalidDataSourceOAuthCodeError
|
||||
|
||||
with (
|
||||
app.test_request_context("/?code=code-1"),
|
||||
patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=_services(service),
|
||||
),
|
||||
):
|
||||
result = unwrap(OAuthDataSourceBinding.get)(OAuthDataSourceBinding(), _request_context(), "notion")
|
||||
|
||||
assert result == ({"error": "Invalid code"}, HTTPStatus.BAD_REQUEST)
|
||||
|
||||
|
||||
def test_sync_converts_route_uuid_and_delegates() -> None:
|
||||
service = MagicMock()
|
||||
context = _request_context()
|
||||
binding_id = UUID("11111111-1111-1111-1111-111111111111")
|
||||
|
||||
with patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=_services(service),
|
||||
):
|
||||
result = unwrap(OAuthDataSourceSync.get)(OAuthDataSourceSync(), context, "notion", binding_id)
|
||||
|
||||
assert result == ({"result": "success"}, HTTPStatus.OK)
|
||||
service.sync.assert_called_once_with(context, binding_id=str(binding_id))
|
||||
|
||||
|
||||
def test_sync_hides_provider_failure_details() -> None:
|
||||
service = MagicMock()
|
||||
service.sync.side_effect = DataSourceOAuthError("provider details")
|
||||
binding_id = UUID("11111111-1111-1111-1111-111111111111")
|
||||
|
||||
with (
|
||||
patch(
|
||||
"controllers.console.auth.data_source_oauth.application_services",
|
||||
return_value=_services(service),
|
||||
),
|
||||
patch("controllers.console.auth.data_source_oauth.logger.exception") as log_exception,
|
||||
):
|
||||
result = unwrap(OAuthDataSourceSync.get)(OAuthDataSourceSync(), _request_context(), "notion", binding_id)
|
||||
|
||||
assert result == ({"error": "OAuth data source process failed"}, HTTPStatus.BAD_REQUEST)
|
||||
log_exception.assert_called_once()
|
||||
@@ -0,0 +1,323 @@
|
||||
"""Unit tests for the email-registration Flask adapter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Generator
|
||||
from contextlib import contextmanager
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from pydantic import ValidationError
|
||||
from pytest_mock import MockerFixture
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from controllers.console import bp as console_bp
|
||||
from controllers.console.auth.email_register import (
|
||||
EmailRegisterCheckApi,
|
||||
EmailRegisterResetApi,
|
||||
EmailRegisterResetPayload,
|
||||
EmailRegisterSendEmailApi,
|
||||
)
|
||||
from controllers.console.auth.error import (
|
||||
EmailAlreadyInUseError,
|
||||
EmailCodeError,
|
||||
EmailRegisterLimitError,
|
||||
EmailRegisterRateLimitExceededError,
|
||||
InvalidEmailError,
|
||||
InvalidTokenError,
|
||||
NormalizedEmailAlreadyInUseError,
|
||||
PasswordMismatchError,
|
||||
)
|
||||
from controllers.console.error import (
|
||||
AccountInFreezeError,
|
||||
EmailDomainSuspendedError,
|
||||
EmailSendIpLimitError,
|
||||
SeatsLimitExceeded,
|
||||
)
|
||||
from enums import DeploymentEdition
|
||||
from extensions.ext_application_services import build_application_services
|
||||
from extensions.ext_redis import RedisClientWrapper
|
||||
from services.account.email_registration_service import AccountEmailRegistrationService
|
||||
from services.account_errors import (
|
||||
AccountEmailAlreadyInUseError,
|
||||
AccountEmailDomainSuspendedError,
|
||||
AccountEmailFrozenError,
|
||||
AccountNormalizedEmailAlreadyInUseError,
|
||||
EmailRegistrationPasswordMismatchError,
|
||||
EmailRegistrationSeatsLimitError,
|
||||
EmailRegistrationSendIPLimitedError,
|
||||
EmailRegistrationSendRateLimitError,
|
||||
EmailRegistrationVerificationLimitError,
|
||||
InvalidEmailRegistrationAddressError,
|
||||
InvalidEmailRegistrationCodeError,
|
||||
InvalidEmailRegistrationTokenError,
|
||||
)
|
||||
from services.entities.account_entities import AccountEmailRegistrationVerification, AccountSessionTokens
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _cloud_edition(config_overrides: Callable[..., None]) -> None:
|
||||
config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _request(
|
||||
app: Flask,
|
||||
service: AccountEmailRegistrationService,
|
||||
*,
|
||||
path: str,
|
||||
payload: dict[str, str],
|
||||
) -> Generator[None]:
|
||||
services = SimpleNamespace(accounts=SimpleNamespace(email_registration=service))
|
||||
with (
|
||||
patch("controllers.console.auth.email_register.application_services", return_value=services),
|
||||
patch(
|
||||
"controllers.console.flask_admission.SystemFeatureService.is_email_password_login_enabled",
|
||||
return_value=True,
|
||||
),
|
||||
patch(
|
||||
"controllers.console.flask_admission.SystemFeatureService.is_registration_allowed",
|
||||
return_value=True,
|
||||
),
|
||||
patch("controllers.console.auth.email_register.extract_remote_ip", return_value="127.0.0.1"),
|
||||
app.test_request_context(path, method="POST", json=payload),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def service(
|
||||
sqlite_session_factory: sessionmaker[Session],
|
||||
redis_transport: tuple[RedisClientWrapper, MagicMock],
|
||||
mocker: MockerFixture,
|
||||
) -> AccountEmailRegistrationService:
|
||||
service = build_application_services(
|
||||
database_client=sqlite_session_factory,
|
||||
deployment_edition=DeploymentEdition.COMMUNITY,
|
||||
initialization_password="",
|
||||
redis=redis_transport[0],
|
||||
).accounts.email_registration
|
||||
mocker.patch.object(service, "send_code")
|
||||
mocker.patch.object(service, "verify_code")
|
||||
mocker.patch.object(service, "register")
|
||||
return service
|
||||
|
||||
|
||||
def test_normalized_email_conflict_exposes_a_distinct_error_code() -> None:
|
||||
error = NormalizedEmailAlreadyInUseError()
|
||||
|
||||
assert error.code == 400
|
||||
assert error.data is not None
|
||||
assert error.data["code"] == "normalized_email_already_in_use"
|
||||
|
||||
|
||||
def test_send_email_delegates_with_remote_ip(app: Flask, service: AccountEmailRegistrationService) -> None:
|
||||
service.send_code.return_value = "token-123"
|
||||
|
||||
with _request(
|
||||
app,
|
||||
service,
|
||||
path="/email-register/send-email",
|
||||
payload={"email": "Invitee@Example.com", "language": "zh-Hans"},
|
||||
):
|
||||
response = EmailRegisterSendEmailApi().post()
|
||||
|
||||
assert response == {"result": "success", "data": "token-123"}
|
||||
assert service.send_code.call_args.kwargs == {
|
||||
"remote_ip": "127.0.0.1",
|
||||
"requested_email": "Invitee@Example.com",
|
||||
"requested_language": "zh-Hans",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("service_error", "http_error"),
|
||||
[
|
||||
pytest.param(EmailRegistrationSendIPLimitedError(), EmailSendIpLimitError, id="ip-limit"),
|
||||
pytest.param(EmailRegistrationSendRateLimitError(1), EmailRegisterRateLimitExceededError, id="send-limit"),
|
||||
pytest.param(AccountEmailFrozenError(), AccountInFreezeError, id="frozen"),
|
||||
pytest.param(AccountEmailDomainSuspendedError(), EmailDomainSuspendedError, id="suspended-domain"),
|
||||
],
|
||||
)
|
||||
def test_send_email_translates_application_errors(
|
||||
app: Flask,
|
||||
service: AccountEmailRegistrationService,
|
||||
service_error: Exception,
|
||||
http_error: type[Exception],
|
||||
) -> None:
|
||||
service.send_code.side_effect = service_error
|
||||
|
||||
with _request(
|
||||
app,
|
||||
service,
|
||||
path="/email-register/send-email",
|
||||
payload={"email": "invitee@example.com"},
|
||||
):
|
||||
with pytest.raises(http_error):
|
||||
EmailRegisterSendEmailApi().post()
|
||||
|
||||
|
||||
def test_verify_email_code_serializes_application_result(app: Flask, service: AccountEmailRegistrationService) -> None:
|
||||
service.verify_code.return_value = AccountEmailRegistrationVerification(
|
||||
email="user@example.com",
|
||||
token="verified-token",
|
||||
)
|
||||
|
||||
with _request(
|
||||
app,
|
||||
service,
|
||||
path="/email-register/validity",
|
||||
payload={"email": "User@Example.com", "code": "123456", "token": "pending-token"},
|
||||
):
|
||||
response = EmailRegisterCheckApi().post()
|
||||
|
||||
assert response == {"is_valid": True, "email": "user@example.com", "token": "verified-token"}
|
||||
service.verify_code.assert_called_once_with(
|
||||
email="User@Example.com",
|
||||
code="123456",
|
||||
token="pending-token",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("service_error", "http_error"),
|
||||
[
|
||||
pytest.param(EmailRegistrationVerificationLimitError(), EmailRegisterLimitError, id="attempt-limit"),
|
||||
pytest.param(InvalidEmailRegistrationTokenError(), InvalidTokenError, id="token"),
|
||||
pytest.param(InvalidEmailRegistrationAddressError(), InvalidEmailError, id="email"),
|
||||
pytest.param(InvalidEmailRegistrationCodeError(), EmailCodeError, id="code"),
|
||||
],
|
||||
)
|
||||
def test_verify_email_code_translates_application_errors(
|
||||
app: Flask,
|
||||
service: AccountEmailRegistrationService,
|
||||
service_error: Exception,
|
||||
http_error: type[Exception],
|
||||
) -> None:
|
||||
service.verify_code.side_effect = service_error
|
||||
|
||||
with _request(
|
||||
app,
|
||||
service,
|
||||
path="/email-register/validity",
|
||||
payload={"email": "user@example.com", "code": "wrong", "token": "pending-token"},
|
||||
):
|
||||
with pytest.raises(http_error):
|
||||
EmailRegisterCheckApi().post()
|
||||
|
||||
|
||||
def test_register_delegates_and_serializes_tokens(app: Flask, service: AccountEmailRegistrationService) -> None:
|
||||
service.register.return_value = AccountSessionTokens(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
csrf_token="csrf",
|
||||
)
|
||||
|
||||
with _request(
|
||||
app,
|
||||
service,
|
||||
path="/email-register",
|
||||
payload={
|
||||
"token": "verified-token",
|
||||
"new_password": "ValidPass123!",
|
||||
"password_confirm": "ValidPass123!",
|
||||
"language": "zh-Hans",
|
||||
"timezone": "Asia/Shanghai",
|
||||
},
|
||||
):
|
||||
response = EmailRegisterResetApi().post()
|
||||
|
||||
assert response == {
|
||||
"result": "success",
|
||||
"data": {"access_token": "access", "refresh_token": "refresh", "csrf_token": "csrf"},
|
||||
}
|
||||
assert service.register.call_args.kwargs == {
|
||||
"remote_ip": "127.0.0.1",
|
||||
"token": "verified-token",
|
||||
"new_password": "ValidPass123!",
|
||||
"password_confirm": "ValidPass123!",
|
||||
"language": "zh-Hans",
|
||||
"timezone": "Asia/Shanghai",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("service_error", "http_error"),
|
||||
[
|
||||
pytest.param(EmailRegistrationPasswordMismatchError(), PasswordMismatchError, id="password"),
|
||||
pytest.param(InvalidEmailRegistrationTokenError(), InvalidTokenError, id="token"),
|
||||
pytest.param(
|
||||
AccountNormalizedEmailAlreadyInUseError(),
|
||||
NormalizedEmailAlreadyInUseError,
|
||||
id="normalized-email-in-use",
|
||||
),
|
||||
pytest.param(AccountEmailAlreadyInUseError(), EmailAlreadyInUseError, id="email-in-use"),
|
||||
pytest.param(EmailRegistrationSeatsLimitError(), SeatsLimitExceeded, id="seat-limit"),
|
||||
pytest.param(AccountEmailFrozenError(), AccountInFreezeError, id="frozen"),
|
||||
pytest.param(AccountEmailDomainSuspendedError(), EmailDomainSuspendedError, id="suspended-domain"),
|
||||
],
|
||||
)
|
||||
def test_register_translates_application_errors(
|
||||
app: Flask,
|
||||
service: AccountEmailRegistrationService,
|
||||
service_error: Exception,
|
||||
http_error: type[Exception],
|
||||
) -> None:
|
||||
service.register.side_effect = service_error
|
||||
|
||||
with _request(
|
||||
app,
|
||||
service,
|
||||
path="/email-register",
|
||||
payload={
|
||||
"token": "verified-token",
|
||||
"new_password": "ValidPass123!",
|
||||
"password_confirm": "ValidPass123!",
|
||||
},
|
||||
):
|
||||
with pytest.raises(http_error):
|
||||
EmailRegisterResetApi().post()
|
||||
|
||||
|
||||
def test_reset_payload_rejects_invalid_timezone() -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
EmailRegisterResetPayload.model_validate(
|
||||
{
|
||||
"token": "token-123",
|
||||
"new_password": "ValidPass123!",
|
||||
"password_confirm": "ValidPass123!",
|
||||
"timezone": "",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_invalid_password_is_sanitized_by_real_error_handler(caplog: pytest.LogCaptureFixture) -> None:
|
||||
app = Flask(__name__)
|
||||
app.config["TESTING"] = True
|
||||
app.register_blueprint(console_bp)
|
||||
password_marker = "SecretMarker"
|
||||
|
||||
with (
|
||||
patch(
|
||||
"controllers.console.flask_admission.SystemFeatureService.is_email_password_login_enabled",
|
||||
return_value=True,
|
||||
),
|
||||
patch(
|
||||
"controllers.console.flask_admission.SystemFeatureService.is_registration_allowed",
|
||||
return_value=True,
|
||||
),
|
||||
):
|
||||
response = app.test_client().post(
|
||||
"/console/api/email-register",
|
||||
json={
|
||||
"token": "verified-token",
|
||||
"new_password": password_marker,
|
||||
"password_confirm": password_marker,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 422
|
||||
assert password_marker not in response.get_data(as_text=True)
|
||||
assert password_marker not in caplog.text
|
||||
@@ -0,0 +1,235 @@
|
||||
"""Transport-boundary tests for Console forgot-password endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
|
||||
from controllers.console.auth import forgot_password
|
||||
from controllers.console.auth.error import (
|
||||
EmailCodeError,
|
||||
EmailPasswordResetLimitError,
|
||||
InvalidEmailError,
|
||||
InvalidTokenError,
|
||||
PasswordMismatchError,
|
||||
PasswordResetRateLimitExceededError,
|
||||
)
|
||||
from controllers.console.error import AccountNotFound, EmailSendIpLimitError
|
||||
from enums import DeploymentEdition
|
||||
from services import account_errors
|
||||
from services.entities.account_entities import ForgotPasswordVerification
|
||||
from tests.helpers.unit.config_override import apply_config_overrides
|
||||
|
||||
|
||||
class FakeForgotPasswordService:
|
||||
def __init__(self) -> None:
|
||||
self.error: Exception | None = None
|
||||
self.send_arguments: dict[str, str] | None = None
|
||||
self.verify_arguments: dict[str, str] | None = None
|
||||
self.reset_arguments: dict[str, str] | None = None
|
||||
|
||||
def _raise_if_needed(self) -> None:
|
||||
if self.error is not None:
|
||||
raise self.error
|
||||
|
||||
def send_code(
|
||||
self,
|
||||
*,
|
||||
email: str,
|
||||
language: str,
|
||||
ip_address: str,
|
||||
) -> str:
|
||||
self.send_arguments = {"email": email, "language": language, "ip_address": ip_address}
|
||||
self._raise_if_needed()
|
||||
return "reset-token"
|
||||
|
||||
def verify_code(
|
||||
self,
|
||||
*,
|
||||
email: str,
|
||||
code: str,
|
||||
token: str,
|
||||
) -> ForgotPasswordVerification:
|
||||
self.verify_arguments = {"email": email, "code": code, "token": token}
|
||||
self._raise_if_needed()
|
||||
return ForgotPasswordVerification(email="user@example.com", token="promoted-token")
|
||||
|
||||
def reset(
|
||||
self,
|
||||
*,
|
||||
token: str,
|
||||
new_password: str,
|
||||
password_confirm: str,
|
||||
) -> None:
|
||||
self.reset_arguments = {
|
||||
"token": token,
|
||||
"new_password": new_password,
|
||||
"password_confirm": password_confirm,
|
||||
}
|
||||
self._raise_if_needed()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def admit_forgot_password_requests(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
apply_config_overrides(
|
||||
monkeypatch,
|
||||
DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,
|
||||
ENABLE_EMAIL_PASSWORD_LOGIN=True,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def service(monkeypatch: pytest.MonkeyPatch) -> FakeForgotPasswordService:
|
||||
service = FakeForgotPasswordService()
|
||||
services = SimpleNamespace(accounts=SimpleNamespace(forgot_password=service))
|
||||
monkeypatch.setattr(forgot_password, "application_services", lambda: services)
|
||||
monkeypatch.setattr(forgot_password, "extract_remote_ip", lambda _request: "127.0.0.1")
|
||||
return service
|
||||
|
||||
|
||||
def test_send_parses_input_and_serializes_service_result(app: Flask, service: FakeForgotPasswordService) -> None:
|
||||
with app.test_request_context(
|
||||
"/forgot-password",
|
||||
method="POST",
|
||||
json={"email": "User@Example.com", "language": "zh-Hans"},
|
||||
):
|
||||
response = forgot_password.ForgotPasswordSendEmailApi().post()
|
||||
|
||||
assert response == {"result": "success", "data": "reset-token"}
|
||||
assert service.send_arguments == {
|
||||
"email": "User@Example.com",
|
||||
"language": "zh-Hans",
|
||||
"ip_address": "127.0.0.1",
|
||||
}
|
||||
|
||||
|
||||
def test_send_defaults_unsupported_language(app: Flask, service: FakeForgotPasswordService) -> None:
|
||||
with app.test_request_context(
|
||||
"/forgot-password",
|
||||
method="POST",
|
||||
json={"email": "user@example.com", "language": "fr-FR"},
|
||||
):
|
||||
forgot_password.ForgotPasswordSendEmailApi().post()
|
||||
|
||||
assert service.send_arguments is not None
|
||||
assert service.send_arguments["language"] == "en-US"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("service_error", "request_error"),
|
||||
[
|
||||
(account_errors.ForgotPasswordSendIPLimitedError(), EmailSendIpLimitError),
|
||||
(account_errors.ForgotPasswordSendRateLimitError(2), PasswordResetRateLimitExceededError),
|
||||
],
|
||||
)
|
||||
def test_send_maps_application_errors(
|
||||
app: Flask,
|
||||
service: FakeForgotPasswordService,
|
||||
service_error: Exception,
|
||||
request_error: type[Exception],
|
||||
) -> None:
|
||||
service.error = service_error
|
||||
with (
|
||||
app.test_request_context(
|
||||
"/forgot-password",
|
||||
method="POST",
|
||||
json={"email": "user@example.com"},
|
||||
),
|
||||
pytest.raises(request_error),
|
||||
):
|
||||
forgot_password.ForgotPasswordSendEmailApi().post()
|
||||
|
||||
|
||||
def test_verify_serializes_promoted_token(app: Flask, service: FakeForgotPasswordService) -> None:
|
||||
with app.test_request_context(
|
||||
"/forgot-password/validity",
|
||||
method="POST",
|
||||
json={"email": "USER@example.com", "code": "123456", "token": "verification-token"},
|
||||
):
|
||||
response = forgot_password.ForgotPasswordCheckApi().post()
|
||||
|
||||
assert response == {"is_valid": True, "email": "user@example.com", "token": "promoted-token"}
|
||||
assert service.verify_arguments == {
|
||||
"email": "USER@example.com",
|
||||
"code": "123456",
|
||||
"token": "verification-token",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("service_error", "request_error"),
|
||||
[
|
||||
(account_errors.ForgotPasswordVerificationLimitError(), EmailPasswordResetLimitError),
|
||||
(account_errors.InvalidForgotPasswordTokenError(), InvalidTokenError),
|
||||
(account_errors.InvalidForgotPasswordEmailError(), InvalidEmailError),
|
||||
(account_errors.InvalidForgotPasswordCodeError(), EmailCodeError),
|
||||
],
|
||||
)
|
||||
def test_verify_maps_application_errors(
|
||||
app: Flask,
|
||||
service: FakeForgotPasswordService,
|
||||
service_error: Exception,
|
||||
request_error: type[Exception],
|
||||
) -> None:
|
||||
service.error = service_error
|
||||
with (
|
||||
app.test_request_context(
|
||||
"/forgot-password/validity",
|
||||
method="POST",
|
||||
json={"email": "user@example.com", "code": "123456", "token": "token"},
|
||||
),
|
||||
pytest.raises(request_error),
|
||||
):
|
||||
forgot_password.ForgotPasswordCheckApi().post()
|
||||
|
||||
|
||||
def test_reset_delegates_and_serializes_result(app: Flask, service: FakeForgotPasswordService) -> None:
|
||||
with app.test_request_context(
|
||||
"/forgot-password/resets",
|
||||
method="POST",
|
||||
json={
|
||||
"token": "reset-token",
|
||||
"new_password": "ValidPass123!",
|
||||
"password_confirm": "ValidPass123!",
|
||||
},
|
||||
):
|
||||
response = forgot_password.ForgotPasswordResetApi().post()
|
||||
|
||||
assert response == {"result": "success"}
|
||||
assert service.reset_arguments == {
|
||||
"token": "reset-token",
|
||||
"new_password": "ValidPass123!",
|
||||
"password_confirm": "ValidPass123!",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("service_error", "request_error"),
|
||||
[
|
||||
(account_errors.ForgotPasswordMismatchError(), PasswordMismatchError),
|
||||
(account_errors.InvalidForgotPasswordTokenError(), InvalidTokenError),
|
||||
(account_errors.AccountNotFoundError(), AccountNotFound),
|
||||
],
|
||||
)
|
||||
def test_reset_maps_application_errors(
|
||||
app: Flask,
|
||||
service: FakeForgotPasswordService,
|
||||
service_error: Exception,
|
||||
request_error: type[Exception],
|
||||
) -> None:
|
||||
service.error = service_error
|
||||
with (
|
||||
app.test_request_context(
|
||||
"/forgot-password/resets",
|
||||
method="POST",
|
||||
json={
|
||||
"token": "reset-token",
|
||||
"new_password": "ValidPass123!",
|
||||
"password_confirm": "ValidPass123!",
|
||||
},
|
||||
),
|
||||
pytest.raises(request_error),
|
||||
):
|
||||
forgot_password.ForgotPasswordResetApi().post()
|
||||
@@ -0,0 +1,447 @@
|
||||
"""Transport-boundary tests for Console authentication endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from types import SimpleNamespace
|
||||
from typing import Never
|
||||
|
||||
import pytest
|
||||
from flask import Flask, Response
|
||||
|
||||
from controllers.console import wraps
|
||||
from controllers.console.auth import login
|
||||
from controllers.console.auth.error import (
|
||||
AuthenticationFailedError,
|
||||
EmailCodeError,
|
||||
EmailCodeLoginRateLimitExceededError,
|
||||
EmailCodeLoginServiceUnavailableError,
|
||||
EmailPasswordLoginLimitError,
|
||||
InvalidEmailError,
|
||||
InvalidTokenError,
|
||||
NormalizedEmailAlreadyInUseError,
|
||||
PasswordResetRateLimitExceededError,
|
||||
TurnstileServiceUnavailableError,
|
||||
TurnstileVerificationFailedError,
|
||||
)
|
||||
from controllers.console.error import (
|
||||
AccountBannedError,
|
||||
AccountInFreezeError,
|
||||
AccountNotFound,
|
||||
EmailDomainSuspendedError,
|
||||
EmailSendIpLimitError,
|
||||
InvalidAccountPasswordRequestError,
|
||||
NotAllowedCreateWorkspace,
|
||||
SeatsLimitExceeded,
|
||||
WorkspacesLimitExceeded,
|
||||
)
|
||||
from enums import DeploymentEdition
|
||||
from services import account_errors
|
||||
from services.entities.account_entities import AccountSessionTokens
|
||||
from services.entities.account_login_entities import (
|
||||
EmailCodeLoginCommand,
|
||||
EmailCodeSendCommand,
|
||||
PasswordLoginCommand,
|
||||
PasswordLoginResult,
|
||||
)
|
||||
from tests.helpers.unit.controllers.knowledge_fs_controller_fakes import narrowed
|
||||
|
||||
TEST_TOKEN = "00000000-0000-4000-8000-000000000001"
|
||||
TOKENS = AccountSessionTokens(access_token="access-token", refresh_token="refresh-token", csrf_token="csrf-token")
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeAuthenticationService:
|
||||
error: account_errors.AccountApplicationError | None = None
|
||||
password_commands: list[PasswordLoginCommand] = field(default_factory=list)
|
||||
email_code_send_commands: list[EmailCodeSendCommand] = field(default_factory=list)
|
||||
email_code_login_commands: list[EmailCodeLoginCommand] = field(default_factory=list)
|
||||
reset_arguments: list[tuple[str, str | None, str]] = field(default_factory=list)
|
||||
logout_account_ids: list[str] = field(default_factory=list)
|
||||
refresh_tokens: list[str] = field(default_factory=list)
|
||||
workspace_found: bool = True
|
||||
|
||||
def _raise_if_needed(self) -> None:
|
||||
if self.error is not None:
|
||||
raise self.error
|
||||
|
||||
def login_with_password(self, command: PasswordLoginCommand) -> PasswordLoginResult:
|
||||
self.password_commands.append(command)
|
||||
self._raise_if_needed()
|
||||
return PasswordLoginResult(
|
||||
tokens=TOKENS if self.workspace_found else None,
|
||||
workspace_found=self.workspace_found,
|
||||
)
|
||||
|
||||
def logout(self, account_id: str) -> None:
|
||||
self.logout_account_ids.append(account_id)
|
||||
|
||||
def send_reset_password_email(self, *, email: str, language: str | None, ip_address: str) -> str:
|
||||
self.reset_arguments.append((email, language, ip_address))
|
||||
self._raise_if_needed()
|
||||
return "reset-token"
|
||||
|
||||
def send_email_code(self, command: EmailCodeSendCommand) -> str:
|
||||
self.email_code_send_commands.append(command)
|
||||
self._raise_if_needed()
|
||||
return "email-code-token"
|
||||
|
||||
def login_with_email_code(self, command: EmailCodeLoginCommand) -> AccountSessionTokens:
|
||||
self.email_code_login_commands.append(command)
|
||||
self._raise_if_needed()
|
||||
return TOKENS
|
||||
|
||||
def refresh(self, refresh_token: str) -> AccountSessionTokens:
|
||||
self.refresh_tokens.append(refresh_token)
|
||||
self._raise_if_needed()
|
||||
return TOKENS
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def admit_authentication_requests(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
config_overrides: Callable[..., None],
|
||||
) -> None:
|
||||
config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.CLOUD)
|
||||
monkeypatch.setattr(wraps.SystemFeatureService, "is_email_password_login_enabled", lambda: True)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def service(monkeypatch: pytest.MonkeyPatch) -> FakeAuthenticationService:
|
||||
service = FakeAuthenticationService()
|
||||
services = SimpleNamespace(accounts=SimpleNamespace(authentication=service))
|
||||
monkeypatch.setattr(login, "application_services", lambda: services)
|
||||
monkeypatch.setattr(login, "extract_remote_ip", lambda _request: "127.0.0.1")
|
||||
return service
|
||||
|
||||
|
||||
def _encode(value: str) -> str:
|
||||
return base64.b64encode(value.encode()).decode()
|
||||
|
||||
|
||||
def test_password_login_parses_input_and_serializes_cookies(
|
||||
app: Flask,
|
||||
service: FakeAuthenticationService,
|
||||
) -> None:
|
||||
with app.test_request_context(
|
||||
"/login",
|
||||
method="POST",
|
||||
json={
|
||||
"email": "User@Example.com",
|
||||
"password": _encode("password"),
|
||||
"invite_token": "invite-token",
|
||||
},
|
||||
):
|
||||
response = narrowed(login.LoginApi().post(), Response)
|
||||
|
||||
assert response.json == {"result": "success", "data": None}
|
||||
assert service.password_commands == [
|
||||
PasswordLoginCommand(
|
||||
email="User@Example.com",
|
||||
password="password",
|
||||
invite_token="invite-token",
|
||||
ip_address="127.0.0.1",
|
||||
)
|
||||
]
|
||||
cookies = response.headers.getlist("Set-Cookie")
|
||||
assert any("access_token=" in cookie for cookie in cookies)
|
||||
assert any("refresh_token=" in cookie for cookie in cookies)
|
||||
assert any("csrf_token=" in cookie for cookie in cookies)
|
||||
|
||||
|
||||
def test_password_login_serializes_missing_workspace(
|
||||
app: Flask,
|
||||
service: FakeAuthenticationService,
|
||||
) -> None:
|
||||
service.workspace_found = False
|
||||
with app.test_request_context(
|
||||
"/login",
|
||||
method="POST",
|
||||
json={"email": "user@example.com", "password": _encode("password")},
|
||||
):
|
||||
response = narrowed(login.LoginApi().post(), dict)
|
||||
|
||||
assert response["result"] == "fail"
|
||||
assert "workspace not found" in response["data"]
|
||||
|
||||
|
||||
def test_invitation_login_with_empty_password_returns_authentication_failure(
|
||||
app: Flask,
|
||||
service: FakeAuthenticationService,
|
||||
) -> None:
|
||||
service.error = account_errors.InvalidLoginCredentialsError()
|
||||
with app.test_request_context(
|
||||
"/login",
|
||||
method="POST",
|
||||
json={"email": "user@example.com", "password": _encode(""), "invite_token": "invite-token"},
|
||||
):
|
||||
with pytest.raises(AuthenticationFailedError):
|
||||
login.LoginApi().post()
|
||||
|
||||
assert service.password_commands == [
|
||||
PasswordLoginCommand(
|
||||
email="user@example.com",
|
||||
password="",
|
||||
invite_token="invite-token",
|
||||
ip_address="127.0.0.1",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def test_invitation_login_with_weak_password_returns_policy_failure(
|
||||
app: Flask,
|
||||
service: FakeAuthenticationService,
|
||||
) -> None:
|
||||
service.error = account_errors.InvalidAccountPasswordError("Password must contain letters and numbers")
|
||||
with app.test_request_context(
|
||||
"/login",
|
||||
method="POST",
|
||||
json={"email": "user@example.com", "password": _encode("letters-only"), "invite_token": "invite-token"},
|
||||
):
|
||||
with pytest.raises(InvalidAccountPasswordRequestError, match="letters and numbers"):
|
||||
login.LoginApi().post()
|
||||
|
||||
|
||||
def test_reset_password_delegates_transport_values(app: Flask, service: FakeAuthenticationService) -> None:
|
||||
with app.test_request_context(
|
||||
"/reset-password",
|
||||
method="POST",
|
||||
json={"email": "User@Example.com", "language": "zh-Hans"},
|
||||
):
|
||||
response = login.ResetPasswordSendEmailApi().post()
|
||||
|
||||
assert response == {"result": "success", "data": "reset-token"}
|
||||
assert service.reset_arguments == [("User@Example.com", "zh-Hans", "127.0.0.1")]
|
||||
|
||||
|
||||
def test_email_code_send_delegates_validated_command(app: Flask, service: FakeAuthenticationService) -> None:
|
||||
with app.test_request_context(
|
||||
"/email-code-login",
|
||||
method="POST",
|
||||
json={"email": "user@example.com", "turnstile_token": "challenge"},
|
||||
):
|
||||
response = login.EmailCodeLoginSendEmailApi().post()
|
||||
|
||||
assert response == {"result": "success", "data": "email-code-token"}
|
||||
assert service.email_code_send_commands == [
|
||||
EmailCodeSendCommand(
|
||||
email="user@example.com",
|
||||
language=None,
|
||||
turnstile_token="challenge",
|
||||
ip_address="127.0.0.1",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def test_email_code_login_decodes_code_and_serializes_tokens(
|
||||
app: Flask,
|
||||
service: FakeAuthenticationService,
|
||||
) -> None:
|
||||
with app.test_request_context(
|
||||
"/email-code-login/validity",
|
||||
method="POST",
|
||||
json={
|
||||
"email": "User@Example.com",
|
||||
"code": _encode("123456"),
|
||||
"token": TEST_TOKEN,
|
||||
"timezone": "Asia/Singapore",
|
||||
},
|
||||
):
|
||||
response = login.EmailCodeLoginApi().post()
|
||||
|
||||
assert response.json == {"result": "success"}
|
||||
assert service.email_code_login_commands == [
|
||||
EmailCodeLoginCommand(
|
||||
email="User@Example.com",
|
||||
code="123456",
|
||||
token=TEST_TOKEN,
|
||||
turnstile_token=None,
|
||||
language=None,
|
||||
timezone="Asia/Singapore",
|
||||
ip_address="127.0.0.1",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def test_logout_uses_optional_current_account(
|
||||
app: Flask,
|
||||
service: FakeAuthenticationService,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
logout_calls: list[bool] = []
|
||||
monkeypatch.setattr(login.flask_login, "logout_user", lambda: logout_calls.append(True))
|
||||
monkeypatch.setattr(
|
||||
login,
|
||||
"current_account_with_tenant_optional",
|
||||
lambda: (SimpleNamespace(id="account-1"), "workspace-1"),
|
||||
)
|
||||
|
||||
with app.test_request_context("/logout", method="POST"):
|
||||
response = login.LogoutApi().post()
|
||||
|
||||
assert response.json == {"result": "success"}
|
||||
assert service.logout_account_ids == ["account-1"]
|
||||
assert logout_calls == [True]
|
||||
|
||||
|
||||
def test_logout_clears_cookies_without_current_account(
|
||||
app: Flask,
|
||||
service: FakeAuthenticationService,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
logout_calls: list[bool] = []
|
||||
monkeypatch.setattr(login.flask_login, "logout_user", lambda: logout_calls.append(True))
|
||||
monkeypatch.setattr(login, "current_account_with_tenant_optional", lambda: (None, None))
|
||||
|
||||
with app.test_request_context("/logout", method="POST"):
|
||||
response = login.LogoutApi().post()
|
||||
|
||||
assert response.json == {"result": "success"}
|
||||
assert service.logout_account_ids == []
|
||||
assert logout_calls == []
|
||||
cookies = response.headers.getlist("Set-Cookie")
|
||||
assert any("access_token=" in cookie for cookie in cookies)
|
||||
assert any("refresh_token=" in cookie for cookie in cookies)
|
||||
assert any("csrf_token=" in cookie for cookie in cookies)
|
||||
|
||||
|
||||
def test_refresh_maps_invalid_session_to_unauthorized(
|
||||
app: Flask,
|
||||
service: FakeAuthenticationService,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
service.error = account_errors.InvalidRefreshTokenError("Invalid refresh token")
|
||||
monkeypatch.setattr(login, "extract_refresh_token", lambda _request: "bad-token")
|
||||
|
||||
with app.test_request_context("/refresh-token", method="POST"):
|
||||
response, status = narrowed(login.RefreshTokenApi().post(), tuple)
|
||||
|
||||
assert status == 401
|
||||
assert response == {"result": "fail", "message": "Invalid refresh token"}
|
||||
|
||||
|
||||
def test_refresh_rejects_missing_cookie(
|
||||
app: Flask,
|
||||
service: FakeAuthenticationService,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(login, "extract_refresh_token", lambda _request: None)
|
||||
|
||||
with app.test_request_context("/refresh-token", method="POST"):
|
||||
response, status = narrowed(login.RefreshTokenApi().post(), tuple)
|
||||
|
||||
assert status == 401
|
||||
assert response["message"] == "No refresh token provided"
|
||||
assert service.refresh_tokens == []
|
||||
|
||||
|
||||
def test_refresh_does_not_require_completed_setup(
|
||||
app: Flask,
|
||||
service: FakeAuthenticationService,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
config_overrides: Callable[..., None],
|
||||
) -> None:
|
||||
config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY)
|
||||
monkeypatch.setattr(wraps, "_is_setup_completed", lambda: False)
|
||||
monkeypatch.setattr(login, "extract_refresh_token", lambda _request: "old-refresh")
|
||||
|
||||
with app.test_request_context("/refresh-token", method="POST"):
|
||||
response = narrowed(login.RefreshTokenApi().post(), Response)
|
||||
|
||||
assert response.json == {"result": "success"}
|
||||
assert service.refresh_tokens == ["old-refresh"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("translate", "application_error", "request_error"),
|
||||
[
|
||||
(
|
||||
login._raise_account_state_error,
|
||||
account_errors.AccountEmailDomainSuspendedError(),
|
||||
EmailDomainSuspendedError,
|
||||
),
|
||||
(login._raise_account_state_error, account_errors.AccountEmailFrozenError(), AccountInFreezeError),
|
||||
(login._raise_account_state_error, account_errors.LoginAccountBannedError(), AccountBannedError),
|
||||
(login._raise_password_login_error, account_errors.LoginRateLimitError(), EmailPasswordLoginLimitError),
|
||||
(login._raise_password_login_error, account_errors.InvalidLoginCredentialsError(), AuthenticationFailedError),
|
||||
(
|
||||
login._raise_password_login_error,
|
||||
account_errors.InvalidAccountPasswordError("invalid password"),
|
||||
InvalidAccountPasswordRequestError,
|
||||
),
|
||||
(login._raise_password_login_error, account_errors.InvalidLoginInvitationEmailError(), InvalidEmailError),
|
||||
(login._raise_password_login_error, account_errors.LoginWorkspaceLimitError(), WorkspacesLimitExceeded),
|
||||
(login._raise_password_login_error, account_errors.AccountNotFoundError(), AccountNotFound),
|
||||
(
|
||||
login._raise_reset_password_email_error,
|
||||
account_errors.ResetPasswordEmailRateLimitError(1),
|
||||
PasswordResetRateLimitExceededError,
|
||||
),
|
||||
(login._raise_email_code_send_error, account_errors.EmailCodeSendIPLimitedError(), EmailSendIpLimitError),
|
||||
(
|
||||
login._raise_email_code_send_error,
|
||||
account_errors.EmailCodeSendRateLimitError(5),
|
||||
EmailCodeLoginRateLimitExceededError,
|
||||
),
|
||||
(
|
||||
login._raise_email_code_send_error,
|
||||
account_errors.HumanVerificationRejectedError(),
|
||||
TurnstileVerificationFailedError,
|
||||
),
|
||||
(
|
||||
login._raise_email_code_send_error,
|
||||
account_errors.HumanVerificationUnavailableError(),
|
||||
TurnstileServiceUnavailableError,
|
||||
),
|
||||
(
|
||||
login._raise_email_code_send_error,
|
||||
account_errors.EmailCodeLoginUnavailableError(),
|
||||
EmailCodeLoginServiceUnavailableError,
|
||||
),
|
||||
(login._raise_email_code_login_error, account_errors.InvalidEmailCodeTokenError(), InvalidTokenError),
|
||||
(login._raise_email_code_login_error, account_errors.EmailCodeEmailMismatchError(), InvalidEmailError),
|
||||
(login._raise_email_code_login_error, account_errors.InvalidEmailCodeError(), EmailCodeError),
|
||||
(
|
||||
login._raise_email_code_login_error,
|
||||
account_errors.HumanVerificationRejectedError(),
|
||||
TurnstileVerificationFailedError,
|
||||
),
|
||||
(
|
||||
login._raise_email_code_login_error,
|
||||
account_errors.EmailCodeLoginUnavailableError(),
|
||||
EmailCodeLoginServiceUnavailableError,
|
||||
),
|
||||
(login._raise_email_code_login_error, account_errors.AccountNotFoundError(), AccountNotFound),
|
||||
(login._raise_email_code_login_error, account_errors.LoginWorkspaceLimitError(), WorkspacesLimitExceeded),
|
||||
(
|
||||
login._raise_email_code_login_error,
|
||||
account_errors.LoginWorkspaceCreationNotAllowedError(),
|
||||
NotAllowedCreateWorkspace,
|
||||
),
|
||||
(login._raise_email_code_login_error, account_errors.LoginSeatLimitError(), SeatsLimitExceeded),
|
||||
(
|
||||
login._raise_email_code_login_error,
|
||||
account_errors.AccountNormalizedEmailAlreadyInUseError(),
|
||||
NormalizedEmailAlreadyInUseError,
|
||||
),
|
||||
# Every flow-specific translator falls back to the shared account-state mapping.
|
||||
(login._raise_email_code_login_error, account_errors.AccountEmailFrozenError(), AccountInFreezeError),
|
||||
],
|
||||
)
|
||||
def test_maps_application_errors_to_transport_errors(
|
||||
translate: Callable[[account_errors.AccountApplicationError], Never],
|
||||
application_error: account_errors.AccountApplicationError,
|
||||
request_error: type[Exception],
|
||||
) -> None:
|
||||
with pytest.raises(request_error):
|
||||
translate(application_error)
|
||||
|
||||
|
||||
def test_flow_translators_only_map_what_their_flow_raises() -> None:
|
||||
"""A reset-password error cannot reach the password login flow, so it passes through unmapped."""
|
||||
error = account_errors.ResetPasswordEmailRateLimitError(1)
|
||||
with pytest.raises(account_errors.ResetPasswordEmailRateLimitError) as raised:
|
||||
login._raise_password_login_error(error)
|
||||
assert raised.value is error
|
||||
@@ -0,0 +1,305 @@
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from types import SimpleNamespace
|
||||
from typing import NoReturn
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from werkzeug.exceptions import Forbidden, UnprocessableEntity
|
||||
from werkzeug.wrappers import Response
|
||||
|
||||
from controllers.console import wraps as console_wraps
|
||||
from controllers.console.auth import oauth as oauth_controller
|
||||
from controllers.console.auth.oauth import OAuthCallback, OAuthLogin
|
||||
from enums import DeploymentEdition
|
||||
from libs.oauth import encode_oauth_state
|
||||
from services.account_errors import (
|
||||
InvalidOAuthProviderError,
|
||||
OAuthIdentityLockUnavailableError,
|
||||
OAuthInvitationAccountMismatchError,
|
||||
OAuthProviderRequestError,
|
||||
OAuthRegistrationError,
|
||||
)
|
||||
from services.entities.account_entities import AccountSessionTokens
|
||||
from services.entities.account_oauth_entities import (
|
||||
OAuthAuthorizationRequest,
|
||||
OAuthCallbackCommand,
|
||||
OAuthCallbackResult,
|
||||
OAuthInvitationResult,
|
||||
OAuthSignInResult,
|
||||
)
|
||||
from services.system_feature_service import SystemFeatureService
|
||||
from tests.helpers.unit.controllers.knowledge_fs_controller_fakes import narrowed
|
||||
|
||||
CONSOLE_WEB_URL = "https://console.example.com"
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeOAuthService:
|
||||
authorization_url: str = "https://provider.example/authorize"
|
||||
callback_result: OAuthCallbackResult = OAuthSignInResult(
|
||||
tokens=AccountSessionTokens("access-token", "refresh-token", "csrf-token"),
|
||||
oauth_new_user=False,
|
||||
)
|
||||
authorization_error: Exception | None = None
|
||||
callback_error: Exception | None = None
|
||||
authorization_calls: list[tuple[str, OAuthAuthorizationRequest]] = field(default_factory=list)
|
||||
callback_calls: list[OAuthCallbackCommand] = field(default_factory=list)
|
||||
|
||||
def start_authorization(self, provider: str, request: OAuthAuthorizationRequest) -> str:
|
||||
self.authorization_calls.append((provider, request))
|
||||
if self.authorization_error is not None:
|
||||
raise self.authorization_error
|
||||
return self.authorization_url
|
||||
|
||||
def complete_authorization(self, command: OAuthCallbackCommand) -> OAuthCallbackResult:
|
||||
self.callback_calls.append(command)
|
||||
if self.callback_error is not None:
|
||||
raise self.callback_error
|
||||
return self.callback_result
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _oauth_admission(
|
||||
config_overrides: Callable[..., None],
|
||||
) -> None:
|
||||
config_overrides(
|
||||
DEPLOYMENT_EDITION=DeploymentEdition.CLOUD,
|
||||
ENABLE_SOCIAL_OAUTH_LOGIN=True,
|
||||
CONSOLE_WEB_URL=CONSOLE_WEB_URL,
|
||||
)
|
||||
|
||||
|
||||
def _install_service(monkeypatch: pytest.MonkeyPatch, service: FakeOAuthService) -> None:
|
||||
services = SimpleNamespace(accounts=SimpleNamespace(oauth=service))
|
||||
monkeypatch.setattr(oauth_controller, "application_services", lambda: services)
|
||||
|
||||
|
||||
def test_login_parses_input_and_delegates_to_application_service(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
service = FakeOAuthService()
|
||||
_install_service(monkeypatch, service)
|
||||
|
||||
with app.test_request_context(
|
||||
"/oauth/login/github?invite_token=invite&timezone=Asia%2FShanghai&language=zh-Hans&redirect_url=%2Fapps"
|
||||
):
|
||||
response = narrowed(OAuthLogin().get("github"), Response)
|
||||
|
||||
assert response.status_code == 302
|
||||
assert response.headers["Location"] == "https://provider.example/authorize"
|
||||
assert service.authorization_calls == [
|
||||
(
|
||||
"github",
|
||||
OAuthAuthorizationRequest(
|
||||
invite_token="invite",
|
||||
timezone="Asia/Shanghai",
|
||||
language="zh-Hans",
|
||||
redirect_url="/apps",
|
||||
),
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def test_login_returns_adapter_error_for_unknown_provider(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
service = FakeOAuthService(authorization_error=InvalidOAuthProviderError())
|
||||
_install_service(monkeypatch, service)
|
||||
|
||||
with app.test_request_context("/oauth/login/unknown"):
|
||||
payload, status = narrowed(OAuthLogin().get("unknown"), tuple)
|
||||
|
||||
assert status == 400
|
||||
assert payload == {"error": "Invalid provider"}
|
||||
|
||||
|
||||
def test_oauth_admission_does_not_query_enterprise_features(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
config_overrides: Callable[..., None],
|
||||
) -> None:
|
||||
config_overrides(DEPLOYMENT_EDITION=DeploymentEdition.ENTERPRISE)
|
||||
monkeypatch.setattr(console_wraps, "_is_setup_completed", lambda: True)
|
||||
service = FakeOAuthService()
|
||||
_install_service(monkeypatch, service)
|
||||
|
||||
def unexpected_feature_query() -> NoReturn:
|
||||
raise AssertionError("OAuth admission must not query Enterprise features")
|
||||
|
||||
monkeypatch.setattr(SystemFeatureService, "get_license", unexpected_feature_query)
|
||||
|
||||
with app.test_request_context("/oauth/login/github"):
|
||||
response = narrowed(OAuthLogin().get("github"), Response)
|
||||
|
||||
assert response.status_code == 302
|
||||
assert service.authorization_calls
|
||||
|
||||
|
||||
def test_callback_passes_stable_values_and_serializes_session_cookies(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
service = FakeOAuthService()
|
||||
_install_service(monkeypatch, service)
|
||||
cookie_calls: list[tuple[str, str]] = []
|
||||
monkeypatch.setattr(oauth_controller, "extract_remote_ip", lambda _request: "203.0.113.10")
|
||||
monkeypatch.setattr(
|
||||
oauth_controller,
|
||||
"set_access_token_to_cookie",
|
||||
lambda _request, _response, token: cookie_calls.append(("access", token)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
oauth_controller,
|
||||
"set_refresh_token_to_cookie",
|
||||
lambda _request, _response, token: cookie_calls.append(("refresh", token)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
oauth_controller,
|
||||
"set_csrf_token_to_cookie",
|
||||
lambda _request, _response, token: cookie_calls.append(("csrf", token)),
|
||||
)
|
||||
state = encode_oauth_state(
|
||||
invite_token="invite",
|
||||
timezone="Asia/Shanghai",
|
||||
language="zh-Hans",
|
||||
redirect_url="/apps",
|
||||
)
|
||||
|
||||
with app.test_request_context(
|
||||
f"/oauth/authorize/github?code=code-1&state={state}",
|
||||
headers={"Accept-Language": "en-US,en;q=0.9"},
|
||||
):
|
||||
response = narrowed(OAuthCallback().get("github"), Response)
|
||||
|
||||
assert response.status_code == 302
|
||||
assert response.headers["Location"] == "/apps?oauth_new_user=false"
|
||||
assert service.callback_calls == [
|
||||
OAuthCallbackCommand(
|
||||
provider="github",
|
||||
code="code-1",
|
||||
invite_token="invite",
|
||||
timezone="Asia/Shanghai",
|
||||
language="zh-Hans",
|
||||
browser_language="en-US",
|
||||
ip_address="203.0.113.10",
|
||||
)
|
||||
]
|
||||
assert cookie_calls == [
|
||||
("access", "access-token"),
|
||||
("refresh", "refresh-token"),
|
||||
("csrf", "csrf-token"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("redirect_url", "expected"),
|
||||
[
|
||||
("https://console.example.com/apps", "https://console.example.com/apps?oauth_new_user=false"),
|
||||
("https://console.example.com.malicious.example/apps", f"{CONSOLE_WEB_URL}?oauth_new_user=false"),
|
||||
("//malicious.example.com/apps", f"{CONSOLE_WEB_URL}?oauth_new_user=false"),
|
||||
("///malicious.example.com/apps", f"{CONSOLE_WEB_URL}?oauth_new_user=false"),
|
||||
(r"\\malicious.example.com/apps", f"{CONSOLE_WEB_URL}?oauth_new_user=false"),
|
||||
],
|
||||
)
|
||||
def test_callback_serializes_safe_redirect_target(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
redirect_url: str,
|
||||
expected: str,
|
||||
) -> None:
|
||||
service = FakeOAuthService()
|
||||
_install_service(monkeypatch, service)
|
||||
state = encode_oauth_state(redirect_url=redirect_url)
|
||||
|
||||
with app.test_request_context(f"/oauth/authorize/github?code=code-1&state={state}"):
|
||||
response = narrowed(OAuthCallback().get("github"), Response)
|
||||
|
||||
assert response.headers["Location"] == expected
|
||||
|
||||
|
||||
def test_callback_serializes_invitation_completion_target(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
tokens = AccountSessionTokens("access-token", "refresh-token", "csrf-token")
|
||||
service = FakeOAuthService(callback_result=OAuthInvitationResult(tokens=tokens, invite_token="invite token"))
|
||||
_install_service(monkeypatch, service)
|
||||
|
||||
with app.test_request_context("/oauth/authorize/github?code=code-1"):
|
||||
response = narrowed(OAuthCallback().get("github"), Response)
|
||||
|
||||
assert response.headers["Location"] == f"{CONSOLE_WEB_URL}/signin/invite-settings?invite_token=invite+token"
|
||||
|
||||
|
||||
def test_callback_rejects_missing_code_before_service_call(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
service = FakeOAuthService()
|
||||
_install_service(monkeypatch, service)
|
||||
|
||||
with app.test_request_context("/oauth/authorize/github"), pytest.raises(UnprocessableEntity):
|
||||
OAuthCallback().get("github")
|
||||
|
||||
assert service.callback_calls == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error", [OAuthProviderRequestError(), OAuthIdentityLockUnavailableError()])
|
||||
def test_callback_maps_oauth_processing_error_to_bad_request(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
error: Exception,
|
||||
) -> None:
|
||||
service = FakeOAuthService(callback_error=error)
|
||||
_install_service(monkeypatch, service)
|
||||
|
||||
with app.test_request_context("/oauth/authorize/github?code=code-1"):
|
||||
payload, status = narrowed(OAuthCallback().get("github"), tuple)
|
||||
|
||||
assert status == 400
|
||||
assert payload == {"error": "OAuth process failed"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("error", "expected_query"),
|
||||
[
|
||||
(
|
||||
OAuthInvitationAccountMismatchError("invite-token"),
|
||||
"message=This+invitation+was+sent+to+another+account.+Please+sign+in+with+the+invited+account."
|
||||
"&invite_token=invite-token",
|
||||
),
|
||||
(OAuthRegistrationError("Registration failed"), "message=Registration+failed"),
|
||||
],
|
||||
)
|
||||
def test_callback_serializes_application_errors_as_signin_redirects(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
error: Exception,
|
||||
expected_query: str,
|
||||
) -> None:
|
||||
service = FakeOAuthService(callback_error=error)
|
||||
_install_service(monkeypatch, service)
|
||||
|
||||
with app.test_request_context("/oauth/authorize/github?code=code-1"):
|
||||
response = narrowed(OAuthCallback().get("github"), Response)
|
||||
|
||||
assert response.status_code == 302
|
||||
assert response.headers["Location"] == f"{CONSOLE_WEB_URL}/signin?{expected_query}"
|
||||
|
||||
|
||||
def test_oauth_admission_rejects_disabled_social_login(
|
||||
app: Flask,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
config_overrides: Callable[..., None],
|
||||
) -> None:
|
||||
service = FakeOAuthService()
|
||||
_install_service(monkeypatch, service)
|
||||
config_overrides(ENABLE_SOCIAL_OAUTH_LOGIN=False)
|
||||
|
||||
with app.test_request_context("/oauth/login/github"), pytest.raises(Forbidden):
|
||||
OAuthLogin().get("github")
|
||||
|
||||
assert service.authorization_calls == []
|
||||
@@ -0,0 +1,233 @@
|
||||
from datetime import UTC, datetime
|
||||
from http import HTTPStatus
|
||||
from inspect import unwrap
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from werkzeug.exceptions import NotFound
|
||||
|
||||
from controllers.console.auth.oauth_server import (
|
||||
OAuthProviderAppResponse,
|
||||
OAuthServerAppApi,
|
||||
OAuthServerUserAccountApi,
|
||||
OAuthServerUserAuthorizeApi,
|
||||
OAuthServerUserTokenApi,
|
||||
)
|
||||
from machinery.context import RequestContext
|
||||
from services.entities.oauth_server_entities import (
|
||||
OAuthAuthorizationCode,
|
||||
OAuthProviderAccount,
|
||||
OAuthProviderAppPresentation,
|
||||
OAuthTokenSet,
|
||||
)
|
||||
from services.oauth_server_service import OAuthServerClientNotFoundError, OAuthServerUnauthorizedError
|
||||
|
||||
|
||||
def _context() -> RequestContext:
|
||||
return RequestContext("request-1", "trace-1", "account-1", "workspace-1")
|
||||
|
||||
|
||||
def _services(service: MagicMock) -> SimpleNamespace:
|
||||
return SimpleNamespace(oauth_server=service)
|
||||
|
||||
|
||||
def test_provider_parses_payload_delegates_and_serializes() -> None:
|
||||
app = Flask(__name__)
|
||||
service = MagicMock()
|
||||
service.get_provider.return_value = OAuthProviderAppPresentation(
|
||||
app_icon="icon",
|
||||
app_label={"en-US": "Test App"},
|
||||
scope="read",
|
||||
auto_authorize=True,
|
||||
)
|
||||
|
||||
with (
|
||||
app.test_request_context(json={"client_id": "client-1", "redirect_uri": "https://example.com/callback"}),
|
||||
patch("controllers.console.auth.oauth_server.application_services", return_value=_services(service)),
|
||||
):
|
||||
result = unwrap(OAuthServerAppApi.post)(OAuthServerAppApi())
|
||||
|
||||
assert result == (
|
||||
{
|
||||
"app_icon": "icon",
|
||||
"app_label": {"en-US": "Test App"},
|
||||
"scope": "read",
|
||||
"auto_authorize": True,
|
||||
},
|
||||
HTTPStatus.OK,
|
||||
)
|
||||
service.get_provider.assert_called_once_with(
|
||||
client_id="client-1",
|
||||
redirect_uri="https://example.com/callback",
|
||||
)
|
||||
|
||||
|
||||
def test_authorize_uses_admission_request_context() -> None:
|
||||
app = Flask(__name__)
|
||||
service = MagicMock()
|
||||
service.authorize.return_value = OAuthAuthorizationCode(code="authorization-code")
|
||||
context = _context()
|
||||
|
||||
with (
|
||||
app.test_request_context(json={"client_id": "client-1"}),
|
||||
patch("controllers.console.auth.oauth_server.application_services", return_value=_services(service)),
|
||||
):
|
||||
result = unwrap(OAuthServerUserAuthorizeApi.post)(OAuthServerUserAuthorizeApi(), context)
|
||||
|
||||
assert result == ({"code": "authorization-code"}, HTTPStatus.OK)
|
||||
service.authorize.assert_called_once_with(context, client_id="client-1")
|
||||
|
||||
|
||||
def test_token_endpoint_delegates_grant_data() -> None:
|
||||
app = Flask(__name__)
|
||||
service = MagicMock()
|
||||
service.exchange_token.return_value = OAuthTokenSet(
|
||||
access_token="access-1",
|
||||
token_type="Bearer",
|
||||
expires_in=43200,
|
||||
refresh_token="refresh-1",
|
||||
)
|
||||
|
||||
with (
|
||||
app.test_request_context(
|
||||
json={
|
||||
"client_id": "client-1",
|
||||
"grant_type": "authorization_code",
|
||||
"code": "code-1",
|
||||
"client_secret": "secret",
|
||||
"redirect_uri": "https://example.com/callback",
|
||||
}
|
||||
),
|
||||
patch("controllers.console.auth.oauth_server.application_services", return_value=_services(service)),
|
||||
):
|
||||
result = unwrap(OAuthServerUserTokenApi.post)(OAuthServerUserTokenApi())
|
||||
|
||||
assert result == (
|
||||
{
|
||||
"access_token": "access-1",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 43200,
|
||||
"refresh_token": "refresh-1",
|
||||
},
|
||||
HTTPStatus.OK,
|
||||
)
|
||||
service.exchange_token.assert_called_once_with(
|
||||
client_id="client-1",
|
||||
grant_type="authorization_code",
|
||||
code="code-1",
|
||||
client_secret="secret",
|
||||
redirect_uri="https://example.com/callback",
|
||||
refresh_token=None,
|
||||
)
|
||||
|
||||
|
||||
def test_account_endpoint_parses_bearer_token_and_serializes_account() -> None:
|
||||
app = Flask(__name__)
|
||||
service = MagicMock()
|
||||
service.get_account.return_value = OAuthProviderAccount(
|
||||
id="account-1",
|
||||
name="Test User",
|
||||
email="test@example.com",
|
||||
avatar="avatar",
|
||||
interface_language="en-US",
|
||||
timezone="UTC",
|
||||
created_at=datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC),
|
||||
)
|
||||
|
||||
with (
|
||||
app.test_request_context(
|
||||
json={"client_id": "client-1"},
|
||||
headers={"Authorization": "Bearer access-1"},
|
||||
),
|
||||
patch("controllers.console.auth.oauth_server.application_services", return_value=_services(service)),
|
||||
):
|
||||
result = unwrap(OAuthServerUserAccountApi.post)(OAuthServerUserAccountApi())
|
||||
|
||||
assert result == (
|
||||
{
|
||||
"id": "account-1",
|
||||
"name": "Test User",
|
||||
"email": "test@example.com",
|
||||
"avatar": "avatar",
|
||||
"interface_language": "en-US",
|
||||
"timezone": "UTC",
|
||||
"created_at": 1704164645,
|
||||
},
|
||||
HTTPStatus.OK,
|
||||
)
|
||||
service.get_account.assert_called_once_with(client_id="client-1", access_token="access-1")
|
||||
|
||||
|
||||
def test_account_endpoint_serializes_nullable_account_preferences() -> None:
|
||||
app = Flask(__name__)
|
||||
service = MagicMock()
|
||||
service.get_account.return_value = OAuthProviderAccount(
|
||||
id="account-1",
|
||||
name="Test User",
|
||||
email="test@example.com",
|
||||
avatar=None,
|
||||
interface_language=None,
|
||||
timezone=None,
|
||||
created_at=datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC),
|
||||
)
|
||||
|
||||
with (
|
||||
app.test_request_context(
|
||||
json={"client_id": "client-1"},
|
||||
headers={"Authorization": "Bearer access-1"},
|
||||
),
|
||||
patch("controllers.console.auth.oauth_server.application_services", return_value=_services(service)),
|
||||
):
|
||||
result = unwrap(OAuthServerUserAccountApi.post)(OAuthServerUserAccountApi())
|
||||
|
||||
assert result == (
|
||||
{
|
||||
"id": "account-1",
|
||||
"name": "Test User",
|
||||
"email": "test@example.com",
|
||||
"avatar": None,
|
||||
"interface_language": None,
|
||||
"timezone": None,
|
||||
"created_at": 1704164645,
|
||||
},
|
||||
HTTPStatus.OK,
|
||||
)
|
||||
|
||||
|
||||
def test_account_endpoint_returns_bearer_challenge_for_missing_header() -> None:
|
||||
app = Flask(__name__)
|
||||
service = MagicMock()
|
||||
service.get_account.side_effect = OAuthServerUnauthorizedError("access_token is required")
|
||||
|
||||
with (
|
||||
app.test_request_context(json={"client_id": "client-1"}),
|
||||
patch("controllers.console.auth.oauth_server.application_services", return_value=_services(service)),
|
||||
):
|
||||
response = unwrap(OAuthServerUserAccountApi.post)(OAuthServerUserAccountApi())
|
||||
|
||||
assert response.status_code == HTTPStatus.UNAUTHORIZED
|
||||
assert response.get_json() == {"error": "Authorization header is required"}
|
||||
assert response.headers["WWW-Authenticate"] == "Bearer"
|
||||
service.get_account.assert_called_once_with(client_id="client-1", access_token=None)
|
||||
|
||||
|
||||
def test_account_endpoint_preserves_client_validation_before_bearer_challenge() -> None:
|
||||
app = Flask(__name__)
|
||||
service = MagicMock()
|
||||
service.get_account.side_effect = OAuthServerClientNotFoundError("client_id is invalid")
|
||||
|
||||
with (
|
||||
app.test_request_context(json={"client_id": "missing"}),
|
||||
patch("controllers.console.auth.oauth_server.application_services", return_value=_services(service)),
|
||||
):
|
||||
with pytest.raises(NotFound, match="client_id is invalid"):
|
||||
unwrap(OAuthServerUserAccountApi.post)(OAuthServerUserAccountApi())
|
||||
|
||||
|
||||
def test_oauth_provider_app_response_requires_auto_authorize() -> None:
|
||||
# A missing field must fail validation instead of silently defaulting:
|
||||
# an optional field would surface as `undefined` in the generated TS
|
||||
# contract and silently disable silent authorization.
|
||||
assert "auto_authorize" in OAuthProviderAppResponse.model_json_schema()["required"]
|
||||
Reference in new issue
Block a user