Skip to main content

pkg-auth

Clean-architecture identity + ACL for multi-framework Python services. Handles JWT authentication (via Keycloak) and database-backed authorization (users, organizations, roles, permissions, memberships) in a single package with first-class support for FastAPI, Django, and Strawberry GraphQL.

v3.0.0 is a breaking change. The permissions.is_platform flag is replaced by a tri-state visibility enum (platform_only/shared/tenant_only); permission description is now a localized JSONB map; and a first-class Service model with a default-deny service guard is added. See docs/Upgrade-Service-Guard.md for the 3.0.0 upgrade guide. Earlier migrations: docs/MIGRATION_v1.md, docs/MIGRATION_v2.md.

Install

# Core (identity only — no DB deps)
pip install pkg-auth

# With ACL + FastAPI (most common for fritill services)
pip install "pkg-auth[acl-sqlalchemy,fastapi]"

# With ACL + Django
pip install "pkg-auth[acl-django,django]"

# With optional Redis cache
pip install "pkg-auth[cache-redis]"

# Everything
pip install "pkg-auth[all]"

Available extras: acl-sqlalchemy, acl-django, cache-redis, fastapi, django, strawberry, all.

Quickstart (FastAPI)

from fastapi import Depends, FastAPI
from pkg_auth.authentication import IdentityContext
from pkg_auth.authorization import AuthContext
from pkg_auth.integrations.fastapi import (
    create_authentication,
    make_get_auth_context,
    require_permission,
)

# --- Wire authentication + authorization ---

auth = create_authentication(
    keycloak_base_url="https://auth.example.com",
    realm="fritill",
    audience="courses-service",
)

# Mode B (consumer — the common case): pass resolve_user_use_case.
# Mode A (source-of-truth): pass sync_user_use_case instead. Exactly
# one of the two is required; passing both raises ValueError.
get_auth_context = make_get_auth_context(
    get_identity=auth.get_identity,
    resolve_user_use_case=resolve_user,   # or: sync_user_use_case=sync_user (Mode A)
    resolve_use_case=resolve,
    organization_repo=org_repo,
)

app = FastAPI()

# --- Use in routes ---

@app.get("/courses/{id}")
async def get_course(
    id: str,
    bundle: tuple[IdentityContext, AuthContext] = Depends(
        require_permission("course:view", get_auth_context=get_auth_context)
    ),
):
    identity, auth_ctx = bundle
    return {"course_id": id, "roles": sorted(auth_ctx.role_names)}

See examples/itqadem_courses_app for a complete working example.

Features

  • Authentication — Keycloak JWT validation producing an IdentityContext.
  • Service token — a service's own Keycloak token (client credentials), cached and refreshed, for calling other services.
  • Authorization (ACL) — database-backed users, organizations, roles, permissions, and memberships, resolved into a hot-path AuthContext (role_names, perms).
  • Permission visibility — tri-state catalog visibility (platform_only / shared / tenant_only).
  • Localized descriptions — permission descriptions stored as localized JSONB (LocalizedText, ACL_DEFAULT_LOCALE).
  • Services & service guard — first-class Service / OrganizationService model with a default-deny service guard; the platform org bypasses it.
  • Mode A / Mode B — be the source of truth for the users table, or consume a shared ACL read-only.
  • Integrations — FastAPI, Django, and Strawberry GraphQL.
  • CLIs — keycloak-init-client, pkg-auth-sync-catalog, pkg-auth-sync-services.

Architecture

pkg_auth/
  authentication/             JWT validation → IdentityContext; the service's own token
  authorization/              Full ACL (users, orgs, roles, perms, memberships)
    domain/                   Pure entities, ports (Protocol), exceptions
    application/use_cases/    Business logic (use cases)
    adapters/
      sqlalchemy/             Canonical schema + Alembic migrations (0001–0005) + repos
      django_orm/             Mirror models (managed=False) + repos
      cache/                  InMemoryTTLCache / RedisCache + decorator
  integrations/
    fastapi/                  Deps + require_permission + exception handlers
    django/                   Middleware + decorators
    strawberry/               Context getter + permission classes
  admin/                      Keycloak admin client (user provisioning)

Layering rules: domain has zero external imports; application imports only domain; adapters import their framework; integrations import everything.

Documentation

Metadata

Release files for pkg-auth 3.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pkg-auth 3.3.0
File Size Uploaded Provenance Actions
pkg_auth-3.3.0.tar.gz 76.6 kB Without provenance Details for pkg_auth-3.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pkg-auth 3.3.0
File Interpreter ABI Platform Actions
pkg_auth-3.3.0-py3-none-any.whl Python 3 none any Details for pkg_auth-3.3.0-py3-none-any.whl

Total release size: 200.1 kB

Release files / pkg_auth-3.3.0.tar.gz

Download URL pkg_auth-3.3.0.tar.gz
Size 76.6 kB
Tags Source
SHA-256 checksum
How to use checksums
ed2c622182447fe153572154f9ba2a02e3444b112fe95f23c763a561dce298d4
BLAKE2b-256 checksum
How to use checksums
4c59927c3c05b53bbb77a4f2f79bb23b16f702c4272767a503365e0a55feb5aa
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / pkg_auth-3.3.0-py3-none-any.whl

Download URL pkg_auth-3.3.0-py3-none-any.whl
Size 123.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d820ff7d079161aee2a26019fc3865f05b8fd596a7bbc637f9076399e89efec7
BLAKE2b-256 checksum
How to use checksums
2f83f8b61d247ede20194ede78eb40634ad2989ff19460f23e123a03c4f7aa5f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Security for pkg-auth 3.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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