Skip to content

armgit / dify

Public Imported from GitHub
0

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

test: exercise account Redis command serialization (#43169)

Asuka Minato4c640ff898cc
diff --git a/api/tests/unit_tests/controllers/inner_api/app/test_file_grants.py b/api/tests/unit_tests/controllers/inner_api/app/test_file_grants.py
index 49350be56cd..a0b91cc5f1c 100644
--- a/api/tests/unit_tests/controllers/inner_api/app/test_file_grants.py
+++ b/api/tests/unit_tests/controllers/inner_api/app/test_file_grants.py
@@ -261,13 +261,17 @@ def test_mint_rejects_a_run_deadline_without_produce_scope(app: Flask) -> None:
@pytest.mark.usefixtures("granted_config", "seeded_app", "sqlite_db")
-def test_mint_rejects_a_run_deadline_beyond_the_workflow_limit(app: Flask) -> None:
+def test_mint_rejects_a_run_deadline_beyond_the_workflow_limit(app: Flask, monkeypatch: pytest.MonkeyPatch) -> None:
+ now = 1_700_000_000
+ # Keep the one-second boundary fixed between payload construction and validation.
+ monkeypatch.setattr("extensions.ext_application_services.time", SimpleNamespace(time=lambda: now))
+
with pytest.raises(InvalidGrantRequestError):
_mint(
app,
_payload(
scopes=["resolve", "produce"],
- run_deadline=int(time.time()) + MAX_WORKFLOW_EXECUTION_SECONDS + 1,
+ run_deadline=now + MAX_WORKFLOW_EXECUTION_SECONDS + 1,
),
)
diff --git a/api/tests/unit_tests/services/account/test_adapters.py b/api/tests/unit_tests/services/account/test_adapters.py
index 20810f0970b..553d7b0f1a5 100644
--- a/api/tests/unit_tests/services/account/test_adapters.py
+++ b/api/tests/unit_tests/services/account/test_adapters.py
@@ -1,6 +1,5 @@
from datetime import UTC, datetime
from hashlib import sha256
-from typing import cast
from unittest.mock import MagicMock, patch
import pytest
@@ -30,12 +29,14 @@ from services.entities.account_entities import (
)
-def test_invitation_token_store_reads_workspace_invitation_key() -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.get.return_value = b"account-1"
+def test_invitation_token_store_reads_workspace_invitation_key(
+ redis_transport: tuple[RedisClientWrapper, MagicMock],
+) -> None:
+ redis, commands = redis_transport
+ commands.return_value = b"account-1"
lookup = InvitationLookup(workspace_id="workspace-1", email="[email protected]", token="token-1")
- result = RedisInvitationTokenStore(redis=cast(RedisClientWrapper, redis)).find(lookup)
+ result = RedisInvitationTokenStore(redis=redis).find(lookup)
assert result == InvitationToken(
account_id="account-1",
@@ -43,18 +44,24 @@ def test_invitation_token_store_reads_workspace_invitation_key() -> None:
workspace_id="workspace-1",
)
email_hash = sha256(b"[email protected]").hexdigest()
- redis.get.assert_called_once_with(f"member_invite_token:workspace-1, {email_hash}:token-1")
+ commands.assert_called_once_with(
+ "GET",
+ f"member_invite_token:workspace-1, {email_hash}:token-1",
+ keys=[f"member_invite_token:workspace-1, {email_hash}:token-1"],
+ )
-def test_invitation_token_store_reads_global_invitation_payload() -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.get.return_value = (
+def test_invitation_token_store_reads_global_invitation_payload(
+ redis_transport: tuple[RedisClientWrapper, MagicMock],
+) -> None:
+ redis, commands = redis_transport
+ commands.return_value = (
b'{"account_id":"account-1","email":"[email protected]","workspace_id":"workspace-1",'
b'"role":"editor","requires_setup":false}'
)
lookup = InvitationLookup(workspace_id=None, email="[email protected]", token="token-1")
- result = RedisInvitationTokenStore(redis=cast(RedisClientWrapper, redis)).find(lookup)
+ result = RedisInvitationTokenStore(redis=redis).find(lookup)
assert result == InvitationToken(
account_id="account-1",
@@ -63,17 +70,18 @@ def test_invitation_token_store_reads_global_invitation_payload() -> None:
role="editor",
requires_setup=False,
)
- redis.get.assert_called_once_with("member_invite:token:token-1")
+ commands.assert_called_once_with("GET", "member_invite:token:token-1", keys=["member_invite:token:token-1"])
-def test_invitation_token_store_revokes_its_redis_key() -> None:
- redis = MagicMock(spec=RedisClientWrapper)
+def test_invitation_token_store_revokes_its_redis_key(redis_transport: tuple[RedisClientWrapper, MagicMock]) -> None:
+ redis, commands = redis_transport
lookup = InvitationLookup(workspace_id="workspace-1", email="[email protected]", token="token-1")
- RedisInvitationTokenStore(redis=cast(RedisClientWrapper, redis)).revoke(lookup)
+ RedisInvitationTokenStore(redis=redis).revoke(lookup)
email_hash = sha256(b"[email protected]").hexdigest()
- redis.delete.assert_called_once_with(f"member_invite_token:workspace-1, {email_hash}:token-1")
+ commands.assert_any_call("DEL", f"member_invite_token:workspace-1, {email_hash}:token-1")
+ assert commands.call_count == 1
def test_billing_eligibility_skips_gateway_when_disabled() -> None:
@@ -239,9 +247,9 @@ def test_token_gateway_issues_account_bound_state() -> None:
}
-def test_security_gateway_counts_normal_ip_request() -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.get.side_effect = [None, None]
+def test_security_gateway_counts_normal_ip_request(redis_transport: tuple[RedisClientWrapper, MagicMock]) -> None:
+ redis, commands = redis_transport
+ commands.side_effect = [None, None, True, True]
gateway = RedisChangeEmailSecurityGateway(
redis=redis,
email_send_ip_limit_per_minute=60,
@@ -251,13 +259,16 @@ def test_security_gateway_counts_normal_ip_request() -> None:
assert gateway.is_ip_limited("127.0.0.1") is False
- redis.setex.assert_called_once_with("email_send_ip_limit_minute:127.0.0.1", 60, 1)
- redis.expire.assert_called_once_with("email_send_ip_limit_minute:127.0.0.1", 60)
+ commands.assert_any_call("SETEX", "email_send_ip_limit_minute:127.0.0.1", 60, 1)
+ commands.assert_any_call("EXPIRE", "email_send_ip_limit_minute:127.0.0.1", 60)
+ assert commands.call_count == 4
-def test_security_gateway_freezes_second_over_limit_ip_strike() -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.get.side_effect = [None, 2, 1]
+def test_security_gateway_freezes_second_over_limit_ip_strike(
+ redis_transport: tuple[RedisClientWrapper, MagicMock],
+) -> None:
+ redis, commands = redis_transport
+ commands.side_effect = [None, 2, 1, True]
gateway = RedisChangeEmailSecurityGateway(
redis=redis,
email_send_ip_limit_per_minute=1,
@@ -267,7 +278,8 @@ def test_security_gateway_freezes_second_over_limit_ip_strike() -> None:
assert gateway.is_ip_limited("127.0.0.1") is True
- redis.setex.assert_called_once_with("email_send_ip_limit_freeze:127.0.0.1", 3600, 1)
+ commands.assert_any_call("SETEX", "email_send_ip_limit_freeze:127.0.0.1", 3600, 1)
+ assert commands.call_count == 4
def test_verification_gateway_binds_token_to_the_target_account() -> None:
diff --git a/api/tests/unit_tests/services/account/test_email_registration_adapters.py b/api/tests/unit_tests/services/account/test_email_registration_adapters.py
index 60cd7e9b4c7..3a3c533cabb 100644
--- a/api/tests/unit_tests/services/account/test_email_registration_adapters.py
+++ b/api/tests/unit_tests/services/account/test_email_registration_adapters.py
@@ -1,5 +1,5 @@
from collections.abc import Callable
-from unittest.mock import Mock, patch
+from unittest.mock import MagicMock, Mock, patch
import pytest
from redis import RedisError
@@ -63,12 +63,14 @@ def test_token_gateway_issues_verified_registration_state() -> None:
@pytest.mark.parametrize(("count", "limited"), [(0, False), (1, False), (2, True)])
def test_security_gateway_preserves_shared_ip_limit(
- config_overrides: Callable[..., None], count: int, limited: bool
+ redis_transport: tuple[RedisClientWrapper, MagicMock],
+ config_overrides: Callable[..., None],
+ count: int,
+ limited: bool,
) -> None:
config_overrides(EMAIL_SEND_IP_LIMIT_PER_MINUTE=1)
- redis = Mock(spec=RedisClientWrapper)
- redis.get.side_effect = [None, str(count), None]
- redis.set.return_value = True
+ redis, commands = redis_transport
+ commands.side_effect = [None, str(count), None, True] if limited else [None, str(count), True, True]
gateway = RedisEmailRegistrationSecurityGateway(
redis=redis,
login_security=Mock(spec=ConsoleAuthSecurityGateway),
@@ -78,15 +80,18 @@ def test_security_gateway_preserves_shared_ip_limit(
assert gateway.is_ip_limited("127.0.0.1") is limited
if limited:
- redis.set.assert_called_once_with("email_send_ip_limit_hour:127.0.0.1", 1, ex=600, nx=True)
+ commands.assert_any_call("SET", "email_send_ip_limit_hour:127.0.0.1", 1, "NX", "EX", 600)
else:
- redis.setex.assert_called_once_with("email_send_ip_limit_minute:127.0.0.1", 60, count + 1)
- redis.expire.assert_called_once_with("email_send_ip_limit_minute:127.0.0.1", 60)
+ commands.assert_any_call("SETEX", "email_send_ip_limit_minute:127.0.0.1", 60, count + 1)
+ commands.assert_any_call("EXPIRE", "email_send_ip_limit_minute:127.0.0.1", 60)
+ assert commands.call_count == 4
-def test_security_gateway_uses_registration_and_login_keys() -> None:
- redis = Mock(spec=RedisClientWrapper)
- redis.get.return_value = 1
+def test_security_gateway_uses_registration_and_login_keys(
+ redis_transport: tuple[RedisClientWrapper, MagicMock],
+) -> None:
+ redis, commands = redis_transport
+ commands.return_value = 1
gateway = RedisEmailRegistrationSecurityGateway(
redis=redis,
login_security=RedisConsoleAuthSecurityGateway(redis=redis),
@@ -101,9 +106,10 @@ def test_security_gateway_uses_registration_and_login_keys() -> None:
gateway.reset_verification_failures("[email protected]")
gateway.reset_login_failures("[email protected]")
- redis.setex.assert_called_once_with("email_register_error_rate_limit:[email protected]", 600, 2)
- redis.delete.assert_called_once_with("email_register_error_rate_limit:[email protected]")
+ commands.assert_any_call("SETEX", "email_register_error_rate_limit:[email protected]", 600, 2)
+ commands.assert_any_call("DEL", "email_register_error_rate_limit:[email protected]")
reset_login_error_rate_limit.assert_called_once_with("[email protected]")
+ assert commands.call_count == 3
@pytest.mark.parametrize(("count", "limited"), [(5, False), (6, True)])
diff --git a/api/tests/unit_tests/services/account/test_login_adapters.py b/api/tests/unit_tests/services/account/test_login_adapters.py
index abd23dd2c5e..3138115cd3e 100644
--- a/api/tests/unit_tests/services/account/test_login_adapters.py
+++ b/api/tests/unit_tests/services/account/test_login_adapters.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import logging
from collections.abc import Callable
from dataclasses import dataclass, field
-from typing import cast, override
+from typing import override
from unittest.mock import MagicMock
import pytest
@@ -58,36 +58,42 @@ def _persist_account(session: Session) -> Account:
return account
-def test_security_gateway_owns_login_failure_state() -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.get.side_effect = [b"6", b"2"]
- gateway = adapters.RedisConsoleAuthSecurityGateway(redis=cast(RedisClientWrapper, redis))
+def test_security_gateway_owns_login_failure_state(redis_transport: tuple[RedisClientWrapper, MagicMock]) -> None:
+ redis, commands = redis_transport
+ commands.side_effect = [b"6", b"2", True, 1]
+ gateway = adapters.RedisConsoleAuthSecurityGateway(redis=redis)
assert gateway.is_login_limited("[email protected]") is True
gateway.record_login_failure("[email protected]")
gateway.reset_login_failures("[email protected]")
- redis.setex.assert_called_once_with(
+ commands.assert_any_call(
+ "SETEX",
"login_error_rate_limit:[email protected]",
adapters.dify_config.LOGIN_LOCKOUT_DURATION,
3,
)
- redis.delete.assert_called_once_with("login_error_rate_limit:[email protected]")
+ commands.assert_any_call("DEL", "login_error_rate_limit:[email protected]")
+ assert commands.call_count == 4
-def test_security_gateway_owns_email_send_ip_limit(config_overrides: Callable[..., None]) -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.get.side_effect = [None, b"2", None]
- redis.set.return_value = True
+def test_security_gateway_owns_email_send_ip_limit(
+ redis_transport: tuple[RedisClientWrapper, MagicMock], config_overrides: Callable[..., None]
+) -> None:
+ redis, commands = redis_transport
+ commands.side_effect = [None, b"2", None, True]
config_overrides(EMAIL_SEND_IP_LIMIT_PER_MINUTE=1)
- gateway = adapters.RedisConsoleAuthSecurityGateway(redis=cast(RedisClientWrapper, redis))
+ gateway = adapters.RedisConsoleAuthSecurityGateway(redis=redis)
assert gateway.is_email_send_ip_limited("127.0.0.1") is True
- redis.set.assert_called_once_with("email_send_ip_limit_hour:127.0.0.1", 1, ex=600, nx=True)
+ commands.assert_any_call("SET", "email_send_ip_limit_hour:127.0.0.1", 1, "NX", "EX", 600)
+ assert commands.call_count == 4
-def test_session_gateway_owns_refresh_token_storage(monkeypatch: pytest.MonkeyPatch) -> None:
- redis = MagicMock(spec=RedisClientWrapper)
+def test_session_gateway_owns_refresh_token_storage(
+ redis_transport: tuple[RedisClientWrapper, MagicMock], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ redis, commands = redis_transport
issued_payloads: list[dict[str, object]] = []
class FakePassportService:
@@ -98,20 +104,23 @@ def test_session_gateway_owns_refresh_token_storage(monkeypatch: pytest.MonkeyPa
monkeypatch.setattr(adapters, "PassportService", FakePassportService)
monkeypatch.setattr(adapters.secrets, "token_hex", lambda _length: "refresh")
monkeypatch.setattr(adapters, "generate_csrf_token", lambda _account_id: "csrf")
- gateway = adapters.RedisAccountSessionGateway(redis=cast(RedisClientWrapper, redis))
+ gateway = adapters.RedisAccountSessionGateway(redis=redis)
result = gateway.issue("account-1")
assert result == AccountSessionTokens(access_token="access", refresh_token="refresh", csrf_token="csrf")
assert issued_payloads[0]["user_id"] == "account-1"
- assert redis.setex.call_args_list[0].args[0] == "refresh_token:refresh"
- assert redis.setex.call_args_list[1].args[0] == "account_refresh_token:account-1"
+ assert commands.call_args_list[0].args[1] == "refresh_token:refresh"
+ assert commands.call_args_list[1].args[1] == "account_refresh_token:account-1"
+ assert commands.call_count == 2
-def test_session_gateway_resolves_rotates_and_revokes_refresh_tokens(monkeypatch: pytest.MonkeyPatch) -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.get.side_effect = [b"account-1", b"stored-refresh"]
- gateway = adapters.RedisAccountSessionGateway(redis=cast(RedisClientWrapper, redis))
+def test_session_gateway_resolves_rotates_and_revokes_refresh_tokens(
+ redis_transport: tuple[RedisClientWrapper, MagicMock], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ redis, commands = redis_transport
+ commands.side_effect = [b"account-1", 1, 1, b"stored-refresh", 1, 1]
+ gateway = adapters.RedisAccountSessionGateway(redis=redis)
monkeypatch.setattr(
gateway,
"_issue",
@@ -124,23 +133,23 @@ def test_session_gateway_resolves_rotates_and_revokes_refresh_tokens(monkeypatch
assert gateway.rotate(refresh_token="refresh", account_id="account-1").refresh_token == "new-refresh"
gateway.revoke("account-1")
- deleted_keys = [call.args[0] for call in redis.delete.call_args_list]
+ deleted_keys = [call.args[1] for call in commands.call_args_list if call.args[0] == "DEL"]
assert deleted_keys == [
"refresh_token:refresh",
"account_refresh_token:account-1",
"refresh_token:stored-refresh",
"account_refresh_token:account-1",
]
+ assert commands.call_count == 6
-def test_session_gateway_returns_none_for_unknown_refresh_token() -> None:
- redis = MagicMock(spec=RedisClientWrapper)
- redis.get.return_value = None
+def test_session_gateway_returns_none_for_unknown_refresh_token(
+ redis_transport: tuple[RedisClientWrapper, MagicMock],
+) -> None:
+ redis, commands = redis_transport
+ commands.return_value = None
- assert (
- adapters.RedisAccountSessionGateway(redis=cast(RedisClientWrapper, redis)).resolve_refresh_token("bad-token")
- is None
- )
+ assert adapters.RedisAccountSessionGateway(redis=redis).resolve_refresh_token("bad-token") is None
def test_workspace_provisioning_persists_owner_workspace(