Skip to main content

inkPass SDK for Python

Official Python SDK for inkPass - Authentication & Authorization Service

Python Version License: MIT

Features

  • ✅ Type-safe - Full type hints and Pydantic models
  • ✅ Async/await - Built on httpx for modern async Python
  • ✅ Retries where safe - Reads are retried with exponential backoff when InkPass sends no answer; calls that change state are sent once
  • ✅ Error handling - Comprehensive exception hierarchy
  • ✅ Fail-safe - Permission checks default to deny on errors
  • ✅ Well-tested - Extensive test coverage
  • ✅ Easy integration - Simple FastAPI middleware patterns

Installation

uv add inkpass-sdk
# or: pip install inkpass-sdk

From Source (Development)

# From the monorepo root:
cd packages/inkpass-sdk-python
pip install -e ".[dev]"

Quick Start

Basic Usage

import asyncio
from inkpass_sdk import InkPassClient, InkPassConfig

async def main():
    # Initialize client
    config = InkPassConfig(base_url="http://inkpass:8000")
    client = InkPassClient(config)

    # Register user
    registration = await client.register(
        email="user@example.com",
        password="SecurePassword123!",
        organization_name="My Organization"
    )

    # Login
    tokens = await client.login(
        email="user@example.com",
        password="SecurePassword123!"
    )

    # Validate token
    user = await client.validate_token(tokens.access_token)
    print(f"Logged in as: {user.email}")

    # Check permission
    can_create = await client.check_permission(
        token=tokens.access_token,
        resource="workflows",
        action="create"
    )
    print(f"Can create workflows: {can_create}")

    # Clean up
    await client.close()

asyncio.run(main())
from inkpass_sdk import InkPassClient, InkPassConfig

async def main():
    config = InkPassConfig(base_url="http://inkpass:8000")

    # Automatically closes on exit
    async with InkPassClient(config) as client:
        user = await client.validate_token(token)
        # ... do work

FastAPI Integration

from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from inkpass_sdk import InkPassClient, InkPassConfig

app = FastAPI()
security = HTTPBearer()

# Initialize inkPass client
inkpass_client = InkPassClient(InkPassConfig(base_url="http://inkpass:8000"))

# Dependency: Get current user
async def get_current_user(
    credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
):
    user = await inkpass_client.validate_token(credentials.credentials)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid token")
    return user

# Dependency: Require permission
def require_permission(resource: str, action: str):
    async def checker(
        user=Depends(get_current_user),
        credentials=Depends(security)
    ):
        has_perm = await inkpass_client.check_permission(
            credentials.credentials, resource, action
        )
        if not has_perm:
            raise HTTPException(status_code=403, detail="Permission denied")
        return user
    return checker

# Protected route with permission
@app.post("/workflows")
async def create_workflow(
    user=Depends(require_permission("workflows", "create"))
):
    return {"workflow": "created"}

API Reference

Client Configuration

from inkpass_sdk import InkPassConfig

config = InkPassConfig(
    base_url="http://inkpass:8000",  # inkPass service URL
    api_key="optional-service-key",   # For service-to-service auth
    timeout=5.0,                       # Timeout of each attempt (seconds)
    max_retries=3,                     # Attempts in all, the first included, of a read
    retry_min_wait=1,                  # First wait between attempts (seconds), then doubling
    retry_max_wait=10,                 # Longest wait between attempts (seconds)
    verify_ssl=True,                   # Verify SSL certificates
)

Client Methods

register(email, password, organization_name=None)

Register a new user.

Returns: RegistrationResponse

result = await client.register(
    email="user@example.com",
    password="SecurePass123!",
    organization_name="My Org"  # Optional
)
# result.user_id, result.email, result.organization_id

login(email, password)

Authenticate user and get tokens.

Returns: TokenResponse

tokens = await client.login("user@example.com", "password")
# tokens.access_token, tokens.refresh_token, tokens.expires_in

validate_token(token)

Validate JWT token and get user info.

Returns: UserResponse | None

user = await client.validate_token(token)
if user:
    print(f"User: {user.email}, Org: {user.organization_id}")

check_permission(token, resource, action, context=None)

Check if user has permission.

Returns: bool (Fail-safe: returns False on errors)

can_create = await client.check_permission(
    token=access_token,
    resource="workflows",
    action="create",
    context={"project_id": "123"}  # Optional ABAC context
)

create_api_key(token, name, scopes=None, *, expires_in_days=None, never_expires=False, user_id=None, step_up_token=None)

