Metadata-Version: 2.5
Name: ayes
Version: 0.0.1
Summary: Pundit-style authorization policies for Python web apps.
Author: API-Air
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: authorization,fastapi,multi-tenant,permissions,policy,pundit
Classifier: Development Status :: 1 - Planning
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.11
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.115; extra == 'fastapi'
Description-Content-Type: text/markdown

# Ayes

**Pundit-style authorization policies for Python web apps.** FastAPI first.

*The ayes have it:* every action your app allows has been voted through by a policy.

> Status: **pre-alpha, design phase.** Nothing below is implemented yet. The API sketched here is a
> proposal, open to change.

Ayes answers one question, everywhere in your app, the same way:

> *May this user do this action on this object?*

Authentication tells you **who** is calling. Ayes decides **what they may do**. It does this with
plain Python policy classes, one per kind of object, the way Ruby's Pundit does. Then it checks
that every route actually asks.

## Why

FastAPI deliberately ships no authorization layer. OAuth2 scopes answer "may this token write
invoices?", not "may this user edit *this* invoice?". So most apps grow access checks inline,
route by route. Each route recombines the rules a little differently, and the gaps look alike:

- an object reachable from another tenant because two checks were made separately and never
  compared;
- three code paths for the same action, and only two of them apply the rule;
- the same refusal answered 403 here, 404 there, 422 elsewhere, leaking whether an object exists.

Ayes' goal is to make those mistakes hard to write and easy to catch.

## Principles

1. **One policy per object, plain Python.** A class with one method per action. No DSL to learn.
2. **Explicit, not magic.** The route names its policy and its action. Nothing is inferred from
   class or function names.
3. **Authorize the object, then hand it over.** The FastAPI dependency loads the object, checks it,
   and gives the route the *authorized* object. The route can't load a different one by mistake.
4. **Tenancy is an invariant, not a rule you remember.** If your app is multi-tenant, "same tenant"
   is checked once, before any policy runs.
5. **Normalized refusals.** Out of scope → 404 (never confirm an object exists). In scope, not
   allowed → 403. Allowed, but the object's state forbids it → 409.
6. **Scopes for lists.** A policy also says which rows a user may list, as a query filter.
7. **Async first.** Policies often need the database. The user's context (tenants, roles) is loaded
   once per request, not once per check.
8. **The rules are a table, and the table is tested.** You declare who may do what. Ayes generates
   the test cases from that declaration.
9. **No route left behind.** A test inspects every route and fails if one doesn't go through a
   policy (with an explicit allow-list for public routes).

## API sketch (draft)

A multi-tenant publishing tool: each workspace is a tenant, and holds articles. In a workspace, a
person is an `admin`, an `editor` or a `user`. Users write drafts; editors edit and publish;
admins can also delete.

```python
from ayes import Policy, Refused


class ArticlePolicy(Policy[Article]):
    def tenant_of(self, article: Article) -> UUID:
        return article.workspace_id

    async def view(self) -> bool:
        return (
            self.obj.is_published or self.role in {"admin", "editor"} or self.is_author
        )

    async def update(self) -> bool:
        return self.role in {"admin", "editor"} or (
            self.is_author and self.obj.is_draft
        )

    async def publish(self) -> bool:
        return self.role in {"admin", "editor"}

    async def delete(self) -> bool:
        if self.obj.is_under_legal_hold:
            raise Refused.state("article_under_legal_hold")  # → 409
        return self.role == "admin"

    @property
    def is_author(self) -> bool:
        return self.obj.author_id == self.user.id

    @classmethod
    def scope(cls, user: Context) -> ColumnElement[bool]:
        return Article.workspace_id.in_(user.workspace_ids)
```

In a FastAPI route:

```python
from ayes.fastapi import authorize

CanUpdate = Depends(authorize(ArticlePolicy, "update", load=get_article))


@router.patch("/articles/{article_id}")
async def update_article(
    article: Annotated[Article, CanUpdate],
    payload: ArticleUpdate,
):
    # No access checks here: `article` is already authorized.
    ...
```

Declaring the rules, and getting the tests:

```python
from ayes.testing import Matrix

matrix = Matrix(
    ArticlePolicy,
    roles=["admin", "editor", "user", "outsider"],
    rules={
        "update": ["admin", "editor"],
        "publish": ["admin", "editor"],
        "delete": ["admin"],
    },
)

# One test per role × action, plus the cross-tenant case.
test_article_policy = matrix.pytest()
```

Checking coverage:

```python
from ayes.testing import assert_all_routes_authorized


def test_every_route_is_authorized():
    assert_all_routes_authorized(app, public={"/health", "/auth/login"})
```

## Coming from Pundit

| Pundit (Rails) | Ayes |
|---|---|
| `PostPolicy#update?` | `PostPolicy.update()`, async |
| `authorize @post` | `Depends(authorize(PostPolicy, "update", load=...))`, returns the post |
| `policy_scope(Post)` | `PostPolicy.scope(user)`, a SQL filter |
| `verify_authorized` | `assert_all_routes_authorized(app)`, in CI rather than at runtime |
| `rescue_from Pundit::NotAuthorizedError` | one exception handler mapping refusals to 404 / 403 / 409 |
| `permitted_attributes` | fields allowed per action, checked against the request model |

## Roadmap

- **0.1** — core: `Policy`, request context, tenant invariant, normalized refusals, FastAPI
  `authorize` dependency, list scopes.
- **0.2** — testing: declared rule matrix → generated tests; route coverage check (report mode,
  then blocking).
- **0.3** — permitted fields; SQLAlchemy helpers.
- Later — Django and Flask integrations, if the core holds up.

## License

Apache-2.0. See `LICENSE` and `NOTICE`.
