Metadata-Version: 2.5
Name: caronte-sdk
Version: 0.4.2
Summary: Python client for the Argos authorizer (OIDC + RBAC)
Project-URL: Homepage, https://github.com/xlucvvs/packages/tree/main/caronte/python
Project-URL: Repository, https://github.com/xlucvvs/packages
Project-URL: Bug Tracker, https://github.com/xlucvvs/packages/issues
Author-email: Lucas Ribeiro <lucasribeiro.sec@gmail.com>
License: CC0 1.0 Universal
        
        Statement of Purpose
        
        The laws of most jurisdictions throughout the world automatically confer
        exclusive Copyright and Related Rights (defined below) upon the creator and
        subsequent owner(s) of an original work of authorship and/or a database
        (each, a "Work").
        
        Certain owners wish to permanently relinquish those rights to a Work for the
        purpose of contributing to a commons of creative, cultural and scientific works
        that the public can reliably and without fear of infringement build upon,
        modify, incorporate in other works, cite, and distribute, as freely as
        possible, without legal restriction.
        
        To the greatest extent permitted by, but not in contravention of, applicable
        law, Affirmer hereby overtly, fully, permanently, irrevocably and
        unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
        and Related Rights and associated claims and causes of action, in the Work.
        
        Should any part of this dedication be judged legally invalid or ineffective
        under applicable law, the dedication shall be preserved to the maximum extent
        permitted by law.
        
        For more information, please see:
        https://creativecommons.org/publicdomain/zero/1.0/
License-File: LICENSE
Keywords: auth,authorization,jwt,oidc,rbac
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: Django
Classifier: Framework :: FastAPI
Classifier: Framework :: Flask
Classifier: Intended Audience :: Developers
Classifier: License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Security
Requires-Python: >=3.11
Requires-Dist: httpx>=0.27
Requires-Dist: pyjwt[crypto]>=2.8
Requires-Dist: python-jose[cryptography]>=3.3
Provides-Extra: dev
Requires-Dist: cryptography>=42; extra == 'dev'
Requires-Dist: django>=4.0; extra == 'dev'
Requires-Dist: fastapi>=0.111; extra == 'dev'
Requires-Dist: flask>=2.0; extra == 'dev'
Requires-Dist: httpx>=0.27; extra == 'dev'
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.24; extra == 'dev'
Requires-Dist: opentelemetry-instrumentation-httpx>=0.45b0; extra == 'dev'
Requires-Dist: opentelemetry-sdk>=1.24; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: respx>=0.21; extra == 'dev'
Requires-Dist: starlette>=0.37; extra == 'dev'
Requires-Dist: strawberry-graphql>=0.235; extra == 'dev'
Provides-Extra: django
Requires-Dist: django>=4.0; extra == 'django'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.111; extra == 'fastapi'
Requires-Dist: starlette>=0.37; extra == 'fastapi'
Provides-Extra: flask
Requires-Dist: flask>=2.0; extra == 'flask'
Provides-Extra: otel
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.24; extra == 'otel'
Requires-Dist: opentelemetry-instrumentation-django>=0.45b0; extra == 'otel'
Requires-Dist: opentelemetry-instrumentation-fastapi>=0.45b0; extra == 'otel'
Requires-Dist: opentelemetry-instrumentation-flask>=0.45b0; extra == 'otel'
Requires-Dist: opentelemetry-instrumentation-httpx>=0.45b0; extra == 'otel'
Requires-Dist: opentelemetry-sdk>=1.24; extra == 'otel'
Provides-Extra: strawberry
Requires-Dist: strawberry-graphql>=0.235; extra == 'strawberry'
Description-Content-Type: text/markdown

# caronte-sdk

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

## Installation

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

## Quick start with FastAPI

```python
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}
```

## Standalone client

```python
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())
```

## 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. |

```python
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.

```bash
pip install "caronte-sdk[otel]"
```

```python
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:

```python
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.
