SPB Git

Repository Public

SDK_PYTHON.md 14.5 KB

# MacLustr Identity — Python SDK

Package maclustr_identity, source in sdk/python. Python 3.10+, one dependency (httpx), fully typed (py.typed), synchronous and asynchronous clients with the same surface.

Status: not published to PyPI. Install from the repository path (see below). Version 0.1.0.

# Security rule: server-side only

A secret key (mlid_sk_test_…, mlid_sk_live_…) can read, revoke and erase every verification of your application. This SDK is meant for server code: never embed a key in a web page, a mobile or desktop app, a shared notebook or a repository. The person being verified only ever receives the session url. The webhook signing secret (whsec_…) is server-side only as well.

The clients refuse a value that is not a secret key and never print the key (repr() shows the base URL and the mode). Created objects hide client_secret, url and webhook secret from their repr().

# Install

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

integrations/demo-wallet/setup.sh installs it in editable mode (-e ../../sdk/python).

# Quickstart

python
import os
from maclustr_identity import MacLustrIdentity, MacLustrIdentityError

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

def may_raise_limit(user_id: str) -> bool:
    try:
        return identity.is_user_verified(user_id) is not None
    except MacLustrIdentityError:
        return False                      # unreachable or failing service: stay refused (fail closed)

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 the browser to session.url

Async:

python
from maclustr_identity import AsyncMacLustrIdentity

async with AsyncMacLustrIdentity(api_key=os.environ["MLID_SECRET_KEY"]) as identity:
    verification = await identity.is_user_verified("user_42")

A complete application is in integrations/demo-wallet; the generic guide is in integrations/README.md.

# Clients

MacLustrIdentity(api_key, *, base_url="https://identity.spboucher.ai", timeout=30.0, max_retries=2, http_client=None) AsyncMacLustrIdentity(...) — same arguments, http_client being an httpx.AsyncClient.

Argument
api_key required; must start with mlid_sk_test_ or mlid_sk_live_
base_url origin of the service, no path
timeout seconds, per attempt
max_retries retries after the first attempt
http_client your own httpx.Client / httpx.AsyncClient (it is then yours to close)

Both are context managers (with / async with); otherwise call close() / await aclose(). Attributes: base_url, livemode, verification_sessions, verifications, webhooks.

Every method below exists on both clients; on the async client it is awaitable, and list_auto_paging is an async iterator (async for).

# verification_sessions

Method Returns
create(*, purpose, external_user_id=None, verification_policy=None, return_url=None, locale=None, metadata=None, expires_in_minutes=None, idempotency_key=None) CreatedVerificationSession
retrieve(session_id) VerificationSession
list(*, limit=None, starting_after=None, status=None, external_user_id=None) Page[VerificationSession]
list_auto_paging(*, limit=None, status=None, external_user_id=None) iterator of VerificationSession
cancel(session_id, *, idempotency_key=None) VerificationSession

purpose is required (≤ 120 characters, shown to the person). verification_policy defaults to identity_document_face_v1; identity_document_v1 is the document-only policy. return_url must be allowed for the application. metadata is at most 2000 bytes and must not hold personal data. expires_in_minutes is clamped to 10..1440 (default 60). CreatedVerificationSession adds client_secret and url, returned by create only.

Session statuses: created, awaiting_consent, awaiting_document, awaiting_selfie, processing, manual_review, verified, inconclusive, rejected, expired, cancelled, revoked. A cancellation emits verification.cancelled. An unknown starting_after raises InvalidRequestError (invalid_cursor).

# verifications

Method Returns
retrieve(verification_id) Verification
status(verification_id) VerificationStatusSummary (status, valid, assurance_level, expires_at)
list(*, limit=None, starting_after=None, status=None, external_user_id=None) Page[Verification]
list_auto_paging(*, limit=None, status=None, external_user_id=None) iterator of Verification
revoke(verification_id, *, reason=None, idempotency_key=None) Verification
delete_personal_data(verification_id) PersonalDataDeletion (deleted, counters in .raw)

