2026-10-19 21:46:52 +00:00
|
|
|
import unittest
|
|
|
|
|
|
|
|
|
|
from shared_backend.auth import (
|
|
|
|
|
AuthStore,
|
|
|
|
|
EmptyPasswordHashError,
|
|
|
|
|
InvalidUsernameError,
|
|
|
|
|
TotpAlreadyEnabledError,
|
|
|
|
|
hash_password,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class _FakeDatabase:
|
|
|
|
|
"""Records queries and answers them from canned results."""
|
|
|
|
|
|
|
|
|
|
def __init__(self) -> None:
|
|
|
|
|
self.executed: list[tuple[str, tuple]] = []
|
|
|
|
|
self.fetched: list[tuple[str, tuple]] = []
|
|
|
|
|
self.execute_status = "UPDATE 1"
|
|
|
|
|
self.totp_enabled = False
|
|
|
|
|
self.rows_by_condition: dict[str, dict] = {}
|
|
|
|
|
|
|
|
|
|
async def execute(self, query: str, *args) -> str:
|
|
|
|
|
self.executed.append((query, args))
|
|
|
|
|
return self.execute_status
|
|
|
|
|
|
|
|
|
|
async def fetchval(self, query: str, *args):
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
async def fetchrow(self, query: str, *args):
|
|
|
|
|
self.fetched.append((query, args))
|
|
|
|
|
if "totp_enabled" in query:
|
2026-10-20 15:27:53 +00:00
|
|
|
return {"secret": "S", "enabled": self.totp_enabled, "last_used_step": -1}
|
2026-10-19 21:46:52 +00:00
|
|
|
for condition, row in self.rows_by_condition.items():
|
|
|
|
|
if condition in query:
|
|
|
|
|
return row
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _user_row(username: str, email: str = "") -> dict:
|
|
|
|
|
return {
|
|
|
|
|
"id": 1,
|
|
|
|
|
"username": username,
|
|
|
|
|
"email": email,
|
|
|
|
|
"password_hash": "h",
|
|
|
|
|
"role": "user",
|
|
|
|
|
"created_at": None,
|
|
|
|
|
"updated_at": None,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase):
|
|
|
|
|
def setUp(self) -> None:
|
|
|
|
|
self.db = _FakeDatabase()
|
|
|
|
|
self.store = AuthStore(self.db, single_user=False) # type: ignore[arg-type]
|
|
|
|
|
|
|
|
|
|
async def test_ensure_schema_requests_the_case_insensitive_username_index(self) -> None:
|
|
|
|
|
await self.store.ensure_schema()
|
|
|
|
|
statements = " ".join(query for query, _ in self.db.executed)
|
|
|
|
|
self.assertIn("auth_users_username_lower_idx", statements)
|
|
|
|
|
self.assertIn("lower(username)", statements)
|
|
|
|
|
# The index is created only while no clashing pair exists.
|
|
|
|
|
self.assertIn("HAVING count(*) > 1", statements)
|
2026-10-20 15:27:53 +00:00
|
|
|
self.assertIn(
|
|
|
|
|
"ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1", statements
|
|
|
|
|
)
|
2026-10-19 21:46:52 +00:00
|
|
|
|
|
|
|
|
async def test_set_totp_secret_refuses_while_enabled(self) -> None:
|
|
|
|
|
self.db.execute_status = "UPDATE 0"
|
|
|
|
|
self.db.totp_enabled = True
|
|
|
|
|
with self.assertRaises(TotpAlreadyEnabledError):
|
|
|
|
|
await self.store.set_totp_secret(1, "NEWSECRET")
|
|
|
|
|
self.assertIn("NOT totp_enabled", self.db.executed[0][0])
|
|
|
|
|
|
|
|
|
|
async def test_set_totp_secret_succeeds_while_disabled(self) -> None:
|
|
|
|
|
await self.store.set_totp_secret(1, "NEWSECRET")
|
|
|
|
|
self.db.execute_status = "UPDATE 0" # no such user: nothing to refuse
|
|
|
|
|
await self.store.set_totp_secret(2, "NEWSECRET")
|
|
|
|
|
|
2026-10-20 15:27:53 +00:00
|
|
|
async def test_totp_enrollment_records_its_step_and_replay_is_rejected(self) -> None:
|
|
|
|
|
class ReplayDatabase(_FakeDatabase):
|
|
|
|
|
def __init__(self) -> None:
|
|
|
|
|
super().__init__()
|
|
|
|
|
self.state = {
|
|
|
|
|
"secret": "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
|
|
|
|
|
"enabled": False,
|
|
|
|
|
"last_used_step": -1,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async def fetchrow(self, query: str, *args):
|
|
|
|
|
if "FROM auth_users WHERE id = $1" in query and "totp_enabled" in query:
|
|
|
|
|
return dict(self.state)
|
|
|
|
|
return await super().fetchrow(query, *args)
|
|
|
|
|
|
|
|
|
|
async def execute(self, query: str, *args) -> str:
|
|
|
|
|
self.executed.append((query, args))
|
|
|
|
|
step, _, secret = args
|
|
|
|
|
if "SET totp_enabled = true" in query:
|
|
|
|
|
if (
|
|
|
|
|
not self.state["enabled"]
|
|
|
|
|
and secret == self.state["secret"]
|
|
|
|
|
and self.state["last_used_step"] < step
|
|
|
|
|
):
|
|
|
|
|
self.state["enabled"] = True
|
|
|
|
|
self.state["last_used_step"] = step
|
|
|
|
|
return "UPDATE 1"
|
|
|
|
|
return "UPDATE 0"
|
|
|
|
|
if "SET last_used_step = $1" in query:
|
|
|
|
|
if (
|
|
|
|
|
self.state["enabled"]
|
|
|
|
|
and secret == self.state["secret"]
|
|
|
|
|
and self.state["last_used_step"] < step
|
|
|
|
|
):
|
|
|
|
|
self.state["last_used_step"] = step
|
|
|
|
|
return "UPDATE 1"
|
|
|
|
|
return "UPDATE 0"
|
|
|
|
|
return await super().execute(query, *args)
|
|
|
|
|
|
|
|
|
|
database = ReplayDatabase()
|
|
|
|
|
store = AuthStore(database) # type: ignore[arg-type]
|
|
|
|
|
self.assertTrue(await store.enable_totp(1, "287082", 59.0))
|
|
|
|
|
self.assertEqual(database.state["last_used_step"], 1)
|
|
|
|
|
self.assertFalse(await store.consume_totp_code(1, "287082", 59.0))
|
|
|
|
|
self.assertEqual(database.state["last_used_step"], 1)
|
|
|
|
|
|
2026-10-19 21:46:52 +00:00
|
|
|
async def test_credential_writes_refuse_an_empty_hash_and_an_at_username(self) -> None:
|
|
|
|
|
writes = [
|
|
|
|
|
lambda u, h: self.store.create_user(u, "", h),
|
|
|
|
|
lambda u, h: self.store.create_managed_user(u, "", h),
|
|
|
|
|
lambda u, h: self.store.update_credentials(1, u, "", h),
|
|
|
|
|
lambda u, h: self.store.update_user(1, username=u, password_hash=h),
|
|
|
|
|
]
|
|
|
|
|
for write in writes:
|
|
|
|
|
with self.assertRaises(EmptyPasswordHashError):
|
|
|
|
|
await write("alice", "")
|
|
|
|
|
with self.assertRaises(InvalidUsernameError):
|
|
|
|
|
await write("alice@example.com", "hash")
|
|
|
|
|
self.assertEqual(self.db.executed, [])
|
|
|
|
|
self.assertEqual(self.db.fetched, [])
|
|
|
|
|
|
|
|
|
|
async def test_update_user_leaves_unspecified_fields_alone(self) -> None:
|
|
|
|
|
await self.store.update_user(1, email="a@b.com")
|
|
|
|
|
await self.store.update_user(1, role="admin")
|
|
|
|
|
self.assertEqual(len(self.db.executed), 2)
|
|
|
|
|
|
|
|
|
|
async def test_find_by_identifier_tries_the_username_before_the_email(self) -> None:
|
|
|
|
|
self.db.rows_by_condition = {
|
|
|
|
|
"username = $1": _user_row("owner@example.com", "second@example.com"),
|
|
|
|
|
"lower(email) = lower($1)": _user_row("owner", "owner@example.com"),
|
|
|
|
|
}
|
|
|
|
|
found = await self.store.find_by_identifier("owner@example.com")
|
|
|
|
|
self.assertEqual(found.username, "owner@example.com")
|
|
|
|
|
self.assertEqual(len(self.db.fetched), 1)
|
|
|
|
|
|
|
|
|
|
del self.db.rows_by_condition["username = $1"]
|
|
|
|
|
found = await self.store.find_by_identifier("owner@example.com")
|
|
|
|
|
self.assertEqual(found.username, "owner")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class PasswordLengthTests(unittest.TestCase):
|
|
|
|
|
def test_hash_password_refuses_more_than_72_bytes(self) -> None:
|
|
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
|
hash_password("a" * 73)
|
|
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
|
hash_password("é" * 37) # 74 bytes
|
|
|
|
|
self.assertTrue(hash_password("a" * 72).startswith("bcrypt$"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
unittest.main()
|