Create a new API key. Without expires_in_days (1 to 365) it lasts 90 days. Only an owner may ask for a key that never expires (never_expires=True); anyone else gets OwnerRequiredError. An owner may bind the key to any member of the organization with user_id: that key impersonates the member (it acts as them, capped at what they hold now) but stays the owner's: only its issuer rescopes it or reads its usage, and every other owner of the organization sees and may revoke it (list_impersonation_keys); admins and the member it acts as, an owner included, never see it. It pauses while its issuer or its member is suspended, and ends for good (revoked, with the reason) when its issuer stops being an owner, leaves or is deleted, or its member leaves. Its impersonated_by is the owner's user ID, and validate_api_key returns it too; record it with every action the key takes. A key bound to no member records its issuer too (issued_by) and is not cut when that person leaves: owners rotate it by hand.

Returns: APIKeyResponse (with expires_at, user_id, impersonated_by, issued_by, status and status_reason)

api_key = await client.create_api_key(
    token=access_token,
    name="Service API Key",
    scopes=["read", "write"],
    expires_in_days=30,
)
# api_key.key (shown only once!)

list_api_keys(token, *, include_revoked=False, scope="mine") and list_impersonation_keys(token, *, include_revoked=False)

list_api_keys lists the keys the caller issued. With scope="organization", an owner or an admin lists every key of the organization they could revoke with revoke_api_key, by the same rule; anyone else gets OwnerOrAdminRequiredError. list_impersonation_keys, for owners only (OwnerRequiredError for anyone else), lists every impersonation key in the organization. Each APIKeySummary has status (active, paused, revoked or expired) and status_reason (for example issuer_suspended, issuer_demoted, member_removed or owner_oversight). Never the key or its hash.

# Every key an admin could revoke: their own and those of the members they manage.
keys = await client.list_api_keys(access_token, scope="organization")

revoke_api_key(key_id, token)

Revoke a key: the caller's own, a key of a member the caller may act on (an owner's only by an owner), and, for an owner, any impersonation key or key bound to no member. InkPass keeps the key's record and writes who revoked it to its append-only audit trail. A key the caller may not revoke answers PermissionDeniedError, the same as a missing one. Not retried.

set_member_status(organization_id, user_id, status, *, token, step_up_token=None)

Suspend ("suspended") or restore ("active") someone's membership in the caller's organization. A suspension cuts access to that organization only and revokes nothing: their API keys and grants there pause, their standing reads active: false, suspended: true, and when it is their home organization their sessions end and they cannot sign in. Needs users:manage; acting on an owner or an admin is an owner's decision, a restore is held to the grant ceiling and may need step_up_token, and the last owner is never suspended. It never clears the platform operator's account lock.

Returns: the member as the member list shows them, with membership_status Raises: OrganizationMismatchError, OwnerRequiredError, NotPermittedError, MemberNotFoundError, LastOwnerError, MembershipMissingError, AccountLockedError; ValueError, before any request, for an id that is not a UUID

member = await client.set_member_status("org-id", "user-id", "suspended", token=access_token)
# member["membership_status"] == "suspended"

Sessions

logout(token)

Sign out: the session the access token belongs to ends, and its access and refresh tokens stop working at once. Other sessions of the same person are untouched. AuthenticationError if the session already ended. Not retried.

refresh(refresh_token)

Access tokens last 30 minutes, refresh tokens 7 days. refresh exchanges the refresh token for a new pair and returns a TokenResponse. The refresh token is rotated: the old one stops working, and presenting an already-used one is taken as theft and ends the whole session. So refresh is never retried, and a transport error raises OutcomeUnknownError: sign in again rather than refreshing with the old token. InkPass allows 10 refreshes (and 10 sign-outs) a minute per client address; a backend refreshing for many people from one address should refresh shortly before expires_in, not on every request.

tokens = await client.login(email, password)
...
tokens = await client.refresh(tokens.refresh_token)  # store both new tokens
...
await client.logout(tokens.access_token)

register_client_user(client_slug, email, password, ...) and login_client_user(client_slug, email, password, two_fa_code=None)

Sign-up and sign-in for a user of a multi-client tenant. register_client_user returns the account as a UserResponse and opens no session: InkPass sends no token on registration, and outside development the account stays pending until verify_email. login_client_user returns (user, access_token), where user is a ClientUserSession: the UserResponse plus the session InkPass opened, access_token, refresh_token, token_type and expires_in. refresh_token and expires_in are None from an InkPass that does not send them.