Verification attributes: verification_id, session_id, status, assurance_level, method, verification_policy, policy_version, livemode, simulated, external_user_id, reasons (list of Reason(code, message)), dimensions, decision_engine, created_at, verified_at, expires_at, revoked_at, personal_data_deleted_at, and the property is_valid (status verified and not expired). It never contains a name, a document number, an image or any extracted field.

Verification statuses: verified, manual_review, inconclusive, rejected, revoked. A status added by a later service version is kept as received (is_valid is then False). dimensions maps each dimension to {"status": …} with optional notes; scores are not kept once a decision is made. reason_codes lists the codes of reasons: among them review_not_completed (the review by a person was not completed before its deadline: the result is inconclusive and the person may start again) and decision_overturned (a contested decision was set aside). KNOWN_REASON_CODES and RETRYABLE_SESSION_STATUSES are exported. Assurance levels: document_check, document_face_liveness_check, document_manual_review, document_face_manual_review, and sandbox_simulated for sandbox results (simulated=True).

# is_user_verified(external_user_id)

Lists the user's verified verifications (newest first) and returns the first valid one, or None. It raises like any other call when the service is unreachable: treat that as "not verified".

# webhooks

Method Returns
create(*, url, events=None, description=None, idempotency_key=None, max_retries=None) CreatedWebhookEndpoint (with secret, once)
list() Page[WebhookEndpoint]
delete(endpoint_id) DeletedWebhookEndpoint
rotate_secret(endpoint_id, *, idempotency_key=None, max_retries=None) RotatedWebhookSecret
construct_event(payload, sig_header, secret, tolerance=300) Event (same as Webhook.construct_event)
verify_signature(payload, sig_header, secret, tolerance=300) None

# Objects

All objects are frozen dataclasses built with from_dict. The complete JSON is kept in .raw; a field the API did not send is None, an unknown field is ignored (but stays in .raw), so API evolutions do not raise. Timestamps are ISO 8601 strings; parse_datetime(value) returns an aware datetime. Page has data, has_more, and supports len() and iteration.

# Webhooks

python
from maclustr_identity import Webhook, SignatureVerificationError

try:
    event = Webhook.construct_event(payload, sig_header, secret, tolerance=300)
except SignatureVerificationError:
    return 400
  • payload is the raw request body (bytes or str): await request.body() in FastAPI / Starlette, request.get_data() in Flask, request.body in Django. A parsed dict is refused (payload_not_raw).
  • sig_header is the MLID-Signature header: t=<unix seconds>,v1=<hex>[,v1=<hex>]. Each v1 is HMAC-SHA256(secret, "<t>." + raw body). After rotate_secret, two v1 values are sent for 24 hours and either secret verifies.
  • Comparison uses hmac.compare_digest. The timestamp must be within tolerance seconds of now.
  • Error codes: signature_header_invalid, signature_mismatch, signature_expired, payload_not_raw, payload_invalid, secret_missing.
  • Other headers: MLID-Event-Id (stable across retries), MLID-Delivery-Id, MLID-Event-Type.

Event attributes: id, type, api_version, created (unix seconds), livemode, object, raw, and two convenience properties:

Event types Set property
verification.created, verification.processing, verification.expired, verification.cancelled event.session (VerificationSession)
verification.completed, verification.verified, verification.inconclusive, verification.manual_review, verification.rejected, verification.revoked event.verification (Verification)

event.session_ended_without_decision is true for verification.cancelled and verification.expired: nothing was decided and the person may start a new session. verification.cancelled is sent when your server cancels a session and when the person withdraws consent, including during a manual review; in that last case no decision event follows and the session carries the verification_id of the review that will never conclude. An event type or object kind this SDK version does not know never raises: event.type is the string received, event.object is the plain dict and both properties are None.

Deliveries are at-least-once and unordered: deduplicate on event.id, and do not let an older event overwrite a newer state. Webhook.sign(payload, secret, timestamp=None) builds a header for your own tests.

