Repository Public
1# =============================================================================2# SP BOUCHER | INFRASTRUCTURE & AUTOMATION3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : MacLustr Identity7# File : sdk/python/src/maclustr_identity/testing.py8# Description : Helpers for automated tests of YOUR integration.9# Module : maclustr_identity10# Repository : https://git.spboucher.ai/maclustr-identity11# Project Website : https://identity.spboucher.ai12# Created : 2026-12-0113# Last Modified : 2026-12-0114#15# Author : Simon-Pierre Boucher16# Position : Professor of Finance17# Institution : Université du Québec en Outaouais (UQO)18# Organization : SP Boucher19# Website : https://spboucher.ai20# Git : https://git.spboucher.ai21#22# Preferred Contact: admin@spboucher.ai23# Technical Contact: dev@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Helpers for automated tests of YOUR integration.4243``complete_sandbox_session`` plays the person's part of a SANDBOX session through the session-flow endpoints,44using only the session client secret (``vsc_…``): no image, no document, no secret key. Live sessions refuse it.45"""46from __future__ import annotations4748import re49from typing import Any50from urllib.parse import unquote, urlsplit5152import httpx5354from .errors import MacLustrIdentityError, error_from_response55from .types import SandboxScenario565758def _target(url: str | None, session_id: str | None, client_secret: str | None, base_url: str | None) -> tuple[str, dict[str, str]]:59 if url:60 u = urlsplit(url)61 m = re.search(r"/verify/([^/?#]+)", u.path)62 session_id = session_id or (unquote(m.group(1)) if m else None)63 client_secret = client_secret or (u.fragment or None)64 base_url = base_url or f"{u.scheme}://{u.netloc}"65 if not session_id or not client_secret or not base_url:66 raise MacLustrIdentityError("Provide url, or session_id, client_secret and base_url.", type="invalid_request_error", code="sandbox_arguments_missing")67 return f"{base_url.rstrip('/')}/v1/sessions/{session_id}", {"Authorization": f"Bearer {client_secret}", "Accept": "application/json"}686970def _check(r: httpx.Response) -> Any:71 try:72 body = r.json() if r.content else None73 except ValueError:74 body = None75 if not r.is_success:76 raise error_from_response(r.status_code, body, {k.lower(): v for k, v in r.headers.items()})77 return body787980def _consent_body(state: dict[str, Any], method: str | None) -> dict[str, Any]:81 if state.get("livemode"):82 raise MacLustrIdentityError("complete_sandbox_session only works on sandbox sessions (created with an mlid_sk_test_ key).",83 type="invalid_request_error", code="sandbox_only")84 methods = state.get("methods") or []85 chosen = next((m for m in methods if m["id"] == method), None) if method else (methods[0] if methods else None)86 if not chosen:87 raise MacLustrIdentityError(f"Method {method or '(none)'} is not offered by this session.", type="invalid_request_error",88 code="method_not_available", param="method")89 # The consent text version is always the one the service just sent: it changes whenever the text does.90 texts = chosen.get("consent") or {}91 version = next((t.get("version") for t in texts.values() if isinstance(t, dict) and t.get("version")), None)92 body: dict[str, Any] = {"method": chosen["id"], "accepted": True, "text_version": version}93 if chosen.get("biometric"):94 body["biometric_consent"] = True95 return body969798def complete_sandbox_session(url: str | None = None, *, session_id: str | None = None, client_secret: str | None = None, base_url: str | None = None,99 scenario: SandboxScenario = "verified", method: str | None = None, http_client: httpx.Client | None = None) -> dict[str, Any]:100 """Records consent then applies a sandbox scenario. Returns the flow state (``status`` is the outcome)."""101 base, headers = _target(url, session_id, client_secret, base_url)102 http = http_client or httpx.Client()103 try:104 state = _check(http.get(base, headers=headers))105 _check(http.post(base + "/consent", headers=headers, json=_consent_body(state, method)))106 return _check(http.post(base + "/sandbox", headers=headers, json={"scenario": scenario}))107 finally:108 if http_client is None:109 http.close()110111112async def acomplete_sandbox_session(url: str | None = None, *, session_id: str | None = None, client_secret: str | None = None, base_url: str | None = None,113 scenario: SandboxScenario = "verified", method: str | None = None,114 http_client: httpx.AsyncClient | None = None) -> dict[str, Any]:115 """Async variant of :func:`complete_sandbox_session`."""116 base, headers = _target(url, session_id, client_secret, base_url)117 http = http_client or httpx.AsyncClient()118 try:119 state = _check(await http.get(base, headers=headers))120 _check(await http.post(base + "/consent", headers=headers, json=_consent_body(state, method)))121 return _check(await http.post(base + "/sandbox", headers=headers, json={"scenario": scenario}))122 finally:123 if http_client is None:124 await http.aclose()125