ci: expand CI checks and make consumer sync opt-in
- Add Go, npm, Python, and Java validation to CI - Run Go tests against PostgreSQL - Record performance fixes in the report
This commit is contained in:
1 parent
199a5efaef
commit
22887fef03
100 files changed
+9740
-429
No files matched your search
@@ -0,0 +1,81 @@
|
||||
import unittest
|
||||
|
||||
from shared_backend.clientip import client_address, parse_trusted_proxies
|
||||
from shared_backend.ratelimit import MAX_TRACKED_ATTEMPT_KEYS, AttemptLimiter
|
||||
|
||||
|
||||
class ParseTrustedProxiesTests(unittest.TestCase):
|
||||
def test_accepts_cidrs_and_bare_addresses(self) -> None:
|
||||
networks = parse_trusted_proxies(" 10.0.0.0/8, 192.168.1.5 ,fd00::/8,, ::1 ")
|
||||
self.assertEqual(
|
||||
[str(network) for network in networks],
|
||||
["10.0.0.0/8", "192.168.1.5/32", "fd00::/8", "::1/128"],
|
||||
)
|
||||
|
||||
def test_empty_trusts_no_proxy(self) -> None:
|
||||
self.assertEqual(parse_trusted_proxies(" "), [])
|
||||
self.assertEqual(parse_trusted_proxies(None), [])
|
||||
|
||||
def test_rejects_invalid_entries(self) -> None:
|
||||
for value in ("not-an-ip", "10.0.0.0/33", "10.0.0.1, bogus"):
|
||||
with self.assertRaises(ValueError, msg=value):
|
||||
parse_trusted_proxies(value)
|
||||
|
||||
|
||||
class ClientAddressTests(unittest.TestCase):
|
||||
def test_forwarded_for_is_ignored_without_trusted_proxies(self) -> None:
|
||||
self.assertEqual(client_address("203.0.113.7", ["198.51.100.1"], []), "203.0.113.7")
|
||||
|
||||
def test_forwarded_for_is_ignored_from_an_unknown_peer(self) -> None:
|
||||
trusted = parse_trusted_proxies("10.0.0.0/8")
|
||||
self.assertEqual(client_address("203.0.113.7", ["198.51.100.1"], trusted), "203.0.113.7")
|
||||
|
||||
def test_a_trusted_peer_has_its_header_honoured(self) -> None:
|
||||
trusted = parse_trusted_proxies("10.0.0.0/8, 172.16.0.0/12")
|
||||
cases = [
|
||||
("single client", ["198.51.100.9"], "198.51.100.9"),
|
||||
("second trusted hop", ["198.51.100.9, 172.16.4.4"], "198.51.100.9"),
|
||||
("spoofed left-most entry", ["6.6.6.6, 198.51.100.9, 172.16.4.4"], "198.51.100.9"),
|
||||
("entries across header lines", ["6.6.6.6", "198.51.100.9"], "198.51.100.9"),
|
||||
("malformed entry", ["198.51.100.9, not-an-ip"], "10.0.0.2"),
|
||||
("no header", [], "10.0.0.2"),
|
||||
("every hop trusted", ["10.1.1.1, 172.16.4.4"], "10.1.1.1"),
|
||||
]
|
||||
for name, forwarded, want in cases:
|
||||
with self.subTest(name):
|
||||
self.assertEqual(client_address("10.0.0.2", forwarded, trusted), want)
|
||||
|
||||
def test_an_ipv4_mapped_peer_matches_an_ipv4_range(self) -> None:
|
||||
trusted = parse_trusted_proxies("10.0.0.0/8")
|
||||
self.assertEqual(
|
||||
client_address("::ffff:10.0.0.2", ["198.51.100.9"], trusted), "198.51.100.9"
|
||||
)
|
||||
|
||||
def test_a_non_ip_peer_is_returned_as_is(self) -> None:
|
||||
self.assertEqual(client_address("testclient", ["198.51.100.9"], []), "testclient")
|
||||
|
||||
|
||||
class AttemptLimiterTests(unittest.TestCase):
|
||||
def test_window_and_limit(self) -> None:
|
||||
now = [1000.0]
|
||||
limiter = AttemptLimiter(60, 2, clock=lambda: now[0])
|
||||
self.assertTrue(limiter.allow("k"))
|
||||
self.assertTrue(limiter.allow("k"))
|
||||
self.assertFalse(limiter.allow("k"))
|
||||
self.assertTrue(limiter.allow("other"))
|
||||
now[0] += 60
|
||||
self.assertTrue(limiter.allow("k"))
|
||||
|
||||
def test_the_table_is_bounded(self) -> None:
|
||||
now = [0.0]
|
||||
limiter = AttemptLimiter(3600, 1, clock=lambda: now[0])
|
||||
for i in range(MAX_TRACKED_ATTEMPT_KEYS):
|
||||
limiter.allow(str(i))
|
||||
self.assertFalse(limiter.allow("new-key"))
|
||||
self.assertFalse(limiter.allow("0")) # a tracked key keeps its own count
|
||||
now[0] += 3600 # every window has ended, so stale keys are dropped to make room
|
||||
self.assertTrue(limiter.allow("new-key"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -13,6 +13,7 @@ from shared_backend.authclient import (
|
||||
InvalidSessionError,
|
||||
ManagedUser,
|
||||
PublicUser,
|
||||
forwarded_client_ip,
|
||||
resolve_user,
|
||||
token_from_request,
|
||||
)
|
||||
@@ -49,6 +50,37 @@ def _fake_http_error(status: int, payload: dict) -> urllib.error.HTTPError:
|
||||
)
|
||||
|
||||
|
||||
class AuthClientForwardedClientIpTests(unittest.IsolatedAsyncioTestCase):
|
||||
"""forwarded_client_ip makes credential calls carry the end user's address (S-009)."""
|
||||
|
||||
async def _login_request(self, address):
|
||||
client = AuthClient("https://authguard.example")
|
||||
payload = {"user": {"id": 1, "username": "a", "email": "", "role": "user"}}
|
||||
with patch(
|
||||
"shared_backend.authclient.urllib.request.urlopen",
|
||||
return_value=_FakeResponse(200, payload),
|
||||
) as urlopen:
|
||||
if address is None:
|
||||
await client.login("a", "secret-password")
|
||||
else:
|
||||
with forwarded_client_ip(address):
|
||||
await client.login("a", "secret-password")
|
||||
return urlopen.call_args.args[0]
|
||||
|
||||
async def test_the_address_is_sent_as_x_forwarded_for(self) -> None:
|
||||
request = await self._login_request("203.0.113.9")
|
||||
self.assertEqual(request.get_header("X-forwarded-for"), "203.0.113.9")
|
||||
|
||||
async def test_no_header_is_sent_outside_the_block(self) -> None:
|
||||
request = await self._login_request(None)
|
||||
self.assertIsNone(request.get_header("X-forwarded-for"))
|
||||
|
||||
async def test_a_value_that_is_not_an_ip_address_is_dropped(self) -> None:
|
||||
for value in ("203.0.113.9\r\nX-Evil: 1", "not-an-ip", ""):
|
||||
request = await self._login_request(value)
|
||||
self.assertIsNone(request.get_header("X-forwarded-for"), repr(value))
|
||||
|
||||
|
||||
class AuthClientBaseUrlTests(unittest.TestCase):
|
||||
def test_bare_public_host_assumes_https(self) -> None:
|
||||
self.assertEqual(AuthClient("auth.example.com").base_url, "https://auth.example.com")
|
||||
@@ -155,6 +187,57 @@ class AuthClientValidateTests(unittest.IsolatedAsyncioTestCase):
|
||||
await self.client.validate("a-token")
|
||||
|
||||
|
||||
class AuthClientValidationCacheTests(unittest.IsolatedAsyncioTestCase):
|
||||
def setUp(self) -> None:
|
||||
self.client = AuthClient("https://authguard.example")
|
||||
payload = {"valid": True, "user_id": 42, "username": "alice", "role": "admin"}
|
||||
self.valid = _FakeResponse(200, payload)
|
||||
|
||||
async def test_repeated_validate_reuses_the_answer(self) -> None:
|
||||
with patch(
|
||||
"shared_backend.authclient.urllib.request.urlopen", return_value=self.valid
|
||||
) as urlopen:
|
||||
first = await self.client.validate("a-token")
|
||||
second = await self.client.validate("a-token")
|
||||
|
||||
self.assertEqual(first, second)
|
||||
urlopen.assert_called_once()
|
||||
|
||||
async def test_invalid_session_is_cached_too(self) -> None:
|
||||
with patch(
|
||||
"shared_backend.authclient.urllib.request.urlopen",
|
||||
return_value=_FakeResponse(401, {"valid": False}),
|
||||
) as urlopen:
|
||||
with self.assertRaises(InvalidSessionError):
|
||||
await self.client.validate("bad-token")
|
||||
with self.assertRaises(InvalidSessionError):
|
||||
await self.client.validate("bad-token")
|
||||
|
||||
urlopen.assert_called_once()
|
||||
|
||||
async def test_logout_drops_the_cached_answer(self) -> None:
|
||||
with patch(
|
||||
"shared_backend.authclient.urllib.request.urlopen",
|
||||
side_effect=[self.valid, _FakeResponse(200, {}), _FakeResponse(401, {"valid": False})],
|
||||
) as urlopen:
|
||||
await self.client.validate("a-token")
|
||||
await self.client.logout("a-token")
|
||||
with self.assertRaises(InvalidSessionError):
|
||||
await self.client.validate("a-token")
|
||||
|
||||
self.assertEqual(urlopen.call_count, 3)
|
||||
|
||||
async def test_set_base_url_clears_the_cache(self) -> None:
|
||||
with patch(
|
||||
"shared_backend.authclient.urllib.request.urlopen", return_value=self.valid
|
||||
) as urlopen:
|
||||
await self.client.validate("a-token")
|
||||
self.client.set_base_url("https://authguard2.example")
|
||||
await self.client.validate("a-token")
|
||||
|
||||
self.assertEqual(urlopen.call_count, 2)
|
||||
|
||||
|
||||
class TokenFromRequestTests(unittest.TestCase):
|
||||
def test_prefers_authorization_header_over_cookie(self) -> None:
|
||||
headers = {"Authorization": "Bearer header-token"}
|
||||
|
||||
@@ -10,6 +10,7 @@ from shared_backend.authclient import (
|
||||
AuthClient,
|
||||
PublicUser,
|
||||
SessionResult,
|
||||
_forwarded_client_ip,
|
||||
)
|
||||
|
||||
|
||||
@@ -44,6 +45,8 @@ def _build_app(
|
||||
client: AuthClient | None = None,
|
||||
*,
|
||||
internal_secret: str | None = None,
|
||||
local_profile_without_authguard: bool = False,
|
||||
trusted_proxies: str = "",
|
||||
) -> FastAPI:
|
||||
def get_client(request: Request) -> AuthClient | None:
|
||||
return client
|
||||
@@ -53,15 +56,23 @@ def _build_app(
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(
|
||||
ap.build_auth_router(get_client, get_store, internal_secret=internal_secret),
|
||||
ap.build_auth_router(
|
||||
get_client,
|
||||
get_store,
|
||||
internal_secret=internal_secret,
|
||||
local_profile_without_authguard=local_profile_without_authguard,
|
||||
trusted_proxies=trusted_proxies,
|
||||
),
|
||||
prefix="/api/auth",
|
||||
)
|
||||
return app
|
||||
|
||||
|
||||
class AuthDisabledModeTests(unittest.TestCase):
|
||||
"""client=None (AUTHGUARD_URL unset) - every route reports the fixed
|
||||
placeholder superadmin identity and nothing is gated. This is also a
|
||||
"""client=None (AUTHGUARD_URL unset) with the local-mode opt-in - every
|
||||
route reports the fixed placeholder superadmin identity and nothing is
|
||||
gated. Without the opt-in the same deployment fails closed; see
|
||||
UnconfiguredAuthGuardTests. This is also a
|
||||
regression test for a real bug this module had: request/response models
|
||||
declared *inside* build_auth_router, combined with `from __future__
|
||||
import annotations`, made FastAPI silently misparse every JSON body as a
|
||||
@@ -69,7 +80,7 @@ class AuthDisabledModeTests(unittest.TestCase):
|
||||
bug)."""
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.client = TestClient(_build_app(_FakeStore()))
|
||||
self.client = TestClient(_build_app(_FakeStore(), local_profile_without_authguard=True))
|
||||
|
||||
def test_status_reports_local_superadmin(self) -> None:
|
||||
response = self.client.get("/api/auth/status")
|
||||
@@ -118,6 +129,25 @@ class AuthDisabledModeTests(unittest.TestCase):
|
||||
self.assertEqual(self.client.put("/api/auth/me", json={}).status_code, 409)
|
||||
|
||||
|
||||
class UnconfiguredAuthGuardTests(unittest.TestCase):
|
||||
"""client=None without local_profile_without_authguard: a missing
|
||||
AUTHGUARD_URL must not turn guarded routes into the local superadmin."""
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.client = TestClient(
|
||||
_build_app(_FakeStore(login_required=True)), raise_server_exceptions=False
|
||||
)
|
||||
|
||||
def test_guarded_routes_fail_closed(self) -> None:
|
||||
self.assertEqual(self.client.get("/api/auth/status").status_code, 500)
|
||||
self.assertEqual(self.client.get("/api/auth/me").status_code, 500)
|
||||
self.assertEqual(self.client.get("/api/auth/users").status_code, 500)
|
||||
self.assertEqual(self.client.post("/api/auth/logout").status_code, 500)
|
||||
|
||||
def test_login_flag_read_is_still_public(self) -> None:
|
||||
self.assertEqual(self.client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||
|
||||
|
||||
class AccessSettingsTests(unittest.TestCase):
|
||||
def test_get_is_public_and_put_requires_an_admin_session(self) -> None:
|
||||
store = _FakeStore(login_required=True)
|
||||
@@ -142,7 +172,7 @@ class AccessSettingsTests(unittest.TestCase):
|
||||
store = _FakeStore(login_required=True)
|
||||
client = TestClient(_build_app(store))
|
||||
response = client.put("/api/auth/access", json={"loginRequired": False})
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertEqual(response.status_code, 500)
|
||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||
|
||||
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
|
||||
@@ -275,12 +305,142 @@ class EnabledModeSetupAndLoginTests(unittest.TestCase):
|
||||
self.assertIsNone(body["user"])
|
||||
|
||||
|
||||
class _AddressRecordingClient(_RoleClient):
|
||||
"""Records the address AuthClient would send as X-Forwarded-For for each credential call, and
|
||||
counts the calls that reached AuthGuard."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.forwarded: list[str | None] = []
|
||||
self.login_calls = 0
|
||||
self.totp_calls = 0
|
||||
|
||||
async def login(self, username_or_email: str, password: str, totp_token: str = ""):
|
||||
self.login_calls += 1
|
||||
self.forwarded.append(_forwarded_client_ip.get())
|
||||
return await super().login(username_or_email, password, totp_token)
|
||||
|
||||
async def register(self, username: str, email: str, password: str) -> SessionResult:
|
||||
self.forwarded.append(_forwarded_client_ip.get())
|
||||
return await super().register(username, email, password)
|
||||
|
||||
async def totp_verify(self, token: str, code: str) -> None:
|
||||
self.totp_calls += 1
|
||||
self.forwarded.append(_forwarded_client_ip.get())
|
||||
if code != "123456":
|
||||
raise APIError(401, "bad code")
|
||||
|
||||
async def totp_disable(self, token: str, code: str) -> None:
|
||||
self.totp_calls += 1
|
||||
self.forwarded.append(_forwarded_client_ip.get())
|
||||
raise APIError(401, "bad code")
|
||||
|
||||
|
||||
class AttemptLimitTests(unittest.TestCase):
|
||||
"""Login and the TOTP routes refuse further attempts with 429 (S-009)."""
|
||||
|
||||
def _login(self, client: TestClient, identifier: str = "Victim") -> int:
|
||||
response = client.post(
|
||||
"/api/auth/login", json={"identifier": identifier, "password": "wrong"}
|
||||
)
|
||||
return response.status_code
|
||||
|
||||
def test_login_is_limited_per_account_before_authguard_is_called(self) -> None:
|
||||
fake = _AddressRecordingClient()
|
||||
client = TestClient(_build_app(_FakeStore(), fake))
|
||||
for attempt in range(ap.LOGIN_ACCOUNT_LIMIT):
|
||||
self.assertEqual(self._login(client), 401, f"attempt {attempt + 1}")
|
||||
self.assertEqual(self._login(client), 429)
|
||||
self.assertEqual(self._login(client, "VICTIM"), 429) # the account key ignores case
|
||||
self.assertEqual(fake.login_calls, ap.LOGIN_ACCOUNT_LIMIT)
|
||||
self.assertEqual(self._login(client, "someone-else"), 401)
|
||||
|
||||
def test_login_is_limited_per_client_address(self) -> None:
|
||||
fake = _AddressRecordingClient()
|
||||
client = TestClient(_build_app(_FakeStore(), fake), client=("203.0.113.7", 40000))
|
||||
statuses = [self._login(client, f"user{i}") for i in range(ap.LOGIN_CLIENT_LIMIT + 1)]
|
||||
self.assertEqual(statuses[:-1], [401] * ap.LOGIN_CLIENT_LIMIT)
|
||||
self.assertEqual(statuses[-1], 429)
|
||||
|
||||
def test_totp_verify_and_disable_share_a_per_user_limit(self) -> None:
|
||||
fake = _AddressRecordingClient()
|
||||
client = TestClient(_build_app(_FakeStore(), fake))
|
||||
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
|
||||
for _ in range(ap.TOTP_ATTEMPT_LIMIT - 1):
|
||||
response = client.post("/api/auth/totp/verify", json={"totpToken": "000000"})
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertEqual(
|
||||
client.post("/api/auth/totp/disable", json={"totpToken": "000000"}).status_code, 401
|
||||
)
|
||||
self.assertEqual(
|
||||
client.post("/api/auth/totp/verify", json={"totpToken": "123456"}).status_code, 429
|
||||
)
|
||||
self.assertEqual(
|
||||
client.post("/api/auth/totp/disable", json={"totpToken": "000000"}).status_code, 429
|
||||
)
|
||||
self.assertEqual(fake.totp_calls, ap.TOTP_ATTEMPT_LIMIT)
|
||||
|
||||
|
||||
class ClientAddressForwardingTests(unittest.TestCase):
|
||||
"""The client address is the TCP peer unless the peer is a trusted proxy (decision 5), and it
|
||||
reaches AuthGuard as X-Forwarded-For through forwarded_client_ip."""
|
||||
|
||||
def _login_address(self, *, peer: str, trusted: str, forwarded: str | None) -> str | None:
|
||||
fake = _AddressRecordingClient()
|
||||
client = TestClient(
|
||||
_build_app(_FakeStore(), fake, trusted_proxies=trusted), client=(peer, 40000)
|
||||
)
|
||||
headers = {"X-Forwarded-For": forwarded} if forwarded is not None else {}
|
||||
response = client.post(
|
||||
"/api/auth/login",
|
||||
json={"identifier": "a@b.com", "password": "correct"},
|
||||
headers=headers,
|
||||
)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
return fake.forwarded[-1]
|
||||
|
||||
def test_the_tcp_peer_is_forwarded_without_trusted_proxies(self) -> None:
|
||||
got = self._login_address(peer="203.0.113.7", trusted="", forwarded="6.6.6.6")
|
||||
self.assertEqual(got, "203.0.113.7")
|
||||
|
||||
def test_a_spoofed_header_from_an_untrusted_peer_is_ignored(self) -> None:
|
||||
got = self._login_address(peer="203.0.113.7", trusted="10.0.0.0/8", forwarded="6.6.6.6")
|
||||
self.assertEqual(got, "203.0.113.7")
|
||||
|
||||
def test_a_trusted_peer_has_its_header_walked_right_to_left(self) -> None:
|
||||
got = self._login_address(
|
||||
peer="10.0.0.2", trusted="10.0.0.0/8", forwarded="6.6.6.6, 198.51.100.9, 10.0.0.1"
|
||||
)
|
||||
self.assertEqual(got, "198.51.100.9")
|
||||
|
||||
def test_setup_and_totp_forward_the_address_too(self) -> None:
|
||||
fake = _AddressRecordingClient()
|
||||
fake.setup_required = True
|
||||
client = TestClient(_build_app(_FakeStore(), fake), client=("198.51.100.20", 40000))
|
||||
client.post(
|
||||
"/api/auth/setup",
|
||||
json={"username": "admin", "email": "admin@example.com", "password": "password123"},
|
||||
)
|
||||
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
|
||||
client.post("/api/auth/totp/verify", json={"totpToken": "123456"})
|
||||
client.post("/api/auth/totp/disable", json={"totpToken": "123456"})
|
||||
self.assertEqual(fake.forwarded, ["198.51.100.20"] * 3)
|
||||
|
||||
def test_the_forwarded_address_does_not_leak_outside_the_call(self) -> None:
|
||||
self._login_address(peer="203.0.113.7", trusted="", forwarded=None)
|
||||
self.assertIsNone(_forwarded_client_ip.get())
|
||||
|
||||
def test_an_invalid_trusted_proxy_list_fails_at_startup(self) -> None:
|
||||
with self.assertRaises(ValueError):
|
||||
_build_app(_FakeStore(), trusted_proxies="10.0.0.0/8, not-an-ip")
|
||||
|
||||
|
||||
class RequestValidationTests(unittest.TestCase):
|
||||
"""Every JSON-body route must actually parse its body (see the docstring
|
||||
on AuthDisabledModeTests for the regression this guards against)."""
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.client = TestClient(_build_app(_FakeStore()))
|
||||
self.client = TestClient(_build_app(_FakeStore(), local_profile_without_authguard=True))
|
||||
|
||||
def test_setup_rejects_missing_fields_with_422_not_500(self) -> None:
|
||||
response = self.client.post("/api/auth/setup", json={})
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import json
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from shared_backend.auth import (
|
||||
hash_password,
|
||||
password_hash_needs_upgrade,
|
||||
verify_and_upgrade_password,
|
||||
verify_password,
|
||||
)
|
||||
from shared_backend.clientip import client_address, parse_trusted_proxies
|
||||
from shared_backend.totp import verify_totp
|
||||
|
||||
# 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"
|
||||
|
||||
|
||||
@unittest.skipUnless(
|
||||
CONTRACT_PATH.exists(), "contract/auth-contract.json is not part of this checkout"
|
||||
)
|
||||
class AuthContractTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls.contract = json.loads(CONTRACT_PATH.read_text(encoding="utf-8"))
|
||||
|
||||
def test_password_hashes_verify_as_the_contract_says_for_python(self) -> None:
|
||||
password = self.contract["password"]
|
||||
for entry in password["hashes"]:
|
||||
with self.subTest(entry["name"]):
|
||||
self.assertEqual(
|
||||
verify_password(password["plaintext"], entry["hash"]),
|
||||
entry["verifies"]["python"],
|
||||
)
|
||||
self.assertFalse(verify_password(password["wrongPassword"], 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"]
|
||||
)
|
||||
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))
|
||||
|
||||
def test_the_password_length_contract_holds_for_python(self) -> None:
|
||||
too_long = self.contract["password"]["tooLongToHash"]
|
||||
try:
|
||||
hash_password("a" * too_long["bytes"])
|
||||
accepted = True
|
||||
except ValueError:
|
||||
accepted = False
|
||||
self.assertEqual(accepted, too_long["accepted"]["python"])
|
||||
|
||||
def test_totp_verifies_as_the_contract_says(self) -> None:
|
||||
totp = self.contract["totp"]
|
||||
for entry in totp["cases"]:
|
||||
with self.subTest(entry["name"]):
|
||||
secret = entry.get("secret", totp["secret"])
|
||||
self.assertEqual(verify_totp(secret, entry["code"], entry["unix"]), entry["valid"])
|
||||
|
||||
def test_client_address_follows_the_contract(self) -> None:
|
||||
section = self.contract["clientAddress"]
|
||||
for entry in section["cases"]:
|
||||
with self.subTest(entry["name"]):
|
||||
trusted = parse_trusted_proxies(entry["trusted"])
|
||||
self.assertEqual(
|
||||
client_address(entry["peer"], entry["forwarded"], trusted), entry["want"]
|
||||
)
|
||||
for value in section["invalidTrustedProxyLists"]:
|
||||
with self.subTest(value), self.assertRaises(ValueError):
|
||||
parse_trusted_proxies(value)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,9 +1,26 @@
|
||||
import asyncio
|
||||
import os
|
||||
import unittest
|
||||
from datetime import timedelta
|
||||
|
||||
from shared_backend.auth import ResetManager, hash_password, verify_password
|
||||
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
|
||||
|
||||
@@ -14,6 +31,95 @@ class SharedBackendTests(unittest.TestCase):
|
||||
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)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import unittest
|
||||
|
||||
from shared_backend.coreconfig import Info, Store
|
||||
from shared_backend.coreconfig import Info, Store, internal_secret_matches
|
||||
|
||||
|
||||
class StoreDefaultsTests(unittest.TestCase):
|
||||
@@ -62,5 +62,29 @@ class StoreSetTests(unittest.TestCase):
|
||||
self.assertEqual(info.to_json()["carrierNodeUrl"], "http://carrier.example.com")
|
||||
|
||||
|
||||
class InternalSecretTests(unittest.TestCase):
|
||||
def test_unset_or_empty_secret_never_matches(self):
|
||||
self.assertFalse(internal_secret_matches(None, None))
|
||||
self.assertFalse(internal_secret_matches(None, ""))
|
||||
self.assertFalse(internal_secret_matches("", ""))
|
||||
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"))
|
||||
|
||||
|
||||
class UrlValidationTests(unittest.TestCase):
|
||||
def test_rejects_urls_that_are_not_http_or_https_with_a_host(self):
|
||||
store = Store(Info(auth_guard_url="http://auth.example.com"))
|
||||
for bad in ["javascript:alert(1)", "auth.example.com", "ftp://carrier.example.com", "http://"]:
|
||||
with self.subTest(url=bad), self.assertRaises(ValueError):
|
||||
store.set(Info(auth_guard_url=bad))
|
||||
with self.assertRaises(ValueError):
|
||||
store.set(Info(carrier_node_urls=["http://carrier.example.com:99999"]))
|
||||
self.assertEqual(store.auth_guard_url, "http://auth.example.com")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,120 @@
|
||||
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:
|
||||
return {"secret": "S", "enabled": self.totp_enabled}
|
||||
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)
|
||||
|
||||
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")
|
||||
|
||||
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()
|
||||
Reference in new issue
Block a user