user, access_token = await client.login_client_user("wendell", email, password)
...
tokens = await client.refresh(user.refresh_token)  # a TokenResponse; store both new tokens

verify_email(email, code, *, client_slug=None) and resend_verification(email, *, client_slug=None)

Prove the mailbox of a pending account with the code InkPass mailed, or mail a new code. Pass the client_slug the person registered under: without it InkPass looks the address up in its default client, so a person of another client is not found (verify_email raises ValidationError, resend_verification mails nothing and answers as for any address).

await client.register_client_user("wendell", email, password)
await client.verify_email(email, code_from_the_email, client_slug="wendell")

Step-up

Some calls need proof that the person re-authenticated this session within the last five minutes. Without it, InkPass answers 403 and the SDK raises StepUpRequiredError (a PermissionDeniedError, code == "step_up_required") with required_factors: some of "password", "email_code" (an account with no password) and "two_fa_code" (2FA on; a recovery code stands in for it). Get a token with step_up and repeat the call with step_up_token=; the token is bound to the session that took it.

  • transfer_ownership (and InkPass's 2FA and email-change routes) always need it.
  • The grant routes, invite_member, resend_invitation, assign_role, create_api_key and a restore through set_member_status, need it only while InkPass runs with STEP_UP_ENFORCE_GRANTS=true; with it off (the default) they only count the request. Pass a token anyway, or handle StepUpRequiredError, so nothing breaks when it is turned on.
from inkpass_sdk import StepUpRequiredError

try:
    invitation = await client.invite_member("new@example.com", "developer", token=access_token)
except StepUpRequiredError as e:
    if "email_code" in e.required_factors:
        await client.start_step_up_email(access_token)  # then ask the person for the code
    proof = await client.step_up(access_token, password=password)  # or email_code=, two_fa_code=
    invitation = await client.invite_member(
        "new@example.com", "developer", token=access_token, step_up_token=proof.step_up_token
    )

step_up_requirements(token) returns the factors without trying a call.

Members, invitations and roles

These act in the caller's own organization, with a user access token or, for list_members, remove_member, invite_member, list_invitations, get_member_role and assign_role, an API key bound to a member (see API keys that act as a member). Leave out token to send the configured API key.

list_members(organization_id, *, token)

Returns: list[Member]: id, email, role (owner, admin, member or another role name), account status, membership_status (active or suspended), home_organization, first_name, last_name. Needs users:view; another organization is PermissionDeniedError.

invite_member(email, role="member", *, token, step_up_token=None)

Invite someone with a role: one of list_roles, or "member" for a membership bound to no role. Only an owner or an admin invites (OwnerOrAdminRequiredError), and only an owner invites an owner or an admin (OwnerRequiredError). A duplicate or an existing member is ValidationError. Not retried; a transport error raises OutcomeUnknownError.

How the invitee gets the code. InkPass emails the invitation itself, in the background, with a link to <accept_url>?token=<code>. accept_url is your product's own accept page: the invitations.accept_url in your InkPass client's settings, which only the platform control plane sets (PATCH /api/v1/internal/clients/{client_slug}), on an origin InkPass lists in CORS_ORIGINS, https in production, with no query or fragment. A client without one gets the InkPass-wide {FRONTEND_URL}/invite/accept. The code is never returned to the caller (Invitation has no code field), so the invitee learns it only from that email. Your accept page reads token from its URL and passes it to validate_invitation and accept_invitation with your client_slug. Invitations expire after 7 days. resend_invitation sends a new code, and the old one stops working.

Returns: Invitation: id, email, role, status, invited_by_email, expires_at, created_at

Also: list_invitations(*, token, status=None), revoke_invitation(invitation_id, *, token), resend_invitation(invitation_id, *, token, step_up_token=None).

validate_invitation(code, *, client_slug=None) and accept_invitation(code, password, *, two_fa_code=None, client_slug=None)

Public calls, made with no token. validate_invitation returns an InvitationCheck (valid, email, role, organization_name, error) so the accept page can show what the code is for. accept_invitation creates the account with this password for a new email. For an existing account, the password must be that account's own, plus its 2FA code when 2FA is on. It signs the invitee in.

Pass client_slug, your InkPass client: both calls then use /api/v1/auth/clients/{client_slug}/invitations/check|accept, and an invitation into another product's organization answers exactly as an unknown code (valid=False, ResourceNotFoundError). Without client_slug they use the unscoped routes, which see only the invitations of a client with no accept page of its own; once your client has one, pass client_slug. The account and the session belong to the invitation's client. An account with the same email in another product is not used: the invitee gets a separate account in yours.

Returns: InvitationAcceptance: a TokenResponse (access_token, refresh_token, expires_in) plus user_id, email, organization_id, role, is_new_user Raises: ResourceNotFoundError (unknown code), ValidationError (expired, used, revoked, weak or wrong password), InkPassError with status 409, ServiceUnavailableError with status 503 (busy, retry). Not retried; a transport error raises OutcomeUnknownError.

check = await client.validate_invitation(code, client_slug="worthsend")
if check.valid:
    session = await client.accept_invitation(code, password, client_slug="worthsend")
    # session.access_token, session.refresh_token, session.organization_id, session.role

list_roles(token), get_member_role(user_id, *, token), assign_role(user_id, role, *, token, step_up_token=None)

get_member_role returns a MemberRole whose role (a Role: role_name, display_name, priority, ...) is None for a plain member bound to no role. assign_role needs users:manage. The caller must be able to grant what the role carries, and may only change the role of someone who holds no more than they do (PermissionDeniedError). Granting owner or admin, or changing an owner's or an admin's role, is an owner's decision (OwnerRequiredError). The last owner is never demoted (LastOwnerError). An unknown role is ValidationError. "member" makes them a plain member bound to no role: the returned MemberRole.role is then None. The SDK sends it as is; an InkPass older than the release that accepts it answers ValidationError.

get_my_role(token)

The caller's own role in their organization, as a MemberRole; it needs no permission, so a plain member can read it (their role is None). Retried like the other reads. It takes a user token: InkPass answers an API key with 401 (AuthenticationError). An API-key caller reads owner_role from validate_api_key instead, the role of the member the key acts as.

API keys that act as a member

create_api_key(token, name, user_id=member_id) issues a key that acts as that member (an owner may name anyone; anyone else only themselves). validate_api_key(key) returns the member the key acts as: user_id, organization_id, owner_email, owner_status and owner_email_verified. These are None once the member has left. It also returns owner_role (that member's role in the key's organization: owner, admin, member or a template role; None once they left), key_status (active, paused, ...) and last_used_at (when the key was last used before this request; a retried read may see the time of its own earlier attempt). All three are None from an InkPass that does not send them yet. get_api_key_usage(key_id, token) returns an APIKeyUsage with the key's status (active, paused, expired), status_reason and last_used_at. revoke_api_key stops the key at once, because InkPass checks the key's status on every request.

Such a key manages members as its member on six routes: list_members, list_invitations and get_member_role need users:view, invite_member users:create, remove_member users:delete and assign_role users:manage. The permission must be named among the key's scopes: * does not stand in, and a scope the member no longer holds stops working at once. Through a key the caller grants no more than the key's scopes and makes no owner decision (OwnerRequiredError), even when the member is an owner; no step-up is asked. A key bound to no member gets MemberKeyRequiredError (member_key_required, 403). Keys still cannot manage API keys.

client = InkPassClient(InkPassConfig(api_key=member_key))
members = await client.list_members(org_id)
await client.invite_member("new@example.com", "developer")

Response Models

All responses are Pydantic models with full type safety:

from inkpass_sdk import (
    TokenResponse,
    UserResponse,
    RegistrationResponse,
    PermissionCheckResponse,
    APIKeyResponse,
)

# TokenResponse
tokens: TokenResponse
tokens.access_token: str
tokens.refresh_token: str
tokens.token_type: str
tokens.expires_in: int

# UserResponse
user: UserResponse
user.id: str
user.email: str
user.organization_id: str
user.status: str
user.two_fa_enabled: bool

Exception Handling

from inkpass_sdk import (
    InkPassError,              # Base exception
    AuthenticationError,        # 401 errors
    PermissionDeniedError,      # 403 errors
    ResourceNotFoundError,      # 404 errors
    ValidationError,            # 400 and 422 errors; status_code says which
    ServiceUnavailableError,    # 503 errors
    OutcomeUnknownError,        # no answer to a change that may have gone through
    StepUpRequiredError,        # 403: re-authenticate with step_up (see Step-up)
    OwnerOrAdminRequiredError,  # 403: only an owner or an admin invites
    OwnerRequiredError,         # 403: an owner's decision
)

try:
    user = await client.validate_token(token)
except AuthenticationError as e:
    print(f"Auth failed: {e.message}")
except ServiceUnavailableError as e:
    print(f"Service down: {e.message}")
except InkPassError as e:
    print(f"Error: {e.message} (status: {e.status_code})")

Advanced Usage

Custom Retry Configuration

Only calls that are safe to repeat are retried: the reads (validate_token, validate_api_key, check_permission, the list_* and get_* calls but get_billing_portal_url, step_up_requirements, validate_invitation, is_billing_configured, and FileClient's download, get_download_url, list_files and get_file) and set_organization_fallback_tier, which changes nothing when the tier is already set. They are retried only when InkPass cannot be reached or sends no answer (httpx.RequestError); an answer, an error status such as 503 included, is never retried. After the last attempt they raise ServiceUnavailableError (check_permission returns False, is_billing_configured returns False).

Everything that creates or changes state is sent once: register, login, refresh, logout, create_api_key, revoke_api_key, invitations, roles, members, billing writes, step_up, get_billing_portal_url (it opens a Stripe session), and FileClient's upload, delete, duplicate and move. A transport error raises ServiceUnavailableError, or OutcomeUnknownError where the change may have been made.

config = InkPassConfig(
    base_url="http://inkpass:8000",
    timeout=5.0,            # Each attempt
    max_retries=5,          # Up to 5 attempts in all; 0 or 1 sends a read once
    retry_min_wait=2,       # Waits 2, 4, 8, 16 seconds ...
    retry_max_wait=30,      # ... never longer than 30
)

Service-to-Service Authentication

# Use API key instead of user tokens
config = InkPassConfig(
    base_url="http://inkpass:8000",
    api_key="your-service-api-key"
)

client = InkPassClient(config)
# Client will automatically use API key for requests

Internal Service Authentication

Internal InkPass routes use X-Service-API-Key. Configure those separately from ordinary InkPass API keys:

from datetime import datetime, timezone
from inkpass_sdk import (
    InkPassClient,
    InkPassConfig,
    OutcomeUnknownError,
    ServiceUnavailableError,
)

config = InkPassConfig(
    base_url="http://inkpass:8004",
    service_api_key="wendell-service-key",
)

# Organization and user ids are UUIDs, as a string or a uuid.UUID; anything else raises
# ValueError before any request.
org_id = "6f1c2d3e-4b5a-4c6d-8e7f-90a1b2c3d4e5"

async with InkPassClient(config) as client:
    subscription = await client.get_organization_subscription(org_id)

    updated = await client.set_organization_subscription_tier(
        organization_id=org_id,
        tier="open_beta_unlimited",
        status="active",
        ends_at=datetime(2026, 7, 3, tzinfo=timezone.utc),
        source="wendell_open_beta",
        metadata={"offer_code": "ob_abc123"},
    )

    # The tier a canceled, past-due or expired subscription lands on: one of the
    # organization's active product plans, free by design (price 0, or the template's free
    # plan). Free until it is changed. An organization holding the previous fallback as its
    # fallback moves to the new one; a grant of that tier stays.
    updated = await client.set_organization_fallback_tier(org_id, tier="starter")
    print(updated.fallback_tier)

    # Only the platform service removes a tier, even one another service alone granted; a
    # tier in use (the fallback, the one it holds, a Stripe-priced one) is refused.
    try:
        await client.remove_organization_tier(org_id, tier="pilot")
    except OutcomeUnknownError:
        ...  # No answer: it may be removed. A retry gets ResourceNotFoundError if it is.
    except ServiceUnavailableError:
        ...  # 503: the organization was busy, nothing was removed. Safe to retry.

An organization's tiers are the slugs of its own active product plans. Every organization starts with free, open_beta_unlimited, unlimited and enterprise, and may add plans and remove the ones no service set; a tier that is not one of them is refused with ValidationError.

ends_at ends the tier when it passes (the effective tier becomes the fallback, expired), unless the subscription's current state came from a verified Stripe event: Stripe's ends_at is the end of the paid period of a subscription that renews.

list_client_members(organization_id, *, membership_status="active", limit=50, cursor=None, service_identity_key=None)

A product's backend reads the members of one of its client's organizations with a service identity and no user session. The identity is a key (inkpass_service_...) that InkPass issues to the product's client holding organization_members:read; the platform's control plane issues, rotates and revokes it (below). Set it as InkPassConfig(service_identity_key=...), or pass service_identity_key= for one call.

InkPass reads the client from the identity, so it answers for that client's organizations only: another client's organization and an unknown one get the same ResourceNotFoundError. A missing, unknown, revoked or expired identity, or an inactive client, is AuthenticationError; an identity without organization_members:read is PermissionDeniedError. A service API key does not work here. More than 600 requests a minute with one identity is RateLimitError.

It returns a ClientMemberPage (schema_version inkpass.members.v1, client_slug, organization_id, members, next_cursor) of ClientMember (user_id, email, first_name, last_name, role, membership_status, home_organization, account_status), in order of user ID. membership_status is active, suspended or all; limit 1 to 100. Pass next_cursor as cursor for the next page; it is None on the last. A cursor this list did not return is ValidationError.

client = InkPassClient(InkPassConfig(base_url=INKPASS_URL, service_identity_key=identity_key))
cursor = None
while True:
    page = await client.list_client_members(org_id, cursor=cursor)
    for member in page.members:
        ...
    if page.next_cursor is None:
        break
    cursor = page.next_cursor

Clients: create_client, update_client_settings, list_clients

Each product has its own InkPass client: its users, organizations and service identities belong to it. The control plane creates and configures it with the same control-plane service key as the service identity calls below.

  • create_client(name, slug, *, settings=None) returns the new AuthClient. A slug already in use is ValidationError. Sent once; a transport error raises OutcomeUnknownError, after which list_clients tells whether it was created.
  • update_client_settings(client_slug, settings) merges settings into the client's and returns it: a top-level key replaces the stored value, two dicts merge one level deep, and keys not named stay. An unknown slug is ResourceNotFoundError. Retried.
  • list_clients() returns every client, oldest first. Retried.

A slug is letters, digits, ., _ and -, starting with a letter or digit; anything else, or settings that are not a dict, raises ValueError before any request. Settings InkPass refuses, for example an invitations.accept_url it would not use, are ValidationError.

control_plane = InkPassClient(InkPassConfig(base_url=INKPASS_URL, service_api_key=factory_key))
if "rulemark" not in {client.slug for client in await control_plane.list_clients()}:
    await control_plane.create_client("Rulemark", "rulemark")
await control_plane.update_client_settings("rulemark", {"branding": {"name": "Rulemark"}})

Service identities: issue_service_identity, rotate_service_identity, list_service_identities, revoke_service_identity

The platform's control plane (for example a factory that publishes products) manages the service identities of each product's client. These calls need a control-plane service key as InkPassConfig(service_api_key=...): a service InkPass names in INTERNAL_CONTROL_PLANE_SERVICES. Another service key is PermissionDeniedError, an unknown one AuthenticationError. No user token, API key or service identity reaches them; without a service key they raise ValueError before any request.

  • issue_service_identity(client_slug, name, permissions, *, organization_slug=None) creates one and returns an IssuedServiceIdentity whose key is shown this once: InkPass keeps only its hash. It is bound to organization_slug, an organization of the client, or by default to the client's <client_slug>-services organization. An existing identity of that name is InkPassError with status 409.
  • rotate_service_identity(client_slug, name, permissions, *, organization_slug=None) gives an existing one a new key, returned once. The old key stops at once; permissions replaces the identity's set; a revoked identity is active again. A missing one is ResourceNotFoundError.
  • list_service_identities(*, client_slug=None, organization_slug=None) returns ServiceIdentity objects, revoked ones included, with key_prefix and never the key.
  • revoke_service_identity(identity_id) stops the key at once and returns the identity (is_active False, revoked_at set). Revoking it again changes nothing.

name is lowercase letters, digits and hyphens, starting with a letter, at most 63 characters. A permission outside InkPass's allow-list (organization_members:read, notifications:send, ...) or a malformed name is ValidationError; an unknown client or organization is ResourceNotFoundError. Issue and rotate are sent once; a transport error raises OutcomeUnknownError, after which rotate_service_identity gets a key you hold. The list and revoke are retried.

control_plane = InkPassClient(InkPassConfig(base_url=INKPASS_URL, service_api_key=factory_key))
try:
    issued = await control_plane.issue_service_identity(
        "rulemark", "members-reader", ["organization_members:read"]
    )
except InkPassError as error:
    if error.status_code != 409:
        raise
    issued = await control_plane.rotate_service_identity(
        "rulemark", "members-reader", ["organization_members:read"]
    )
store_secret(issued.key)  # hand it to the product; it is never shown again
...
await control_plane.revoke_service_identity(issued.id)

Do not put service API keys or service identity keys in browser, CLI, or mobile clients.

Your Own HTTP Client (Tests Without a Server)

InkPassClient and FileClient take a keyword-only http_client, an httpx.AsyncClient to send every request with. In tests, give it an httpx.MockTransport:

import httpx
from inkpass_sdk import InkPassClient

def handler(request: httpx.Request) -> httpx.Response:
    return httpx.Response(200, json={"user_id": "u", "organization_id": "o", "role": None})

http_client = httpx.AsyncClient(
    base_url="http://inkpass.test", transport=httpx.MockTransport(handler)
)
async with InkPassClient(http_client=http_client) as client:
    my_role = await client.get_my_role("jwt")
await http_client.aclose()  # yours to close

The client is used as is: give it the InkPass base_url, since the SDK sends relative paths, and its own timeout and TLS settings apply instead of the config's. You own it: close() and async with leave it open. Without http_client, the SDK creates its own from the config and closes it, as before.

Disable SSL Verification (Development Only)

config = InkPassConfig(
    base_url="https://inkpass:8443",
    verify_ssl=False  # NOT recommended for production!
)

File Management (Den)

The SDK includes a FileClient for managing files in InkPass Den storage. This is primarily used for service-to-service communication (e.g., Tentacle agents uploading/downloading files).

FileClient Usage

Every file call names the InkPass client that owns the organization. Den rejects a call with 403 (PermissionDeniedError) when the organization does not belong to that client, and gives the same response whether or not the organization exists. client_id is a required keyword on every FileClient method; passing None omits it, which only an InkPass that predates the check accepts.

from inkpass_sdk.files import FileClient
from uuid import UUID

# Initialize client with service API key
file_client = FileClient(
    base_url="http://inkpass:8002",
    service_api_key="sk_tentacle_xxx"
)

# Upload a file
with open("output.png", "rb") as f:
    result = await file_client.upload(
        client_id="client-uuid",
        org_id=UUID("org-uuid"),
        workflow_id="wf-123",
        agent_id="image-gen",
        file_data=f,
        filename="generated-image.png",
        content_type="image/png",
        folder_path="/agent-outputs",
        tags=["generated", "marketing"],
        is_public=True,  # CDN-accessible
    )
    print(f"Uploaded: {result['id']}")

# Download a file
data = await file_client.download(
    client_id="client-uuid",
    org_id=UUID("org-uuid"),
    file_id=UUID("file-uuid"),
)
content = data.read()

# Get a temporary download URL (signed)
url = await file_client.get_download_url(
    client_id="client-uuid",
    org_id=UUID("org-uuid"),
    file_id=UUID("file-uuid"),
    expires_in=3600,  # 1 hour
)

# List files
files = await file_client.list_files(
    client_id="client-uuid",
    org_id=UUID("org-uuid"),
    workflow_id="wf-123",
    folder_path="/agent-outputs",
    tags=["marketing"],
)

# Delete a file (must be created by this agent or be temporary)
await file_client.delete(
    client_id="client-uuid",
    org_id=UUID("org-uuid"),
    file_id=UUID("file-uuid"),
    agent_id="image-gen",
)

Temporary Files

Agents can create temporary files that auto-expire:

result = await file_client.upload(
    client_id=client_id,
    org_id=org_id,
    workflow_id="wf-123",
    agent_id="data-processor",
    file_data=temp_data,
    filename="temp-result.json",
    content_type="application/json",
    is_temporary=True,
    expires_in_hours=24,  # Auto-delete after 24 hours
)

Public Files (CDN)

For marketing assets that need CDN delivery:

result = await file_client.upload(
    client_id=client_id,
    org_id=org_id,
    workflow_id="wf-marketing",
    agent_id="content-gen",
    file_data=image_data,
    filename="hero-image.png",
    content_type="image/png",
    is_public=True,  # Enables CDN URL
    folder_path="/public/marketing",
)
# result['cdn_url'] will contain the CDN URL

Testing

Run Tests

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run with coverage
pytest --cov=inkpass_sdk --cov-report=html

# Run specific test
pytest tests/test_client.py::test_login_success

Mock Client for Testing

from unittest.mock import AsyncMock, MagicMock, patch
from inkpass_sdk import InkPassClient, UserResponse

async def test_my_function():
    client = InkPassClient()

    # Mock response
    mock_user = UserResponse(
        id="user-123",
        email="test@example.com",
        organization_id="org-123",
        status="active",
        two_fa_enabled=False,
    )

    with patch.object(client, 'validate_token', return_value=mock_user):
        user = await client.validate_token("test-token")
        assert user.email == "test@example.com"

Examples

See the examples/ directory for complete examples:

Run examples:

# Basic usage
python examples/basic_usage.py

# FastAPI integration
uvicorn examples.fastapi_integration:app --reload

Best Practices

1. Use Context Manager

# ✅ Good - Automatically closes
async with InkPassClient(config) as client:
    user = await client.validate_token(token)

# ❌ Bad - Manual cleanup required
client = InkPassClient(config)
user = await client.validate_token(token)
await client.close()  # Easy to forget!

2. Reuse Client Instances

# ✅ Good - Reuse connection pool
inkpass_client = InkPassClient(config)

@app.get("/endpoint1")
async def endpoint1():
    return await inkpass_client.validate_token(token)

@app.get("/endpoint2")
async def endpoint2():
    return await inkpass_client.check_permission(token, "resource", "action")

# ❌ Bad - Creates new connection each time
@app.get("/endpoint")
async def endpoint():
    client = InkPassClient(config)  # Don't do this!
    return await client.validate_token(token)

3. Handle Errors Gracefully

# ✅ Good - Handle specific errors
try:
    user = await client.validate_token(token)
except AuthenticationError:
    return {"error": "Please login again"}
except ServiceUnavailableError:
    return {"error": "Service temporarily unavailable"}
except InkPassError as e:
    logger.error(f"inkPass error: {e}")
    return {"error": "Authentication service error"}

# ❌ Bad - Catch-all
try:
    user = await client.validate_token(token)
except Exception:
    pass  # What went wrong?

4. Trust Fail-Safe Permission Checks

# Permission checks default to False on errors
# This is intentional for security!

can_delete = await client.check_permission(token, "data", "delete")
if can_delete:
    # Safe to proceed - we know they have permission
    delete_data()
else:
    # Deny access - could be no permission OR service error
    # Either way, safer to deny
    raise PermissionDenied()

Troubleshooting

Connection Errors

# Check service is running
curl http://inkpass:8000/health

# Verify base_url is correct
config = InkPassConfig(base_url="http://inkpass:8000")  # No trailing slash!

Token Validation Fails

# Check token hasn't expired
tokens = await client.login(email, password)
print(f"Token expires in: {tokens.expires_in} seconds")

# Access tokens last 30 minutes: refresh before expires_in (refresh tokens rotate)
tokens = await client.refresh(tokens.refresh_token)

Permission Checks Always Return False

# Verify permission exists in inkPass
# Verify user has permission assigned
# Check resource and action names match exactly

Development

Setup Development Environment

# Create virtual environment
python -m venv venv
source venv/bin/activate  # or `venv\Scripts\activate` on Windows

# Install in development mode
pip install -e ".[dev]"

# Run tests
pytest

# Run linters
black inkpass_sdk/
ruff check inkpass_sdk/
mypy inkpass_sdk/

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Run tests and linters
  6. Submit a pull request

License

MIT License - see repository root LICENSE.

Support

See https://fluxtopus.com.

Metadata

Release files for inkpass-sdk 0.9.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 inkpass-sdk 0.9.0
File Size Uploaded Provenance Actions
inkpass_sdk-0.9.0.tar.gz 81.4 kB Without provenance Details for inkpass_sdk-0.9.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for inkpass-sdk 0.9.0
File Interpreter ABI Platform Actions
inkpass_sdk-0.9.0-py3-none-any.whl Python 3 none any Details for inkpass_sdk-0.9.0-py3-none-any.whl

Total release size: 140.0 kB

Release files / inkpass_sdk-0.9.0.tar.gz

Download URL inkpass_sdk-0.9.0.tar.gz
Size 81.4 kB
Tags Source
SHA-256 checksum
How to use checksums
7b8b9dbed23a683d9eb2d20dcb1b4356218ef63d1b358bea07d5d49c233ee43b
BLAKE2b-256 checksum
How to use checksums
7acbd993b7b85659631e6cbe3686d4901ca36b63df54506d7a89545fbff3e68c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.3 {"installer":{"name":"uv","version":"0.10.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / inkpass_sdk-0.9.0-py3-none-any.whl

Download URL inkpass_sdk-0.9.0-py3-none-any.whl
Size 58.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2badeea3ab748558ab29df0432ec936a88f894552af5fc4a255dc2b0510cc458
BLAKE2b-256 checksum
How to use checksums
3df9fc46928e9f27071b53ac352aed204159f444ab80606396c5bacb153baaa3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.3 {"installer":{"name":"uv","version":"0.10.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for inkpass-sdk 0.9.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