SPB Git

Repository Public

_client.py 21.3 KB 383 lines python

1# =============================================================================2#                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : MacLustr Identity7# File             : sdk/python/src/maclustr_identity/_client.py8# Description      : Synchronous and asynchronous clients.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"""Synchronous and asynchronous clients. Both hold a secret API key: server-side code only."""42from __future__ import annotations4344import asyncio45import time46from typing import Any, AsyncIterator, Callable, Iterator, Mapping, TypeVar4748import httpx4950from ._base import DEFAULT_BASE_URL, BaseClient, clean_params, seg, should_retry51from .errors import MacLustrIdentityError52from .types import (CreatedVerificationSession, CreatedWebhookEndpoint, DeletedWebhookEndpoint, Event, Page, PersonalDataDeletion,53                    RotatedWebhookSecret, Verification, VerificationSession, VerificationStatusSummary, WebhookEndpoint)54from .webhook import DEFAULT_TOLERANCE, Webhook5556T = TypeVar("T")575859def _page(body: dict[str, Any], build: Callable[[dict[str, Any]], T]) -> Page[T]:60    return Page(data=[build(x) for x in body.get("data", [])], has_more=bool(body.get("has_more")))616263def _session_body(purpose: str, external_user_id: str | None, verification_policy: str | None, return_url: str | None, locale: str | None,64                  metadata: Mapping[str, Any] | None, expires_in_minutes: int | None) -> dict[str, Any]:65    return clean_params(purpose=purpose, external_user_id=external_user_id, verification_policy=verification_policy, return_url=return_url,66                        locale=locale, metadata=dict(metadata) if metadata is not None else None, expires_in_minutes=expires_in_minutes)676869def _require_user(external_user_id: str) -> None:70    if not isinstance(external_user_id, str) or not external_user_id:71        raise MacLustrIdentityError("external_user_id is required.", type="invalid_request_error", code="external_user_id_required", param="external_user_id")727374class _WebhookHelpers:75    @staticmethod76    def construct_event(payload: bytes | str, sig_header: str | None, secret: str, tolerance: int = DEFAULT_TOLERANCE) -> Event:77        """Verifies MLID-Signature against the raw body, then returns the parsed event."""78        return Webhook.construct_event(payload, sig_header, secret, tolerance)7980    @staticmethod81    def verify_signature(payload: bytes | str, sig_header: str | None, secret: str, tolerance: int = DEFAULT_TOLERANCE) -> None:82        Webhook.verify_signature(payload, sig_header, secret, tolerance)838485# --------------------------------------------------------------------------------------------- synchronous8687class MacLustrIdentity(BaseClient):88    """Synchronous client.8990    >>> identity = MacLustrIdentity(api_key=os.environ["MLID_SECRET_KEY"])91    >>> session = identity.verification_sessions.create(purpose="Raise the transfer limit", external_user_id="user_42")92    """9394    def __init__(self, api_key: str, *, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0, max_retries: int = 2,95                 http_client: httpx.Client | None = None) -> None:96        super().__init__(api_key, base_url=base_url, timeout=timeout, max_retries=max_retries)97        self._owns_http = http_client is None98        self._http = http_client or httpx.Client(follow_redirects=False)99        self._sleep: Callable[[float], None] = time.sleep100        self.verification_sessions = VerificationSessions(self)101        self.verifications = Verifications(self)102        self.webhooks = Webhooks(self)103104    def close(self) -> None:105        if self._owns_http:106            self._http.close()107108    def __enter__(self) -> "MacLustrIdentity":109        return self110111    def __exit__(self, *exc: object) -> None:112        self.close()113114    def request(self, method: str, path: str, *, params: Mapping[str, Any] | None = None, body: Any = None,115                idempotency_key: str | None = None, max_retries: int | None = None) -> Any:116        """Low-level request with retries. Prefer the resource methods."""117        req = self._prepare(method, path, params=params, body=body, idempotency_key=idempotency_key)118        retries = self.max_retries if max_retries is None else max(0, max_retries)119        attempt = 0120        while True:121            try:122                response = self._http.request(req.method, req.url, headers=req.headers, params=req.params, content=req.content, timeout=self.timeout)123                return self._decode(response)124            except httpx.HTTPError as exc:125                error: MacLustrIdentityError = self._connection_error(exc, self.timeout)126            except MacLustrIdentityError as exc:127                if exc.code == "invalid_response" or not should_retry(exc.status, exc.code):128                    raise129                error = exc130            if attempt >= retries:131                raise error132            self._sleep(self._retry_delay(error, attempt))133            attempt += 1134135    def is_user_verified(self, external_user_id: str) -> Verification | None:136        """Returns the newest valid ``verified`` verification of one of your users, or None.137138        A revoked, expired, rejected or pending verification never counts. Raises APIConnectionError when the139        identity service cannot be reached: treat that as "not verified" (fail closed).140        """141        _require_user(external_user_id)142        for v in self.verifications.list_auto_paging(external_user_id=external_user_id, status="verified", limit=100):143            if v.is_valid:144                return v145        return None146147148class _Resource:149    def __init__(self, client: MacLustrIdentity) -> None:150        self._c = client151152153class VerificationSessions(_Resource):154    def create(self, *, purpose: str, external_user_id: str | None = None, verification_policy: str | None = None, return_url: str | None = None,155               locale: str | None = None, metadata: Mapping[str, Any] | None = None, expires_in_minutes: int | None = None,156               idempotency_key: str | None = None) -> CreatedVerificationSession:157        """Creates a session. The response is the only time ``client_secret`` and ``url`` are returned."""158        body = _session_body(purpose, external_user_id, verification_policy, return_url, locale, metadata, expires_in_minutes)159        return CreatedVerificationSession.from_dict(self._c.request("POST", "/verification-sessions", body=body, idempotency_key=idempotency_key))160161    def retrieve(self, session_id: str) -> VerificationSession:162        return VerificationSession.from_dict(self._c.request("GET", f"/verification-sessions/{seg(session_id)}"))163164    def list(self, *, limit: int | None = None, starting_after: str | None = None, status: str | None = None,165             external_user_id: str | None = None) -> Page[VerificationSession]:166        """One page, newest first."""167        params = clean_params(limit=limit, starting_after=starting_after, status=status, external_user_id=external_user_id)168        return _page(self._c.request("GET", "/verification-sessions", params=params), VerificationSession.from_dict)169170    def list_auto_paging(self, *, limit: int | None = None, status: str | None = None, external_user_id: str | None = None) -> Iterator[VerificationSession]:171        """Every matching session, fetching pages as needed."""172        cursor: str | None = None173        while True:174            page = self.list(limit=limit, starting_after=cursor, status=status, external_user_id=external_user_id)175            yield from page.data176            if not page.has_more or not page.data:177                return178            cursor = page.data[-1].id179180    def cancel(self, session_id: str, *, idempotency_key: str | None = None) -> VerificationSession:181        """Cancels a session that has no decision yet. Raises ConflictError otherwise."""182        return VerificationSession.from_dict(self._c.request("POST", f"/verification-sessions/{seg(session_id)}/cancel", idempotency_key=idempotency_key))183184185class Verifications(_Resource):186    def retrieve(self, verification_id: str) -> Verification:187        return Verification.from_dict(self._c.request("GET", f"/verifications/{seg(verification_id)}"))188189    def status(self, verification_id: str) -> VerificationStatusSummary:190        """Lightweight status: status, valid, assurance_level, expires_at."""191        return VerificationStatusSummary.from_dict(self._c.request("GET", f"/verifications/{seg(verification_id)}/status"))192193    def list(self, *, limit: int | None = None, starting_after: str | None = None, status: str | None = None,194             external_user_id: str | None = None) -> Page[Verification]:195        """One page, newest first."""196        params = clean_params(limit=limit, starting_after=starting_after, status=status, external_user_id=external_user_id)197        return _page(self._c.request("GET", "/verifications", params=params), Verification.from_dict)198199    def list_auto_paging(self, *, limit: int | None = None, status: str | None = None, external_user_id: str | None = None) -> Iterator[Verification]:200        cursor: str | None = None201        while True:202            page = self.list(limit=limit, starting_after=cursor, status=status, external_user_id=external_user_id)203            yield from page.data204            if not page.has_more or not page.data:205                return206            cursor = page.data[-1].verification_id207208    def revoke(self, verification_id: str, *, reason: str | None = None, idempotency_key: str | None = None) -> Verification:209        """Revokes a ``verified`` verification (idempotent on an already revoked one)."""210        return Verification.from_dict(self._c.request("POST", f"/verifications/{seg(verification_id)}/revoke", body=clean_params(reason=reason),211                                                      idempotency_key=idempotency_key))212213    def delete_personal_data(self, verification_id: str) -> PersonalDataDeletion:214        """Destroys every personal data element kept for this verification. The result record itself remains."""215        return PersonalDataDeletion.from_dict(self._c.request("DELETE", f"/verifications/{seg(verification_id)}/personal-data"))216217218class Webhooks(_Resource, _WebhookHelpers):219    def create(self, *, url: str, events: list[str] | None = None, description: str | None = None, idempotency_key: str | None = None,220               max_retries: int | None = None) -> CreatedWebhookEndpoint:221        """Creates an endpoint. The signing secret (``whsec_…``) is returned once: store it server-side.222223        Retried like any other POST: the service deduplicates on the Idempotency-Key, so a retry returns the endpoint224        (and the secret) of the first attempt instead of creating a second one. ``max_retries=0`` disables retries.225        """226        return CreatedWebhookEndpoint.from_dict(self._c.request("POST", "/webhooks", body=clean_params(url=url, events=events, description=description),227                                                                idempotency_key=idempotency_key, max_retries=max_retries))228229    def list(self) -> Page[WebhookEndpoint]:230        return _page(self._c.request("GET", "/webhooks"), WebhookEndpoint.from_dict)231232    def delete(self, endpoint_id: str) -> DeletedWebhookEndpoint:233        return DeletedWebhookEndpoint.from_dict(self._c.request("DELETE", f"/webhooks/{seg(endpoint_id)}"))234235    def rotate_secret(self, endpoint_id: str, *, idempotency_key: str | None = None, max_retries: int | None = None) -> RotatedWebhookSecret:236        """Returns a new secret. Deliveries carry both signatures for 24 hours.237238        Retried like any other POST with the same Idempotency-Key: the retry returns the secret of the first attempt,239        it never rotates twice. To rotate again later, make a new call.240        """241        return RotatedWebhookSecret.from_dict(self._c.request("POST", f"/webhooks/{seg(endpoint_id)}/rotate-secret", idempotency_key=idempotency_key,242                                                              max_retries=max_retries))243244245# --------------------------------------------------------------------------------------------- asynchronous246247class AsyncMacLustrIdentity(BaseClient):248    """Asynchronous client with the same surface as :class:`MacLustrIdentity`.249250    >>> async with AsyncMacLustrIdentity(api_key=os.environ["MLID_SECRET_KEY"]) as identity:251    ...     verified = await identity.is_user_verified("user_42")252    """253254    def __init__(self, api_key: str, *, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0, max_retries: int = 2,255                 http_client: httpx.AsyncClient | None = None) -> None:256        super().__init__(api_key, base_url=base_url, timeout=timeout, max_retries=max_retries)257        self._owns_http = http_client is None258        self._http = http_client or httpx.AsyncClient(follow_redirects=False)259        self._sleep: Callable[[float], Any] = asyncio.sleep260        self.verification_sessions = AsyncVerificationSessions(self)261        self.verifications = AsyncVerifications(self)262        self.webhooks = AsyncWebhooks(self)263264    async def aclose(self) -> None:265        if self._owns_http:266            await self._http.aclose()267268    async def __aenter__(self) -> "AsyncMacLustrIdentity":269        return self270271    async def __aexit__(self, *exc: object) -> None:272        await self.aclose()273274    async def request(self, method: str, path: str, *, params: Mapping[str, Any] | None = None, body: Any = None,275                      idempotency_key: str | None = None, max_retries: int | None = None) -> Any:276        """Low-level request with retries. Prefer the resource methods."""277        req = self._prepare(method, path, params=params, body=body, idempotency_key=idempotency_key)278        retries = self.max_retries if max_retries is None else max(0, max_retries)279        attempt = 0280        while True:281            try:282                response = await self._http.request(req.method, req.url, headers=req.headers, params=req.params, content=req.content, timeout=self.timeout)283                return self._decode(response)284            except httpx.HTTPError as exc:285                error: MacLustrIdentityError = self._connection_error(exc, self.timeout)286            except MacLustrIdentityError as exc:287                if exc.code == "invalid_response" or not should_retry(exc.status, exc.code):288                    raise289                error = exc290            if attempt >= retries:291                raise error292            await self._sleep(self._retry_delay(error, attempt))293            attempt += 1294295    async def is_user_verified(self, external_user_id: str) -> Verification | None:296        """Returns the newest valid ``verified`` verification of one of your users, or None. Fail closed on errors."""297        _require_user(external_user_id)298        async for v in self.verifications.list_auto_paging(external_user_id=external_user_id, status="verified", limit=100):299            if v.is_valid:300                return v301        return None302303304class _AsyncResource:305    def __init__(self, client: AsyncMacLustrIdentity) -> None:306        self._c = client307308309class AsyncVerificationSessions(_AsyncResource):310    async def create(self, *, purpose: str, external_user_id: str | None = None, verification_policy: str | None = None, return_url: str | None = None,311                     locale: str | None = None, metadata: Mapping[str, Any] | None = None, expires_in_minutes: int | None = None,312                     idempotency_key: str | None = None) -> CreatedVerificationSession:313        body = _session_body(purpose, external_user_id, verification_policy, return_url, locale, metadata, expires_in_minutes)314        return CreatedVerificationSession.from_dict(await self._c.request("POST", "/verification-sessions", body=body, idempotency_key=idempotency_key))315316    async def retrieve(self, session_id: str) -> VerificationSession:317        return VerificationSession.from_dict(await self._c.request("GET", f"/verification-sessions/{seg(session_id)}"))318319    async def list(self, *, limit: int | None = None, starting_after: str | None = None, status: str | None = None,320                   external_user_id: str | None = None) -> Page[VerificationSession]:321        params = clean_params(limit=limit, starting_after=starting_after, status=status, external_user_id=external_user_id)322        return _page(await self._c.request("GET", "/verification-sessions", params=params), VerificationSession.from_dict)323324    async def list_auto_paging(self, *, limit: int | None = None, status: str | None = None, external_user_id: str | None = None) -> AsyncIterator[VerificationSession]:325        cursor: str | None = None326        while True:327            page = await self.list(limit=limit, starting_after=cursor, status=status, external_user_id=external_user_id)328            for item in page.data:329                yield item330            if not page.has_more or not page.data:331                return332            cursor = page.data[-1].id333334    async def cancel(self, session_id: str, *, idempotency_key: str | None = None) -> VerificationSession:335        return VerificationSession.from_dict(await self._c.request("POST", f"/verification-sessions/{seg(session_id)}/cancel", idempotency_key=idempotency_key))336337338class AsyncVerifications(_AsyncResource):339    async def retrieve(self, verification_id: str) -> Verification:340        return Verification.from_dict(await self._c.request("GET", f"/verifications/{seg(verification_id)}"))341342    async def status(self, verification_id: str) -> VerificationStatusSummary:343        return VerificationStatusSummary.from_dict(await self._c.request("GET", f"/verifications/{seg(verification_id)}/status"))344345    async def list(self, *, limit: int | None = None, starting_after: str | None = None, status: str | None = None,346                   external_user_id: str | None = None) -> Page[Verification]:347        params = clean_params(limit=limit, starting_after=starting_after, status=status, external_user_id=external_user_id)348        return _page(await self._c.request("GET", "/verifications", params=params), Verification.from_dict)349350    async def list_auto_paging(self, *, limit: int | None = None, status: str | None = None, external_user_id: str | None = None) -> AsyncIterator[Verification]:351        cursor: str | None = None352        while True:353            page = await self.list(limit=limit, starting_after=cursor, status=status, external_user_id=external_user_id)354            for item in page.data:355                yield item356            if not page.has_more or not page.data:357                return358            cursor = page.data[-1].verification_id359360    async def revoke(self, verification_id: str, *, reason: str | None = None, idempotency_key: str | None = None) -> Verification:361        return Verification.from_dict(await self._c.request("POST", f"/verifications/{seg(verification_id)}/revoke", body=clean_params(reason=reason),362                                                            idempotency_key=idempotency_key))363364    async def delete_personal_data(self, verification_id: str) -> PersonalDataDeletion:365        return PersonalDataDeletion.from_dict(await self._c.request("DELETE", f"/verifications/{seg(verification_id)}/personal-data"))366367368class AsyncWebhooks(_AsyncResource, _WebhookHelpers):369    async def create(self, *, url: str, events: list[str] | None = None, description: str | None = None, idempotency_key: str | None = None,370                     max_retries: int | None = None) -> CreatedWebhookEndpoint:371        return CreatedWebhookEndpoint.from_dict(await self._c.request("POST", "/webhooks", body=clean_params(url=url, events=events, description=description),372                                                                      idempotency_key=idempotency_key, max_retries=max_retries))373374    async def list(self) -> Page[WebhookEndpoint]:375        return _page(await self._c.request("GET", "/webhooks"), WebhookEndpoint.from_dict)376377    async def delete(self, endpoint_id: str) -> DeletedWebhookEndpoint:378        return DeletedWebhookEndpoint.from_dict(await self._c.request("DELETE", f"/webhooks/{seg(endpoint_id)}"))379380    async def rotate_secret(self, endpoint_id: str, *, idempotency_key: str | None = None, max_retries: int | None = None) -> RotatedWebhookSecret:381        return RotatedWebhookSecret.from_dict(await self._c.request("POST", f"/webhooks/{seg(endpoint_id)}/rotate-secret", idempotency_key=idempotency_key,382                                                                    max_retries=max_retries))383
Files main
Menu

Theme