Skip to main content

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 agent Application proofs, resolves current human, agent, and service principals, validates Kubernetes projected workload tokens, evaluates the reviewed Casbin policy and peer-principal intersections, 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, Applications, OIDC tokens, Permissions, models, and Casbin records. Domain repositories remain authoritative for their resources, actions, fields, tables, ACLs, and RLS migrations.

Install

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

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:

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.

Peer principals, bindings, and token rules

IdentityContext/v2 is immutable and uses exactly human, agent, or service. Authentication mechanism, session, workload, delegated authority, and MCP/OpenAPI channel remain separate. The durable issuer-qualified subject is always the actor; in delegated agent execution it remains the agent, while the human grantor and exact live grant are separate references. PrincipalPresentation/v1 is safe user-facing identity data and never authorizes an operation.

Human API validation checks signature, issuer, audience, authorized party, expiry, not-before, scopes, organization, key identity, and the exact tokenType=access-token profile. Callers 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.

Each agent is a distinct non-interactive Casdoor User owned by juntai-system. An Agent-category Application is only an AuthenticatorBinding/v1. For client credentials, verify_agent() verifies standard sub as the Application, azp and standard aud as its exact client ID, plus six signed JWT-Custom claims for binding ID, principal ID, binding revision, authority epoch, logical audience, and logical resource. resolve_agent_identity() then requires the current Application and User to reference the same principal, binding, epoch, and revisions, and verifies the running application-version reference and every selected profile against the principal's current eligibility lists. A custom claim never substitutes for standard JWT validation or current-state resolution. Raw credentials are never returned or logged.

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.

Services use audience-bound projected ServiceAccount tokens validated through the live Kubernetes TokenReview API. Namespace and ServiceAccount are mapped by trusted service configuration. 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.

PeerPrincipalEvaluator is the shared fail-closed path. Self mode evaluates direct grants; delegated mode replaces direct grants with the current grantor authority intersected with the exact DelegationGrant/v1. It never unions self grants. Both modes then intersect the principal/agent ceiling, application installation, profile, invocation/session/task, and final domain policy. The exact equations are:

A_self = G_self ∩ C_principal ∩ C_install ∩ C_profile ∩ C_invocation_session_task ∩ P_domain
A_delegated = A_grantor(current) ∩ G_delegation ∩ C_principal ∩ C_install ∩ C_profile ∩ C_invocation_session_task ∩ P_domain

G_self is deliberately absent from A_delegated. The default current-state staleness is at most 30 seconds; high-risk operations can require a live check. Revocation, expiry, lost grantor authority, stale epochs, or any tenant/application/audience/resource/purpose/profile/task/session mismatch denies without fallback. MCP and OpenAPI select audit channel only.

Casbin conventions

The reviewed logical policy tuple is:

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

This package pins juntai-iam-contracts==1.1.1. That separate, language-neutral package owns the wire schemas, deterministic fixtures, canonicalization, and cross-language conformance matrix. juntai-iam owns Python validation and enforcement only. It does not copy the schemas, issue credentials, persist a principal or grant, or expose a network service. A schema-valid request still grants no authority until current proof and every evaluation layer allow it.

Verification

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. Platform's official-image acceptance additionally proves two distinct agent Applications, signed JWT-Custom binding claims, supported User/Application/Permission convergence, and absence of the historical patch.
  • 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.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

juntai_iam-1.1.0.tar.gz (32.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

juntai_iam-1.1.0-py3-none-any.whl (35.9 kB view details)

Uploaded Python 3

File details

Details for the file juntai_iam-1.1.0.tar.gz.

File metadata

  • Download URL: juntai_iam-1.1.0.tar.gz
  • Upload date:
  • Size: 32.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for juntai_iam-1.1.0.tar.gz
Algorithm Hash digest
SHA256 fdee2c39ff5b356d33c7c9cf727ecf842a6ca80a679b7063144791127a71e4ba
MD5 6699a12f4dbfaf75dc3193c2e532d7e7
BLAKE2b-256 133522154d80b98d7357e325aefcae59333d17f5a06f08ec5225dcc29a209d4e

See more details on using hashes here.

Provenance

The following attestation bundles were made for juntai_iam-1.1.0.tar.gz:

Publisher: publish-python.yml on zephytiju/JuntaiIAMPython

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file juntai_iam-1.1.0-py3-none-any.whl.

File metadata

  • Download URL: juntai_iam-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 35.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for juntai_iam-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 007362537726dbd69c75952b73c62b90e4f7ea92a48ab214ba0ad3ffcb533e6c
MD5 acc84cbb9ecc88160601321a482288c8
BLAKE2b-256 373dd30575cea71b7c5cb010bbac6434617e4c28dc09b502e4844b9d2983f85a

See more details on using hashes here.

Provenance

The following attestation bundles were made for juntai_iam-1.1.0-py3-none-any.whl:

Publisher: publish-python.yml on zephytiju/JuntaiIAMPython

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

1.1.0 This release

2 files

1.0.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page