- Add Go, npm, Python, and Java validation to CI - Run Go tests against PostgreSQL - Record performance fixes in the report
175 lines
6.8 KiB
Python
175 lines
6.8 KiB
Python
import asyncio
|
|
import os
|
|
import unittest
|
|
from datetime import timedelta
|
|
|
|
import bcrypt
|
|
|
|
from shared_backend.auth import (
|
|
ResetManager,
|
|
hash_password,
|
|
hash_password_async,
|
|
password_hash_needs_upgrade,
|
|
verify_and_upgrade_password,
|
|
verify_and_upgrade_password_async,
|
|
verify_password,
|
|
verify_password_async,
|
|
)
|
|
from shared_backend.config import DatabaseConfig
|
|
from shared_backend.postgres import (
|
|
StartupRetryOptions,
|
|
is_transient_connection_error,
|
|
retry_startup,
|
|
)
|
|
from shared_backend.tokens import hash_token, new_session_token
|
|
from shared_backend.totp import totp_provisioning_uri, verify_totp
|
|
|
|
|
|
class SharedBackendTests(unittest.TestCase):
|
|
def test_password_round_trip(self):
|
|
password_hash = hash_password("correct horse battery staple")
|
|
self.assertTrue(verify_password("correct horse battery staple", password_hash))
|
|
self.assertFalse(verify_password("wrong password", password_hash))
|
|
|
|
def test_async_password_helpers_match_the_sync_ones(self):
|
|
async def run():
|
|
password_hash = await hash_password_async("correct horse battery staple")
|
|
self.assertTrue(verify_password("correct horse battery staple", password_hash))
|
|
self.assertTrue(
|
|
await verify_password_async("correct horse battery staple", password_hash)
|
|
)
|
|
self.assertFalse(await verify_password_async("wrong password", password_hash))
|
|
|
|
asyncio.run(run())
|
|
|
|
def test_new_hashes_carry_the_scheme_prefix_and_the_current_cost(self):
|
|
password_hash = hash_password("correct horse battery staple")
|
|
self.assertTrue(password_hash.startswith("bcrypt$$2b$12$"))
|
|
self.assertFalse(password_hash_needs_upgrade(password_hash))
|
|
|
|
def test_unprefixed_legacy_bcrypt_hashes_still_verify_and_are_upgraded(self):
|
|
legacy = bcrypt.hashpw(
|
|
b"correct horse battery staple", bcrypt.gensalt(rounds=12)
|
|
).decode()
|
|
self.assertTrue(verify_password("correct horse battery staple", legacy))
|
|
self.assertFalse(verify_password("wrong password", legacy))
|
|
self.assertTrue(password_hash_needs_upgrade(legacy))
|
|
|
|
valid, upgraded = verify_and_upgrade_password("correct horse battery staple", legacy)
|
|
self.assertTrue(valid)
|
|
self.assertTrue(upgraded.startswith("bcrypt$$2b$12$"))
|
|
self.assertTrue(verify_password("correct horse battery staple", upgraded))
|
|
self.assertFalse(password_hash_needs_upgrade(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)
|
|
).decode()
|
|
self.assertTrue(password_hash_needs_upgrade(low_cost))
|
|
valid, upgraded = verify_and_upgrade_password("correct horse battery staple", low_cost)
|
|
self.assertTrue(valid)
|
|
self.assertIsNotNone(upgraded)
|
|
|
|
def test_a_wrong_password_and_a_current_hash_are_not_rewritten(self):
|
|
current = hash_password("correct horse battery staple")
|
|
password = "correct horse battery staple"
|
|
self.assertEqual(verify_and_upgrade_password(password, current), (True, None))
|
|
self.assertEqual(verify_and_upgrade_password("wrong password", current), (False, None))
|
|
|
|
def test_unknown_formats_fail_closed(self):
|
|
unknown = [
|
|
"",
|
|
"bcrypt$",
|
|
"bcrypt$not-a-bcrypt-string",
|
|
"pbkdf2-sha256$600000$00$00",
|
|
"$1$abc",
|
|
]
|
|
for stored in unknown:
|
|
self.assertFalse(verify_password("correct horse battery staple", stored), stored)
|
|
|
|
def test_async_upgrade_matches_the_sync_one(self):
|
|
password = "correct horse battery staple"
|
|
legacy = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12)).decode()
|
|
|
|
async def run():
|
|
valid, upgraded = await verify_and_upgrade_password_async(password, legacy)
|
|
self.assertTrue(valid)
|
|
self.assertTrue(await verify_password_async(password, upgraded))
|
|
|
|
asyncio.run(run())
|
|
|
|
def test_startup_retry_only_retries_transient_connection_errors(self):
|
|
import asyncpg
|
|
|
|
async def retry_with(error):
|
|
attempts = []
|
|
|
|
async def operation():
|
|
attempts.append(1)
|
|
raise error
|
|
|
|
policy = StartupRetryOptions(interval_seconds=0.001, max_attempts=3)
|
|
with self.assertRaises(type(error)):
|
|
await retry_startup(operation, policy)
|
|
return len(attempts)
|
|
|
|
self.assertTrue(is_transient_connection_error(ConnectionRefusedError()))
|
|
self.assertTrue(is_transient_connection_error(asyncpg.exceptions.ConnectionDoesNotExistError("closed")))
|
|
self.assertFalse(is_transient_connection_error(asyncpg.exceptions.InvalidPasswordError("bad")))
|
|
self.assertFalse(is_transient_connection_error(ValueError("bad")))
|
|
self.assertEqual(asyncio.run(retry_with(ValueError("bad"))), 1)
|
|
self.assertEqual(asyncio.run(retry_with(ConnectionRefusedError())), 3)
|
|
|
|
def test_session_token_hash(self):
|
|
token, token_hash = new_session_token()
|
|
self.assertNotEqual(token, token_hash)
|
|
self.assertEqual(hash_token(token), token_hash)
|
|
|
|
def test_reset_manager_round_trip_and_one_time_use(self):
|
|
messages = []
|
|
manager = ResetManager(log=messages.append)
|
|
code = manager.request()
|
|
|
|
self.assertEqual(len(code), 8)
|
|
self.assertIn(f"ADMIN RESET CODE: {code}", messages[0])
|
|
self.assertTrue(manager.confirm(f" {code.lower()} "))
|
|
self.assertFalse(manager.confirm(code))
|
|
|
|
def test_reset_manager_expires(self):
|
|
manager = ResetManager(ttl=timedelta(seconds=-1), log=lambda _message: None)
|
|
code = manager.request()
|
|
self.assertFalse(manager.confirm(code))
|
|
|
|
def test_totp_rfc6238_sha1_vectors(self):
|
|
secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
|
|
vectors = [
|
|
(59, "287082"),
|
|
(1111111109, "081804"),
|
|
(1111111111, "050471"),
|
|
(1234567890, "005924"),
|
|
(2000000000, "279037"),
|
|
]
|
|
for timestamp, code in vectors:
|
|
self.assertTrue(verify_totp(secret, code, timestamp))
|
|
self.assertTrue(
|
|
totp_provisioning_uri("Example App", "admin@example.com", secret).startswith(
|
|
"otpauth://totp/"
|
|
)
|
|
)
|
|
|
|
def test_database_config_from_environment(self):
|
|
config = DatabaseConfig.from_env(
|
|
{
|
|
**os.environ,
|
|
"DATABASE_URL": "postgresql://user:password@localhost:5432/app",
|
|
"DATABASE_MAX_CONNS": "7",
|
|
"DATABASE_MIN_CONNS": "2",
|
|
}
|
|
)
|
|
self.assertEqual(config.max_size, 7)
|
|
self.assertEqual(config.min_size, 2)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|