Metadata-Version: 2.4
Name: juntai-iam
Version: 1.0.0
Summary: Side-effect-free Juntai identity and authorization integration library
Author: Juntai Platform Team
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/zephytiju/JuntaiIAMPython
Project-URL: Repository, https://github.com/zephytiju/JuntaiIAMPython.git
Project-URL: Issues, https://github.com/zephytiju/JuntaiIAMPython/issues
Keywords: iam,oidc,casdoor,casbin,kingbasees,kubernetes
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: casbin<2.0.0,>=1.43.0
Requires-Dist: httpx<1.0.0,>=0.27.0
Requires-Dist: PyJWT[crypto]<3.0.0,>=2.9.0
Provides-Extra: test
Requires-Dist: build==1.3.0; extra == "test"
Requires-Dist: jsonschema<5.0.0,>=4.23.0; extra == "test"
Requires-Dist: psycopg[binary]<4.0.0,>=3.2.0; extra == "test"
Requires-Dist: pytest<9.0.0,>=8.3.0; extra == "test"
Requires-Dist: ruff<1.0.0,>=0.12.0; extra == "test"
Provides-Extra: kes
Requires-Dist: ksycopg2==2.9.1; platform_system != "Darwin" and extra == "kes"
Dynamic: license-file

# Juntai IAM Python

`juntai-iam` is the side-effect-free Python integration library for Juntai
identity and domain authorization. It validates Casdoor API access tokens and
Kubernetes projected workload tokens, evaluates the reviewed Casbin policy
model, installs trusted transaction-local KingbaseES context, and enforces
field-read and field-write decisions.

This repository does **not** contain an IAM service, HTTP listener, browser
session, tenant administration API, secret backend, policy store, audit chain,
database migration owner, provider runtime, deployment image, OpenAPI artifact,
or generated TypeScript client. Casdoor remains authoritative for organizations,
users, groups, roles, OIDC tokens, permissions, models, and Casbin records.
Domain repositories remain authoritative for their resources, actions, fields,
tables, ACLs, and RLS migrations.

## Install

```bash
python -m pip install "juntai-iam>=1,<2"
```

The stable import root is `juntai.iam`. Importing it performs no discovery,
network request, token validation, database connection, migration, policy
synchronization, listener startup, or global middleware installation.

## Compose a service boundary

```python
from juntai.iam import (
    JUNTAI_POLICY_MODEL_V1,
    AuthorizationRequest,
    CasdoorAccessTokenVerifier,
    CasdoorPolicyEvaluator,
    IamMiddleware,
    iam_transaction_context,
    project_allowed_fields,
)

verifier = CasdoorAccessTokenVerifier.from_discovery(
    issuer=settings.oidc_issuer,
    audiences={settings.api_audience},
    required_scopes={"juntai.api"},
)
evaluator = CasdoorPolicyEvaluator(
    model=JUNTAI_POLICY_MODEL_V1,
    policy_source=policy_source,
)
iam = IamMiddleware(verifier=verifier, evaluator=evaluator)
```

Construct these objects once in the service composition root and inject them.
The policy source reads a revisioned snapshot from the configured Casdoor policy
integration; this package does not persist or mutate policy.

For a protected operation:

```python
identity = iam.require_human_or_delegated(request)
decision = await iam.authorize(
    identity,
    AuthorizationRequest(
        tenant=identity.tenant_id,
        resource=f"axiom/workflows/{workflow_id}",
        action="read",
        requested_fields=("id", "name", "created_at", "secret_notes"),
    ),
)

with database.transaction() as transaction:
    with iam_transaction_context(transaction, identity, decision):
        row = repository.get(transaction, workflow_id)

return project_allowed_fields(row, decision)
```

Build tenant, resource, action, and requested fields from verified identity and
the domain route. Never accept an authorization decision, tenant, group, role,
resource, action, or field grant from an untrusted request.

## Identity and token rules

