# SPDX-License-Identifier: AGPL-3.0-or-later """Sicherheitsbausteine ohne Datenbank.""" from __future__ import annotations import base64 from ipaddress import ip_network import pytest from surveybox.security import csrf, recovery, totp from surveybox.security.client_ip import client_ip, ip_key from surveybox.security.headers import security_headers from surveybox.security.tokens import derive_key, new_token, token_hash # --- TOTP: Testvektoren aus RFC 6238, Anhang B (SHA-1, letzte 6 Ziffern) ------- RFC_SECRET = base64.b32encode(b"12345678901234567890").decode().rstrip("=") @pytest.mark.parametrize( ("unix_time", "expected"), [(59, "287082"), (1111111109, "081804"), (1111111111, "050471"), (1234567890, "005924"), (2000000000, "279037"), (20000000000, "353130")], ) def test_totp_rfc6238_vectors(unix_time: int, expected: str) -> None: assert totp.code_at_step(RFC_SECRET, totp.current_step(unix_time)) == expected def test_totp_accepts_neighbour_steps_and_rejects_replay() -> None: secret = totp.generate_secret() t = 1_700_000_000 step = totp.current_step(t) previous = totp.code_at_step(secret, step - 1) assert totp.verify(secret, previous, t, None) == step - 1 assert totp.verify(secret, previous, t, last_step=step - 1) is None # schon benutzt far = totp.code_at_step(secret, step - 3) assert totp.verify(secret, far, t, None) is None def test_totp_normalizes_input() -> None: secret = totp.generate_secret() t = 1_700_000_000 code = totp.code_at_step(secret, totp.current_step(t)) assert totp.verify(secret, f"{code[:3]} {code[3:]}", t, None) is not None assert totp.verify(secret, "12345", t, None) is None def test_provisioning_uri_is_escaped() -> None: uri = totp.provisioning_uri("ABC", "a b@example.de", "Survey box") assert uri.startswith("otpauth://totp/Survey%20box%3Aa%20b%40example.de?") assert "issuer=Survey%20box" in uri # --- CSRF --------------------------------------------------------------------- def test_csrf_token_roundtrip() -> None: cookie = new_token(24) token = csrf.form_token("k" * 40, cookie) assert csrf.token_valid("k" * 40, cookie, token) assert not csrf.token_valid("k" * 40, new_token(24), token) assert not csrf.token_valid("x" * 40, cookie, token) assert not csrf.token_valid("k" * 40, None, token) assert not csrf.token_valid("k" * 40, cookie, None) @pytest.mark.parametrize( ("origin", "referer", "ok"), [ ("https://umfrage.example", None, True), ("https://UMFRAGE.example", None, True), ("https://evil.example", None, False), ("null", "https://umfrage.example/login", True), (None, "https://umfrage.example/account?x=1", True), (None, "https://umfrage.example.evil.example/", False), (None, None, False), ("http://umfrage.example", None, False), ], ) def test_origin_check(origin: str | None, referer: str | None, ok: bool) -> None: assert csrf.origin_allowed("https://umfrage.example", origin, referer) is ok # --- Header ------------------------------------------------------------------- def test_security_headers() -> None: h = security_headers(https=True) assert "script-src 'self'" in h["Content-Security-Policy"] assert "unsafe-inline" not in h["Content-Security-Policy"] assert "frame-ancestors 'none'" in h["Content-Security-Policy"] assert h["Strict-Transport-Security"].startswith("max-age=") assert "Strict-Transport-Security" not in security_headers(https=False) # Mit "no-referrer" schicken Browser bei Formularen "Origin: null"; dann # scheitert jede Anmeldung an der CSRF-Prüfung (Fehler in Phase 2a). assert h["Referrer-Policy"] == "same-origin" assert h["X-Frame-Options"] == "DENY" def test_frame_ancestors_allow_embedding() -> None: h = security_headers(https=True, frame_ancestors="'self' https://cloud.example.de") assert "frame-ancestors 'self' https://cloud.example.de" in h["Content-Security-Policy"] # X-Frame-Options kennt nur eine Adresse und würde den Rahmen verbieten assert "X-Frame-Options" not in h # --- Client-IP ---------------------------------------------------------------- PROXIES = [ip_network("172.30.40.0/24"), ip_network("10.0.0.5/32")] @pytest.mark.parametrize( ("peer", "xff", "expected"), [ ("203.0.113.9", None, "203.0.113.9"), ("203.0.113.9", "1.2.3.4", "203.0.113.9"), # kein vertrauter Proxy: Header ignorieren ("172.30.40.1", "198.51.100.7", "198.51.100.7"), ("172.30.40.1", "6.6.6.6, 198.51.100.7", "198.51.100.7"), # gefälschter Eintrag links ("172.30.40.1", "198.51.100.7, 10.0.0.5", "198.51.100.7"), # Proxykette ("172.30.40.1", "kaputt", "172.30.40.1"), (None, None, "unknown"), ], ) def test_client_ip(peer: str | None, xff: str | None, expected: str) -> None: assert client_ip(peer, xff, PROXIES) == expected def test_ip_key_is_pseudonymous() -> None: key = ip_key("s" * 40, "198.51.100.7") assert "198" not in key and len(key) == 32 assert key == ip_key("s" * 40, "198.51.100.7") assert key != ip_key("t" * 40, "198.51.100.7") # --- Tokens, Schlüssel, Wiederherstellungscodes ------------------------------- def test_derived_keys_differ_by_purpose() -> None: a = derive_key("s" * 40, "csrf") assert len(a) == 32 assert a != derive_key("s" * 40, "totp") assert a == derive_key("s" * 40, "csrf") assert len(derive_key("s" * 40, "x", length=80)) == 80 def test_token_hash_is_stable() -> None: t = new_token() assert len(t) >= 40 assert token_hash(t) == token_hash(t) and len(token_hash(t)) == 32 def test_recovery_codes() -> None: codes = recovery.generate_codes() assert len(codes) == 10 and len(set(codes)) == 10 assert all(len(c) == 14 and c.count("-") == 2 for c in codes) code = codes[0] h = recovery.code_hash("s" * 40, code) assert recovery.code_hash("s" * 40, code.lower().replace("-", " ")) == h assert recovery.code_hash("s" * 40, codes[1]) != h def test_secretbox_roundtrip_and_context() -> None: pytest.importorskip("cryptography") from surveybox.security import secretbox blob = secretbox.encrypt("s" * 40, "totp", b"GEHEIM", b"user:1") assert b"GEHEIM" not in blob assert secretbox.decrypt("s" * 40, "totp", blob, b"user:1") == b"GEHEIM" with pytest.raises(secretbox.DecryptionError): secretbox.decrypt("s" * 40, "totp", blob, b"user:2") # anderes Konto with pytest.raises(secretbox.DecryptionError): secretbox.decrypt("t" * 40, "totp", blob, b"user:1") # anderer Schlüssel def test_password_rules() -> None: pytest.importorskip("argon2") from surveybox.security import passwords assert passwords.password_problems("kurz") == ["too_short"] assert "equals_email" in passwords.password_problems("anna@example.de", "Anna@Example.de") assert "too_simple" in passwords.password_problems("aaaaaaaaaaaaaaa") assert passwords.password_problems("ein langer satz mit wörtern") == [] h = passwords.hash_password("ein langer satz mit wörtern") assert h.startswith("$argon2id$") assert passwords.verify_password(h, "ein langer satz mit wörtern") == (True, False) assert passwords.verify_password(h, "falsch")[0] is False assert passwords.verify_password(None, "egal") == (False, False)