ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
fix(auth): reject inactive user credentials
Mafifrizi1f56b8250f99
diff --git a/ares/db/database.py b/ares/db/database.pyindex f10eaa3..3d9c4f2 100644--- a/ares/db/database.py+++ b/ares/db/database.py@@ -1117,6 +1117,7 @@ class AresDatabase:"""SELECT ak.*, u.username, u.roleFROM api_keys ak JOIN users u ON ak.user_id=u.idWHERE ak.key_prefix=? AND ak.is_active=1+ AND u.is_active=1AND (ak.expires_at IS NULLOR (@@ -1130,10 +1131,27 @@ class AresDatabase:for row in rows:if verify_password(raw_key, row["key_hash"]):- await self._conn.execute(- "UPDATE api_keys SET last_used=datetime('now') WHERE id=?", (row["id"],)- )+ async with self._conn.execute(+ """UPDATE api_keys+ SET last_used=datetime('now')+ WHERE id=? AND is_active=1+ AND (+ expires_at IS NULL+ OR (+ julianday(expires_at) IS NOT NULL+ AND julianday(expires_at) > julianday('now')+ )+ )+ AND EXISTS (+ SELECT 1 FROM users u+ WHERE u.id=api_keys.user_id AND u.is_active=1+ )""",+ (row["id"],),+ ) as cur:+ changed = cur.rowcountawait self._conn.commit()+ if changed != 1:+ return Nonereturn {"username": row["username"],"role": row["role"],@@ -1289,6 +1307,7 @@ class AresDatabase:"""SELECT rt.*, u.username, u.role, u.id as uidFROM refresh_tokens rt JOIN users u ON rt.user_id=u.idWHERE rt.id=? AND rt.is_revoked=0+ AND u.is_active=1AND julianday(rt.expires_at) IS NOT NULLAND julianday(rt.expires_at) > julianday('now')""",(old_hash,),@@ -1304,7 +1323,11 @@ class AresDatabase:SET is_revoked=1, used_at=datetime('now')WHERE id=? AND is_revoked=0AND julianday(expires_at) IS NOT NULL- AND julianday(expires_at) > julianday('now')""",+ AND julianday(expires_at) > julianday('now')+ AND EXISTS (+ SELECT 1 FROM users u+ WHERE u.id=refresh_tokens.user_id AND u.is_active=1+ )""",(old_hash,),) as cur:changed = cur.rowcountdiff --git a/ares/db/postgres.py b/ares/db/postgres.pyindex 4a2e8a2..3b93735 100644--- a/ares/db/postgres.py+++ b/ares/db/postgres.py@@ -858,9 +858,10 @@ class PostgresDatabase:prefix = raw_key[:12]async with self._pool.acquire() as conn:rows = await conn.fetch(- """SELECT ak.*, u.username, u.role+ """SELECT ak.id, ak.key_hashFROM api_keys ak JOIN users u ON ak.user_id=u.idWHERE ak.key_prefix=$1 AND ak.is_active=1+ AND u.is_active=1AND (ak.expires_at IS NULL OR ak.expires_at > now())""",prefix,)@@ -868,15 +869,26 @@ class PostgresDatabase:d = self._row_to_dict(row)if verify_password(raw_key, d["key_hash"]):async with self._pool.acquire() as conn:- await conn.execute(- "UPDATE api_keys SET last_used=now() WHERE id=$1", d["id"]+ updated = await conn.fetchrow(+ """UPDATE api_keys AS ak+ SET last_used=now()+ FROM users AS u+ WHERE ak.id=$1+ AND ak.is_active=1+ AND (ak.expires_at IS NULL OR ak.expires_at > now())+ AND u.id=ak.user_id+ AND u.is_active=1+ RETURNING ak.id, ak.scopes, u.username, u.role""",+ d["id"],)+ if updated is None:+ return Nonereturn {- "username": d["username"],- "role": d["role"],+ "username": updated["username"],+ "role": updated["role"],"auth_type": "api_key",- "key_id": d["id"],- "scopes": [d["scopes"]] if d.get("scopes") else [],+ "key_id": updated["id"],+ "scopes": [updated["scopes"]] if updated["scopes"] else [],}return None@@ -933,6 +945,7 @@ class PostgresDatabase:AND rt.is_revoked=0AND rt.expires_at > now()AND u.id=rt.user_id+ AND u.is_active=1RETURNING u.id AS uid, u.username, u.role""",old_hash,user_id,diff --git a/tests/integration/test_postgres_auth_token_lifecycle.py b/tests/integration/test_postgres_auth_token_lifecycle.pyindex 3f56516..3a890c2 100644--- a/tests/integration/test_postgres_auth_token_lifecycle.py+++ b/tests/integration/test_postgres_auth_token_lifecycle.py@@ -313,6 +313,122 @@ class _BarrierPool:return getattr(self._pool, name)+class _ApiKeyLookupBarrierConnection:+ def __init__(+ self,+ connection: Any,+ lookup_complete: asyncio.Event,+ release_lookup: asyncio.Event,+ lookup_pending: list[bool],+ authoritative_update_seen: list[bool],+ ) -> None:+ self._connection = connection+ self._lookup_complete = lookup_complete+ self._release_lookup = release_lookup+ self._lookup_pending = lookup_pending+ self._authoritative_update_seen = authoritative_update_seen++ async def fetch(self, query: str, *args: object) -> Any:+ rows = await self._connection.fetch(query, *args)+ normalized = " ".join(query.upper().split())+ if (+ self._lookup_pending[0]+ and "FROM API_KEYS AK JOIN USERS U" in normalized+ ):+ self._lookup_pending[0] = False+ self._lookup_complete.set()+ try:+ await asyncio.wait_for(self._release_lookup.wait(), timeout=10)+ except TimeoutError:+ pytest.fail(+ "API-key candidate lookup barrier was not released",+ pytrace=False,+ )+ return rows++ async def fetchrow(self, query: str, *args: object) -> Any:+ row = await self._connection.fetchrow(query, *args)+ normalized = " ".join(query.upper().split())+ if "UPDATE API_KEYS AS AK SET LAST_USED=NOW()" in normalized:+ self._authoritative_update_seen[0] = all(+ field in normalized+ for field in (+ "RETURNING",+ "AK.ID",+ "AK.SCOPES",+ "U.USERNAME",+ "U.ROLE",+ )+ )+ return row++ def __getattr__(self, name: str) -> Any:+ return getattr(self._connection, name)+++class _ApiKeyLookupBarrierAcquireContext:+ def __init__(+ self,+ acquire_context: Any,+ lookup_complete: asyncio.Event,+ release_lookup: asyncio.Event,+ lookup_pending: list[bool],+ authoritative_update_seen: list[bool],+ ) -> None:+ self._acquire_context = acquire_context+ self._lookup_complete = lookup_complete+ self._release_lookup = release_lookup+ self._lookup_pending = lookup_pending+ self._authoritative_update_seen = authoritative_update_seen++ async def __aenter__(self) -> _ApiKeyLookupBarrierConnection:+ connection = await self._acquire_context.__aenter__()+ return _ApiKeyLookupBarrierConnection(+ connection,+ self._lookup_complete,+ self._release_lookup,+ self._lookup_pending,+ self._authoritative_update_seen,+ )++ async def __aexit__(self, *exc_info: object) -> bool | None:+ return await self._acquire_context.__aexit__(*exc_info)+++class _ApiKeyLookupBarrierPool:+ def __init__(+ self,+ pool: Any,+ lookup_complete: asyncio.Event,+ release_lookup: asyncio.Event,+ ) -> None:+ self._pool = pool+ self._lookup_complete = lookup_complete+ self._release_lookup = release_lookup+ self._lookup_pending = [True]+ self._authoritative_update_seen = [False]++ def acquire(+ self,+ *args: object,+ **kwargs: object,+ ) -> _ApiKeyLookupBarrierAcquireContext:+ return _ApiKeyLookupBarrierAcquireContext(+ self._pool.acquire(*args, **kwargs),+ self._lookup_complete,+ self._release_lookup,+ self._lookup_pending,+ self._authoritative_update_seen,+ )++ @property+ def authoritative_update_seen(self) -> bool:+ return self._authoritative_update_seen[0]++ def __getattr__(self, name: str) -> Any:+ return getattr(self._pool, name)++async def _wait_for_blocked_backend_sessions(database: PostgresDatabase,holder_pid: int,@@ -534,6 +650,171 @@ async def test_postgres_api_key_expiry_contract() -> None:)+async def test_postgres_inactive_owner_api_key_is_denied_without_usage() -> None:+ async with _postgres_harness() as harness:+ database = harness.database+ user_id = await _insert_user(database)+ key_id, raw_key = await database.create_api_key(+ user_id,+ "inactive-owner-key",+ expires_days=1,+ )++ active_verification = await database.verify_api_key(raw_key)+ _require_fixed(+ active_verification is not None,+ "expected active-owner API key verification to succeed",+ )++ usage_marker = datetime(2000, 1, 1, tzinfo=timezone.utc)+ async with database._pool.acquire() as connection:+ await connection.execute(+ "UPDATE api_keys SET last_used=$1 WHERE id=$2",+ usage_marker,+ key_id,+ )+ await connection.execute(+ "UPDATE users SET is_active=0 WHERE id=$1",+ user_id,+ )+ usage_before = await connection.fetchval(+ "SELECT last_used FROM api_keys WHERE id=$1",+ key_id,+ )++ inactive_verification = await database.verify_api_key(raw_key)+ async with database._pool.acquire() as connection:+ usage_after = await connection.fetchval(+ "SELECT last_used FROM api_keys WHERE id=$1",+ key_id,+ )+ await connection.execute(+ "UPDATE users SET is_active=1 WHERE id=$1",+ user_id,+ )++ _require_fixed(+ inactive_verification is None,+ "expected inactive-owner API key verification to be rejected",+ )+ _require_fixed(+ usage_before == usage_marker and usage_after == usage_before,+ "expected inactive-owner API key usage metadata to remain unchanged",+ )++ reactivated_verification = await database.verify_api_key(raw_key)+ _require_fixed(+ reactivated_verification is not None,+ "expected reactivated-owner API key verification to succeed",+ )++ async with database._pool.acquire() as connection:+ await connection.execute(+ "UPDATE api_keys SET is_active=0 WHERE id=$1",+ key_id,+ )+ revoked_verification = await database.verify_api_key(raw_key)+ _require_fixed(+ revoked_verification is None,+ "expected revoked API key verification to remain rejected",+ )+++async def test_postgres_api_key_returns_authoritative_current_role() -> None:+ async with _postgres_harness() as harness:+ database = harness.database+ user_id = await _insert_user(database)+ key_id, raw_key = await database.create_api_key(+ user_id,+ "authoritative-identity-key",+ expires_days=1,+ )+ real_pool = database._pool+ lookup_complete = asyncio.Event()+ release_lookup = asyncio.Event()+ verification: asyncio.Task[Any] | None = None+ result: dict[str, Any] | None = None++ async with real_pool.acquire() as observer:+ last_used_before = await observer.fetchval(+ "SELECT last_used FROM api_keys WHERE id=$1",+ key_id,+ )++ barrier_pool = _ApiKeyLookupBarrierPool(+ real_pool,+ lookup_complete,+ release_lookup,+ )+ database._pool = barrier_pool+ try:+ verification = asyncio.create_task(database.verify_api_key(raw_key))+ try:+ await asyncio.wait_for(lookup_complete.wait(), timeout=10)+ except TimeoutError:+ pytest.fail(+ "production API-key lookup did not reach the barrier",+ pytrace=False,+ )++ async with real_pool.acquire() as updater:+ await updater.execute(+ "UPDATE users SET role=$1 WHERE id=$2",+ "team_lead",+ user_id,+ )+ async with real_pool.acquire() as observer:+ role_after_commit = await observer.fetchval(+ "SELECT role FROM users WHERE id=$1",+ user_id,+ )+ last_used_while_paused = await observer.fetchval(+ "SELECT last_used FROM api_keys WHERE id=$1",+ key_id,+ )+ _require_fixed(+ role_after_commit == "team_lead",+ "expected role change to commit before API-key update",+ )+ _require_fixed(+ last_used_before is None and last_used_while_paused is None,+ "expected candidate lookup not to update API-key usage metadata",+ )++ release_lookup.set()+ try:+ result = await asyncio.wait_for(verification, timeout=10)+ except TimeoutError:+ pytest.fail(+ "API-key verification did not finish after barrier release",+ pytrace=False,+ )+ finally:+ release_lookup.set()+ await _cancel_task(verification)+ database._pool = real_pool++ async with real_pool.acquire() as observer:+ last_used_after = await observer.fetchval(+ "SELECT last_used FROM api_keys WHERE id=$1",+ key_id,+ )+ _require_fixed(+ result is not None and result.get("role") == "team_lead",+ "expected authoritative API-key result to use the committed role",+ )+ _require_fixed(+ barrier_pool.authoritative_update_seen,+ "expected authoritative update to return current identity metadata",+ )+ _require_fixed(+ last_used_after is not None,+ "expected authoritative API-key update to record usage metadata",+ )++@pytest.mark.asyncioasync def test_postgres_refresh_expiry_contract() -> None:async with _postgres_harness() as harness:@@ -579,6 +860,59 @@ async def test_postgres_refresh_expiry_contract() -> None:assert await _active_refresh_count(database, user_id) == 1+async def test_postgres_inactive_owner_refresh_is_immutable_and_reactivates() -> None:+ async with _postgres_harness() as harness:+ database = harness.database+ user_id = await _insert_user(database)+ predecessor = await database.create_refresh_token(user_id)+ async with database._pool.acquire() as connection:+ await connection.execute(+ "UPDATE users SET is_active=0 WHERE id=$1",+ user_id,+ )++ inactive_result = await database.rotate_refresh_token(predecessor)+ async with database._pool.acquire() as connection:+ inactive_rows = await connection.fetch(+ """SELECT user_id, is_revoked, used_at+ FROM refresh_tokens+ WHERE user_id=$1""",+ user_id,+ )+ _require_fixed(+ inactive_result == (None, None),+ "expected inactive-owner refresh rotation to be rejected",+ )+ _require_fixed(+ len(inactive_rows) == 1+ and inactive_rows[0]["user_id"] == user_id+ and inactive_rows[0]["is_revoked"] == 0+ and inactive_rows[0]["used_at"] is None,+ "expected inactive-owner refresh predecessor to remain unchanged",+ )++ async with database._pool.acquire() as connection:+ await connection.execute(+ "UPDATE users SET is_active=1 WHERE id=$1",+ user_id,+ )+ reactivated_user, successor = await database.rotate_refresh_token(predecessor)+ _require_fixed(+ reactivated_user is not None and successor is not None,+ "expected reactivated-owner refresh rotation to succeed",+ )+ reused_result = await database.rotate_refresh_token(predecessor)+ _require_fixed(+ reused_result == (None, None),+ "expected the reactivated predecessor to rotate only once",+ )+ _require_fixed(+ await _active_refresh_count(database, user_id) == 1,+ "expected exactly one active refresh successor after reactivation",+ )++@pytest.mark.asyncioasync def test_postgres_access_token_timestamp_adapter_round_trip() -> None:async with _postgres_harness() as harness:@@ -989,6 +1323,66 @@ async def test_refresh_writers_use_expected_transaction_lock()+async def test_rotation_cas_rechecks_inactive_owner_after_advisory_wait() -> None:+ async with _postgres_harness() as harness:+ database = harness.database+ user_id = await _insert_user(database)+ predecessor = await database.create_refresh_token(user_id)+ lock_key = _refresh_token_user_lock_key(user_id)+ rotation: asyncio.Task[Any] | None = None++ try:+ async with database._pool.acquire() as holder:+ async with holder.transaction():+ await holder.execute(+ "SELECT pg_advisory_xact_lock($1::BIGINT)",+ lock_key,+ )+ rotation = asyncio.create_task(+ database.rotate_refresh_token(predecessor)+ )+ await _wait_for_advisory_wait(database, rotation)+ async with database._pool.acquire() as deactivator:+ await deactivator.execute(+ "UPDATE users SET is_active=0 WHERE id=$1",+ user_id,+ )+ _require_fixed(+ not rotation.done(),+ "expected rotation to remain blocked until lock release",+ )++ assert rotation is not None+ try:+ result = await asyncio.wait_for(rotation, timeout=10)+ except TimeoutError:+ pytest.fail(+ "rotation did not finish after inactive-owner lock release",+ pytrace=False,+ )+ finally:+ await _cancel_task(rotation)++ _require_fixed(+ result == (None, None),+ "expected inactive-owner CAS to lose after advisory lock release",+ )+ async with database._pool.acquire() as connection:+ rows = await connection.fetch(+ """SELECT is_revoked, used_at+ FROM refresh_tokens+ WHERE user_id=$1""",+ user_id,+ )+ _require_fixed(+ len(rows) == 1+ and rows[0]["is_revoked"] == 0+ and rows[0]["used_at"] is None,+ "expected inactive-owner CAS loss to leave predecessor unchanged",+ )++@pytest.mark.asyncioasync def test_successor_collision_rolls_back_predecessor(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/test_api_endpoints.py b/tests/unit/test_api_endpoints.pyindex e4c9f3d..6b25778 100644--- a/tests/unit/test_api_endpoints.py+++ b/tests/unit/test_api_endpoints.py@@ -130,6 +130,11 @@ def _run(coro):return asyncio.get_event_loop().run_until_complete(coro)+def _require_fixed(condition: bool, message: str) -> None:+ if not condition:+ pytest.fail(message, pytrace=False)++# ── shared async client ───────────────────────────────────────────────────────@@ -361,6 +366,225 @@ class TestAuthFlow:c, _, __ = aclientassert (await c.get("/campaigns/any-id")).status_code == 401+ @pytest.mark.asyncio+ async def test_inactive_api_key_uses_generic_failure_without_endpoint_work(+ self, aclient+ ):+ """Response/handler mapping; real SQLite containment is covered below."""+ c, db, _ = aclient+ _reset_rate_limiter()+ db.verify_api_key.return_value = None+ db.verify_api_key.reset_mock()+ db.list_campaigns.reset_mock()++ response = await c.get("/campaigns", headers=_api_key_headers())+ response_body = response.json()+ generic_failure = (+ response_body.get("code") == 401+ and response_body.get("detail")+ == "Not authenticated. Provide Bearer token or X-API-Key."+ and response_body.get("type") == "api_error"+ )+ if not (+ response.status_code == 401+ and generic_failure+ and db.verify_api_key.await_count == 1+ and db.list_campaigns.await_count == 0+ ):+ pytest.fail(+ "expected inactive API key to fail generically before endpoint work",+ pytrace=False,+ )+ if "inactive" in response.text.lower():+ pytest.fail(+ "expected API-key authentication failure not to disclose account status",+ pytrace=False,+ )++ @pytest.mark.asyncio+ async def test_inactive_refresh_uses_generic_failure_without_successor(+ self, aclient+ ):+ """Response/handler mapping; real SQLite containment is covered below."""+ c, db, _ = aclient+ _reset_rate_limiter()+ db.rotate_refresh_token.return_value = (None, None)+ db.rotate_refresh_token.reset_mock()+ db.create_refresh_token.reset_mock()++ response = await c.post(+ "/auth/refresh",+ json={"refresh_token": "inactive-refresh-fixture"},+ )+ response_body = response.json()+ generic_failure = (+ response_body.get("code") == 401+ and response_body.get("detail") == "Refresh token invalid or expired"+ and response_body.get("type") == "api_error"+ )+ if not (+ response.status_code == 401+ and generic_failure+ and db.rotate_refresh_token.await_count == 1+ and db.create_refresh_token.await_count == 0+ ):+ pytest.fail(+ "expected inactive refresh to fail generically without a successor",+ pytrace=False,+ )+ if "inactive" in response.text.lower():+ pytest.fail(+ "expected refresh authentication failure not to disclose account status",+ pytrace=False,+ )++ @pytest.mark.asyncio+ async def test_real_sqlite_inactive_credentials_fail_at_api_boundary(+ self,+ aclient,+ tmp_path,+ monkeypatch,+ ):+ c, _, app = aclient+ from ares.api.server import get_db+ from ares.db.database import AresDatabase++ real_db = await AresDatabase.create(tmp_path / "inactive-boundary.db")+ original_app_db = getattr(app.state, "db", None)+ no_override = object()+ original_override = app.dependency_overrides.get(get_db, no_override)+ handler_calls = [0]+ original_list_campaigns = real_db.list_campaigns++ async def counted_list_campaigns(*args, **kwargs):+ handler_calls[0] += 1+ return await original_list_campaigns(*args, **kwargs)++ with monkeypatch.context() as patch:+ patch.setattr(real_db, "list_campaigns", counted_list_campaigns)+ app.state.db = real_db+ app.dependency_overrides[get_db] = lambda: real_db+ try:+ user_id = await real_db.create_user(+ "inactive-boundary-user",+ "SyntheticBoundaryPass1!",+ "operator",+ )+ key_id, raw_key = await real_db.create_api_key(+ user_id,+ "inactive-boundary-key",+ )+ refresh_token = await real_db.create_refresh_token(user_id)+ async with real_db.conn.execute(+ "SELECT id FROM refresh_tokens WHERE user_id=?",+ (user_id,),+ ) as cur:+ original_refresh_row = await cur.fetchone()+ original_refresh_id = (+ original_refresh_row["id"]+ if original_refresh_row is not None+ else None+ )++ active_response = await c.get(+ "/campaigns",+ headers={"X-API-Key": raw_key},+ )+ active_control = (+ active_response.status_code == 200 and handler_calls[0] == 1+ )+ _require_fixed(+ active_control,+ "expected active real SQLite API key to reach protected work",+ )++ usage_marker = "2000-01-01 00:00:00"+ await real_db.conn.execute(+ "UPDATE api_keys SET last_used=? WHERE id=?",+ (usage_marker, key_id),+ )+ await real_db.conn.execute(+ "UPDATE users SET is_active=0 WHERE id=?",+ (user_id,),+ )+ await real_db.conn.commit()+ handler_calls[0] = 0++ api_response = await c.get(+ "/campaigns",+ headers={"X-API-Key": raw_key},+ )+ refresh_response = await c.post(+ "/auth/refresh",+ json={"refresh_token": refresh_token},+ )++ api_body = api_response.json()+ refresh_body = refresh_response.json()+ api_contract = (+ api_response.status_code == 401+ and api_body.get("detail")+ == "Not authenticated. Provide Bearer token or X-API-Key."+ and "inactive" not in api_response.text.lower()+ and handler_calls[0] == 0+ )+ refresh_contract = (+ refresh_response.status_code == 401+ and refresh_body.get("detail")+ == "Refresh token invalid or expired"+ and "inactive" not in refresh_response.text.lower()+ and "refresh_token" not in refresh_body+ )++ async with real_db.conn.execute(+ "SELECT last_used FROM api_keys WHERE id=?",+ (key_id,),+ ) as cur:+ api_key_row = await cur.fetchone()+ async with real_db.conn.execute(+ """SELECT id, user_id, is_revoked, used_at+ FROM refresh_tokens+ WHERE user_id=?""",+ (user_id,),+ ) as cur:+ refresh_rows = await cur.fetchall()++ usage_unchanged = (+ api_key_row is not None+ and api_key_row["last_used"] == usage_marker+ )+ predecessor_unchanged = (+ len(refresh_rows) == 1+ and original_refresh_id is not None+ and refresh_rows[0]["id"] == original_refresh_id+ and refresh_rows[0]["user_id"] == user_id+ and refresh_rows[0]["is_revoked"] == 0+ and refresh_rows[0]["used_at"] is None+ )+ _require_fixed(+ api_contract,+ "expected inactive real SQLite API key to fail generically",+ )+ _require_fixed(+ refresh_contract,+ "expected inactive real SQLite refresh to fail generically",+ )+ _require_fixed(+ usage_unchanged,+ "expected inactive API-key usage metadata to remain unchanged",+ )+ _require_fixed(+ predecessor_unchanged,+ "expected inactive refresh predecessor to remain unchanged",+ )+ finally:+ app.state.db = original_app_db+ if original_override is no_override:+ app.dependency_overrides.pop(get_db, None)+ else:+ app.dependency_overrides[get_db] = original_override+ await real_db.close()+# ── RBAC enforcement ──────────────────────────────────────────────────────────diff --git a/tests/unit/test_sqlite_auth_token_lifecycle.py b/tests/unit/test_sqlite_auth_token_lifecycle.pyindex 1229996..43d56e5 100644--- a/tests/unit/test_sqlite_auth_token_lifecycle.py+++ b/tests/unit/test_sqlite_auth_token_lifecycle.py@@ -93,6 +93,20 @@ async def _active_refresh_count(db: AresDatabase, user_id: str) -> int:return int((await cur.fetchone())["n"])+def _require_fixed(condition: bool, message: str) -> None:+ if not condition:+ pytest.fail(message, pytrace=False)+++async def _api_key_last_used(db: AresDatabase, key_id: str) -> object:+ async with db.conn.execute(+ "SELECT last_used FROM api_keys WHERE id=?",+ (key_id,),+ ) as cur:+ row = await cur.fetchone()+ return None if row is None else row["last_used"]++async def _run_cleanup_helper(db: AresDatabase,helper_name: str,@@ -886,6 +900,112 @@ async def test_plain_memory_instances_are_isolated_and_independently_anchored()await first.close()+async def test_inactive_owner_api_key_is_denied_without_usage_and_reactivates(+ db_and_user: tuple[AresDatabase, str],+) -> None:+ db, user_id = db_and_user+ key_id, raw_key = await db.create_api_key(user_id, "inactive-owner-key")++ active_verification = await db.verify_api_key(raw_key)+ _require_fixed(+ active_verification is not None,+ "expected active-owner API key verification to succeed",+ )++ usage_marker = "2000-01-01 00:00:00"+ await db.conn.execute(+ "UPDATE api_keys SET last_used=? WHERE id=?",+ (usage_marker, key_id),+ )+ await db.conn.execute(+ "UPDATE users SET is_active=0 WHERE id=?",+ (user_id,),+ )+ await db.conn.commit()+ usage_before = await _api_key_last_used(db, key_id)++ inactive_verification = await db.verify_api_key(raw_key)+ usage_after = await _api_key_last_used(db, key_id)+ _require_fixed(+ inactive_verification is None,+ "expected inactive-owner API key verification to be rejected",+ )+ _require_fixed(+ usage_before == usage_marker and usage_after == usage_before,+ "expected inactive-owner API key usage metadata to remain unchanged",+ )++ await db.conn.execute(+ "UPDATE users SET is_active=1 WHERE id=?",+ (user_id,),+ )+ await db.conn.commit()+ reactivated_verification = await db.verify_api_key(raw_key)+ _require_fixed(+ reactivated_verification is not None,+ "expected reactivated-owner API key verification to succeed",+ )++ await db.conn.execute(+ "UPDATE api_keys SET is_active=0 WHERE id=?",+ (key_id,),+ )+ await db.conn.commit()+ revoked_verification = await db.verify_api_key(raw_key)+ _require_fixed(+ revoked_verification is None,+ "expected revoked API key verification to remain rejected",+ )+++async def test_inactive_owner_refresh_is_immutable_and_reactivates(+ db_and_user: tuple[AresDatabase, str],+) -> None:+ db, user_id = db_and_user+ predecessor = await db.create_refresh_token(user_id)+ await db.conn.execute(+ "UPDATE users SET is_active=0 WHERE id=?",+ (user_id,),+ )+ await db.conn.commit()++ inactive_result = await db.rotate_refresh_token(predecessor)+ inactive_rows = await _refresh_rows(db)+ _require_fixed(+ inactive_result == (None, None),+ "expected inactive-owner refresh rotation to be rejected",+ )+ _require_fixed(+ len(inactive_rows) == 1+ and inactive_rows[0]["user_id"] == user_id+ and inactive_rows[0]["is_revoked"] == 0+ and inactive_rows[0]["used_at"] is None,+ "expected inactive-owner refresh predecessor to remain unchanged",+ )++ await db.conn.execute(+ "UPDATE users SET is_active=1 WHERE id=?",+ (user_id,),+ )+ await db.conn.commit()+ reactivated_user, successor = await db.rotate_refresh_token(predecessor)+ _require_fixed(+ reactivated_user is not None and successor is not None,+ "expected reactivated-owner refresh rotation to succeed",+ )+ reused_result = await db.rotate_refresh_token(predecessor)+ _require_fixed(+ reused_result == (None, None),+ "expected the reactivated predecessor to rotate only once",+ )+ _require_fixed(+ await _active_refresh_count(db, user_id) == 1,+ "expected exactly one active refresh successor after reactivation",+ )++@pytest.mark.asyncioasync def test_api_key_rejects_iso_expiry_earlier_on_current_utc_date(db_and_user: tuple[AresDatabase, str],