Metadata-Version: 2.4
Name: permitplane-backend
Version: 0.1.0
Summary: Server-side helpers for PermitPlane vendor backends: typed client, safe retries and webhook verification.
Author: Bitbat Oy
License-Expression: Apache-2.0
Project-URL: Homepage, https://permitplane.com
Keywords: permitplane,licensing,license,webhooks,idempotency
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: test
Requires-Dist: pytest<9,>=8; extra == "test"
Requires-Dist: jsonschema<5,>=4.25; extra == "test"
Dynamic: license-file

# permitplane-backend (Python)

Server-side helpers for PermitPlane vendor backends: a typed client for the
`/integration/v1` backend routes, typed errors, safe retries and webhook
signature verification. Standard library only at runtime, Python >= 3.10.

Install: `pip install permitplane-backend`. Licensed under Apache-2.0.

## Use

```python
import os
from datetime import datetime, timezone
from permitplane_backend import PermitPlaneBackend, derive_idempotency_key

pp = PermitPlaneBackend(
    "https://licensing.example.com",  # https only; a path prefix is allowed
    os.environ["PERMITPLANE_BACKEND_TOKEN"],  # VendorBackend bearer secret
)

# resolve -> read the enrollment -> authorize
customer = pp.resolve_customer(
    product_id=product_id, namespace_id=namespace_id,
    external_subject=user.id, verification_reference=f"myapp-verified:{user.id}",
)
enrollment = pp.get_enrollment(enrollment_id)
pp.authorize_enrollment(
    enrollment_id, customer_id=customer["customer_id"], mode="trial",
    verification_reference=f"myapp-verified:{user.id}", expected_revision=enrollment["revision"],
)

# issue a licence; derive the key from your own order so a restarted worker replays
pp.issue_license(
    product_id=product_id, namespace_id=namespace_id, customer_id=customer["customer_id"],
    policy_id=policy_id, paid_through=datetime(2027, 1, 1, tzinfo=timezone.utc), reason="Order ord_123",
    idempotency_key=derive_idempotency_key("order", "ord_123", "issue"),
)
```

Wire dictionaries stay snake_case (TypedDicts live in `permitplane_backend.types`).
Also available: `deny_enrollment`, `list_policies`, `get_license`,
`act_on_license`, `deliver_license_key`, `revoke_license_key`,
`issue_license_file`. `datetime` values must be timezone-aware.

Offline (air-gapped) installs: `issue_license_file` signs a licence file (scope
`license_files.issue`). `valid_days` (1 to 21) and `installation_key_thumbprint`
(43 base64url characters, binds the file to one installation) are optional.
Write `license_file` to disk exactly as returned.

```python
issued = pp.issue_license_file(
    license_id, product_id=product_id, customer_id=customer_id,
    valid_days=7, installation_key_thumbprint=thumbprint,
)
Path(issued["filename"]).write_text(issued["license_file"], encoding="utf-8", newline="")
```

Self-hosting behind a sub-path works: `"https://host/licensing"` (a trailing
slash is normalised; backslashes, `%` escapes and dot segments are rejected). Plain `http` is accepted only for `127.0.0.1`,
`localhost` and `::1` and only with `allow_insecure_http=True`.

## Errors

Everything extends `PermitPlaneError`. Server errors are `ApiError` subclasses
carrying `status`, `code`, `message` (the server's text), `request_id`,
`details`, `retry_after_seconds`, `idempotency_key`, `method` and `path`.

```python
from permitplane_backend import RevisionConflictError, IdempotencyConflictError

try:
    pp.authorize_enrollment(enrollment_id, **fields)
except RevisionConflictError:
    ...  # reload the enrollment and retry
except IdempotencyConflictError:
    ...  # same key, different body: a bug
```

`str(err)` is `<code> (HTTP <status>, request <id>)`. Error objects never
contain the token, request bodies or response bodies.

## Idempotency and retries

Keyed operations (resolve, authorize, deny, issue, act) always send an
`Idempotency-Key`: yours via `idempotency_key=`, or a generated one reused for
every automatic retry and exposed as `err.idempotency_key`. The server keeps
receipts for 24 hours for resolve/authorize/deny and permanently for
issue/act. A changed body with the same key gives `IdempotencyConflictError`.

Automatic retries (default `max_retries=2`, so at most 3 attempts; `timeout`
15 s per attempt; `max_retry_delay` 5 s; timeouts and delays must be positive and finite, retries an integer from 0 to 10, else `ConfigurationError` or, per call, `RequestValidationError`) apply to GETs and keyed POSTs on
transport errors, timeouts, 502, 503, 504, 429 and 409 `operation_in_progress`.
`deliver_license_key`, `revoke_license_key` and `issue_license_file` are never
retried automatically; repeating them yourself is safe (a repeated
`issue_license_file` signs and records a new file).

The server currently sends `Retry-After: 60` on every 429 and 503. That is
above `max_retry_delay`, so those surface immediately as `RateLimitedError` or
`ServiceUnavailableError` with `retry_after_seconds == 60`. Do not block a
request handler for a minute; queue the work and retry later.

## Security

- The token is server-only. Never ship it to apps or browsers.
- Redirects are refused (`UnexpectedResponseError`); the token is never
  forwarded elsewhere. Responses are capped at 1 MiB and `timeout` is a total per-attempt deadline (headers and body), not just a per-read one.
- `deliver_license_key` responses contain a secret licence key. Do not log them.
- `repr(client)` omits the token. A custom CA bundle can be passed as `ca_bundle=`.

## Webhooks

Header `PermitPlane-Signature: t=<unix seconds>,v1=<sig>[,v1=<sig>]`, where
`sig` is the lowercase hex HMAC-SHA256 of `"<t>." + raw body` keyed with the
UTF-8 bytes of the full secret (`ppwhsec_...`). Tolerance is 300 seconds (inclusive), uppercase hex is tolerated, and
any matching `v1` is accepted, so you can pass old and new secrets together.

```python
from permitplane_backend import parse_webhook_event, WebhookSignatureError

try:
    event = parse_webhook_event(
        request.body,  # the RAW body (Django: request.body), never re-serialized JSON
        request.headers.get("PermitPlane-Signature"),
        [os.environ["PP_WEBHOOK_SECRET"]],
    )
except WebhookSignatureError:
    ...  # respond 400
```

Dedupe on the event id, and call `get_license` for the authoritative state
rather than trusting arrival order.
