Metadata-Version: 2.5
Name: ais-identity
Version: 0.1.0
Summary: Framework-free Python core for Alpin Insight Identity Control Plane (ICp): verified claims, access decisions, token client and node evaluation.
Project-URL: Homepage, https://github.com/alpininsight/insight-identity-sdk
Project-URL: Documentation, https://github.com/alpininsight/insight-identity-sdk/tree/develop/packages/ais-identity#readme
Project-URL: Issues, https://github.com/alpininsight/insight-identity-sdk/issues
Author: Alpin Insight Solutions GmbH & Co. KG
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: httpx<1,>=0.28
Requires-Dist: pyjwt[crypto]<3,>=2.14.0
Description-Content-Type: text/markdown

# ais-identity

Part of the Python SDK for **Alpin Insight Identity Control Plane (ICp)**.

Framework-free core: verified claims, access decisions, token client and node
evaluation. Imports no web framework; `ais-identity-django` and
`ais-identity-fastapi` translate it into each framework's idiom.

Pre-release: not yet published to PyPI. See the
[repository README](https://github.com/alpininsight/insight-identity-sdk#readme).

## Deciding access

```python
from ais_identity import AccessContext, Requirement, decide

context = AccessContext.from_claims(verified_claims)
decision = decide(
    context,
    Requirement(any_scopes=["sources:read", "sources:configure"], require_tenant=True),
)
if not decision:
    raise PermissionError(decision.reason)  # a stable code, e.g. "missing_scope"
```

`from_claims` never verifies anything. Pass claims that a verifier or an OIDC
backend has already checked.

A `Requirement` says explicitly what a list means:

| Field | Meaning |
|---|---|
| `global_roles`, `tenant_roles` | any one of the roles |
| `all_scopes` | every scope |
| `any_scopes` | at least one scope |
| `capabilities` | every capability bundle, read from `capability_claim` (`gateway_roles` or `mcp_roles`) |
| `scope_claim` | where scopes are read; falls back to the OAuth `scope` string; `None` accepts any scope claim |
| `node`, `node_action`, `resource_type` | ask the provider whether the subject may use `node_action` at an organization unit |
| `write` | a data-plane write, subject to the write policy |
| `require_tenant` | deny unless one verified tenant resolves |

There is deliberately no plain `scopes` field: the two libraries this SDK
replaces read such a list in opposite ways. `ais_identity.compat` maps both
legacy forms, and tests pin each mapping against its original implementation.

`decide` checks the claims first, then the node, then the write rule, and
returns a `Decision` with `allowed`, a `reason` from `DenyReason`, advisories,
and `status_code` (401 without identity context, otherwise 403).

**Breaking.** Without a subject, `decide` denies every requirement. That
includes a pure login requirement such as an empty `Requirement()`, as well
as role, scope and node checks. The denial is `missing_identity_context` and
the node evaluator is not called. A local login with no OIDC `sub` stays
denied until the adapter's local-context hook supplies that `sub`.

## Principals and the write rule

The provider marks machines, not humans. On provider `develop` (`de7c7c9`),
`principal_type` is
[`MACHINE_PRINCIPAL_TYPE`](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/access_tokens.py#L59)
(`"service-client"`) and appears only on
[`client_credentials`](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/access_tokens.py#L229-L242)
tokens, where `sub` equals `client_id`. `AccessContext.principal` is
`HUMAN` when the claim is absent. A missing claim is never a service client.
SPIRE token exchange, off by default, sets `WORKLOAD`
([`spire_federation.py` L251-L257](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/spire_federation.py#L251-L257)).
The legacy client-id audience rejects that value on purpose. An unknown value
raises `UnknownPrincipalTypeError` instead of guessing.

Data-plane writes need a service client. A human may write only when every
scope guarding the call is an approved exception. `WritePolicy(mode=WARN)`, the
default, lets such a write through with an advisory; `ENFORCE` denies it.

## Verifying bearer tokens

```python
from ais_identity import AccessContext, Discovery, TokenVerifier

discovery = Discovery("https://id.example.com")  # issuer URL
verifier = TokenVerifier(
    discovery,
    expected_audience="https://api.alpininsight.ai/api/v1/sources",
)
context = AccessContext.from_claims(verifier.verify(bearer_token))
```

`expected_audience` is one canonical https resource URI: the gateway host plus
the group's catalog `base_path`, not `/api/v1/<group>`. Sources (scope
`sources:read`) is `https://api.alpininsight.ai/api/v1/sources`; development is
`https://api.dev.alpininsight.ai/api/v1/sources`. Digitraffic marine is
`https://api.alpininsight.ai/api/v1/digitraffic/marine`. Sources and
source-control share `/api/v1/sources` and are distinguished by scope. The
string must match exactly. A prefix such as `/api/v1/procurement` does not
match `/api/v1/procurement/ted`. A trailing slash, query, fragment, userinfo,
different casing, or whitespace is `token_audience_invalid`. Provider
`develop` (`de7c7c9`) puts one string in `aud`. The verifier also accepts a
one-entry array without changing the verified claim; empty and multiple-entry
arrays are `token_audience_invalid`. `client_id` is required (`token_azp_invalid` when
it is missing), including when `allowed_clients` is empty. `azp` is optional;
when it is present it must equal `client_id` (`token_azp_invalid`).
`allowed_clients` restricts those identifiers.

Today, on provider `develop` (`de7c7c9`), every service-API token has `aud`
equal to `client_id`. `resource` binds only MCP scopes. The canonical URI as
`aud` is
[insight-oidc-provider#821](https://github.com/alpininsight/insight-oidc-provider/pull/821)
(still open, `f856b25`) and is not today's behavior. Configuring
`expected_audience` without `legacy_client_audiences` rejects every real
token today.

`legacy_client_audiences` accepts one client id only when `client_id` equals
the single audience and `sub`, and `principal_type` is `PrincipalKind.SERVICE_CLIENT`
(`service-client`). On provider `develop` (`de7c7c9`) that claim is
[`MACHINE_PRINCIPAL_TYPE`](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/access_tokens.py#L59)
and is set only for
[`client_credentials`](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/access_tokens.py#L229-L242),
where `sub` equals `client_id`. User JWTs (`authorization_code` and user
refresh) omit the claim. A missing claim is never a service client and is
`token_audience_invalid`. SPIRE token exchange, off by default, can set
`principal_type` to `workload` with `aud` equal to `client_id`
([`spire_federation.py` L251-L257](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/spire_federation.py#L251-L257)).
The legacy transition rejects `workload` on purpose. A non-empty list emits
`PendingDeprecationWarning`, because every resource server needs the list
today. After #821 is deployed that warning becomes `DeprecationWarning`.
Empty the list only then. The parameter stays, so dropping the fallback later
is not a breaking change. A filter that errors only on `DeprecationWarning`
does not fail a resource server that still passes the list. Service APIs have
no slug audiences. A legacy match is logged once per audience per process and
is valid only together with `expected_audience`.
[insight-oidc-provider#828](https://github.com/alpininsight/insight-oidc-provider/issues/828)
is the later rejection of a request that omits `resource`. Removal of the
client-id audience is tracked in
[insight-oidc-provider#819](https://github.com/alpininsight/insight-oidc-provider/issues/819).
`audience=` is deprecated (`DeprecationWarning`): it still accepts any overlap
and cannot be combined with `expected_audience`. `expected_audience`, Django
`EXPECTED_AUDIENCE`, and Django `EVALUATION_RESOURCE` share
`resource_uri_problem`: lowercase `https`, no backslash, no invalid port such
as `:99999`, and no `..` path segment.

`verify` returns claims only after every check passed: algorithm allowlist
(`none` and symmetric algorithms are refused), `typ` `at+jwt`, the signing key
by `kid` from the JWKS, signature, `iss`, `aud`, `exp`, `nbf` and `iat` with
leeway, and the required claims. A failure raises `TokenVerificationError`
with a `code` such as `token_expired`, `token_audience_invalid`, or
`token_azp_invalid`. An unknown `kid` asks `Discovery.refresh_keys` for one
more fetch. A scheduled fetch
neither starts nor resets that cooldown. An unknown id is loaded immediately
only if no cooldown from an earlier unknown-id refresh is active. Unknown ids
share one extra request per `min_jwks_refresh_interval` (30 seconds by default),
even when a shorter `jwks_ttl` schedules another fetch during that wait. This
keeps forged key ids from bypassing the extra-fetch limit. A failed JWKS read
is remembered for the same interval and raised again as `DiscoveryError`
without a new request. A new signing key
still belongs in the JWKS before tokens use it (OpenID Connect Core 1.0
§10.1.1). Known keys follow `jwks_ttl` (default 600 seconds).

`verify` raises `DiscoveryError` only when the discovery document or the JWKS
cannot be read. That includes a JWKS outage after a valid discovery document:
`jwks_uri` returns HTTP 503, a body that is not JSON, or JSON without a
`keys` list. An empty `keys` list is not a `DiscoveryError`. An unknown `kid`
is `DiscoveryError` (answer 503) only when the JWKS read fails, because the
refresh cannot be fetched. When the JWKS is reachable and the `kid` is still
missing after the refresh, or from the cached key set within
`min_jwks_refresh_interval`, `verify` raises `TokenVerificationError` with
code `token_key_unknown` (answer 401, `Bearer error="invalid_token"`).
`jwt.InvalidKeyError` does not inherit from `jwt.PyJWKError`. A matching key
whose material cannot be used, such as an RSA modulus `n` of `"AA"`, makes
PyJWT raise `InvalidKeyError`; `verify` maps it to `token_key_unknown`. The
token is rejected either way.
`DiscoveryError` is not wrapped in `TokenVerificationError`.

Map the two errors to HTTP like this. The 503 body is fixed text and must
not contain `str(exc)`: that message includes the discovery URL.
`Retry-After` is an optional recommendation for the host. The adapter does
not set it.

```python
from ais_identity import DiscoveryError, TokenVerificationError


def verify_request(token: str) -> tuple[int, dict[str, str], object]:
    try:
        claims = verifier.verify(token)
    except TokenVerificationError:
        return 401, {"WWW-Authenticate": 'Bearer error="invalid_token"'}, ""
    except DiscoveryError:
        # Fixed body. str(exc) includes the discovery URL.
        # Retry-After is optional for the host. The adapter does not set it.
        return 503, {"Retry-After": "30"}, "Identity provider unavailable."
    return 200, {}, claims
```

## Getting a token as a service client

```python
from ais_identity import ClientCredentials, TokenClient

tokens = TokenClient(ClientCredentials(client_id, client_secret), discovery=discovery)
headers = {"Authorization": tokens.token(["sources:read"]).authorization}
```

The host passes the secret in; the SDK never reads environment variables or
secret stores. Tokens are cached per scope set and resource (RFC 8707),
refreshed ahead of expiry, and concurrent callers share one request.
`AsyncTokenClient` offers the same for `asyncio`.

The call above omits `resource`. That succeeds only as transitional behaviour:
the Provider sets `aud` to the client id.
[insight-oidc-provider #819](https://github.com/alpininsight/insight-oidc-provider/issues/819)
retains this no-`resource` fallback during the transition. Rejecting requests
that omit `resource` is a later migration whose timing will be tracked in a
separate Provider issue, not part of the initial #819 implementation. For an
allowlisted `resource`, #819 will give the token exactly one `aud`, the API's
canonical resource URI (for example `https://api.example.com/reports`); a
non-allowlisted resource will yield `invalid_target`. That resource-bound
service-API behaviour is not live. Until it is implemented, do not pass a
request URL as `resource`, and do not expect this token to satisfy any other
API audience. See the
[service-client persona](https://github.com/alpininsight/insight-identity-sdk/blob/develop/docs/personas/service-client.md#audience-is-a-separate-prerequisite).

`NodeEvaluationClient(..., resource=)` sends that indicator on the
`access:evaluate` token request and passes the same value to `invalidate`
after HTTP 401. Leave `resource` unset, or blank, and the request is
unchanged. The parameter defaults to off.

Do not set `resource` until the provider supports a dedicated binding for
`access:evaluate`. `POST /api/access/v1/evaluation` has no canonical resource
URI today. `access:` is not in the provider's `SERVICE_API_SCOPE_PREFIXES`, so
the current provider ignores `resource=` for `access:evaluate` and the audience
stays the client id. The proposed URI is
`{OIDC_ISSUER}/api/access/v1/evaluation`
([alpininsight/insight-oidc-provider#838](https://github.com/alpininsight/insight-oidc-provider/issues/838)).
Until the provider binds it, a set value returns `invalid_target` once unknown
targets are rejected
([alpininsight/insight-oidc-provider#821](https://github.com/alpininsight/insight-oidc-provider/pull/821))
and turns every node check into a deny. Django reads the optional value from
`AIS_IDENTITY["EVALUATION_RESOURCE"]`. Empty, whitespace-only, and `None`
omit `resource` and raise no check, including with a legacy
`EVALUATION_TOKEN` callable. That is the recommended state until the provider
binding exists. Surrounding whitespace on a set value is stripped.
`ais_identity.E005` and `ais_identity.W005` run only when the adapter sends
the value (a `TokenClient` built from `EVALUATION_CREDENTIALS`). The value
must then match the canonical form (alpininsight/insight-oidc-provider#821,
`canonical_resource_problem()` in `src/oidc_core/resource_indicators.py`,
lines 124-152 at `f856b25b15efed0f88c0dd072dc07d4f8ebc8d90`): an absolute https URI
with a host and no userinfo, no query, no fragment, no trailing slash, no
whitespace, and at most 2048 characters. The SDK is deliberately stricter
than that function: it rejects a backslash, it requires the scheme to be
exactly lowercase `https`, it rejects an invalid port, and it rejects a
`..` path segment. Anything else is `ais_identity.E005`. The hint names the
reason first, then says the value may be set only after
alpininsight/insight-oidc-provider#838 ("Do not set it"). A canonical value
warns with `ais_identity.W005` until that binding is live.
`ais_identity.E005`, `ais_identity.W005`, `ais_identity.W006`, and
`ais_identity.W007` are `check_evaluation_resource`, registered with
`deploy=True`, so they run on `manage.py check --deploy` and not on every
management command. They do not reuse `ais_identity.W001`, `W002`, or `W003`.
Silence the transitional `ais_identity.W005` with
`SILENCED_SYSTEM_CHECKS = ["ais_identity.W005"]`.
When the value is set but unused (no node evaluation, or
`EVALUATION_CLIENT`), the warning is only `ais_identity.W006`
("EVALUATION_RESOURCE is set but unused"). A legacy `EVALUATION_TOKEN`
ignores a set value and warns only "EVALUATION_RESOURCE is set but ignored"
(`ais_identity.W007`); an empty value stays silent. An invalid value
raises `ImproperlyConfigured` before any token request and is not sent.
A canonical value is still sent.

## Asking the provider about an organization unit

```python
from ais_identity import NodeEvaluationClient, evaluation_endpoint

evaluator = NodeEvaluationClient(evaluation_endpoint(issuer), tokens)
decision = decide(context, requirement, node_evaluator=evaluator.for_request())
```

The client calls `POST /api/access/v1/evaluation` with a token carrying
`access:evaluate`. Only HTTP 200 with `"decision": true` allows; HTTP 400, any
other status, a timeout or a failed token request deny. `for_request()` caches
answers for one request only. The cache key is the whole AuthZEN body.

`decide` puts the active tenant on that body's `context` when
`AccessContext.active_tenant` is set. The tenant of the calling policy client
is authoritative. Use one policy client, and one `EVALUATION_CREDENTIALS`
callable, per tenant. A multi-tenant host must use that tenant's policy client
for each active tenant
([contract at `de7c7c9f112dbe9ad648b8132e6da731179608d9`](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/docs/identity-access-contracts.md#L1106-L1110),
"One policy client per tenant"). Do not rely on `context` for tenant
isolation; it never selects the tenant. The fields are exactly
`context.tenant_id` (`AccessTenant.id`) and `context.tenant_slug`
(`AccessTenant.slug`). Both are optional; a missing value is omitted, and
`tenant_type` is not sent. Once
[alpininsight/insight-oidc-provider#839](https://github.com/alpininsight/insight-oidc-provider/issues/839)
is live, the provider evaluates them and a value that does not match that
binding is denied (`tenant_mismatch`). They can only trigger a deny. The
client binding stays authoritative. Today the provider does not evaluate
`context`. No active tenant sends `"context": {}`. `require_tenant=True`
still denies before the provider is asked when the tenant does not resolve.

Callers that build the question themselves pass the same mapping.
`context={}` removes the tenant context:

```python
from ais_identity import NodeQuery, authzen_context

query = NodeQuery(
    subject=access.subject,
    node="ais/lh",
    action="sources:read",
    context=authzen_context(access.active_tenant),
)
query.evaluation_request(context={})  # no tenant context
```

`NodeEvaluationClient.evaluate(..., context=)` does the same replacement when
the argument is not `None`, including when it is an empty mapping.

## Contract artifacts

`ais_identity.contract` ships the claim contract and the approved write-scope
exceptions as versioned JSON, so a JavaScript package can load the same files:

- `claims.v1.json`: every claim the provider emits, with category, condition
  and whether it carries access facts
- `write_exceptions.v1.json`: the approved human write-scope exceptions with
  their approval record
- `fixtures/v1/*.json`: a claim set per persona, for contract tests on the
  provider side and as realistic test input for consumers

`ais_identity.events.emit_decision_event` logs one structured event for denials
and advisories, without payloads or token material. `ais_subject` is the
provider subject and is empty when there is none. The event does not record
a local account id, username, email, or claims.
