Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions doc/sdk/api/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,18 +205,30 @@ class Plugin(TrustedBase):

## Enforcing action permissions

`ActionPermissionMiddleware` sits right after `AuthResolverMiddleware` in the pipeline (before `PermissionMiddleware`). For the action being called, it reads the declared requirement via `handler.get_action_permissions(action)` (`LifecycleManager.get_action_permissions()`, which looks up `fn._xcore_action_permissions` on the dispatched method — see [@action](./decorators.md#action)):
`ActionPermissionMiddleware` sits right after `AuthResolverMiddleware` in the pipeline (before `PermissionMiddleware`). For the action being called, it reads the declared requirements via `handler.get_action_permissions(action)` / `handler.get_action_permission_groups(action)` (`LifecycleManager`, which look up `fn._xcore_action_permissions` / `fn._xcore_action_permission_groups` on the dispatched method — see [@action](./decorators.md#action)):

- **No `permissions` declared** (the default) → no check at all, fully backward compatible.
- **`permissions` declared** → the principal must have at least one matching entry in `roles` or `permissions` for *every* required item, or the call is denied with `{"status": "error", "code": "action_permission_denied"}`. No `principal` (no backend registered, or no token on this call) with a declared requirement is a denial, not a silent pass — fail-closed: an explicit requirement with nobody to prove it can't be waved through.
- **Neither `permissions` nor `permission_groups` declared** (the default) → no check at all, fully backward compatible.
- **`permissions` declared** (AND) → the principal must have a matching entry in `roles` or `permissions` for *every* required item.
- **`permission_groups` declared** (OR of AND) → the principal must fully cover *at least one* of the declared groups — for a role hierarchy where several distinct permissions each grant sufficient access on their own (`permissions` alone would require all of them at once).
- If both are declared on the same action, both conditions apply: `permissions` must be fully satisfied *and* at least one group must be too.
- Either requirement, if declared, is denied with `{"status": "error", "code": "action_permission_denied"}` when unmet. No `principal` (no backend registered, or no token on this call) with a declared requirement is a denial, not a silent pass — fail-closed: an explicit requirement with nobody to prove it can't be waved through.

```python
@action("delete_user", permissions=["admin"])
async def delete_user(self, payload: dict) -> dict:
# only reached if the resolved principal has "admin" in roles or permissions
...

@action("team_report", permission_groups=[["tenants:write"], ["admin:*"]])
async def team_report(self, payload: dict) -> dict:
# the tenant owner (tenants:write) OR a platform admin (admin:*) — never both
...
```

This is a separate system from `PermissionEngine` / `PolicySet` (plugin-to-plugin resource ACL, see [Permissions & Policies](../../plugins/permissions.md)) — that one answers "can plugin A call plugin B", this one answers "does this user have this role". Neither is merged into the other.

`permissions`/`permission_groups` are also mirrored on `ActionSchema` in `schema_registry` for every `@action` (schema or not) — see [decorators: reading permissions/side_effect without a live plugin instance](./decorators.md#reading-permissionsside_effect-without-a-live-plugin-instance). That registry entry is a read-only catalog for external tooling; `ActionPermissionMiddleware` itself still reads the live `LifecycleManager` at call time, not the registry.

Authorization (`permissions`/`permission_groups`) is a different axis from risk/supervision level: a legitimate, authorized caller can still trigger something irreversible. `@action(..., side_effect="read"|"write"|"outbound")` declares that separately and is purely informational to the kernel — see [@action](./decorators.md#action).

No `AuthBackend` implementation ships in this repository — the kernel only ever depends on the protocol (`decode_token`/`extract_token`/`has_permission`), never on how tokens are produced or stored. A plugin author provides one (signed JWT, a shared session store, an external IdP...) and registers it with `register_auth_backend()` in `on_load()`.
40 changes: 36 additions & 4 deletions doc/sdk/api/decorators.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,23 @@ async def get_user(self, payload: dict) -> dict:
| Name | Type | Default | Description |
|------|------|---------|-------------|
| `name` | `str` | — | Action identifier used in `handle(name, payload)` |
| `permissions` | `list[str] \| None` | `None` | Roles/permissions required to invoke this action — stored on `fn._xcore_action_permissions`. Declarative only today: nothing in the kernel enforces it yet (see [Auth](./auth.md#resolving-the-current-user-on-ipc-calls)); it's the hook a future per-action RBAC middleware will read. |
| `permissions` | `list[str] \| None` | `None` | Roles/permissions required to invoke this action — **all** of them (AND). Stored on `fn._xcore_action_permissions`, enforced by `ActionPermissionMiddleware` against the `principal` resolved by `AuthResolverMiddleware` (see [Auth: Enforcing action permissions](./auth.md#enforcing-action-permissions)). No `principal` with a declared requirement is a denial (fail-closed). |
| `permission_groups` | `list[list[str]] \| None` | `None` | Alternative permission groups — satisfied if the principal fully covers **at least one** group (OR of AND). For a role hierarchy where several distinct permissions each grant sufficient access on their own (e.g. a tenant owner *or* a platform admin) — `permissions` alone can't express that, it would require both. Independent and combinable with `permissions`: if both are set, `permissions` must be fully satisfied *and* at least one group must be too. |
| `side_effect` | `"read" \| "write" \| "outbound" \| None` | `None` | Declares how consequential the action is — orthogonal to `permissions`: `permissions` says *who* can call it, `side_effect` says *what risk* it carries once the call is authorized. Purely declarative — the kernel does nothing with it itself; it's for an external consumer (e.g. a bridge exposing actions as LLM tools) to decide whether an action can be a direct tool or needs human approval first. Raises `ValueError` at decoration time if given anything other than one of the three values. An action without a declared `side_effect` should be treated by such a consumer as the riskiest tier — no declaration is not an implicit green light. |

Just these two parameters — nothing else. The decorated method must be `async`, accept `self` and `payload: dict`, and return a `dict`.
The decorated method must be `async`, accept `self` and `payload: dict`, and return a `dict`.

```python
@action("team_report", permission_groups=[["tenants:write"], ["admin:*"]])
async def team_report(self, payload: dict) -> dict:
# allowed for the tenant owner (tenants:write) OR a platform admin
# (admin:*) — never both required at once.
...

@action("send_email", permissions=["admin"], side_effect="outbound")
async def send_email(self, payload: dict) -> dict:
...
```

`@action` and `@schema` are fully independent decorators — stack them (in either order) when an action also needs a versioned schema:

Expand All @@ -39,6 +53,10 @@ Just these two parameters — nothing else. The decorated method must be `async`
async def create_user(self, payload: dict) -> dict: ...
```

### Reading permissions/side_effect without a live plugin instance

Both `fn._xcore_action_permissions`/`_xcore_action_permission_groups`/`_xcore_action_side_effect` (read per-call by `ActionPermissionMiddleware` via `LifecycleManager.get_action_permissions()`/`get_action_permission_groups()`, which need a loaded plugin instance) **and** a mirror of all three on `SchemaRegistry`'s `ActionSchema` (see [Schema metadata](#schema-metadata)) are populated — the registry entry exists for *every* `@action`, with or without `@schema`, specifically so an external consumer can read permissions and schema for the whole system from `schema_registry` alone, without instantiating each plugin's `LifecycleManager`.

---

## @route
Expand Down Expand Up @@ -138,19 +156,33 @@ When `type_response="_"` (default), validation is skipped; `@schema` only stores

### Schema metadata

The schema is stored on the function as `fn._xcore_schema`:
The schema is stored on the function as `fn._xcore_schema`. `@schema` builds the pydantic model **once** from `input` (and once from `output`) and reuses that same model for both validation (via `@validate_payload` internally) and the JSON Schema below — it doesn't rebuild a separate model for each:

```python
{
"version": "2.0",
"input": {"email": "str", "role": "str"},
"input": {"email": "str", "role": "str"}, # {field: type name} — used by BreakingChangeDetector
"output": {"user_id": "int", "created_at": "str"},
"deprecated_fields": {},
"breaking_since": None,
"description": "Create a new user account",
"input_json_schema": { # full JSON Schema from the real pydantic model
"title": "DynamicSchema",
"type": "object",
"properties": {
"email": {"title": "Email", "type": "string"},
"role": {"title": "Role", "type": "string", "default": "user"},
},
"required": ["email"],
},
"output_json_schema": {"...": "same shape, from `output`"},
}
```

`input`/`output` stay flat `{field: type_name}` dicts — that's what `BreakingChangeDetector` compares field-by-field to flag breaking changes, and a full JSON Schema diff would be a different (stricter) comparison. `input_json_schema`/`output_json_schema` are for consumers that need the real shape (nested fields, defaults, constraints) — generating an LLM tool definition, OpenAPI, documentation — not just a type name. Both are `{}` when the corresponding `input`/`output` wasn't declared.

This is also mirrored on `SchemaRegistry`'s `ActionSchema.input_json_schema`/`.output_json_schema` (see [Reading permissions/side_effect without a live plugin instance](#reading-permissionsside_effect-without-a-live-plugin-instance)).

### Deprecation tracking

```python
Expand Down
114 changes: 114 additions & 0 deletions tests/unit/plugins/test_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,91 @@ async def process_action(self, payload):
assert hasattr(plugin.process_action, "_xcore_action")
assert plugin.process_action._xcore_action == "process"

def test_side_effect_stored(self):
class Plugin:
@action("send_email", side_effect="outbound")
async def send_email(self, payload):
return {"status": "ok"}

@action("ping")
async def ping(self, payload):
return {"status": "ok"}

plugin = Plugin()
assert plugin.send_email._xcore_action_side_effect == "outbound"
# Non déclaré : None, jamais une valeur par défaut qui ressemblerait
# à un feu vert implicite.
assert plugin.ping._xcore_action_side_effect is None

def test_side_effect_rejects_unknown_value(self):
with pytest.raises(ValueError):

class Plugin:
@action("bad", side_effect="delete_everything")
async def bad(self, payload):
return {"status": "ok"}


class TestSchemaDecorator:
"""Test @schema decorator — Model pydantic unifié + JSON Schema."""

def test_input_json_schema_reflects_real_model(self):
from xcore.sdk import schema

class Plugin:
@action("create_user")
@schema(
version="2.0",
input={"email": (str, ...), "role": (str, "user")},
output={"user_id": int},
)
async def create_user(self, payload):
return {"status": "ok"}

meta = Plugin.create_user._xcore_schema
js = meta["input_json_schema"]
assert js["required"] == ["email"]
assert js["properties"]["role"]["default"] == "user"
assert meta["output_json_schema"]["properties"]["user_id"]["type"] == "integer"

def test_no_input_no_json_schema(self):
from xcore.sdk import schema

class Plugin:
@action("ping")
@schema(version="1.0")
async def ping(self, payload):
return {"status": "ok"}

meta = Plugin.ping._xcore_schema
assert meta["input_json_schema"] == {}
assert meta["output_json_schema"] == {}

@pytest.mark.asyncio
async def test_validation_still_applies_through_unified_model(self):
"""La validation de payload doit continuer à fonctionner alors que le
Model est désormais construit une seule fois dans @schema (et non
plus refait séparément par @validate_payload)."""
from xcore.sdk import error, schema

class Plugin:
@action("create_user")
@schema(
version="1.0",
input={"email": (str, ...)},
type_response="dict",
)
async def create_user(self, payload):
return {"status": "ok", "email": payload["email"]}

plugin = Plugin()
ok_result = await plugin.create_user({"email": "a@b.com"})
assert ok_result["status"] == "ok"

bad_result = await plugin.create_user({})
assert bad_result["status"] == "error"
assert bad_result["code"] == "validation_error"


class TestTrustedDecorator:
"""Test @trusted decorator."""
Expand Down Expand Up @@ -276,6 +361,35 @@ async def method2(self, payload: dict) -> dict:
assert "action1" in result["msg"]
assert "action2" in result["msg"]

def test_register_schemas_covers_every_action_not_just_schema(self):
"""Une action sans @schema (seulement @action, avec ou sans
permissions) doit quand même apparaître dans le SchemaRegistry —
sinon un consommateur qui ne lit que ce registre perd silencieusement
ses permissions."""
from xcore.kernel.schema.registry import schema_registry

class TestPlugin(AutoDispatchMixin):
@action("bare_ping")
async def bare_ping(self, payload: dict) -> dict:
return {"status": "ok"}

@action("delete_user", permissions=["admin"], side_effect="write")
async def delete_user(self, payload: dict) -> dict:
return {"status": "ok"}

plugin = TestPlugin()
plugin._register_schemas("test_register_plugin")

bare = schema_registry.get("test_register_plugin", "bare_ping")
assert bare is not None
assert bare.permissions == []
assert bare.input_json_schema == {}

delete = schema_registry.get("test_register_plugin", "delete_user")
assert delete is not None
assert delete.permissions == ["admin"]
assert delete.side_effect == "write"


class TestRoutedPlugin:
"""Test RoutedPlugin class."""
Expand Down
34 changes: 32 additions & 2 deletions xcore/kernel/schema/registry.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
"""
SchemaRegistry — Registre central des schémas d'actions de plugins.

Chaque action décorée avec @schema y est enregistrée automatiquement.
Le registry permet de :
Chaque action décorée avec @action y est enregistrée automatiquement, que
@schema soit empilé dessous ou pas — une action sans @schema y apparaît avec
input/output vides mais permissions/permission_groups renseignés s'ils sont
déclarés. Le registry permet de :
- valider les entrées/sorties au dispatch
- persister les schémas (JSON) pour détecter les breaking changes entre déploiements
- exposer la liste des actions versionnées via le CLI
- servir de catalogue complet (schéma + permissions) pour un consommateur
externe (génération de tools LLM, audit...) sans instancier chaque plugin
"""

from __future__ import annotations
Expand All @@ -30,6 +34,32 @@ class ActionSchema:
deprecated_fields: dict[str, str] = field(default_factory=dict) # {field: reason}
breaking_since: str | None = None
description: str = ""
# JSON Schema complet (champs imbriqués, défauts, contraintes...) produit par
# le Model pydantic réel construit dans @schema — {} si l'action n'a pas de
# schéma d'entrée/sortie. `input`/`output` ci-dessus restent la source pour
# BreakingChangeDetector (comparaison type-par-type) ; ces deux champs sont
# pour les consommateurs externes (génération de tools LLM, OpenAPI, etc.)
# qui ont besoin de la forme complète, pas juste du nom du type.
input_json_schema: dict[str, Any] = field(default_factory=dict)
output_json_schema: dict[str, Any] = field(default_factory=dict)
Comment on lines +43 to +44

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Older readers discard schema snapshots

When an older CLI or runtime loads a snapshot written by this version, ActionSchema.to_dict() persists the added fields, but older strict ActionSchema constructors reject them and SchemaRegistry.load() skips the entries. Rollbacks then lose the schemas used for breaking-change comparisons.

Make loading tolerate unknown fields or version and migrate the snapshot format.

Prompt for AI agents
In `xcore/kernel/schema/registry.py` at lines 43-44:

**Older readers discard schema snapshots**

When an older CLI or runtime loads a snapshot written by this version, `ActionSchema.to_dict()` persists the added fields, but older strict `ActionSchema` constructors reject them and `SchemaRegistry.load()` skips the entries. Rollbacks then lose the schemas used for breaking-change comparisons.

Make loading tolerate unknown fields or version and migrate the snapshot format.

# Miroir de fn._xcore_action_permissions / _xcore_action_permission_groups
# (@action(permissions=..., permission_groups=...), voir sdk/decorators.py).
# Dupliqué ici pour qu'un consommateur externe (catalogue d'outils LLM,
# audit, doc...) lise permissions ET schéma pour TOUTE action depuis ce
# seul registre — sans instancier le LifecycleManager de chaque plugin
# (seule autre source : LifecycleManager.get_action_permissions()/
# get_action_permission_groups(), qui exige une instance de plugin vivante
# et reste la source d'autorité pour ActionPermissionMiddleware).
permissions: list[str] = field(default_factory=list)
permission_groups: list[list[str]] = field(default_factory=list)
# Miroir de fn._xcore_action_side_effect (@action(side_effect=...)) —
# "read" | "write" | "outbound" | None. Axe orthogonal aux permissions :
# dit quel risque représente l'action une fois l'appel autorisé, pas qui
# peut l'appeler. Purement déclaratif ici aussi — xcore n'en fait rien,
# c'est un consommateur externe (ex : génération de tools LLM) qui décide
# si une action sans side_effect déclaré doit être traitée comme la plus
# risquée avant de l'exposer comme tool auto-approuvé.
side_effect: str | None = None

@property
def key(self) -> str:
Expand Down
Loading
Loading