docs: record auth hash alignment and validation results

This commit is contained in:
Gabriel20xx committed 2026-10-20 15:26:58 +00:00
1 parent 22887fef03
commit f7819904b9
51 files changed
+1792 -542

No files matched your search

+110 -2
View File
@@ -175,15 +175,32 @@ class AccessSettingsTests(unittest.TestCase):
self.assertEqual(response.status_code, 500)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
def test_internal_update_refuses_a_short_or_placeholder_secret(self) -> None:
for secret in ("short", "change-me-to-a-long-random-value"):
with self.subTest(secret=secret):
store = _FakeStore(login_required=True)
client = TestClient(
_build_app(store, _FakeClient(setup_required=False), internal_secret=secret)
)
response = client.put(
"/api/auth/access/internal",
headers={"X-Internal-Auth": secret},
json={"loginRequired": False},
)
self.assertEqual(response.status_code, 401)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
store = _FakeStore(login_required=True)
client = TestClient(
_build_app(store, _FakeClient(setup_required=False), internal_secret="secret")
_build_app(
store, _FakeClient(setup_required=False), internal_secret="internal-test-secret"
)
)
response = client.put(
"/api/auth/access/internal",
headers={"X-Internal-Auth": "secret"},
headers={"X-Internal-Auth": "internal-test-secret"},
json={"loginRequired": False},
)
self.assertEqual(response.status_code, 200)
@@ -244,6 +261,97 @@ class _RoleClient(_FakeClient):
return PublicUser(id=1, username="a", email="a@b.com", role=roles[token])
class _ProfileClient(_RoleClient):
def __init__(self, *, totp_enabled: bool = False) -> None:
super().__init__()
self.totp_enabled = totp_enabled
self.login_calls: list[tuple[str, str, str]] = []
self.update_calls: list[dict[str, object]] = []
async def me(self, token: str) -> PublicUser:
if token != "admin-token":
raise APIError(401, "unauthenticated")
return PublicUser(
id=1,
username="admin",
email="admin@example.com",
role="superadmin",
totp_enabled=self.totp_enabled,
)
async def login(self, username_or_email: str, password: str, totp_token: str = ""):
self.login_calls.append((username_or_email, password, totp_token))
if password != "current-password":
raise APIError(401, "invalid credentials")
return SessionResult(
user=PublicUser(id=1, username="admin", email="admin@example.com", role="superadmin"),
cookies=["auth_session=reauth-token; Path=/; HttpOnly"],
)
async def update_managed_user(self, token: str, user_id: int, **kwargs) -> None:
self.update_calls.append({"token": token, "user_id": user_id, **kwargs})
class ProfileReauthenticationTests(unittest.TestCase):
def _put(self, fake: _ProfileClient, body: dict[str, str]):
client = TestClient(_build_app(_FakeStore(), fake))
return client.put(
"/api/auth/me",
headers={"Cookie": f"{DEFAULT_COOKIE_NAME}=admin-token"},
json=body,
)
def test_password_update_requires_current_password_and_totp_when_enabled(self) -> None:
no_totp = _ProfileClient()
response = self._put(
no_totp,
{"username": "admin", "email": "admin@example.com", "password": "new-password"},
)
self.assertEqual(response.status_code, 400)
self.assertEqual(no_totp.login_calls, [])
totp = _ProfileClient(totp_enabled=True)
response = self._put(
totp,
{
"username": "admin",
"email": "admin@example.com",
"password": "new-password",
"currentPassword": "current-password",
},
)
self.assertEqual(response.status_code, 400)
self.assertEqual(totp.login_calls, [])
def test_password_update_reauthenticates_and_cleans_up_temporary_session(self) -> None:
fake = _ProfileClient(totp_enabled=True)
response = self._put(
fake,
{
"username": "admin",
"email": "admin@example.com",
"password": "new-password",
"currentPassword": "current-password",
"totpToken": "123456",
},
)
self.assertEqual(response.status_code, 200, response.text)
self.assertEqual(fake.login_calls, [("admin", "current-password", "123456")])
self.assertEqual(
fake.update_calls,
[
{
"token": "admin-token",
"user_id": 1,
"username": "admin",
"email": "admin@example.com",
"password": "new-password",
}
],
)
self.assertIn("reauth-token", fake.logged_out)
class EnabledModeSetupAndLoginTests(unittest.TestCase):
"""Exercises the real (client is not None) path, including the
setup-claim flag's interaction with the store."""
+29 -6
View File
@@ -9,7 +9,12 @@ from shared_backend.auth import (
verify_password,
)
from shared_backend.clientip import client_address, parse_trusted_proxies
from shared_backend.totp import verify_totp
from shared_backend.coreconfig import (
EXAMPLE_INTERNAL_SECRETS,
MIN_INTERNAL_SECRET_LENGTH,
internal_secret_matches,
)
from shared_backend.totp import verify_totp, verify_totp_step
# The Go, Node and Python auth helpers load the same fixtures; see "description" in the file.
CONTRACT_PATH = Path(__file__).resolve().parents[3] / "contract" / "auth-contract.json"
@@ -27,22 +32,24 @@ class AuthContractTests(unittest.TestCase):
password = self.contract["password"]
for entry in password["hashes"]:
with self.subTest(entry["name"]):
plaintext = entry.get("password", password["plaintext"])
wrong_password = entry.get("wrongPassword", password["wrongPassword"])
self.assertEqual(
verify_password(password["plaintext"], entry["hash"]),
verify_password(plaintext, entry["hash"]),
entry["verifies"]["python"],
)
self.assertFalse(verify_password(password["wrongPassword"], entry["hash"]))
self.assertFalse(verify_password(wrong_password, entry["hash"]))
if "python" in entry.get("needsUpgrade", {}):
want = entry["needsUpgrade"]["python"]
self.assertEqual(password_hash_needs_upgrade(entry["hash"]), want)
valid, upgraded = verify_and_upgrade_password(
password["plaintext"], entry["hash"]
plaintext, entry["hash"]
)
self.assertTrue(valid)
self.assertEqual(upgraded is not None, want)
if upgraded is not None:
self.assertTrue(upgraded.startswith("bcrypt$"))
self.assertTrue(verify_password(password["plaintext"], upgraded))
self.assertTrue(upgraded.startswith(("bcrypt$", "bcrypt-sha256$")))
self.assertTrue(verify_password(plaintext, upgraded))
def test_the_password_length_contract_holds_for_python(self) -> None:
too_long = self.contract["password"]["tooLongToHash"]
@@ -59,6 +66,11 @@ class AuthContractTests(unittest.TestCase):
with self.subTest(entry["name"]):
secret = entry.get("secret", totp["secret"])
self.assertEqual(verify_totp(secret, entry["code"], entry["unix"]), entry["valid"])
if entry["valid"]:
self.assertEqual(
verify_totp_step(secret, entry["code"], entry["unix"]),
entry.get("matchedStep", entry["unix"] // 30),
)
def test_client_address_follows_the_contract(self) -> None:
section = self.contract["clientAddress"]
@@ -72,6 +84,17 @@ class AuthContractTests(unittest.TestCase):
with self.subTest(value), self.assertRaises(ValueError):
parse_trusted_proxies(value)
def test_internal_secret_gate_follows_the_contract(self) -> None:
rule = self.contract["internalSecret"]
self.assertEqual(MIN_INTERNAL_SECRET_LENGTH, rule["minLength"])
self.assertEqual(EXAMPLE_INTERNAL_SECRETS, frozenset(rule["placeholders"]))
for entry in rule["cases"]:
with self.subTest(entry["name"]):
self.assertEqual(
internal_secret_matches(entry["provided"], entry["secret"]),
entry["matches"],
)
if __name__ == "__main__":
unittest.main()
+16 -1
View File
@@ -22,7 +22,7 @@ from shared_backend.postgres import (
retry_startup,
)
from shared_backend.tokens import hash_token, new_session_token
from shared_backend.totp import totp_provisioning_uri, verify_totp
from shared_backend.totp import totp_provisioning_uri, verify_totp, verify_totp_step
class SharedBackendTests(unittest.TestCase):
@@ -61,6 +61,19 @@ class SharedBackendTests(unittest.TestCase):
self.assertTrue(verify_password("correct horse battery staple", upgraded))
self.assertFalse(password_hash_needs_upgrade(upgraded))
def test_long_legacy_pbkdf2_password_migrates_without_truncation(self):
import hashlib
password = "legacy:" + "x" * 80
salt = "0123456789abcdef0123456789abcdef"
expected = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), 100_000).hex()
legacy = f"{salt}:{expected}"
valid, upgraded = verify_and_upgrade_password(password, legacy)
self.assertTrue(valid)
self.assertTrue(upgraded.startswith("bcrypt-sha256$$2b$12$"))
self.assertTrue(verify_password(password, upgraded))
self.assertFalse(verify_password(password + "x", upgraded))
def test_a_cost_below_the_current_policy_is_upgraded(self):
low_cost = "bcrypt$" + bcrypt.hashpw(
b"correct horse battery staple", bcrypt.gensalt(rounds=4)
@@ -151,6 +164,8 @@ class SharedBackendTests(unittest.TestCase):
]
for timestamp, code in vectors:
self.assertTrue(verify_totp(secret, code, timestamp))
self.assertEqual(verify_totp_step(secret, code, timestamp), timestamp // 30)
self.assertEqual(verify_totp_step(secret, code, timestamp), timestamp // 30)
self.assertTrue(
totp_provisioning_uri("Example App", "admin@example.com", secret).startswith(
"otpauth://totp/"
@@ -1,6 +1,12 @@
import unittest
from shared_backend.coreconfig import Info, Store, internal_secret_matches
from shared_backend.coreconfig import (
MIN_INTERNAL_SECRET_LENGTH,
Info,
Store,
internal_secret_matches,
internal_secret_usable,
)
class StoreDefaultsTests(unittest.TestCase):
@@ -62,6 +68,9 @@ class StoreSetTests(unittest.TestCase):
self.assertEqual(info.to_json()["carrierNodeUrl"], "http://carrier.example.com")
LONG_SECRET = "shared-secret-value"
class InternalSecretTests(unittest.TestCase):
def test_unset_or_empty_secret_never_matches(self):
self.assertFalse(internal_secret_matches(None, None))
@@ -70,9 +79,26 @@ class InternalSecretTests(unittest.TestCase):
self.assertFalse(internal_secret_matches("", None))
def test_compares_the_whole_secret(self):
self.assertTrue(internal_secret_matches("shared-secret", "shared-secret"))
self.assertFalse(internal_secret_matches("shared-secreT", "shared-secret"))
self.assertFalse(internal_secret_matches(None, "shared-secret"))
self.assertTrue(internal_secret_matches(LONG_SECRET, LONG_SECRET))
self.assertFalse(internal_secret_matches("shared-secret-valuE", LONG_SECRET))
self.assertFalse(internal_secret_matches(None, LONG_SECRET))
def test_short_secret_never_matches(self):
short = "x" * (MIN_INTERNAL_SECRET_LENGTH - 1)
self.assertFalse(internal_secret_matches(short, short))
def test_placeholder_secret_never_matches(self):
for placeholder in ("SECRET", "change-me-to-a-long-random-value"):
with self.subTest(placeholder=placeholder):
self.assertFalse(internal_secret_matches(placeholder, placeholder))
def test_usable_requires_minimum_length_and_no_placeholder(self):
self.assertFalse(internal_secret_usable(None))
self.assertFalse(internal_secret_usable(""))
self.assertFalse(internal_secret_usable("x" * (MIN_INTERNAL_SECRET_LENGTH - 1)))
self.assertTrue(internal_secret_usable("x" * MIN_INTERNAL_SECRET_LENGTH))
self.assertFalse(internal_secret_usable("change-me-to-a-long-random-value"))
self.assertTrue(internal_secret_usable(LONG_SECRET))
class UrlValidationTests(unittest.TestCase):
+50 -1
View File
@@ -29,7 +29,7 @@ class _FakeDatabase:
async def fetchrow(self, query: str, *args):
self.fetched.append((query, args))
if "totp_enabled" in query:
return {"secret": "S", "enabled": self.totp_enabled}
return {"secret": "S", "enabled": self.totp_enabled, "last_used_step": -1}
for condition, row in self.rows_by_condition.items():
if condition in query:
return row
@@ -60,6 +60,9 @@ class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("lower(username)", statements)
# The index is created only while no clashing pair exists.
self.assertIn("HAVING count(*) > 1", statements)
self.assertIn(
"ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1", statements
)
async def test_set_totp_secret_refuses_while_enabled(self) -> None:
self.db.execute_status = "UPDATE 0"
@@ -73,6 +76,52 @@ class AuthStoreHardeningTests(unittest.IsolatedAsyncioTestCase):
self.db.execute_status = "UPDATE 0" # no such user: nothing to refuse
await self.store.set_totp_secret(2, "NEWSECRET")
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)
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),