Repository Public
1# =============================================================================2# SP BOUCHER | INFRASTRUCTURE & AUTOMATION3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : MacLustr Identity7# File : tests/test_platform.py8# Description : Tests de bout en bout de la plateforme : vrai PostgreSQL,9# vrais moteurs, documents fictifs.10# Module : tests11# Repository : https://git.spboucher.ai/maclustr-identity12# Project Website : https://identity.spboucher.ai13# Created : 2026-12-0114# Last Modified : 2026-12-0115#16# Author : Simon-Pierre Boucher17# Position : Professor of Finance18# Institution : Université du Québec en Outaouais (UQO)19# Organization : SP Boucher20# Website : https://spboucher.ai21# Git : https://git.spboucher.ai22#23# Preferred Contact: admin@spboucher.ai24# Technical Contact: dev@spboucher.ai25# Security/Admin : admin@spboucher.ai26#27# Copyright (c) 202628# Simon-Pierre Boucher29# All rights reserved where applicable. This file is governed by the30# applicable project license, copyright notices and relevant law.31# Existing third-party rights and notices remain unaffected.32#33# License : None specified (no license file in this repository)34#35# Do not embed credentials, private keys, access tokens,36# certificates or confidential personal information.37#38# =============================================================================39# END OF SP BOUCHER SOURCE HEADER40# =============================================================================4142"""Tests de bout en bout de la plateforme : vrai PostgreSQL, vrais moteurs, documents fictifs."""43import hashlib44import hmac45import json46import os47import threading48from http.server import BaseHTTPRequestHandler, HTTPServer49import pytest50from services.mlid import audit, db, privacy, webhooks51from services.mlid.config import settings52from services.mlid.engines import pipeline53from conftest import FX545556def new_session(client, ctx, live=False, **body):57 r = client.post("/v1/verification-sessions", headers=ctx.h(live), json={"external_user_id": "user_1", "purpose": "account_verification", **body})58 assert r.status_code == 200, r.text59 return r.json()606162def fh(s):63 return {"Authorization": "Bearer " + s["client_secret"]}646566def consent(client, s, method):67 r = client.post(f"/v1/sessions/{s['id']}/consent", headers=fh(s), json={"method": method, "accepted": True, "biometric_consent": True, "text_version": privacy.CONSENT_VERSION})68 assert r.status_code == 200, r.text69 return r.json()707172def run_worker(internal, token):73 h = {"Authorization": "Bearer " + token}74 job = internal.post("/internal/v1/lease", headers=h, json={"metrics": {"load_per_core": 0.1, "busy": 0}, "capabilities": pipeline.capabilities(), "models": {}}).json()["job"]75 assert job, "aucun travail en file"76 assert "app_id" not in json.dumps(job) and "user_1" not in json.dumps(job)77 result, timings = pipeline.run(job, lambda aid: internal.get(f"/internal/v1/jobs/{job['id']}/artifacts/{aid}", headers=h).content)78 r = internal.post(f"/internal/v1/jobs/{job['id']}/result", headers=h, json={"result": result, "timings": timings})79 assert r.status_code == 200, r.text80 return result, timings, r.json()818283def upload(client, s, side, name):84 return client.post(f"/v1/sessions/{s['id']}/document", headers=fh(s), data={"side": side}, files={"file": (name, (FX / name).read_bytes(), "image/jpeg")})858687# ---------------------------------------------------------------- authentification, erreurs, isolation8889def test_health_and_openapi(client):90 assert client.get("/health").json()["status"] == "ok"91 assert client.get("/health/ready").json()["live_biometric"] is False92 spec = client.get("/api/v1/openapi.json").json()93 for p in ("/v1/verification-sessions", "/v1/verifications/{vid}/personal-data", "/v1/webhooks", "/v1/sessions/{sid}/consent"):94 assert p in spec["paths"]959697def test_auth_errors(client, app_a):98 r = client.get("/v1/verification-sessions")99 assert r.status_code == 401 and r.json()["error"]["code"] == "missing_api_key" and r.json()["error"]["request_id"]100 assert client.get("/v1/verification-sessions", headers={"Authorization": "Bearer mlid_sk_test_nope"}).status_code == 401101 assert client.get("/api/v1/verification-sessions", headers=app_a.h()).status_code == 200102103104def test_live_blocked_by_compliance_gate(client, app_a):105 r = client.post("/v1/verification-sessions", headers=app_a.h(live=True), json={"purpose": "x"})106 assert r.status_code == 403 and r.json()["error"]["code"] == "compliance_gate_closed"107108109def test_isolation_between_apps(client, app_a, app_b):110 s = new_session(client, app_a)111 assert client.get(f"/v1/verification-sessions/{s['id']}", headers=app_a.h()).status_code == 200112 assert client.get(f"/v1/verification-sessions/{s['id']}", headers=app_b.h()).status_code == 404113 assert client.post(f"/v1/verification-sessions/{s['id']}/cancel", headers=app_b.h()).status_code == 404114 assert client.get(f"/v1/verification-sessions/{s['id']}", headers=app_a.h(live=True)).status_code == 404 # cloison test / réel115 assert s["id"] not in json.dumps(client.get("/v1/verification-sessions", headers=app_b.h()).json())116117118def test_idempotency(client, app_a):119 h = {**app_a.h(), "Idempotency-Key": "k-1"}120 a = client.post("/v1/verification-sessions", headers=h, json={"purpose": "p", "external_user_id": "u9"})121 b = client.post("/v1/verification-sessions", headers=h, json={"purpose": "p", "external_user_id": "u9"})122 assert a.json()["id"] == b.json()["id"] and b.headers.get("Idempotent-Replayed") == "true"123 c = client.post("/v1/verification-sessions", headers=h, json={"purpose": "other"})124 assert c.status_code == 409 and c.json()["error"]["code"] == "idempotency_key_reused"125126127def test_scopes_and_key_rotation(client, app_a):128 from services.mlid import registry129 k, secret = registry.create_key(app_a.id, livemode=False, scopes=["sessions:read"])130 h = {"Authorization": "Bearer " + secret}131 assert client.get("/v1/verification-sessions", headers=h).status_code == 200132 assert client.post("/v1/verification-sessions", headers=h, json={"purpose": "p"}).json()["error"]["code"] == "insufficient_scope"133 k2, secret2 = registry.roll_key(app_a.id, k["id"], actor="test", grace_hours=0)134 assert client.get("/v1/verification-sessions", headers=h).status_code == 401135 assert client.get("/v1/verification-sessions", headers={"Authorization": "Bearer " + secret2}).status_code == 200136137138def test_return_url_must_be_allowed(client, app_b):139 from services.mlid import registry140 registry.update_app(app_b.id, {"redirect_urls": ["https://b.example/verified"]}, actor="test")141 assert client.post("/v1/verification-sessions", headers=app_b.h(), json={"purpose": "p", "return_url": "https://evil.example/x"}).json()["error"]["code"] == "return_url_not_allowed"142 assert client.post("/v1/verification-sessions", headers=app_b.h(), json={"purpose": "p", "return_url": "https://b.example/verified?x=1"}).status_code == 200143144145# ---------------------------------------------------------------- bac à sable et webhooks146147class _Hook(BaseHTTPRequestHandler):148 got: list = []149 fail_first = 0150151 def do_POST(self):152 body = self.rfile.read(int(self.headers["Content-Length"]))153 if _Hook.fail_first > 0:154 _Hook.fail_first -= 1155 self.send_response(500); self.end_headers(); return156 _Hook.got.append((dict(self.headers), body))157 self.send_response(200); self.end_headers()158159 def log_message(self, *a):160 pass161162163@pytest.fixture(scope="module")164def hook_server():165 srv = HTTPServer(("127.0.0.1", 0), _Hook)166 threading.Thread(target=srv.serve_forever, daemon=True).start()167 yield f"http://127.0.0.1:{srv.server_address[1]}/hook"168 srv.shutdown()169170171def test_sandbox_flow_with_signed_webhooks(client, app_a, hook_server):172 wh = client.post("/v1/webhooks", headers=app_a.h(), json={"url": hook_server, "events": ["*"]}).json()173 secret = wh["secret"]174 assert secret.startswith("whsec_") and "secret" not in client.get("/v1/webhooks", headers=app_a.h()).json()["data"][0]175 s = new_session(client, app_a)176 assert s["url"].endswith("#" + s["client_secret"])177 st = client.get(f"/v1/sessions/{s['id']}", headers=fh(s)).json()178 assert st["sandbox"] and {m["id"] for m in st["methods"]} == {"document_selfie", "document_review"}179 assert client.get(f"/v1/sessions/{s['id']}", headers={"Authorization": "Bearer vsc_wrong"}).status_code == 401180 # consentement biométrique exprès exigé181 r = client.post(f"/v1/sessions/{s['id']}/consent", headers=fh(s), json={"method": "document_selfie", "accepted": True, "text_version": privacy.CONSENT_VERSION})182 assert r.json()["error"]["code"] == "biometric_consent_required"183 consent(client, s, "document_selfie")184 # le bac à sable refuse toute image185 assert upload(client, s, "front", "passport_scene.jpg").json()["error"]["code"] == "sandbox_no_real_documents"186 _Hook.got.clear(); _Hook.fail_first = 1187 out = client.post(f"/v1/sessions/{s['id']}/sandbox", headers=fh(s), json={"scenario": "verified"}).json()188 assert out["status"] == "verified"189 sess = client.get(f"/v1/verification-sessions/{s['id']}", headers=app_a.h()).json()190 v = client.get(f"/v1/verifications/{sess['verification_id']}", headers=app_a.h()).json()191 assert v["status"] == "verified" and v["simulated"] is True and v["assurance_level"] == "sandbox_simulated" and v["livemode"] is False192 assert client.get(f"/v1/verifications/{v['verification_id']}/status", headers=app_a.h()).json()["valid"] is True193 # livraison : premier essai en échec (500), reprise après le délai194 while webhooks.dispatch_once():195 pass196 assert db.one("select count(*) n from webhook_delivery where state='pending' and attempts=1")["n"] == 1197 db.q("update webhook_delivery set next_attempt_at=now() where state='pending'")198 while webhooks.dispatch_once():199 pass200 types = [json.loads(b)["type"] for _, b in _Hook.got]201 assert set(types) >= {"verification.created", "verification.processing", "verification.completed", "verification.verified"}202 headers, body = _Hook.got[0]203 assert webhooks.verify_signature(secret, headers["MLID-Signature"], body)204 assert not webhooks.verify_signature(secret, headers["MLID-Signature"], body + b" ")205 assert not webhooks.verify_signature("whsec_other", headers["MLID-Signature"], body)206 assert headers["MLID-Event-Id"].startswith("evt_") and len({h["MLID-Delivery-Id"] for h, _ in _Hook.got}) == len(_Hook.got)207 # rotation : les deux secrets signent pendant le chevauchement208 new_secret = client.post(f"/v1/webhooks/{wh['id']}/rotate-secret", headers=app_a.h()).json()["secret"]209 _Hook.got.clear()210 r = client.post(f"/v1/verifications/{v['verification_id']}/revoke", headers=app_a.h(), json={"reason": "test"})211 assert r.json()["status"] == "revoked"212 while webhooks.dispatch_once():213 pass214 headers, body = _Hook.got[-1]215 assert json.loads(body)["type"] == "verification.revoked"216 assert webhooks.verify_signature(secret, headers["MLID-Signature"], body) and webhooks.verify_signature(new_secret, headers["MLID-Signature"], body)217 client.delete(f"/v1/webhooks/{wh['id']}", headers=app_a.h())218219220def test_webhook_ssrf_guard(client, app_a, monkeypatch):221 monkeypatch.setattr(settings, "allow_private_webhooks", False)222 for url in ("http://example.com/h", "https://127.0.0.1/h", "https://10.67.0.1/h", "https://169.254.169.254/latest", "https://user:pw@example.com/h"):223 assert client.post("/v1/webhooks", headers=app_a.h(), json={"url": url}).json()["error"]["code"] == "invalid_webhook_url", url224225226# ---------------------------------------------------------------- mode réel : vrais moteurs sur documents fictifs227228def test_live_passport_document_only_verified(client, internal, app_a, worker_token, gates_open):229 s = new_session(client, app_a, live=True, verification_policy="identity_document_v1")230 consent(client, s, "document_only")231 bad = client.post(f"/v1/sessions/{s['id']}/document", headers=fh(s), data={"side": "front"}, files={"file": ("x.jpg", b"<html>not an image</html>", "image/jpeg")})232 assert bad.json()["error"]["code"] == "unsupported_file_type"233 assert upload(client, s, "front", "passport_scene.jpg").json()["accepted"] is True234 stored = db.one("select * from artifact where session_id=%s", (s["id"],))235 raw = (settings.data_dir / stored["path"]).read_bytes()236 assert b"JFIF" not in raw[:64] and b"\xff\xd8\xff" != raw[:3] # chiffré au repos237 client.post(f"/v1/sessions/{s['id']}/submit", headers=fh(s))238 assert client.get(f"/v1/verification-sessions/{s['id']}", headers=app_a.h(True)).json()["status"] == "processing"239 result, timings, out = run_worker(internal, worker_token)240 assert out["status"] == "verified" and timings["total_ms"] < 15000241 v = client.get(f"/v1/verifications/{out['verification_id']}", headers=app_a.h(True)).json()242 assert v["assurance_level"] == "document_check" and v["simulated"] is False243 blob = json.dumps(v)244 assert "SPECIMEN" not in blob and "ZS123456" not in blob and "1985" not in blob # aucun renseignement personnel dans le résultat245 # pièces détruites dès la décision (clé et fichier)246 art = db.one("select * from artifact where session_id=%s", (s["id"],))247 assert art["deleted_at"] and art["wrapped_key"] is None and not (settings.data_dir / art["path"]).exists()248 assert db.one("select count(*) n from extracted_data where verification_id=%s", (out["verification_id"],))["n"] == 0249250251def test_live_tampered_passport_goes_to_review_then_resolved(client, internal, app_a, worker_token, gates_open):252 from services.mlid import operators, sessions253 s = new_session(client, app_a, live=True, verification_policy="identity_document_v1")254 consent(client, s, "document_only")255 upload(client, s, "front", "passport_tampered_scene.jpg")256 client.post(f"/v1/sessions/{s['id']}/submit", headers=fh(s))257 _, _, out = run_worker(internal, worker_token)258 assert out["status"] == "manual_review"259 v = client.get(f"/v1/verifications/{out['verification_id']}", headers=app_a.h(True)).json()260 assert "document_inconsistent" in [r["code"] for r in v["reasons"]]261 rc = db.one("select * from review_case where verification_id=%s", (out["verification_id"],))262 reviewer, _ = operators.create("rev1", "Réviseure", "reviewer")263 with pytest.raises(Exception):264 sessions.resolve_review(rc["id"], operator=reviewer, resolution="rejected", note="date modifiée") # sans prise en charge : refusé265 db.q("update review_case set state='claimed', claimed_by=%s, claim_until=now() + interval '15 minutes' where id=%s", (reviewer["id"], rc["id"]))266 sessions.resolve_review(rc["id"], operator=reviewer, resolution="rejected", note="date de naissance modifiée")267 assert client.get(f"/v1/verifications/{out['verification_id']}", headers=app_a.h(True)).json()["status"] == "rejected"268 assert db.one("select count(*) n from artifact where session_id=%s and deleted_at is null", (s["id"],))["n"] == 0269 assert db.one("select wrapped_key from extracted_data where verification_id=%s", (out["verification_id"],))["wrapped_key"] is None270271272def test_live_licence_biometric_path(client, internal, app_a, worker_token, gates_open):273 s = new_session(client, app_a, live=True)274 consent(client, s, "document_selfie")275 upload(client, s, "front", "licence_front_scene.jpg")276 upload(client, s, "back", "licence_back_scene.jpg")277 ch = client.post(f"/v1/sessions/{s['id']}/selfie/challenge", headers=fh(s), json={}).json()278 assert len(ch["steps"]) == 2 and ch["expires_in"] == 120279 frames = [("frames", (f"f{i}.jpg", (FX / "a2.jpg").read_bytes(), "image/jpeg")) for i in range(8)]280 assert client.post(f"/v1/sessions/{s['id']}/selfie", headers=fh(s), data={"challenge_id": "chl_wrong"}, files=frames).json()["error"]["code"] == "invalid_challenge"281 assert client.post(f"/v1/sessions/{s['id']}/selfie", headers=fh(s), data={"challenge_id": ch["challenge_id"]}, files=frames).json()["accepted"] is True282 assert client.post(f"/v1/sessions/{s['id']}/selfie", headers=fh(s), data={"challenge_id": ch["challenge_id"]}, files=frames).status_code == 409 # défi à usage unique283 client.post(f"/v1/sessions/{s['id']}/submit", headers=fh(s))284 result, timings, out = run_worker(internal, worker_token)285 # Une photo fixe ne réalise pas le défi : jamais « verified », examen par une personne.286 assert result["document"]["machine_readable"] == "pdf417_aamva" and result["face"]["band"] == "match"287 assert result["liveness"]["passed"] is False and out["status"] == "manual_review"288 assert "embedding" not in json.dumps(result) and "portrait" not in result["document"]289 v = client.get(f"/v1/verifications/{out['verification_id']}", headers=app_a.h(True)).json()290 assert "liveness_failed" in [r["code"] for r in v["reasons"]]291 # droit à la suppression292 d = client.delete(f"/v1/verifications/{out['verification_id']}/personal-data", headers=app_a.h(True)).json()293 assert d["deleted"] and d["artifacts_destroyed"] >= 10294 assert client.get(f"/v1/verifications/{out['verification_id']}", headers=app_a.h(True)).json()["personal_data_deleted_at"]295296297def test_health_card_refused_and_retry(client, internal, app_a, worker_token, gates_open):298 s = new_session(client, app_a, live=True, verification_policy="identity_document_v1")299 consent(client, s, "document_only")300 upload(client, s, "front", "health_card.jpg")301 client.post(f"/v1/sessions/{s['id']}/submit", headers=fh(s))302 _, _, out = run_worker(internal, worker_token)303 assert out == {"retry": True}304 st = client.get(f"/v1/sessions/{s['id']}", headers=fh(s)).json()305 assert st["status"] == "awaiting_document" and st["attempts_left"] == 2306 assert db.one("select count(*) n from artifact where session_id=%s and deleted_at is null", (s["id"],))["n"] == 0307308309def test_withdraw_consent_destroys_everything(client, app_a, gates_open):310 s = new_session(client, app_a, live=True, verification_policy="identity_document_v1")311 consent(client, s, "document_only")312 upload(client, s, "front", "passport_scene.jpg")313 assert client.post(f"/v1/sessions/{s['id']}/withdraw", headers=fh(s)).json()["destroyed"] is True314 assert db.one("select count(*) n from artifact where session_id=%s and deleted_at is null", (s["id"],))["n"] == 0315 assert db.one("select withdrawn_at from consent where session_id=%s", (s["id"],))["withdrawn_at"]316 assert client.get(f"/v1/verification-sessions/{s['id']}", headers=app_a.h(True)).json()["status"] == "cancelled"317318319def test_engine_failure_fails_closed(client, internal, app_a, worker_token, gates_open):320 s = new_session(client, app_a, live=True, verification_policy="identity_document_v1")321 consent(client, s, "document_only")322 upload(client, s, "front", "passport_scene.jpg")323 client.post(f"/v1/sessions/{s['id']}/submit", headers=fh(s))324 h = {"Authorization": "Bearer " + worker_token}325 for _ in range(3):326 job = internal.post("/internal/v1/lease", headers=h, json={"metrics": {}, "capabilities": ["document", "face", "liveness"]}).json()["job"]327 internal.post(f"/internal/v1/jobs/{job['id']}/fail", headers=h, json={"error": "Boom"})328 sess = client.get(f"/v1/verification-sessions/{s['id']}", headers=app_a.h(True)).json()329 assert sess["status"] == "inconclusive" # une panne n'autorise jamais rien330 assert internal.post("/internal/v1/lease", headers={"Authorization": "Bearer mlid_wk_bad"}, json={}).status_code == 401331332333def test_retention_sweep_and_audit_chain(client, app_a, gates_open):334 s = new_session(client, app_a, live=True, verification_policy="identity_document_v1")335 consent(client, s, "document_only")336 upload(client, s, "front", "passport_scene.jpg")337 db.q("update artifact set delete_after = now() - interval '1 minute' where session_id=%s", (s["id"],))338 assert privacy.sweep()["artifacts"] == 1339 ok, n = audit.verify_chain()340 assert ok and n > 5341 db.q("update audit_log set detail='{\"x\":1}' where seq=(select min(seq) from audit_log)")342 assert audit.verify_chain()[0] is False343344345def test_cancel_emits_event_cursor_and_popup_headers(client, app_a):346 s = new_session(client, app_a)347 h = {**app_a.h(), "Idempotency-Key": "cancel-1"}348 a = client.post(f"/v1/verification-sessions/{s['id']}/cancel", headers=h)349 b = client.post(f"/v1/verification-sessions/{s['id']}/cancel", headers=h)350 assert a.json()["status"] == "cancelled" and b.status_code == 200 and b.headers.get("Idempotent-Replayed") == "true"351 assert db.one("select count(*) n from event where type='verification.cancelled' and payload->'data'->'object'->>'id'=%s", (s["id"],))["n"] == 1352 assert client.get("/v1/verification-sessions?starting_after=vs_nope", headers=app_a.h()).json()["error"]["code"] == "invalid_cursor"353 r = client.get(f"/verify/{s['id']}")354 assert r.headers.get("Cross-Origin-Opener-Policy", "unsafe-none") == "unsafe-none"355356357def test_expired_licence_rejected_and_webhook_mode_isolation(client, internal, app_a, worker_token, gates_open, hook_server):358 s = new_session(client, app_a, live=True, verification_policy="identity_document_v1", external_user_id="user_exp")359 consent(client, s, "document_only")360 upload(client, s, "front", "licence_expired_front_scene.jpg")361 upload(client, s, "back", "licence_expired_back_scene.jpg")362 client.post(f"/v1/sessions/{s['id']}/submit", headers=fh(s))363 _, _, out = run_worker(internal, worker_token)364 assert out["status"] == "rejected"365 v = client.get(f"/v1/verifications/{out['verification_id']}", headers=app_a.h(True)).json()366 assert [r["code"] for r in v["reasons"]] == ["document_expired"]367 live_wh = client.post("/v1/webhooks", headers=app_a.h(True), json={"url": hook_server}).json()368 assert client.delete(f"/v1/webhooks/{live_wh['id']}", headers=app_a.h()).status_code == 404 # une clé d'essai ne touche pas un webhook réel369 assert client.post(f"/v1/webhooks/{live_wh['id']}/rotate-secret", headers=app_a.h()).status_code == 404370 assert client.delete(f"/v1/webhooks/{live_wh['id']}", headers=app_a.h(True)).status_code == 200371372373def test_withdraw_during_manual_review_and_retention_validation(client, internal, app_a, worker_token, gates_open):374 from services.mlid import registry375 s = new_session(client, app_a, live=True, verification_policy="identity_document_v1", external_user_id="user_wd")376 consent(client, s, "document_only")377 upload(client, s, "front", "passport_tampered_scene.jpg")378 client.post(f"/v1/sessions/{s['id']}/submit", headers=fh(s))379 _, _, out = run_worker(internal, worker_token)380 assert out["status"] == "manual_review"381 assert client.post(f"/v1/sessions/{s['id']}/withdraw", headers=fh(s)).json()["destroyed"] is True382 assert db.one("select count(*) n from artifact where session_id=%s and deleted_at is null", (s["id"],))["n"] == 0383 assert db.one("select state, resolution from review_case where verification_id=%s", (out["verification_id"],)) == {"state": "resolved", "resolution": "withdrawn"}384 assert db.one("select wrapped_key from extracted_data where verification_id=%s", (out["verification_id"],))["wrapped_key"] is None385 with pytest.raises(Exception):386 registry.update_app(app_a.id, {"retention": {"result_days": 730.5}}, actor="test")387 assert "results_anonymised" in privacy.sweep()388 row = db.one("select response from idempotency limit 1")389 assert row is None or set(row["response"]) == {"enc"} # réponse idempotente chiffrée au repos390391392# ---------------------------------------------------------------- durcissement393394def test_rate_limit_is_shared_and_body_limits(client, app_b):395 from services.mlid import http_common396 from services.mlid.errors import ApiError397 for _ in range(3):398 http_common.limiter.check("test:shared", 3)399 with pytest.raises(ApiError) as e:400 http_common.limiter.check("test:shared", 3)401 assert e.value.status == 429 and int(e.value.headers["Retry-After"]) >= 1402 assert db.one("select sum(n) n from rate_window")["n"] >= 4 # tenu en base : vaut pour tous les processus403 big = client.post("/v1/verification-sessions", headers=app_b.h(), content=b"x" * 300_000)404 assert big.status_code == 413 and big.json()["error"]["code"] == "payload_too_large"405 for _ in range(31):406 r = client.get("/v1/verification-sessions", headers={"Authorization": "Bearer mlid_sk_test_wrong"})407 assert r.status_code == 429 # essais de clés invalides plafonnés408 db.q("delete from rate_window")409410411def test_scores_not_kept_review_deadline_and_scoping(client, internal, app_a, app_b, worker_token, gates_open):412 from services.mlid import operators, sessions413 from services.mlid.console import Op, reviews, claim414 s = new_session(client, app_a, live=True, verification_policy="identity_document_v1", external_user_id="user_sc")415 consent(client, s, "document_only")416 upload(client, s, "front", "passport_tampered_scene.jpg")417 client.post(f"/v1/sessions/{s['id']}/submit", headers=fh(s))418 _, _, out = run_worker(internal, worker_token)419 assert out["status"] == "manual_review"420 rc = db.one("select * from review_case where verification_id=%s", (out["verification_id"],))421 assert rc["due_at"] is not None422 other, _ = operators.create("rev-b", "Réviseur B", "reviewer", [app_b.id])423 mine, _ = operators.create("rev-a", "Réviseur A", "reviewer", [app_a.id])424 assert rc["id"] not in [x["id"] for x in reviews(Op(other))["data"]] # cloisonné par application425 assert rc["id"] in [x["id"] for x in reviews(Op(mine))["data"]]426 with pytest.raises(Exception):427 claim(rc["id"], Op(other))428 db.q("update review_case set due_at = now() - interval '1 minute' where id=%s", (rc["id"],))429 assert sessions.expire_reviews() == 1430 v = db.one("select * from verification where id=%s", (out["verification_id"],))431 assert v["status"] == "inconclusive" and v["decision"]["reasons"][0]["code"] == "review_not_completed"432 assert db.one("select count(*) n from artifact where session_id=%s and deleted_at is null", (s["id"],))["n"] == 0433 assert all("score" not in d for d in v["decision"]["dimensions"].values())434 done = db.q("select decision from verification where status in ('verified','rejected','inconclusive')")435 assert done and all("score" not in d for row in done for d in (row["decision"].get("dimensions") or {}).values())436437438def test_dispute_overturn_and_passkey_management(client, app_a):439 from services.mlid import operators440 from services.mlid.console import Op, dispute_close, dispute_detail, my_passkey_delete, revoke_operator_passkeys441 s = new_session(client, app_a, external_user_id="user_dsp")442 consent(client, s, "document_review")443 client.post(f"/v1/sessions/{s['id']}/sandbox", headers=fh(s), json={"scenario": "rejected"})444 d = client.post(f"/v1/sessions/{s['id']}/dispute", headers=fh(s), json={"message": "Mon permis est valide, je conteste."}).json()445 rev, _ = operators.create("rev-d", "Réviseure D", "reviewer")446 assert dispute_detail(d["id"], Op(rev))["message"].startswith("Mon permis")447 with pytest.raises(Exception):448 dispute_close(d["id"], {"outcome": "nope"}, Op(rev))449 assert dispute_close(d["id"], {"outcome": "overturned"}, Op(rev))["outcome"] == "overturned"450 row = db.one("select * from dispute where id=%s", (d["id"],))451 assert row["message_enc"] is None and row["state"] == "closed"452 sess = client.get(f"/v1/verification-sessions/{s['id']}", headers=app_a.h()).json()453 v = client.get(f"/v1/verifications/{sess['verification_id']}", headers=app_a.h()).json()454 assert v["status"] == "inconclusive" and v["reasons"][0]["code"] == "decision_overturned"455 owner, _ = operators.create("own-x", "Propriétaire X", "owner")456 db.q("insert into operator_credential(id, operator_id, public_key) values (%s,%s,%s)", (b"cred-1", rev["id"], b"k"))457 with pytest.raises(Exception):458 my_passkey_delete(b"cred-1".hex(), Op(rev)) # jamais la dernière clé459 token, _ = operators.open_session(rev, None)460 revoke_operator_passkeys(rev["id"], Op(owner))461 assert operators.from_session(token) is None462 assert db.one("select count(*) n from operator_credential where operator_id=%s", (rev["id"],))["n"] == 0463464465def test_master_key_rotation_and_authenticated_backup(client, app_a, hook_server, gates_open, tmp_path):466 import io467 from services.mlid import backup, crypto, keyrotation, storage468 wh = client.post("/v1/webhooks", headers=app_a.h(), json={"url": hook_server}).json()469 s = new_session(client, app_a, live=True, verification_policy="identity_document_v1")470 consent(client, s, "document_only")471 upload(client, s, "front", "passport_scene.jpg")472 art = db.one("select * from artifact where session_id=%s and deleted_at is null", (s["id"],))473 before = storage.get(art)474 old = crypto.master_key()475 newf = tmp_path / "new.key"476 newf.write_bytes(bytes(range(32)))477 out = keyrotation.rotate(newf)478 assert out["artifacts"] >= 1 and out["webhook_secrets"] >= 1 and crypto.master_key() == bytes(range(32)) != old479 assert storage.get(db.one("select * from artifact where id=%s", (art["id"],))) == before # toujours lisible sous la nouvelle clé480 row = db.one("select secret_enc from webhook_endpoint where id=%s", (wh["id"],))481 assert crypto.unseal_small("webhook-secret", bytes(row["secret_enc"])).decode() == wh["secret"]482 client.post(f"/v1/sessions/{s['id']}/withdraw", headers=fh(s))483 client.delete(f"/v1/webhooks/{wh['id']}", headers=app_a.h())484 key = tmp_path / "backup.key"485 key.write_text("clef-de-sauvegarde-de-test")486 plain = os.urandom(2_500_000)487 enc, dec = io.BytesIO(), io.BytesIO()488 backup.encrypt_stream(io.BytesIO(plain), enc, key)489 backup.decrypt_stream(io.BytesIO(enc.getvalue()), dec, key)490 assert dec.getvalue() == plain and plain[:64] not in enc.getvalue()491 tampered = bytearray(enc.getvalue()); tampered[200_000] ^= 1492 for bad in (bytes(tampered), enc.getvalue()[:-40], enc.getvalue()[:1_200_000]):493 with pytest.raises(Exception):494 backup.decrypt_stream(io.BytesIO(bad), io.BytesIO(), key)495496497def test_worker_relay_carries_large_payloads(hook_server):498 """Le relais par nc (workers distants) transporte de gros corps dans les deux sens sans les altérer."""499 import hashlib as _h500 import httpx501 from http.server import BaseHTTPRequestHandler, HTTPServer502 from services.mlid.worker import relay503504 blob = os.urandom(6_000_000)505506 class H(BaseHTTPRequestHandler):507 def do_GET(self):508 self.send_response(200); self.send_header("Content-Length", str(len(blob))); self.end_headers(); self.wfile.write(blob)509510 def do_POST(self):511 body = self.rfile.read(int(self.headers["Content-Length"]))512 d = _h.sha256(body).hexdigest().encode()513 self.send_response(200); self.send_header("Content-Length", str(len(d))); self.end_headers(); self.wfile.write(d)514515 def log_message(self, *a):516 pass517 srv = HTTPServer(("127.0.0.1", 0), H)518 threading.Thread(target=srv.serve_forever, daemon=True).start()519 port = relay.start("127.0.0.1", srv.server_address[1])520 with httpx.Client(base_url=f"http://127.0.0.1:{port}", timeout=30) as c:521 for _ in range(3):522 assert c.get("/").content == blob523 assert c.post("/", content=blob).text == _h.sha256(blob).hexdigest()524 srv.shutdown()525526527def test_worker_crash_mid_job_is_recovered(client, internal, app_a, worker_token, gates_open):528 """Un worker qui disparaît en cours d'analyse : le bail échoit, le travail repart en file et un autre worker le termine."""529 from services.mlid import scheduler530 s = new_session(client, app_a, live=True, verification_policy="identity_document_v1", external_user_id="user_crash")531 consent(client, s, "document_only")532 upload(client, s, "front", "passport_scene.jpg")533 client.post(f"/v1/sessions/{s['id']}/submit", headers=fh(s))534 h = {"Authorization": "Bearer " + worker_token}535 job = internal.post("/internal/v1/lease", headers=h, json={"metrics": {}, "capabilities": ["document", "face", "liveness"]}).json()["job"]536 assert job and internal.post("/internal/v1/lease", headers=h, json={"metrics": {}, "capabilities": ["document", "face", "liveness"]}).json()["job"] is None537 db.q("update job set lease_until = now() - interval '1 second' where id=%s", (job["id"],)) # le worker ne répond plus538 assert scheduler.reap() >= 1539 assert db.one("select state, attempts from job where id=%s", (job["id"],)) == {"state": "queued", "attempts": 1}540 _, _, out = run_worker(internal, worker_token)541 assert out["status"] in ("verified", "manual_review")542 late = internal.post(f"/internal/v1/jobs/{job['id']}/result", headers=h, json={"result": {"document": {}}, "timings": {}})543 assert late.json() == {"ignored": True} # un résultat tardif ne change plus rien544545546def test_reinviting_never_changes_an_existing_operator(client):547 """Un administrateur ne peut ni rétrograder ni s'approprier un compte existant en le « réinvitant »."""548 from services.mlid import operators549 from services.mlid.console import Op, invite_operator, reinvite_operator550 from starlette.requests import Request551 req = Request({"type": "http", "method": "POST", "path": "/", "headers": [], "client": ("127.0.0.1", 1)})552 owner, _ = operators.create("boss", "Propriétaire", "owner")553 admin, _ = operators.create("adm", "Administratrice", "admin")554 dev, _ = operators.create("dev1", "Développeur", "developer")555 with pytest.raises(Exception) as e:556 invite_operator({"handle": "boss", "display_name": "x", "role": "viewer"}, Op(admin))557 assert getattr(e.value, "code", "") == "handle_taken"558 assert db.one("select role, status from operator where id=%s", (owner["id"],)) == {"role": "owner", "status": "active"}559 with pytest.raises(Exception) as e:560 reinvite_operator(owner["id"], req, Op(admin)) # lien pour un propriétaire : propriétaire seulement561 assert getattr(e.value, "status", 0) == 403562 out = reinvite_operator(dev["id"], req, Op(admin))563 assert "/console/activate#" in out["activation_url"] and out["operator"]["role"] == "developer" and out["operator"]["pending_invite"] is True564 assert db.one("select count(*) n from operator_invite where operator_id=%s and used_at is null", (dev["id"],))["n"] == 1 # l'ancien lien est annulé565 db.q("update operator set status='suspended' where id=%s", (dev["id"],))566 with pytest.raises(Exception):567 reinvite_operator(dev["id"], req, Op(owner)) # un compte suspendu n'est pas réactivé par un lien568 assert db.one("select status from operator where id=%s", (dev["id"],))["status"] == "suspended"569