Metadata-Version: 2.4
Name: iya-pep
Version: 0.1.0
Summary: The iya-sts remote Policy Enforcement Point, embedded in a Python application.
Author: Iya CyberSecurity Solutions, LLC
License: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cryptography>=42
Requires-Dist: regex>=2024.11.6
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Dynamic: license-file

# iya-pep

The [iya-sts](https://github.com/rcbj/iya-sts) remote Policy Enforcement Point, embedded in a Python application.

It is the shared PEP for the Python authentication libraries: [`oidc-caep-risc-python`](https://github.com/rcbj/oidc-caep-risc-python), [`saml2-sp-python`](https://github.com/rcbj/saml2-sp-python), [`wsfed-caep-python`](https://github.com/rcbj/wsfed-caep-python) and [`gnap-caep-risc-python`](https://github.com/rcbj/gnap-caep-risc-python). Each library depends on it and enables it from its own configuration, so an application does not normally use this package directly. The design is in [iya-sts #1206](https://github.com/rcbj/iya-sts/issues/1206). The Java counterpart is [`iya-pep-java`](https://github.com/rcbj/iya-pep-java) and the Rust counterpart is [`iya-pep-rust`](https://github.com/rcbj/iya-pep-rust).

## Modes

- **`central`:** every decision is an AuthZEN evaluation (`POST /access/v1/evaluation`) at iya-sts. An optional Permit cache (`permitCacheMs`, at most 60 s) is off by default.
- **`local`:** a lightweight XACML 3.0 engine decides in process. It holds only the bound application's policies (`GET /xacml/pep/policies?scope=bound-application`) and the realm's AuthZEN catalogue. It refreshes them when a `pep-policies-changed` Shared Signals event arrives, at `fallbackPollMs` (5 minutes) otherwise, or at `pollIntervalMs` (15 s) when the host has no signal stream.

Both modes take the same AuthZEN-shaped request and give the same answer.

## Policy revisions (`local` mode)

The service numbers every change to a realm's policy repository with a revision that only rises ([iya-sts #2352](https://github.com/rcbj/iya-sts/issues/2352)). The policy pull carries the repository's `revision`, a `revision` on each policy, and a `Policy-Revision` header on the 200 and on the 304. Two pulls can be answered by two nodes a moment apart, so the older answer can arrive second; `local` mode uses the revision to tell them apart.

- **An older set is not installed.** A set whose `revision` is lower than the one held is discarded and the held set kept, unless the service has really gone back (below). This is not an error: it is logged once (logger `iya_pep`, warning) when a run of refusals of one revision and token starts, not at every poll, and `status().last_error` and `pull_failures` do not change. A set at the held revision under a different sync token IS installed and its token adopted, since the service moves the token without a new revision for a change that alters no decision (a description, an orphan mark).
- **Each document keeps its highest revision.** If a newer set carries a copy of a policy older than the copy held, the held copy is kept. The check runs whenever the answer numbers its documents, even with no top-level `revision`; then the held sync token is kept too, so the next pull asks the same question.
- **A 304 raises the held revision** to its `Policy-Revision` when that is higher. A lower one is not followed, until the service is seen to have gone back (below).
- **When the service's revision really goes down.** Two server events lower the revision legitimately: a postgres or MariaDB restore from backup rolls the counter back with the policies, and a memory-store server starts numbering near 1 again when it restarts. A PEP that refused forever would keep enforcing the pre-restore policies, or report "not current" at every heartbeat, while looking healthy. So:
  - **Three answers in a row that agree** (`RESTORE_AGREEMENTS`, 3) on the same lower revision and the same sync token are taken as the service itself. On the third, the set is installed as the server sends it, its revision becomes the held one and the per-document revisions are replaced, not merged; for a 304, the held revision is lowered to its `Policy-Revision` and the per-document revisions are forgotten, since they came from the old numbering. Pulls run one at a time, so a lagging node can leave at most one stale answer between newer ones: any answer that does not agree (a newer set, another revision or token, a 304 at the held revision) ends the run and the count starts again. The adoption is logged at warning (logger `iya_pep`) once. After a restore, a PEP therefore follows the server within three poll intervals (or `pep-policies-changed` refreshes).
  - **A full pull is authoritative**: a pull that sends no sync token installs whatever the server answers, at the server's revisions, with no comparison. In this package the only full pull is the first one, at `start()` or the first `pull_now()`; there is no public way to force one later, so the other escape is a restart of the host process.
  - **Two answers at the same revision under different tokens**: the later-installed one's token is kept. Pulls are serialised, so that is the later-issued answer whenever the server issued them in the order they were asked; if not, the next poll sends that token as its `If-None-Match` and the server's 200 repairs it.
- **A 503 `temporarily_unavailable`** (the service is still numbering a change) is not an error either. The held set is kept, and the worker pulls again after `Retry-After`, or at the next poll if that is sooner, and never within one second.
- **The heartbeat reports `policyRevision`**, the revision held, or `null` when none is held. A PEP that reports one is current only when it holds the service's sync token and its revision.
- **`status().policy_revision`** is the revision held, read only, or `None`.
- **A server that sends no revision** is followed by its sync token alone, exactly as before; `policy_revision` stays `None` and the heartbeat reports `null`.
- **The compare and the install are one step.** A pull weighs its answer against the set it read and installs it only if that set is still the one held (compare-and-set), weighing again otherwise. A poll and a `pep-policies-changed` refresh finishing in either order end on the newer set.

`central` mode pulls no policies, so none of this applies to it: it holds no revision, its heartbeat sends no `policyRevision`, and its Permit cache is dropped on a `pep-policies-changed` event as before. `local` maps an evaluation through the catalogue exactly as the service does, and its engine is held to the service's conformance corpus.

## Use

```python
from iya_pep import Access, Mode, Pep, PepConfig, Subject

config = PepConfig("pep-orders", Mode.LOCAL, "/etc/app/pep-key.pem",
                   "https://sts.example/realm/shop", "orders")
pep = Pep.create(config)
pep.start()

subject = Subject.user("alice", claims)
decision = pep.decide(subject, Access.of("read", "order", "42"))
status = decision.http_status()  # 200 for a Permit, 403 for anything else

pep.on_policy_event(event_payload)
pep.stop()
```

- **The subject** is a claims map the host library builds from its own sign-in. Only the claims the realm's catalogue declares are sent, because the service refuses an evaluation that names any other.
- **`decide` never fails, and every failure is a 403.** No policy held yet, a service that cannot be reached or answers badly, an engine fault, or a failure while deciding is `Unavailable`, never a Permit. `Decision.http_status()` is 403 for it as for a Deny (200 only for a Permit). A missing attribute is a Deny. A processing or syntax error is `Unavailable`. An obligation the host did not declare turns a Permit into a Deny.
- **A cached Permit does not outlive an outage or a policy change.** In `central` mode with `permitCacheMs`, a failed evaluation, a failed heartbeat or a `pep-policies-changed` event drops every cached Permit, and none is served until the service answers an evaluation again. A Permit asked for before the drop and answered after it is not cached. The cache is a least-recently-used cache of at most `permitCacheMaxEntries` Permits; an expired Permit is dropped when read, and by a sweep on the worker's tick and at most once per `permitCacheMs` on an insert.
- **Obligations:** a Permit carries only obligations of the types named in `supportedObligations`. Anything else turns the Permit into a Deny.

## The PEP's credential

The PEP has a key of its own: EC P-256, or RSA of 2048 bits or more. With it, the PEP signs an RFC 7523 self-assertion through the `sts-remote-pep` client and gets a DPoP-bound token for each audience: `xacml:pep`, `xacml:pep-audit` and `authzen:evaluate`.

The key is certified, and the PEP bound to its application, with iya-sts's `issue-pep-credential`. `key_thumbprint()` lets the host library refuse a configuration where the PEP's key is one of its own. `reload_key()` reads a rotated key at once; otherwise the file is checked every 30 s.

## Configuration

`PepConfig.from_json(section, default_pdp_url, default_application)` reads a library's `pep` section. JSON members are camelCase, and an unknown member is refused. A number must be a JSON integer: `15000.0` is refused, as Rust refuses it.

| Member | Default | |
|---|---|---|
| `name` | (required) | The PEP's service account: 1 to 128 characters of `[A-Za-z0-9._-]`. |
| `mode` | `local` | `local` (pull the bound application's policies and decide in process) or `central` (ask the service for every decision). |
| `assertionKey` | (required) | The path of the PEP's private key, in PEM. |
| `clientId` | `sts-remote-pep` | |
| `pdpUrl` | the library's issuer | The service, with `/realm/<id>`. An http(s) URL without a query. |
| `application` | the library's client | The application the PEP is bound to. |
| `pollIntervalMs` | 15000 | `local` without a signal stream. 1000 to 86400000. |
| `fallbackPollMs` | 300000 | `local` with one. 1000 to 86400000. |
| `heartbeatIntervalMs` | 30000 | 1000 to 86400000. |
| `decisionRecords` | true | `local`: each decision is sent to the service's audit log. |
| `permitCacheMs` | 0 | `central` only; at most 60000. |
| `permitCacheMaxEntries` | 10000 | The most Permits the `central` cache holds, from 1 to 1000000. Over the cap the least recently used Permit is evicted; expired Permits are dropped when read and swept on an insert and on the PEP's tick. |
| `signals` | false | The host hands over `pep-policies-changed` events. |
| `supportedObligations` | [] | Obligation types the application discharges. |
| `tlsCa` | | PEM trust anchors for the service. |
| `timeoutMs` | 10000 | 100 to 86400000. |

## The thumbprint helpers

A library must refuse a configuration where the PEP's key is one of its own. The package gives it the RFC 7638 thumbprints to compare:

- `pep.key_thumbprint()`: the PEP's own key.
- `jwk_thumbprint(jwk)`: a public JWK (EC, RSA or OKP), as a dict. `None` for one it cannot read.
- `pem_thumbprint(pem)`: the public half of a PEM private key (EC or RSA). `None` for one it cannot read.

```python
from iya_pep import pem_thumbprint

mine = pem_thumbprint(open(app_key_path).read())
if mine is None or pep.key_thumbprint() is None or mine == pep.key_thumbprint():
    raise ValueError("pep.assertionKey must be a key of the PEP's own")
```

A `None` thumbprint is not "different": treat it as a configuration error, so the check fails closed.

## Thread safety

- **One `Pep` is shared by every request thread.** `decide`, `decide_async`, `on_policy_event`, `set_event_stream`, `pull_now`, `status`, `key_thumbprint` and `reload_key` may be called from any number of threads at once, and `start`, `stop` and `close` may race them and each other.
- **`start` and `stop` are serialised.** A `stop` racing a `start` ends with one worker or none, never two, and never hangs: each worker has a stop event of its own, and `stop` waits for it at most `5 s + 4 × timeoutMs`. A worker still inside a network call after that ends on its own once the call returns.
- **One pull at a time.** The worker's pulls and `pull_now()` are serialised, and the install is a compare-and-set on the repository revision, so an older answer is never installed over a newer one unless three in a row agree that the service went back (see *Policy revisions*).
- **A `Decision`, `Subject`, `Access` or `PepConfig` belongs to its caller.** The PEP copies what it caches. Do not change a `PepConfig` after `Pep.create`.
- **`decide_async` runs on the event loop's default executor** (`asyncio.to_thread`), so the number of decisions in flight at once is bounded by that executor's thread count. A host that needs more sets its own with `loop.set_default_executor`.

## Async

`start_async()`, `decide_async(subject, access)` and `stop_async()` are coroutines for an asyncio host, matching Rust's `tokio` feature. The control plane's HTTP client is synchronous (urllib), so each one runs the blocking call with `asyncio.to_thread`, as Rust runs it with `spawn_blocking`. The event loop is never blocked; the calls run on the loop's default executor, which a host may replace with `loop.set_default_executor`. `decide_async` never raises for a PEP failure: a call the executor cannot run is `Unavailable`.

## API

Import `iya_pep`. The distribution name is `iya-pep`. Python 3.11.

`Pep.create(config)` reads the configuration and the key and sends nothing. Token renewal is timed on the monotonic clock, so a wall-clock step neither expires a token early nor keeps one past its life. `start()` registers and pulls before it returns, then keeps a daemon thread. `stop()` ends that thread and sends queued decision records once more; it may be called from any thread, and races with `start()` are safe. `decide(subject, access)` returns a `Decision` and does not raise for a PEP failure. `on_policy_event(payload)` hands over a verified `pep-policies-changed` event; an event naming another PEP is ignored, and a matching event drops cached Permits and pulls. `set_event_stream(state)` tells the heartbeat what the host's signal stream can deliver (`EventStream.NONE`, `REQUESTED`, `EXCLUDED`, or `DOWN`). `pull_now()` pulls and waits; an older set it is answered is discarded, and a 503 `temporarily_unavailable` keeps the held set, neither raising. `status()` returns a `Status` with no secret; in `local` mode its `sync_token` and `policy_revision` describe the set held. `key_thumbprint()` is the RFC 7638 thumbprint. `reload_key()` returns whether the key material changed. The package also exports `jwk_thumbprint(jwk)` and `pem_thumbprint(pem)`, the RFC 7638 thumbprints of a public JWK (EC, RSA or OKP) and of a PEM private key's public half, each `None` for a key it cannot read, so a library compares its own keys with the PEP's.

`Decision.kind()` is `Kind.PERMIT`, `Kind.DENY`, or `Kind.UNAVAILABLE`. `http_status()` is 200 only for a Permit. `why()` explains a Deny or an Unavailable. `obligations()` and `advice()` are lists of `Obligation` (`id`, `kind`, `properties`) and are empty unless the decision is a Permit. `is_permit()` is the same test as the status.

`Subject.user(id, properties)` builds a user. `Access.of(action, resource_type, resource_id)` builds the access; `action_properties`, `resource_properties`, and `context` are optional maps. `PepConfig.from_json(section, default_pdp_url, default_application)` is how a library reads its `pep` object. `Mode.LOCAL` is the default.

## Tests

```sh
docker build --target test .
```

`tests/test_concurrency.py` is the concurrency suite: barrier-started threads over many rounds for parallel decides for different subjects in both modes, a policy event and an outage during a central evaluation, concurrent pulls, `start`/`stop` races, and the bounded Permit cache. `tests/test_revisions.py` holds the revision rules, with barrier-started pulls answered revisions N and N - 1 in either order over many rounds.

Do not run pytest on the host. The image is `python:3.11-slim`.

## License

MIT, in `LICENSE`. `src/test/resources/corpus/oasis/` is Apache-2.0 (`LICENSES/Apache-2.0.txt`). `src/test/resources/corpus/PROVENANCE.md` says why.
