SPB Git

Repository Public

README.md 8.7 KB

# maclustr-identity (Python)

Python SDK for MacLustr Identity, the self-hosted identity-verification platform. Sync and async clients with the same surface, webhook verification, typed objects and exceptions. Python 3.10+. Single dependency: httpx. Ships py.typed.

Secret keys never leave your server. mlid_sk_test_… and mlid_sk_live_… give full access to your application's verifications. This package is server-side only: never embed a key in a web page, a mobile app, a desktop app, a notebook you share or a public repository. The person being verified only receives the session url. The client never prints its key (repr() hides it).

# Install

Nothing is published to PyPI yet. Install from the repository path:

bash
pip install /absolute/path/to/maclustr-identity/sdk/python
# or, with uv
uv pip install /absolute/path/to/maclustr-identity/sdk/python

# Quickstart

python
import os
from maclustr_identity import MacLustrIdentity, APIConnectionError

identity = MacLustrIdentity(api_key=os.environ["MLID_SECRET_KEY"])

# 1. Gate the sensitive action on your server. Fail closed when the service is unreachable.
try:
    verification = identity.is_user_verified(user.id)   # newest valid verification, or None
except APIConnectionError:
    verification = None

if verification is None:
    # 2. Create a session and send the person to its hosted page.
    session = identity.verification_sessions.create(
        purpose="Raise the transfer limit",
        external_user_id=user.id,                        # opaque id, never an e-mail or a name
        return_url="https://wallet.example/verify/return",
    )
    redirect(session.url)

Async:

python
from maclustr_identity import AsyncMacLustrIdentity

async with AsyncMacLustrIdentity(api_key=os.environ["MLID_SECRET_KEY"]) as identity:
    session = await identity.verification_sessions.create(purpose="Raise the transfer limit", external_user_id="user_42")
    async for v in identity.verifications.list_auto_paging(status="verified"):
        print(v.verification_id, v.assurance_level)

# Client options

python
MacLustrIdentity(
    api_key,                                   # required, mlid_sk_test_… or mlid_sk_live_…
    base_url="https://identity.spboucher.ai",  # default
    timeout=30.0,                              # seconds, per attempt
    max_retries=2,                             # after the first attempt
    http_client=None,                          # optional httpx.Client (httpx.AsyncClient for the async client)
)

# Resources

MacLustrIdentity and AsyncMacLustrIdentity expose the same methods (awaitable on the async client).

Call HTTP
verification_sessions.create(purpose=…, external_user_id=…, verification_policy=…, return_url=…, locale=…, metadata=…, expires_in_minutes=…) POST /v1/verification-sessions
verification_sessions.retrieve(id) GET /v1/verification-sessions/{id}
verification_sessions.list(limit=…, starting_after=…, status=…, external_user_id=…) / .list_auto_paging(…) GET /v1/verification-sessions
verification_sessions.cancel(id) POST /v1/verification-sessions/{id}/cancel
verifications.retrieve(id) GET /v1/verifications/{id}
verifications.status(id) GET /v1/verifications/{id}/status
verifications.list(…) / .list_auto_paging(…) GET /v1/verifications
verifications.revoke(id, reason=…) POST /v1/verifications/{id}/revoke
verifications.delete_personal_data(id) DELETE /v1/verifications/{id}/personal-data
webhooks.create(url=…, events=…, description=…) POST /v1/webhooks
webhooks.list() GET /v1/webhooks
webhooks.delete(id) DELETE /v1/webhooks/{id}
webhooks.rotate_secret(id) POST /v1/webhooks/{id}/rotate-secret
is_user_verified(external_user_id) GET /v1/verifications?external_user_id=…&status=verified

Objects are frozen dataclasses (VerificationSession, CreatedVerificationSession, Verification, VerificationStatusSummary, PersonalDataDeletion, WebhookEndpoint, CreatedWebhookEndpoint, RotatedWebhookSecret, Page, Event). Each keeps the full JSON in .raw. Verification.is_valid is true only for a verified, non-expired verification. Timestamps are ISO 8601 strings; parse_datetime() converts.

