SPB Git

Repository Public

capture-fixtures.py 7.3 KB 168 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# Project          : MacLustr Identity8# File             : sdk/capture-fixtures.py9# Description      : Captures the JSON fixtures of the native SDK tests from a10#                    LOCAL backend, so that the Swift and Kotlin test suites11#                    decode exactly what the service sends today.12# Module           : sdk13# Repository       : https://git.spboucher.ai/maclustr-identity14# Project Website  : https://identity.spboucher.ai15# Created          : 2026-12-0116# Last Modified    : 2026-12-0117#18# Author           : Simon-Pierre Boucher19# Position         : Professor of Finance20# Institution      : Université du Québec en Outaouais (UQO)21# Organization     : SP Boucher22# Website          : https://spboucher.ai23# Git              : https://git.spboucher.ai24#25# Preferred Contact: admin@spboucher.ai26# Technical Contact: dev@spboucher.ai27# Security/Admin   : admin@spboucher.ai28#29# Copyright (c) 202630# Simon-Pierre Boucher31# All rights reserved where applicable. This file is governed by the32# applicable project license, copyright notices and relevant law.33# Existing third-party rights and notices remain unaffected.34#35# License          : None specified (no license file in this repository)36#37# Do not embed credentials, private keys, access tokens,38# certificates or confidential personal information.39#40# =============================================================================41# END OF SP BOUCHER SOURCE HEADER42# =============================================================================4344"""Captures the JSON fixtures of the native SDK tests from a LOCAL backend, so that the Swift and Kotlin test45suites decode exactly what the service sends today.4647    MLID_BASE_URL=http://localhost:8872 MLID_SECRET_KEY=mlid_sk_test_… [MLID_LIVE_KEY=mlid_sk_live_…] \48        ../.venv/bin/python capture-fixtures.py4950The sandbox key is enough for the sandbox fixtures. The live fixtures (uploads of the fictional documents of51tests/fixtures) need a live key on a development database whose compliance gates are open: never production,52never staging. No worker is needed. Sessions created here are withdrawn at the end (uploads destroyed).53"""54from __future__ import annotations5556import json57import os58import re59import sys60from pathlib import Path6162import httpx6364HERE = Path(__file__).resolve().parent65OUT = [HERE / "swift/Tests/MacLustrIdentityCoreTests/Fixtures", HERE / "kotlin/identity-core/src/test/resources/fixtures"]66IMAGES = HERE.parent / "tests" / "fixtures"67BASE = os.environ.get("MLID_BASE_URL", "http://localhost:8872")68if not re.fullmatch(r"http://(localhost|127\.0\.0\.1)(:\d+)?", BASE):69    sys.exit("capture-fixtures.py only targets a local backend")707172def save(name: str, body) -> None:73    text = json.dumps(body, indent=2, ensure_ascii=False) + "\n"74    for d in OUT:75        (d / f"{name}.json").write_text(text, encoding="utf-8")76    print("captured", name)777879class Flow:80    def __init__(self, http: httpx.Client, key: str):81        r = http.post("/v1/verification-sessions", headers={"Authorization": f"Bearer {key}"},82                      json={"purpose": "account_verification", "external_user_id": "u_fixture", "locale": "fr-CA"})83        r.raise_for_status()84        self.created = r.json()85        self.http, self.id = http, self.created["id"]86        self.h = {"Authorization": f"Bearer {self.created['client_secret']}"}8788    def call(self, method: str, path: str = "", **kw) -> httpx.Response:89        return self.http.request(method, f"/v1/sessions/{self.id}{path}", headers={**self.h, **kw.pop("headers", {})}, **kw)9091    def ok(self, method: str, path: str = "", **kw):92        r = self.call(method, path, **kw)93        r.raise_for_status()94        return r.json()9596    def consent(self, method: str):97        state = self.ok("GET")98        m = next(x for x in state["methods"] if x["id"] == method)99        return self.ok("POST", "/consent", json={"method": method, "accepted": True, "biometric_consent": m["biometric"],100                                                 "text_version": m["consent"]["fr"]["version"], "locale": "fr-CA"})101102103def sandbox(http: httpx.Client, key: str) -> None:104    f = Flow(http, key)105    save("session_created", {**f.created, "client_secret": "vsc_REDACTED", "url": f.created["url"].split("#")[0] + "#vsc_REDACTED"})106    save("flow_created", f.ok("GET"))107    save("flow_awaiting_document", f.consent("document_selfie"))108    save("flow_sandbox_verified", f.ok("POST", "/sandbox", json={"scenario": "verified"}))109    for scenario in ("manual_review", "inconclusive", "rejected"):110        g = Flow(http, key)111        g.consent("document_review")112        save(f"flow_sandbox_{scenario}", g.ok("POST", "/sandbox", json={"scenario": scenario}))113    c = Flow(http, key)114    c.consent("document_selfie")115    save("withdraw", c.ok("POST", "/withdraw"))116    save("flow_cancelled", c.ok("GET"))117    # Transport errors normalised by the service.118    big = c.call("POST", "/consent", content=b"{" + b" " * (300 * 1024) + b"}", headers={"Content-Type": "application/json"})119    assert big.status_code == 413, big.status_code120    save("error_payload_too_large", big.json())121    limited = None122    r = Flow(http, key)123    for _ in range(130):                       # 120 flow requests per minute and per session124        x = r.call("GET")125        if x.status_code == 429:126            limited = x127            break128    assert limited is not None and limited.headers.get("retry-after"), "rate limit not reached"129    save("error_rate_limited", limited.json())130    print("  Retry-After:", limited.headers["retry-after"])131132133def live(http: httpx.Client, key: str) -> None:134    f = Flow(http, key)135    try:136        save("flow_live_created", f.ok("GET"))137        f.consent("document_selfie")138        for side in ("front", "back"):139            img = (IMAGES / f"licence_{side}_scene.jpg").read_bytes()140            save(f"document_accepted_{side}", f.ok("POST", "/document", data={"side": side}, files={"file": (f"{side}.jpg", img, "image/jpeg")}))141        save("flow_live_awaiting_selfie", f.ok("GET"))142        save("challenge_accessible", f.ok("POST", "/selfie/challenge", json={"accessible": True}))143        ch = f.ok("POST", "/selfie/challenge", json={})144        save("challenge", ch)145        frame = (IMAGES / "a2.jpg").read_bytes()146        frames = [("frames", (f"f{i:02d}.jpg", frame, "image/jpeg")) for i in range(ch["frames"]["min"])]147        save("selfie_accepted", f.ok("POST", "/selfie", data={"challenge_id": ch["challenge_id"]}, files=frames))148        save("flow_live_processing", f.ok("POST", "/submit"))149    finally:150        f.call("POST", "/withdraw")151152153def main() -> None:154    key = os.environ.get("MLID_SECRET_KEY", "")155    if not key.startswith("mlid_sk_test_"):156        sys.exit("MLID_SECRET_KEY must be a sandbox key (mlid_sk_test_…)")157    with httpx.Client(base_url=BASE, timeout=30) as http:158        sandbox(http, key)159        live_key = os.environ.get("MLID_LIVE_KEY", "")160        if live_key.startswith("mlid_sk_live_"):161            live(http, live_key)162        else:163            print("MLID_LIVE_KEY not set: live fixtures left unchanged")164165166if __name__ == "__main__":167    main()168
Files main
Menu

Theme