# SPDX-License-Identifier: AGPL-3.0-or-later """Gemeinsame Hilfen für die Web-Tests gegen PostgreSQL.""" from __future__ import annotations import base64 import hashlib import json import os import re import struct import time from typing import Any from fastapi.testclient import TestClient from sqlalchemy.orm import Session from surveybox import db from surveybox.accounts import service from surveybox.models import Role, UserAccount from surveybox.security import totp from surveybox.settings import get_settings PASSWORD = "ein langer und sicherer satz" ORIGIN = "http://localhost" RP_ID = "localhost" def new_client(app: Any) -> TestClient: return TestClient( app, base_url=ORIGIN, headers={"Origin": ORIGIN, "Accept-Language": "en"}, follow_redirects=False, ) def csrf_from(html: str) -> str: match = re.search(r'name="csrf_token" value="([0-9a-f]+)"', html) assert match, "kein CSRF-Feld auf der Seite" return match.group(1) def token_for(client: TestClient, path: str) -> str: resp = client.get(path) assert resp.status_code == 200, resp.text return csrf_from(resp.text) def make_user( role: Role = Role.PARTICIPANT, email: str = "anna@example.de", with_totp: bool = False ) -> tuple[UserAccount, str | None]: settings = get_settings() with Session(db.get_engine()) as s: user = service.create_user(s, email, "Anna", role, None) service.set_password(s, user, PASSWORD) secret = None if with_totp: secret = totp.generate_secret() code = totp.code_at_step(secret, totp.current_step(time.time())) service.enable_totp(s, settings, user, secret, code) s.commit() s.refresh(user) s.expunge(user) return user, secret def next_totp(secret: str) -> str: return totp.code_at_step(secret, totp.current_step(time.time()) + 1) def login(client: TestClient, email: str, password: str = PASSWORD) -> Any: token = token_for(client, "/login") return client.post( "/login", data={"email": email, "password": password, "csrf_token": token, "next": "/"} ) def post_json(client: TestClient, path: str, body: dict[str, Any], csrf: str) -> Any: return client.post(path, json=body, headers={"X-CSRF-Token": csrf}) # --------------------------------------------------------------------------- # Software-Authenticator: erzeugt Passkey-Antworten wie ein Browser # --------------------------------------------------------------------------- def b64u(data: bytes) -> str: return base64.urlsafe_b64encode(data).rstrip(b"=").decode() def unb64u(value: str) -> bytes: return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) class SoftAuthenticator: """ES256-Passkey mit Benutzerprüfung, Attestation "none".""" def __init__(self, rp_id: str = RP_ID, origin: str = ORIGIN) -> None: from cryptography.hazmat.primitives.asymmetric import ec self.rp_id = rp_id self.origin = origin self.key = ec.generate_private_key(ec.SECP256R1()) self.credential_id = os.urandom(32) self.user_handle: bytes | None = None self.counter = 0 def _rp_hash(self) -> bytes: return hashlib.sha256(self.rp_id.encode()).digest() def _cose_key(self) -> bytes: import cbor2 numbers = self.key.public_key().public_numbers() return cbor2.dumps( {1: 2, 3: -7, -1: 1, -2: numbers.x.to_bytes(32, "big"), -3: numbers.y.to_bytes(32, "big")} ) def _client_data(self, kind: str, challenge: str) -> bytes: return json.dumps( {"type": kind, "challenge": challenge, "origin": self.origin, "crossOrigin": False} ).encode() def create(self, options: dict[str, Any]) -> dict[str, Any]: import cbor2 self.user_handle = unb64u(options["user"]["id"]) client_data = self._client_data("webauthn.create", options["challenge"]) flags = 0x01 | 0x04 | 0x40 # Anwesenheit, Benutzerprüfung, Schlüsseldaten auth_data = ( self._rp_hash() + bytes([flags]) + struct.pack(">I", 0) + b"\x00" * 16 + struct.pack(">H", len(self.credential_id)) + self.credential_id + self._cose_key() ) attestation = cbor2.dumps({"fmt": "none", "attStmt": {}, "authData": auth_data}) return { "id": b64u(self.credential_id), "rawId": b64u(self.credential_id), "type": "public-key", "response": { "clientDataJSON": b64u(client_data), "attestationObject": b64u(attestation), "transports": ["internal"], }, "clientExtensionResults": {}, } def get(self, options: dict[str, Any]) -> dict[str, Any]: from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import ec client_data = self._client_data("webauthn.get", options["challenge"]) self.counter += 1 auth_data = self._rp_hash() + bytes([0x01 | 0x04]) + struct.pack(">I", self.counter) signature = self.key.sign( auth_data + hashlib.sha256(client_data).digest(), ec.ECDSA(hashes.SHA256()) ) return { "id": b64u(self.credential_id), "rawId": b64u(self.credential_id), "type": "public-key", "response": { "clientDataJSON": b64u(client_data), "authenticatorData": b64u(auth_data), "signature": b64u(signature), "userHandle": b64u(self.user_handle) if self.user_handle else None, }, "clientExtensionResults": {}, }