# Idempotency and retries

  • Every POST carries an Idempotency-Key generated by the SDK, reused across the retries of that call. Pass idempotency_key="order-42" to make your own retries safe too. The service deduplicates every keyed POST: session creation and cancellation, revocation, webhook creation and secret rotation. A replay returns the first response (HTTP header Idempotent-Replayed: true); the same key with another body raises ConflictError (idempotency_key_reused).
  • Retries happen only on network errors, HTTP 429 and HTTP 5xx, with exponential backoff and jitter (0.5 s, 1 s, 2 s… capped at 8 s, each multiplied by a random factor in [0.5, 1]). Retry-After is honoured on 429 rate_limited and 503 service_unavailable (capped at 60 s). Quotas (daily_session_limit) are not retried. 4xx errors are never retried. webhooks.create and webhooks.rotate_secret are retried like any other POST, with the same key: a retry returns the endpoint or the secret of the first attempt (max_retries=0 disables retries for one call).

# Exceptions

All inherit MacLustrIdentityError (status, type, code, param, request_id, message).

Class When
InvalidRequestError 400, 411, 413, 422 (invalid_cursor, payload_too_large, length_required…)
AuthenticationError 401
PermissionDeniedError 403
NotFoundError 404 (also for objects of another application or mode)
ConflictError 409
RateLimitError 429 (retry_after in seconds)
APIServerError 5xx (retry_after in seconds on 503 service_unavailable)
APIConnectionError no response (code: connection_failed or request_timeout)
SignatureVerificationError webhook signature missing, malformed, expired or not matching

# Webhooks

Deliveries are signed: MLID-Signature: t=<unix>,v1=<hex>[,v1=<hex>], each v1 being HMAC-SHA256(secret, "<t>." + raw body). During a secret rotation two v1 values are sent for 24 hours. Other headers: MLID-Event-Id, MLID-Delivery-Id, MLID-Event-Type.

python
from maclustr_identity import Webhook, SignatureVerificationError

event = Webhook.construct_event(payload, sig_header, secret, tolerance=300)   # payload: the raw bytes
if event.verification is not None:        # decision events
    v = event.verification
    save(v.external_user_id, v.verification_id, v.status, v.assurance_level, v.expires_at)

payload must be the raw request body (await request.body() in FastAPI, request.get_data() in Flask). Deliveries are at-least-once and unordered: deduplicate on event.id. Complete endpoints: examples/fastapi_webhook.py, examples/flask_webhook.py.

Event types: verification.created, .processing, .expired, .cancelled (event.session is set) and .completed, .verified, .inconclusive, .manual_review, .rejected, .revoked (event.verification is set). After .cancelled, .expired (event.session_ended_without_decision) or an inconclusive result (for example reason review_not_completed: the manual review was not handled before its deadline) the person may simply start a new session. An event type or object kind added by a later service version never raises: event.object is then the plain dict and both properties are None.

# Testing your integration

python
from maclustr_identity.testing import complete_sandbox_session

session = identity.verification_sessions.create(purpose="Test", external_user_id="u1")
complete_sandbox_session(session.url, scenario="verified")   # or manual_review | inconclusive | rejected

It records consent and applies a sandbox scenario using the session client secret only (async variant: acomplete_sandbox_session). Sandbox results are flagged simulated=True with assurance_level="sandbox_simulated". Live sessions refuse it.

# Development

bash
uv venv .venv --python 3.12
uv pip install --python .venv/bin/python -e ".[dev]"
.venv/bin/pytest -m "not integration"    # unit tests
.venv/bin/pytest                         # + integration: local backend on http://localhost:8870 and its dispatcher

Integration tests provision two sandbox applications through the backend CLI (.venv of the repository, database maclustr_identity_sdk), or use MLID_SECRET_KEY / MLID_SECRET_KEY_B when set. They are skipped when no backend answers and refuse anything but localhost.

Files main
Menu

Theme