Skip to main content

caronte-sdk

Python client for the Argos authorizer — handles app authentication, JWT validation, permission checking and automatic operation sync.

Installation

pip install caronte-sdk
# With FastAPI support
pip install "caronte-sdk[fastapi]"

Quick start with FastAPI

from fastapi import FastAPI, Request
from caronte.adapters.fastapi import Caronte, operation

app = FastAPI()

caronte = Caronte(
    app,
    authorizer_url="http://localhost:4000/api",
    app_id="your-app-uuid",
    secret="your-app-secret",
)


@app.get("/public")
@operation(id="public.info", level="public")
async def public_info():
    """Anyone can call this — no token needed."""
    return {"message": "Hello, world!"}


@app.get("/items")
@operation(id="items.list", level="private")
async def list_items(request: Request):
    """Requires any authenticated user (token with non-empty groups)."""
    user = request.state.user  # TokenClaims
    return {"user": user.sub, "items": []}


@app.delete("/items/{item_id}")
@operation(id="items.delete", level="protected")
async def delete_item(item_id: str, request: Request):
    """Requires a user whose group has explicit permission for items.delete."""
    return {"deleted": item_id}

Response envelope ({ status, message, data })

Every route answers in the same shape, on success and on error — status is the HTTP code, message is user-facing text (the UI shows it as a toast), data is the payload (None on error).

from caronte import Conflict, NotFound, ok
from caronte.adapters.fastapi import Envelope, install_envelope, operation

app = FastAPI()
install_envelope(app)   # EnvelopeError / HTTPException / 422 / unexpected 500 → { status, message, data: null }

@app.post("/tags", status_code=201, response_model=Envelope[TagOut])
@operation(id="tags:create", level="protected")
async def create_tag(body: TagCreate, db: Session = Depends(get_db)):
    return ok(TagService(db).create(body.name), "Tag criada.", 201)

class TagService:
    def get(self, tag_id):
        tag = self.repo.get_by_id(tag_id)
        if not tag:
            raise NotFound("Tag não encontrada.")   # → 404 { "status": 404, "message": "...", "data": null }
        return tag
  • caronte.envelope is framework-agnostic: ok, fail, detail_text and the business errors BadRequest (400), Unauthorized (401), Forbidden (403), NotFound (404), Conflict (409), Unprocessable (422), Unavailable (503) — all EnvelopeError subclasses.
  • Envelope[T] (FastAPI adapter) is the response model: it documents the contract in OpenAPI and filters data to the declared fields.
  • Unexpected exceptions become 500 "Erro inesperado no serviço." — the detail goes to the log only.
  • The ASGI middleware's own 401/403 also carry status/message/data (plus the previous error/detail keys, for compatibility).

Standalone client

import asyncio
from caronte import CaronteClient, OperationDescriptor

client = CaronteClient(
    authorizer_url="http://localhost:4000/api",
    app_id="your-app-uuid",
    secret="your-app-secret",
)

client.register_operation(
    OperationDescriptor(identifier="items.list", method="read", level="private")
)

async def main():
    await client.startup()

    # Validate a token from an incoming request
    claims = await client.validate_token("<bearer-token>")

    # Check whether the token has permission
    allowed = client.check_permission(claims, "items.list", "read")
    print(f"Allowed: {allowed}")

asyncio.run(main())

Credentials

A caller authenticates with exactly one of three headers (never Authorization / Bearer):

Header Who Permissions Validation
x-access-token a user logged in through a UI the user's groups (JWT claim) offline, JWT + JWKS
x-app-token a user outside the UI (MCP, script), personal token with fixed expiry (max. 1 year) the user's groups in the client + access level chosen at creation, recalculated by the authorizer introspection
x-api-token a backend service only the operations granted to that token on THIS backend introspection

Opaque tokens (x-app-token, x-api-token) are resolved by POST /realms/{realm}/tokens/introspect, authenticated with this backend's own client-credentials token. The response is cached per token (INTROSPECTION_TTL, 60 s) and every operation is then decided locally, so a client calling many operations costs one round-trip per token per minute. An x-app-token becomes the same TokenClaims a JWT yields (raw.token_type === "app_token", raw.token_id), so handlers read the user exactly as before; logs record actor_type = app_token plus the token id.

Against an authorizer without the introspection endpoint (HTTP 404), x-api-token falls back to the previous per-operation POST /apps/tokens/validate and x-app-token is rejected.

Operation levels

Level Who can access
public Everyone — no token required
private Any authenticated user (token with at least one group)
protected Only users whose groups intersect the operation's allowed_groups

Method auto-detection

The @operation decorator infers the method from the function name:

Function name prefix/keyword Detected method
get_, list_, fetch_, read_ read
delete_, remove_, destroy_ delete
contains stream, subscribe, watch stream
anything else write

Configuration