`IdentityContext` is immutable. Human subjects are issuer-qualified Casdoor
subjects; the tenant is the verified Casdoor organization claim. Display name
and email are presentation-only attributes. API validation checks signature,
issuer, audience, authorized party, expiry, not-before, scopes, organization,
key identity, and the exact `tokenType=access-token` profile. Callers must
forward Casdoor's OAuth `access_token` response field. Casdoor 3.125 aliases
`id_token` to the same JWT bytes, so downstream code cannot infer response-field
provenance; any future distinct ID-token profile is rejected as an API
credential.

Discovery and JWKS are fetched lazily and cached. Unknown keys trigger at most
one bounded refresh and fail closed. Previously validated keys may survive a
configured short issuer outage; `invalidate_keys()` supplies the rotation and
emergency invalidation path.

Workloads use audience-bound projected ServiceAccount tokens validated through
the live Kubernetes TokenReview API. Namespace and ServiceAccount are mapped by
trusted service configuration. `delegated_identity()` accepts only independently
verified workload and user contexts and enforces same-tenant, shortest-expiry
binding. Delegated authorization uses workload-and-user policy intersection.
The TokenReview client may authenticate with a projected reviewer token or an
explicit Kubernetes client-certificate/key pair supplied by the composition
root; credential files are never read at import time.

## Casbin conventions

The reviewed logical policy tuple is:

```text
p = subject_or_role, tenant, resource_pattern, action_pattern, field_pattern, effect
g = subject, role, tenant
```

Evaluation is default deny and any matching deny overrides allows. Tenant is an
exact verified organization identifier and cannot be wildcarded. Resource,
action, and field patterns use literal slash segments, `*` for one segment, and
terminal `**` for descendants. Regular expressions and executable matcher text
are rejected. Operation policies use field pattern `*`; requested fields are
evaluated separately through `field.read` or `field.write` policies.

`AuthorizationDecision` binds the result to the exact tenant, resource, action,
allowed fields, matched policy identifiers, revision, correlation-derived
decision identifier, and audit reason. Call `invalidate()` on the evaluator for
policy revocation, emergency deny, or revision notifications; cache TTL is the
bounded fallback.

## KingbaseES integration

`iam_transaction_context` accepts a DB-API connection or cursor with autocommit
disabled. It uses parameterized `set_config(..., true)` calls for tenant,
subject, groups, roles, workload, delegation, policy revision, correlation, and
decision values. KingbaseES clears them at transaction end, including pooled
connection reuse.

Domain migrations—not this package—must:

- add `tenant_id` to every protected table;
- enable and force RLS;
- define tenant policy using
  `tenant_id = current_setting('juntai.iam.tenant_id', true)`;
- grant runtime access to a dedicated non-superuser, non-owner role without
  `BYPASSRLS`; and
- add domain ACL tables for ownership and high-cardinality sharing.

`assert_forced_rls()` and `assert_least_privileged_runtime_role()` provide
acceptance checks. Missing transaction context yields `NULL` in the recommended
predicate and therefore denies every row.

## Contracts and compatibility

`contracts/identity-context.v1.schema.json` and
`contracts/authorization-request.v1.schema.json` describe in-process data and
test fixtures. They are not network contracts and do not grant authorization.

The legacy `juntai_iam_contracts.auth` path contains only compatibility imports
for `HumanOIDCVerifier` and `KubernetesTokenReviewer`. No legacy service,
`KESRepository`, secret, policy, or HTTP API is retained. Consumers must migrate
to `juntai.iam` and domain-owned RLS/policy integrations.

## Verification

```bash
python -m pip install -e '.[test]'
ruff check .
pytest -m 'not kes and not kubernetes and not casdoor'
python -m build
```

Real-dependency suites are opt-in and never substitute SQLite, in-memory
authority, or fixture platform APIs:

- `tests/casdoor` validates a native Casdoor-issued access token through live
  discovery and JWKS.
- `tests/kubernetes` validates a projected ServiceAccount token with live
  TokenReview.
- `tests/kes` proves forced RLS, missing-context denial, cross-tenant isolation,
  and pooled-connection cleanup against KingbaseES.

The deterministic HTTP/JWT and TokenReview test doubles under `tests/unit` are
unit evidence only.
