"""Tests for zero-login Earth sessions, permanent/scoped API keys, anti-scraping gate, and controlled OpenAPI.""" from __future__ import annotations from datetime import UTC, datetime, timedelta import hashlib import hmac import importlib.util import time from typing import Any from fastapi.testclient import TestClient from httpx import ASGITransport, AsyncClient import pytest from sqlalchemy import create_engine from sqlalchemy.orm import Session from sqlalchemy.pool import StaticPool from starlette.websockets import WebSocketDisconnect from app import main as main_module from app.core import access_gate from app.core.access_gate import ( EARTH_SESSION_COOKIE, EARTH_TOKEN_HEADER, reset_access_gate_caches, ) from app.core.config import settings from app.core.security import create_access_token, get_password_hash from app.db.session import Base, get_db from app.main import app from app.models.api_key import ApiKey from app.models.collected_data import CollectedData from app.models.system_setting import SystemSetting from app.models.user import User from app.services.api_keys import hash_api_key, reset_api_key_runtime_caches class _AsyncSQLiteSession: """Minimal async wrapper around sync SQLAlchemy Session for fast isolated tests.""" def __init__(self, session: Session): self._session = session def add(self, instance: Any) -> None: self._session.add(instance) def add_all(self, instances: list[Any]) -> None: self._session.add_all(instances) async def delete(self, instance: Any) -> None: self._session.delete(instance) async def get(self, entity: Any, ident: Any) -> Any: return self._session.get(entity, ident) async def execute(self, statement: Any, params: dict[str, Any] | None = None): if params is not None: return self._session.execute(statement, params) return self._session.execute(statement) async def scalar(self, statement: Any): return self._session.scalar(statement) async def scalars(self, statement: Any): return self._session.scalars(statement) async def flush(self) -> None: self._session.flush() async def commit(self) -> None: self._session.commit() async def rollback(self) -> None: self._session.rollback() async def refresh(self, instance: Any) -> None: self._session.refresh(instance) class _NoRedisClient: def sismember(self, *_args, **_kwargs): return False @staticmethod def get_client(): raise RuntimeError("Redis disabled in unit test") @pytest.fixture(autouse=True) def _reset_gate_and_redis(monkeypatch): reset_access_gate_caches() reset_api_key_runtime_caches() monkeypatch.setattr("app.core.security.redis_client", _NoRedisClient()) monkeypatch.setattr("app.core.security._AsyncRedisClient", _NoRedisClient) monkeypatch.setattr("app.core.access_gate._AsyncRedisClient", _NoRedisClient) monkeypatch.setattr("app.services.api_keys._AsyncRedisClient", _NoRedisClient) yield app.dependency_overrides.clear() reset_access_gate_caches() reset_api_key_runtime_caches() @pytest.fixture def access_db(): engine = create_engine( "sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool, ) Base.metadata.create_all( engine, tables=[ User.__table__, ApiKey.__table__, SystemSetting.__table__, CollectedData.__table__, ], ) with Session(engine) as session: admin = User( id=1, username="admin-user", email="admin@example.invalid", password_hash=get_password_hash("AdminPass!123"), role="admin", is_active=True, email_verified=True, gatekeeper_groups=[], ) viewer = User( id=2, username="plain-viewer", email="viewer@example.invalid", password_hash=get_password_hash("ViewerPass!123"), role="viewer", is_active=True, email_verified=True, gatekeeper_groups=[], ) partner = User( id=3, username="partner-api", email="partner@example.invalid", password_hash=get_password_hash("PartnerPass!123"), role="viewer", is_active=True, email_verified=True, gatekeeper_groups=["api_access"], ) docs_dev = User( id=4, username="docs-dev", email="docsdev@example.invalid", password_hash=get_password_hash("DocsDevPass!123"), role="viewer", is_active=True, email_verified=True, gatekeeper_groups=["docs_developer"], ) session.add_all([admin, viewer, partner, docs_dev]) session.commit() async_session = _AsyncSQLiteSession(session) async def _override_get_db(): yield async_session app.dependency_overrides[get_db] = _override_get_db yield async_session engine.dispose() def _bearer_headers(user_id: int, username: str) -> dict[str, str]: token = create_access_token({"sub": str(user_id), "username": username}) return {"Authorization": f"Bearer {token}"} @pytest.mark.asyncio async def test_enforce_mode_blocks_anonymous_endpoints_and_allows_public_exemptions( monkeypatch, access_db ): monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce") class _ReadyDbContext: async def __aenter__(self): return self async def __aexit__(self, *args): return False async def execute(self, *_args, **_kwargs): return None class _ReadyRedis: class _Client: async def ping(self): return True @staticmethod def get_client(): return _ReadyRedis._Client() monkeypatch.setattr(main_module, "async_session_factory", lambda: _ReadyDbContext()) monkeypatch.setattr(main_module, "_AsyncRedisClient", _ReadyRedis) transport = ASGITransport(app=app) async with AsyncClient(transport=transport, base_url="http://test") as client: for protected_path in [ "/api/v1/visualization/geo/summary", "/api/v1/layers/cables?bbox=-10,-10,10,10&zoom=5", "/api/v1/vessels/snapshot?bbox=-10,-10,10,10&zoom=5", "/api/v1/news/earth-feed", "/api/v1/data-products/compute/configuration", "/api/v1/earth/brand", "/api/v1/earth/boundaries/manifest", "/api/v1/earth/boundaries/files/earth-boundaries.test.pmtiles", "/api/v1/tv/streams", ]: resp = await client.get(protected_path) assert resp.status_code == 401, f"{protected_path} returned {resp.status_code}" assert (await client.get("/health")).status_code == 200 assert (await client.get("/health/live")).status_code == 200 health_resp = await client.get("/health/ready") assert health_resp.status_code == 200 manifest_resp = await client.get("/api/v1/client/update-manifest") assert manifest_resp.status_code == 200 docs_resp = await client.get("/api/v1/docs/catalog") assert docs_resp.status_code == 200 tc = TestClient(app) with pytest.raises(WebSocketDisconnect) as exc_info: with tc.websocket_connect("/ws"): pass assert exc_info.value.code == 4001 @pytest.mark.asyncio async def test_web_earth_session_zero_login_origin_cookie_ws_and_turnstile( monkeypatch, access_db ): monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce") monkeypatch.setattr(settings, "TURNSTILE_SECRET_KEY", "") transport = ASGITransport(app=app) async with AsyncClient(transport=transport, base_url="http://test") as client: no_origin = await client.post("/api/v1/auth/earth-session", json={"client_type": "web"}) assert no_origin.status_code == 403 cross_site = await client.post( "/api/v1/auth/earth-session", json={"client_type": "web"}, headers={"Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site"}, ) assert cross_site.status_code == 403 ok = await client.post( "/api/v1/auth/earth-session", json={"client_type": "web"}, headers={"Origin": "http://test", "Sec-Fetch-Site": "same-origin"}, ) assert ok.status_code == 200 body = ok.json() assert body["client_type"] == "web" assert body["ws_token"] assert body["turnstile_required"] is False set_cookie = ok.headers.get("set-cookie", "") assert EARTH_SESSION_COOKIE in set_cookie assert "HttpOnly" in set_cookie assert "samesite=strict" in set_cookie.lower() authed_brand = await client.get("/api/v1/earth/brand") assert authed_brand.status_code == 200 tc = TestClient(app) with tc.websocket_connect(f"/ws?earth_token={body['ws_token']}") as ws: hello = ws.receive_json() assert hello["type"] == "connection_established" monkeypatch.setattr(settings, "TURNSTILE_SECRET_KEY", "ts-secret") class _MockTurnstileClient: def __init__(self, success: bool): self._success = success async def __aenter__(self): return self async def __aexit__(self, *args): return False async def post(self, *_args, **_kwargs): class _Resp: def __init__(self, success_flag: bool): self._success_flag = success_flag def raise_for_status(self): return None def json(self): return {"success": self._success_flag} return _Resp(self._success) async with AsyncClient(transport=transport, base_url="http://test") as client: missing_ts = await client.post( "/api/v1/auth/earth-session", json={"client_type": "web"}, headers={"Origin": "http://test"}, ) assert missing_ts.status_code == 403 monkeypatch.setattr( access_gate.httpx, "AsyncClient", lambda **_kw: _MockTurnstileClient(False), ) failed_ts = await client.post( "/api/v1/auth/earth-session", json={"client_type": "web", "turnstile_token": "bad-token"}, headers={"Origin": "http://test"}, ) assert failed_ts.status_code == 403 monkeypatch.setattr( access_gate.httpx, "AsyncClient", lambda **_kw: _MockTurnstileClient(True), ) ok_ts = await client.post( "/api/v1/auth/earth-session", json={"client_type": "web", "turnstile_token": "good-token"}, headers={"Origin": "http://test"}, ) assert ok_ts.status_code == 200 assert ok_ts.json()["turnstile_required"] is True @pytest.mark.asyncio async def test_desktop_earth_handshake_hmac_replay_and_token_access(monkeypatch, access_db): monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce") secret = "desktop-shared-hmac-secret" monkeypatch.setattr(settings, "EARTH_DESKTOP_HANDSHAKE_SECRET", secret) client_header = "planet-earth-desktop/0.82.0" ts = str(int(time.time())) nonce = "nonce-unique-123" sig = hmac.new( secret.encode("utf-8"), f"{ts}.{nonce}.{client_header}".encode("utf-8"), hashlib.sha256, ).hexdigest() transport = ASGITransport(app=app) async with AsyncClient(transport=transport, base_url="http://test") as client: missing_hdr = await client.post("/api/v1/auth/earth-session", json={"client_type": "desktop"}) assert missing_hdr.status_code == 403 bad_sig = await client.post( "/api/v1/auth/earth-session", json={"client_type": "desktop"}, headers={ "X-Planet-Client": client_header, "X-Planet-Client-Timestamp": ts, "X-Planet-Client-Nonce": nonce, "X-Planet-Client-Signature": "0" * 64, }, ) assert bad_sig.status_code == 403 ok = await client.post( "/api/v1/auth/earth-session", json={"client_type": "desktop"}, headers={ "X-Planet-Client": client_header, "X-Planet-Client-Timestamp": ts, "X-Planet-Client-Nonce": nonce, "X-Planet-Client-Signature": sig, }, ) assert ok.status_code == 200 desktop_token = ok.json()["token"] replay = await client.post( "/api/v1/auth/earth-session", json={"client_type": "desktop"}, headers={ "X-Planet-Client": client_header, "X-Planet-Client-Timestamp": ts, "X-Planet-Client-Nonce": nonce, "X-Planet-Client-Signature": sig, }, ) assert replay.status_code == 403 brand_resp = await client.get( "/api/v1/earth/brand", headers={EARTH_TOKEN_HEADER: desktop_token}, ) assert brand_resp.status_code == 200 tc = TestClient(app) with tc.websocket_connect("/ws", headers={EARTH_TOKEN_HEADER: desktop_token}) as ws: hello = ws.receive_json() assert hello["type"] == "connection_established" @pytest.mark.asyncio async def test_api_key_lifecycle_permanent_scopes_rate_limit_revocation_and_ws( monkeypatch, access_db ): monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce") admin_hdrs = _bearer_headers(1, "admin-user") viewer_hdrs = _bearer_headers(2, "plain-viewer") transport = ASGITransport(app=app) async with AsyncClient(transport=transport, base_url="http://test") as client: denied_create = await client.post( "/api/v1/system/api-keys", json={"name": "unauthorized"}, headers=viewer_hdrs, ) assert denied_create.status_code == 403 created = await client.post( "/api/v1/system/api-keys", json={ "name": "ue5-permanent", "scopes": ["earth:all_read"], "rate_limit_per_minute": None, "expires_in_days": None, }, headers=admin_hdrs, ) assert created.status_code == 201 created_data = created.json() raw_perm_key = created_data["api_key"] perm_item = created_data["item"] assert raw_perm_key.startswith("plt_live_") assert perm_item["expires_at"] is None assert perm_item["rate_limit_per_minute"] is None listing = await client.get("/api/v1/system/api-keys", headers=admin_hdrs) assert listing.status_code == 200 listed_item = listing.json()["items"][0] assert listed_item["key_prefix"] == perm_item["key_prefix"] assert raw_perm_key not in listing.text ok_http = await client.get("/api/v1/earth/brand", headers={"X-API-Key": raw_perm_key}) assert ok_http.status_code == 200 ok_tv_query = await client.get(f"/api/v1/tv/streams?api_key={raw_perm_key}") # /tv/streams intentionally requires header X-API-Key (not query), whereas /tv/proxy allows query assert ok_tv_query.status_code == 401 ok_tv_header = await client.get("/api/v1/tv/streams", headers={"X-API-Key": raw_perm_key}) assert ok_tv_header.status_code == 200 tc = TestClient(app) with tc.websocket_connect(f"/ws?api_key={raw_perm_key}") as ws: hello = ws.receive_json() assert hello["type"] == "connection_established" async with AsyncClient(transport=transport, base_url="http://test") as client: scoped_created = await client.post( "/api/v1/system/api-keys", json={ "name": "earth-only-limited", "scopes": ["earth:read"], "rate_limit_per_minute": 2, "expires_in_days": 30, }, headers=admin_hdrs, ) assert scoped_created.status_code == 201 scoped_key = scoped_created.json()["api_key"] assert ( await client.get("/api/v1/earth/brand", headers={"X-API-Key": scoped_key}) ).status_code == 200 assert ( await client.get("/api/v1/earth/brand", headers={"X-API-Key": scoped_key}) ).status_code == 200 assert ( await client.get("/api/v1/earth/brand", headers={"X-API-Key": scoped_key}) ).status_code == 429 out_of_scope = await client.get( "/api/v1/layers/cables?bbox=-10,-10,10,10&zoom=5", headers={"X-API-Key": scoped_key}, ) assert out_of_scope.status_code == 403 revoked = await client.post( f"/api/v1/system/api-keys/{perm_item['id']}/revoke", headers=admin_hdrs, ) assert revoked.status_code == 200 assert revoked.json()["item"]["status"] == "revoked" assert ( await client.get("/api/v1/earth/brand", headers={"X-API-Key": raw_perm_key}) ).status_code == 401 deleted = await client.delete( f"/api/v1/system/api-keys/{scoped_created.json()['item']['id']}", headers=admin_hdrs, ) assert deleted.status_code == 200 expired_raw = "plt_live_expired_unit_test_key" expired_row = ApiKey( name="expired-key", key_prefix="plt_live_exp...", key_hash=hash_api_key(expired_raw), scopes=["earth:all_read"], is_active=True, expires_at=datetime.now(UTC) - timedelta(days=1), ) access_db.add(expired_row) await access_db.commit() async with AsyncClient(transport=transport, base_url="http://test") as client: exp_resp = await client.get("/api/v1/earth/brand", headers={"X-API-Key": expired_raw}) assert exp_resp.status_code == 401 @pytest.mark.asyncio async def test_jwt_api_access_group_enforcement(monkeypatch, access_db): monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce") transport = ASGITransport(app=app) async with AsyncClient(transport=transport, base_url="http://test") as client: assert ( await client.get( "/api/v1/earth/brand", headers=_bearer_headers(1, "admin-user"), ) ).status_code == 200 assert ( await client.get( "/api/v1/earth/brand", headers=_bearer_headers(3, "partner-api"), ) ).status_code == 200 assert ( await client.get( "/api/v1/earth/brand", headers=_bearer_headers(2, "plain-viewer"), ) ).status_code == 403 @pytest.mark.asyncio async def test_news_refresh_requires_auth_and_enforces_cooldown(monkeypatch, access_db): monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce") from app.services import scheduler as scheduler_service monkeypatch.setattr( scheduler_service, "request_earth_news_region_refresh", lambda region: {"refresh_id": "11111111111111111111111111111111", "region": region, "status": "queued"}, ) transport = ASGITransport(app=app) async with AsyncClient(transport=transport, base_url="http://test") as client: anon = await client.post("/api/v1/news/refresh", json={"region": "global"}) assert anon.status_code == 401 hdrs = _bearer_headers(3, "partner-api") for _ in range(3): ok = await client.post("/api/v1/news/refresh", json={"region": "global"}, headers=hdrs) assert ok.status_code == 202 limited = await client.post("/api/v1/news/refresh", json={"region": "global"}, headers=hdrs) assert limited.status_code == 429 @pytest.mark.asyncio async def test_controlled_openapi_and_production_mode_defaults(monkeypatch, access_db): monkeypatch.setattr(settings, "APP_ENV", "production") monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "") assert settings.effective_earth_api_auth_mode == "enforce" spec = importlib.util.spec_from_file_location("app_main_prod_probe", main_module.__file__) assert spec is not None and spec.loader is not None prod_main = importlib.util.module_from_spec(spec) spec.loader.exec_module(prod_main) assert prod_main.app.docs_url is None assert prod_main.app.redoc_url is None assert prod_main.app.openapi_url is None monkeypatch.setattr(settings, "APP_ENV", "development") assert settings.effective_earth_api_auth_mode == "off" monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce") assert settings.effective_earth_api_auth_mode == "enforce" transport = ASGITransport(app=app) async with AsyncClient(transport=transport, base_url="http://test") as client: assert (await client.get("/api/v1/system/openapi.json")).status_code == 401 assert ( await client.get( "/api/v1/system/openapi.json", headers=_bearer_headers(2, "plain-viewer"), ) ).status_code == 403 full_resp = await client.get( "/api/v1/system/openapi.json", headers=_bearer_headers(4, "docs-dev"), ) assert full_resp.status_code == 200 assert "/api/v1/users" in full_resp.json()["paths"] ext_resp = await client.get( "/api/v1/system/openapi-external.json", headers=_bearer_headers(1, "admin-user"), ) assert ext_resp.status_code == 200 ext = ext_resp.json() assert "ApiKeyAuth" in ext["components"]["securitySchemes"] assert "/api/v1/visualization/geo/summary" in ext["paths"] assert "/api/v1/users" not in ext["paths"] assert "/api/v1/settings/integrations" not in ext["paths"] @pytest.mark.asyncio async def test_tile_rate_limit_tier_isolated_from_business_apis(monkeypatch, access_db): monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce") monkeypatch.setattr(settings, "TURNSTILE_SECRET_KEY", "") monkeypatch.setattr(settings, "EARTH_SESSION_RATE_LIMIT_PER_MIN", 2) monkeypatch.setattr(settings, "EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN", 3) from app.api.v1 import earth as earth_api from app.api.v1 import visualization as visualization_api async def _mock_fetch_terrain_tile(_client, _z: int, _x: int, _y: int): return b"png", "image/png", {} async def _mock_get_or_fetch_tile(_source_key: str, _z: int, _x: int, _y: int, **_kwargs): return b"webp", True monkeypatch.setattr(visualization_api, "_fetch_terrain_tile", _mock_fetch_terrain_tile) monkeypatch.setattr(earth_api, "resolve_boundary_artifact", lambda _name: None) import app.services.earth_tiles as earth_tiles_service monkeypatch.setattr(earth_tiles_service, "get_or_fetch_tile", _mock_get_or_fetch_tile) transport = ASGITransport(app=app) async with AsyncClient(transport=transport, base_url="http://test") as client: session_resp = await client.post( "/api/v1/auth/earth-session", json={"client_type": "web"}, headers={"Origin": "http://test", "Sec-Fetch-Site": "same-origin"}, ) assert session_resp.status_code == 200 # Exhaust the tile bucket across boundaries, basemap tiles, and terrarium tiles (3 total). assert ( await client.get("/api/v1/earth/boundaries/files/missing.pmtiles") ).status_code == 404 assert ( await client.get("/api/v1/earth/tiles/sentinel2_hd/2/1/1.webp") ).status_code == 200 assert ( await client.get("/api/v1/visualization/terrain/terrarium/2/1/1.png") ).status_code == 200 assert ( await client.get("/api/v1/earth/boundaries/files/missing.pmtiles") ).status_code == 429 # Business API bucket remains completely unaffected until its own limit (2). assert (await client.get("/api/v1/earth/brand")).status_code == 200 assert (await client.get("/api/v1/earth/boundaries/status")).status_code == 200 assert (await client.get("/api/v1/earth/brand")).status_code == 429 @pytest.mark.asyncio async def test_desktop_earth_session_rate_limit_isolated_by_client_ip(monkeypatch, access_db): monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce") secret = "desktop-shared-hmac-secret" monkeypatch.setattr(settings, "EARTH_DESKTOP_HANDSHAKE_SECRET", secret) monkeypatch.setattr(settings, "EARTH_SESSION_RATE_LIMIT_PER_MIN", 1) client_header = "planet-earth-desktop/0.82.0" def _signed_headers(nonce: str, client_ip: str) -> dict[str, str]: ts = str(int(time.time())) sig = hmac.new( secret.encode("utf-8"), f"{ts}.{nonce}.{client_header}".encode("utf-8"), hashlib.sha256, ).hexdigest() return { "X-Forwarded-For": client_ip, "X-Planet-Client": client_header, "X-Planet-Client-Timestamp": ts, "X-Planet-Client-Nonce": nonce, "X-Planet-Client-Signature": sig, } transport = ASGITransport(app=app) async with AsyncClient(transport=transport, base_url="http://test") as client: r1 = await client.post( "/api/v1/auth/earth-session", json={"client_type": "desktop"}, headers=_signed_headers("nonce-ip-1", "10.0.0.1"), ) r2 = await client.post( "/api/v1/auth/earth-session", json={"client_type": "desktop"}, headers=_signed_headers("nonce-ip-2", "10.0.0.2"), ) assert r1.status_code == 200 and r2.status_code == 200 tok1 = r1.json()["token"] tok2 = r2.json()["token"] c1 = access_gate.verify_earth_session_token(tok1) c2 = access_gate.verify_earth_session_token(tok2) assert c1 is not None and c2 is not None assert c1["cid"] != c2["cid"] assert c1["cid"].startswith("10.0.0.1:") assert c2["cid"].startswith("10.0.0.2:") assert ( await client.get("/api/v1/earth/brand", headers={EARTH_TOKEN_HEADER: tok1}) ).status_code == 200 assert ( await client.get("/api/v1/earth/brand", headers={EARTH_TOKEN_HEADER: tok1}) ).status_code == 429 # Second desktop client IP still has its own fresh quota. assert ( await client.get("/api/v1/earth/brand", headers={EARTH_TOKEN_HEADER: tok2}) ).status_code == 200 @pytest.mark.asyncio async def test_redis_rate_limit_atomic_lua_and_negative_ttl_recovery(monkeypatch): class _FakeLuaRedis: def __init__(self): self.counts: dict[str, int] = {} self.ttls: dict[str, int] = {} self.eval_calls = 0 async def eval(self, script: str, numkeys: int, key: str, window_seconds: int): self.eval_calls += 1 assert numkeys == 1 assert "TTL" in script and "EXPIRE" in script count = self.counts.get(key, 0) + 1 self.counts[key] = count if count == 1 or self.ttls.get(key, -1) < 0: self.ttls[key] = int(window_seconds) return count lua_redis = _FakeLuaRedis() monkeypatch.setattr(access_gate, "_AsyncRedisClient", type("R", (), {"get_client": staticmethod(lambda: lua_redis)})) await access_gate.check_sliding_rate_limit("earth:earth_web:1.2.3.4", limit=2, window_seconds=60) assert lua_redis.eval_calls == 1 assert lua_redis.ttls["access_gate:earth:earth_web:1.2.3.4"] == 60 class _LegacyRedisWithNegativeTtl: def __init__(self): self.counts = {"access_gate:stuck": 1} self.ttls = {"access_gate:stuck": -1} self.expired_with: list[int] = [] async def incr(self, key: str) -> int: self.counts[key] = self.counts.get(key, 0) + 1 return self.counts[key] async def ttl(self, key: str) -> int: return self.ttls.get(key, -1) async def expire(self, key: str, seconds: int) -> bool: self.ttls[key] = seconds self.expired_with.append(seconds) return True legacy_redis = _LegacyRedisWithNegativeTtl() monkeypatch.setattr( access_gate, "_AsyncRedisClient", type("R2", (), {"get_client": staticmethod(lambda: legacy_redis)}), ) await access_gate.check_sliding_rate_limit("stuck", limit=5, window_seconds=60) assert legacy_redis.ttls["access_gate:stuck"] == 60 assert legacy_redis.expired_with == [60]