Complete endpoints, both covered by the test suite: examples/fastapi_webhook.py, examples/flask_webhook.py.

# Idempotency and retries

Every POST sends an Idempotency-Key (sdk-<uuid>), identical across the automatic retries of that call; pass idempotency_key= to cover your own retries. The service honours it on session creation, session cancellation, verification revocation, webhook creation and secret rotation: a repeated key with the same body returns the original response (HTTP header Idempotent-Replayed: true; the SDK returns the object, it does not expose the header), 409 idempotency_key_reused when the body differs, and 409 idempotency_in_progress while the first request is still running.

Only network errors (including timeouts), HTTP 429 and HTTP 5xx are retried, up to max_retries times. Delay before retry n (0-based): a random value in [50 %, 100 %] of min(8 s, 0.5 s × 2ⁿ). When the response carries Retry-After (429 rate_limited, 503 service_unavailable), that delay is used instead, capped at 60 s. Quotas (429 daily_session_limit) are not retried. No other 4xx is ever retried. backoff_delay(attempt) and should_retry(status, code) are exported. webhooks.create and webhooks.rotate_secret are retried like every other POST, with the same key: a retry returns the endpoint (and its secret) or the rotated secret of the first attempt, it never creates or rotates twice (max_retries=0 disables retries for one call). Two separate calls use two keys: calling rotate_secret again rotates again. Rate limits are shared by every process of the service: several of your workers using the same key share one budget.

# Exceptions

MacLustrIdentityError attributes: message, status (None without a response), type, code, param, request_id, headers.

Class HTTP Typical code
InvalidRequestError 400, 411, 413, 422 purpose_required, unknown_policy, return_url_not_allowed, invalid_webhook_url, invalid_cursor (unknown starting_after), payload_too_large (413, body over 256 KB), length_required (411)
AuthenticationError 401 missing_api_key, invalid_api_key
PermissionDeniedError 403 insufficient_scope, application_suspended, compliance_gate_closed, forbidden_network
NotFoundError 404 resource_missing (also for objects of another application or mode, including a webhook endpoint deleted or rotated with a key of the other mode)
ConflictError 409 session_not_cancellable, not_revocable, idempotency_key_reused, idempotency_in_progress
RateLimitError 429 rate_limited, daily_session_limit; has retry_after
APIServerError 5xx internal_error, service_unavailable (503); has retry_after
APIConnectionError none connection_failed, request_timeout
SignatureVerificationError none see Webhooks

# Testing helper

python
from maclustr_identity.testing import complete_sandbox_session, acomplete_sandbox_session

complete_sandbox_session(session.url, scenario="verified")

Arguments: url (or session_id + client_secret + base_url), scenario (verified | manual_review | inconclusive | rejected), method (default: the first method of the policy), http_client. It calls GET /v1/sessions/{id}, POST …/consent and POST …/sandbox with the session client secret and returns the flow state. It raises on a live session.

# Tests

bash
cd sdk/python
uv venv .venv --python 3.12 && uv pip install --python .venv/bin/python -e ".[dev]"
.venv/bin/pytest -m "not integration"   # 56 unit tests: signature, retries, idempotency, errors, tolerant models, pagination, async, examples
.venv/bin/pytest                        # + 12 integration tests against the local backend (MLID_BASE_URL, default http://localhost:8870) with its dispatcher

# Known limitations

  • webhooks.list() is not paginated by the service (at most 16 endpoints per application and mode).
  • webhooks.delete and verifications.delete_personal_data are DELETE calls: the service does not deduplicate them. A retried webhooks.delete whose first answer was lost raises NotFoundError: the endpoint is gone, which is what was asked.
  • The Idempotent-Replayed response header is not exposed by the SDK.
  • A 413 payload_too_large is answered before the body is read and the connection is closed: depending on timing, httpx may report it as an APIConnectionError instead of the 413 when the body is still being sent.
  • No built-in Django example; Webhook.construct_event(request.body, request.headers.get("MLID-Signature"), secret) is all it takes.
Files main
Menu

Theme