Parameter Description
authorizer_url Base URL of Argos, including the API prefix (e.g. http://host/api)
app_id UUID of the app registered in auth.apps
secret Plain-text app secret (never committed — use env vars)
otel_collector_url Optional. OTLP/HTTP endpoint of an OpenTelemetry Collector (e.g. http://localhost:4318). Opt-in — omit it and nothing OTel-related is imported or run.
import os
from caronte.adapters.fastapi import Caronte

caronte = Caronte(
    app,
    authorizer_url=os.environ["AUTHORIZER_URL"],
    app_id=os.environ["APP_ID"],
    secret=os.environ["APP_SECRET"],
)

Observability (OpenTelemetry)

Set otel_collector_url to enable tracing, metrics and logs — auth/JWKS calls (via httpx) and, when installed, your framework's requests (Django/FastAPI/ Flask) get traced and measured automatically and exported to the Collector; Python's standard logging output is forwarded too (via a LoggingHandler on the root logger). Never breaks startup(): a missing [otel] extra or an unreachable Collector just logs a warning.

pip install "caronte-sdk[otel]"
client = CaronteClient(
    authorizer_url=os.environ["AUTHORIZER_URL"],
    realm_id=os.environ["REALM_ID"],
    app_id=os.environ["APP_ID"],
    secret=os.environ["APP_SECRET"],
    otel_collector_url=os.environ.get("OTEL_COLLECTOR_URL"),  # e.g. http://localhost:4318
)

Every framework adapter (caronte.adapters.django/fastapi/flask/strawberry) accepts the same otel_collector_url (Django: CARONTE_OTEL_COLLECTOR_URL setting instead, since the middleware is constructed by Django itself) and forwards it to its internal CaronteClient.

Span attributes

Adapters generally don't create spans themselves — they enrich whichever span the auto-instrumentation registered by otel_collector_url already created for the current request (ASGI/httpx/etc). Django is the one exception: DjangoInstrumentor patches in by inserting itself into settings.MIDDLEWARE from inside CaronteMiddleware.__init__, but Django builds its middleware chain by iterating reversed(settings.MIDDLEWARE) — since CaronteMiddleware must be first in that list, its __init__ runs last in that loop, leaving no earlier slot for the auto-injection to claim. So CaronteMiddleware.__call__ creates the request's SPAN_KIND_SERVER span manually instead of relying on that auto-injection.

Each adapter's auth/permission hook adds, best-effort:

Attribute Set when Value
caronte.operation_id Always, for any @operation-annotated route/resolver the operation's id
caronte.user A token was validated TokenClaims.sub
caronte.permission_result Always, for any annotated route/resolver public / unauthorized / forbidden / allowed

Routes/resolvers with no @operation decorator are left untouched — no caronte.* attributes are added, since there's no caronte-relevant decision being made.

Strawberry: composing with the official OTel extension

caronte.extension only enforces auth/permissions — it never creates spans itself. For per-resolver GraphQL tracing, add the official OTel extension alongside it; that's an app-level choice, not something caronte-sdk forces:

from opentelemetry.instrumentation.strawberry import OpenTelemetryExtensionSync

schema = strawberry.Schema(
    query=Query,
    extensions=[caronte.extension, OpenTelemetryExtensionSync()],
)

Note: without the second extension, resolve() still enriches whatever span is currently active (typically the single request-level span from your ASGI framework's instrumentation) — with multiple resolvers running per request, the last one to run wins on shared attribute keys. Adding OpenTelemetryExtensionSync() gives each resolver its own span instead.

Metadata

Release files for caronte-sdk 0.6.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 caronte-sdk 0.6.0
File Size Uploaded Provenance
caronte_sdk-0.6.0.tar.gz 46.4 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for caronte-sdk 0.6.0
File Interpreter ABI Platform
caronte_sdk-0.6.0-py3-none-any.whl Python 3 none any Details

Total release size: 88.3 kB

Release files / caronte_sdk-0.6.0.tar.gz

Download URL caronte_sdk-0.6.0.tar.gz
Size 46.4 kB
Tags Source
SHA-256 checksum
How to use checksums
7c77a797bbfb14157814c0e614cfff2a0d765b7987047af3898214a2c892f73b
BLAKE2b-256 checksum
How to use checksums
e04070a24f3a7b02048be404e02a49a42c8e653aca6a63f0b7b30e90206e3f14
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.4

Release files / caronte_sdk-0.6.0-py3-none-any.whl

Download URL caronte_sdk-0.6.0-py3-none-any.whl
Size 41.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f6dde566e1364712cd4fff2785b752af44c310224655897698ac3abecd84b802
BLAKE2b-256 checksum
How to use checksums
0bc5a108a33316ddb2c46e57717820b65ecc00b96241a58042b00ef634361306
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.4

Security for caronte-sdk 0.6.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