Metadata-Version: 2.5
Name: ais-identity-django
Version: 0.1.1
Summary: Django app for Alpin Insight Identity Control Plane (ICp): session access context, decorators, mixins and DRF permissions over the ais-identity core.
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-django#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: Framework :: Django
Classifier: Framework :: Django :: 6.0
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: ais-identity==0.1.1
Requires-Dist: django<7,>=6.0.4
Provides-Extra: drf
Requires-Dist: djangorestframework<4,>=3.16; extra == 'drf'
Description-Content-Type: text/markdown

# ais-identity-django

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

Django app over the `ais-identity` core: the session access context,
`access_required`, `AccessRequiredMixin`, DRF permissions, node checks and the
write rule. The semantics live in the core; this package only reads the session
and speaks Django.

Version [0.1.0 is published on PyPI](https://pypi.org/project/ais-identity-django/0.1.0/).
Later source changes require a separate release. See the
[repository README](https://github.com/alpininsight/insight-identity-sdk#readme).

## Setup

```python
INSTALLED_APPS = [..., "ais_identity_django"]

AIS_IDENTITY = {
    "ISSUER": "https://id.example.com",
    # Zero-argument callable returning ais_identity.ClientCredentials for access:evaluate.
    "EVALUATION_CREDENTIALS": "myapp.secrets.evaluation_credentials",
    "WRITE_SCOPE_ENFORCEMENT": "warn",
}
```

The OIDC authentication backend stores verified claims after it checked the ID
token:

```python
from ais_identity_django.session import store_verified_access_claims

store_verified_access_claims(request, verified_claims)
```

The stored projection must include the provider `sub`. If `sub` is missing or
blank, or `principal_type` is unknown, the context is invalid (`source`
`invalid_claims`, no subject and no claim facts). The Django user's primary
key is not used as the subject.

A local Django user with no OIDC session and no `LOCAL_CONTEXT` is denied on
every `decide()` check. That includes a pure login requirement: an empty
`Requirement()`, `@access_required()` with no arguments, and `HasAccess` with
no declarations. The same denial applies to role, scope, capability and node
checks. The reason is `missing_identity_context` and the PDP is not asked. An
untrusted DRF session is denied the same way. **Breaking:** local staff,
admin and test logins that have no OIDC projection cannot pass those checks
until `LOCAL_CONTEXT` supplies a provider `sub`, or the user signs in with a
login that carries an OIDC `sub`. Django's own admin and staff permission
still guards `/admin/`; it does not satisfy `access_required`.
`@access_required()` without arguments is not a login check. For a plain login
check, use `LoginRequiredMixin` / `@login_required` (DRF: `IsAuthenticated`).
insight-ui-user v2.0.0 raises `ImproperlyConfigured` for an undeclared
`AccessRequiredMixin` or an empty `access_required()`
(alpininsight/insight-ui-user#547).

DRF support is optional: `pip install "ais-identity-django[drf]"`.

## Views

```python
from ais_identity_django.access import AccessRequiredMixin, access_required


@access_required(scopes=["sources:read"])  # every listed scope
def report(request): ...


@access_required(scope="sources:read", node="kwarg:unit")  # asks the provider about the unit
def unit(request, unit): ...


class Settings(AccessRequiredMixin, View):
    access_scope = "sources:configure"
    access_write = True  # data-plane write: write rule applies
```

Async function views work with the same decorator. `@access_required()` without
arguments is not a login check, and it still requires a provider subject. For a
plain login check, use `LoginRequiredMixin` / `@login_required` (DRF:
`IsAuthenticated`). Anonymous
users are sent to the login page; a denial raises
`PermissionDenied` and logs one `ais_identity.access_decision` event.
`ais_subject` is the provider `sub` and is empty when there is none. The
deny log does not record the local primary key, the username, the email,
or the claims. A local
staff, admin or test user with no OIDC session passes this decorator only
when `LOCAL_CONTEXT` returns a provider `sub`, or when the login itself
carries an OIDC `sub`.

Capability checks (`capabilities=`, `has_capability`) read the `gateway_roles`
claim. A regular app receives it only when it requests the `capabilities` scope
together with `tenant`, for example `OIDC_RP_SCOPES = "openid email roles tenant
capabilities"`; without it every capability check is false.

### Rolling out the capabilities scope

Changing `OIDC_RP_SCOPES` affects new authorization requests, not existing
Django sessions. Their previously verified access projection does not gain
`gateway_roles` automatically. Before enabling capability-protected views,
invalidate the affected application sessions through the host's session
management, or have those users sign out and sign in again with both `tenant`
and `capabilities` requested. For session backends that cannot revoke cookies
centrally, require reauthentication in the host rather than only deleting
server-side session rows. Keep the views fail-closed until that new login
completes.

The OIDC backend must verify the newly issued ID token and call
`store_verified_access_claims()` with its claims to replace the old projection.
Never insert capability bundles or requested scopes into a session by hand.
An access-token refresh alone is insufficient unless the backend also receives
and verifies fresh identity claims and replaces the stored projection. Test
both an old session (denied) and a new verified session with and without the
required bundle; requesting a scope does not grant a capability.

## Settings

| Key | Meaning | insight-ui-user setting it replaces |
|---|---|---|
| `ISSUER` | provider base URL; derives the evaluation endpoint and the discovery document | |
| `EVALUATION_ENDPOINT` | full URL of `POST /api/access/v1/evaluation` | `INSIGHT_UI_USER_ACCESS_EVALUATION_URL` |
| `EVALUATION_CREDENTIALS` | callable returning `ClientCredentials` for the policy client of one tenant; the SDK fetches and caches the token. The provider takes the tenant from that client's binding, not from AuthZEN `context` ([insight-oidc-provider#839](https://github.com/alpininsight/insight-oidc-provider/issues/839)). One policy client per tenant ([contract at `de7c7c9f112dbe9ad648b8132e6da731179608d9`](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/docs/identity-access-contracts.md#L1106-L1110)) | |
| `EVALUATION_TOKEN` | callable returning a bearer token string | `INSIGHT_UI_USER_ACCESS_EVALUATION_TOKEN` |
| `EVALUATION_CLIENT` | callable returning a ready evaluation client; overrides the three above | |
| `TOKEN_ENDPOINT` | token endpoint; discovered from `ISSUER` when empty | |
| `EVALUATION_RESOURCE` | Optional RFC 8707 resource indicator for the `access:evaluate` token. Default empty, which omits `resource`. See [EVALUATION_RESOURCE](#evaluation_resource). | |
| `EVALUATION_TIMEOUT` | seconds, default 2 | `INSIGHT_UI_USER_ACCESS_EVALUATION_TIMEOUT` |
| `WRITE_SCOPE_ENFORCEMENT` | `warn` (default) or `enforce` | `INSIGHT_UI_USER_WRITE_SCOPE_ENFORCEMENT` |
| `DEVELOPER_ACCESS_CACHE_SECONDS` | freshness of the cached entitlement projection, default 300 | `INSIGHT_UI_USER_DEVELOPER_ACCESS_CACHE_SECONDS` |
| `LOCAL_CONTEXT` | callable `(request, user)` for users without an OIDC session, including local admin, staff and test logins. Return `AccessContext.from_claims({"sub": "<provider sub>"}, source="local_context")`. The subject is the provider `sub`, never `user.pk`. Returning `None`, or a context with no subject, denies every `decide()` check, including a pure login requirement | |
| `EXPECTED_AUDIENCE` | one canonical https resource URI (gateway host + catalog `base_path`). The same strict rule as `resource_uri_problem`: lowercase `https`, no userinfo, query, fragment, trailing slash, backslash, invalid port such as `:99999`, or `..` path segment. Sources: `https://api.alpininsight.ai/api/v1/sources` (development `https://api.dev.alpininsight.ai/api/v1/sources`). Digitraffic marine: `https://api.alpininsight.ai/api/v1/digitraffic/marine`. Not `/api/v1/<group>`. On provider `develop` (`de7c7c9`) this URI is not yet `aud`; see `LEGACY_CLIENT_AUDIENCES`. | |
| `LEGACY_CLIENT_AUDIENCES` | transitional client ids. A match requires `EXPECTED_AUDIENCE`, `client_id` equal to the single audience and `sub`, and `principal_type` `service-client` ([`MACHINE_PRINCIPAL_TYPE`](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/access_tokens.py#L59), only on [`client_credentials`](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/access_tokens.py#L229-L242), where `sub` equals `client_id`). A missing claim is never a service client. `workload` from the SPIRE token exchange ([`spire_federation.py` L251-L257](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/spire_federation.py#L251-L257), off by default) is rejected on purpose. Today every service-API token has `aud` equal to `client_id`, so omitting the list rejects every real token. A non-empty list emits `PendingDeprecationWarning`. After insight-oidc-provider#821 is deployed that warning becomes `DeprecationWarning`. The setting stays. End of life: insight-oidc-provider#819. No slug audiences. | |
| `ALLOWED_CLIENTS` | when set, `client_id` and a present `azp` must be in this list. `client_id` is required even when this list is empty | |

`ais_identity_django.verification.token_verifier()` builds a `TokenVerifier`
from those keys and `ISSUER`. A bad combination is `ais_identity.E004` and
blocks verification. A trailing slash, query, fragment, userinfo,
backslash, invalid port, `..` path segment, or non-https URI is rejected
rather than trimmed. `LEGACY_AUDIENCES` and `ALLOW_MULTIPLE_AUDIENCES` are
not settings; setting either is the same error. Today, on provider `develop`
(`de7c7c9`), every service-API token has `aud` equal to `client_id` and
`resource` binds only MCP scopes. The canonical URI as `aud` is
insight-oidc-provider#821 (still open, `f856b25`). `EXPECTED_AUDIENCE`
without `LEGACY_CLIENT_AUDIENCES` rejects every real token today. A legacy
match is logged once per audience per process and does not include the
token. Sources and source-control share
`/api/v1/sources` and are distinguished by scope.

Values that name code take a dotted path or the callable. The old settings keep
working for every key `AIS_IDENTITY` does not set. An integrating app can
supply a default with `ais_identity_django.conf.register_default()` from its
`AppConfig.ready()`; host settings still override it. System checks warn about a
misspelt enforcement mode (`ais_identity.W002`) and about half-configured node
evaluation (`ais_identity.W003`), which would otherwise deny silently. An
unusable expected audience, legacy list, or client allowlist is an error
(`ais_identity.E004`) because it would block or mis-accept every token check.
W001, W002, and W003 stay on the normal check.

### EVALUATION_RESOURCE

An empty, whitespace-only, or missing
`EVALUATION_RESOURCE` raises no check. `ais_identity.E005`, `ais_identity.W005`,
`ais_identity.W006`, and `ais_identity.W007` come only from
`check_evaluation_resource`, which is registered with `deploy=True`. They run
on `manage.py check --deploy` and do not fire on every management command.
Hosts should run that command with their production settings in their own CI,
so a bad `EVALUATION_RESOURCE` is reported before any node check.
When the adapter would send the indicator, a non-canonical value is
`ais_identity.E005` and a canonical one is `ais_identity.W005` until the
provider binds `access:evaluate`. The canonical form is
`ais_identity.verification.resource_uri_problem`, the same function as
`expected_audience`. It follows what `canonical_resource_problem()` requires
in insight-oidc-provider `src/oidc_core/resource_indicators.py` (lines 124-152
at `f856b25b15efed0f88c0dd072dc07d4f8ebc8d90`;
alpininsight/insight-oidc-provider#821 is still open) and is stricter: it
rejects a backslash, an uppercase scheme, an invalid port such as `:99999`,
and a `..` path segment. Silence the transitional warning with
`SILENCED_SYSTEM_CHECKS = ["ais_identity.W005"]`. `POST /api/access/v1/evaluation` has no canonical resource URI
today, and `access:` is not in `SERVICE_API_SCOPE_PREFIXES`, so the provider
ignores `resource=` and the audience stays the client id. The proposed URI
is `{OIDC_ISSUER}/api/access/v1/evaluation`. Until the provider binds it, a
set value returns `invalid_target` once unknown targets are rejected and
denies every node check. With no node evaluation or `EVALUATION_CLIENT`, a
set value is
`ais_identity.W006` ("EVALUATION_RESOURCE is set but unused") and never
`W005`, `W007`, or an error. A legacy `EVALUATION_TOKEN` warns
`ais_identity.W007` ("EVALUATION_RESOURCE is set but ignored") only when a
value is set. Each of those ids has one message. An invalid value raises
`ImproperlyConfigured` before any token request and is not sent. Without
`manage.py check --deploy`, `@access_required(node=…)` raises that
exception on every such check, even when the context has no subject, and
Django answers HTTP 500. No `ais_identity.access_decision` event is logged.
That is fail-closed, not a deny. `evaluate_node_access()` returns False
without a subject and does not build the client. A canonical value is still
sent. Leave the setting empty until the binding exists.

## Migrating local logins

Hosts whose admin, staff or test users sign in without an OIDC session set
`LOCAL_CONTEXT` before those users can pass any `decide()` check, including
`@access_required()` with no arguments:

```python
from ais_identity import AccessContext


def local_login_context(request, user):
    provider_sub = user.provider_sub  # host mapping; never user.pk
    if not provider_sub:
        return None
    return AccessContext.from_claims({"sub": provider_sub}, source="local_context")


AIS_IDENTITY = {"LOCAL_CONTEXT": "myapp.identity.local_login_context"}
```

The mapping from the local user to `provider_sub` may only come from a
previously verified OIDC login and must not be changeable by the user. Code
that needs a real provider session checks `context.source == "oidc_session"`
(see `source_summary` in `examples/django_identity_layer.py`).
If `LOCAL_CONTEXT` returns a string source, including a `StrEnum`, that is
`oidc_session` after stripping whitespace and ignoring case, the adapter
rewrites that source to `local_context` and logs one warning for that
Django request. A DRF request and a later read of the Django request it
wraps share that warning. The adapter finds that request from `_request`
and does not import DRF. `None`, a number, and `bytes` are left unchanged
and do not warn.
The warning names neither the subject, the Django user, nor the claims. The
rest of the context is kept, so the local login still works.

Tests set the same callable on `settings.AIS_IDENTITY["LOCAL_CONTEXT"]`.
Returning `None` keeps the user authenticated in Django and denied by every
access check.

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 AuthZEN `context` for tenant isolation. `context.tenant_id`
and `context.tenant_slug` are both optional. Once
[alpininsight/insight-oidc-provider#839](https://github.com/alpininsight/insight-oidc-provider/issues/839)
is live they can only cause a deny (`tenant_mismatch`). The client binding
stays authoritative. Today the provider does not evaluate `context`.

`evaluate_node_access()` builds the `NodeQuery` without `context`, so the
caller must pass `context=authzen_context(...)` itself. `context={}` removes
the tenant context, and omitting `context` sends `{}`. If `access.subject`
is None (see #56), `evaluate_node_access` returns False:

```python
from ais_identity import authzen_context
from ais_identity_django.access import get_access_context
from ais_identity_django.nodes import evaluate_node_access

access = get_access_context(request)
node = request.resolver_match.kwargs["unit"]  # the org unit this view addresses

evaluate_node_access(
    request,
    subject=access.subject,
    node=node,
    action="sources:read",
    context=authzen_context(access.active_tenant),
)
```

## Migrating from insight-ui-user

The session keys are unchanged (`insight_ui_user.access_claims.v1`,
`insight_ui_user.developer_access.v1`), so existing sessions keep working.
`profiles.access`, `profiles.node_access` and `profiles.write_scopes` can
re-export from `ais_identity_django.access`, `.session`, `.nodes`, `.writes`
and `.drf`; every public name has a counterpart. Tests that patched
`requests.post` patch `httpx.Client.post` instead.
