diff --git a/doc/sdk/api/auth.md b/doc/sdk/api/auth.md index 37561b92..919af604 100644 --- a/doc/sdk/api/auth.md +++ b/doc/sdk/api/auth.md @@ -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()`. diff --git a/doc/sdk/api/decorators.md b/doc/sdk/api/decorators.md index d62fd262..b5764f38 100644 --- a/doc/sdk/api/decorators.md +++ b/doc/sdk/api/decorators.md @@ -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: @@ -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 @@ -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 diff --git a/tests/unit/plugins/test_decorators.py b/tests/unit/plugins/test_decorators.py index 1e7b19e2..e6e94161 100644 --- a/tests/unit/plugins/test_decorators.py +++ b/tests/unit/plugins/test_decorators.py @@ -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.""" @@ -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.""" diff --git a/xcore/kernel/schema/registry.py b/xcore/kernel/schema/registry.py index 0b4fa3aa..88d4910d 100644 --- a/xcore/kernel/schema/registry.py +++ b/xcore/kernel/schema/registry.py @@ -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 @@ -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) + # 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: diff --git a/xcore/sdk/decorators.py b/xcore/sdk/decorators.py index 6fd715e4..12764017 100644 --- a/xcore/sdk/decorators.py +++ b/xcore/sdk/decorators.py @@ -96,15 +96,31 @@ async def create_user(self, payload: dict) -> dict: def decorator(fn: Callable) -> Callable: input_fields = _normalize_input(input) + # Construit le Model une seule fois ici — validate_payload le reçoit + # tout fait au lieu de refaire son propre create_model() à partir du + # même dict. C'est aussi ce Model qui donne le JSON Schema complet + # (champs imbriqués, défauts, contraintes...), que le seul dict + # {field: type_name} ci-dessous ne peut pas exprimer. + InputModel = ( + create_model("DynamicSchema", **input_fields) if input_fields else None + ) + # Applique validate_payload automatiquement si input est défini wrapped = ( validate_payload( - schema=input_fields, type_response=type_response, unset=unset + schema=InputModel, type_response=type_response, unset=unset )(fn) - if validate and input_fields and type_response != "_" + if validate and InputModel is not None and type_response != "_" else fn ) + output_fields = _normalize_input(output) + OutputModel = ( + create_model("DynamicOutputSchema", **output_fields) + if output_fields + else None + ) + wrapped._xcore_schema = { "version": version, "input": {k: _type_name(v) for k, v in input_fields.items()}, @@ -112,16 +128,24 @@ def decorator(fn: Callable) -> Callable: "deprecated_fields": deprecated_fields or {}, "breaking_since": breaking_since, "description": description, + "input_json_schema": InputModel.model_json_schema() if InputModel else {}, + "output_json_schema": ( + OutputModel.model_json_schema() if OutputModel else {} + ), } return wrapped return decorator +_VALID_SIDE_EFFECTS = frozenset({"read", "write", "outbound"}) + + def action( name: str, permissions: list[str] | None = None, permission_groups: list[list[str]] | None = None, + side_effect: Literal["read", "write", "outbound"] | None = None, ): """ Marque une méthode comme handler d'action. @@ -146,17 +170,37 @@ async def team_report(self, payload: dict) -> dict: # plateforme (admin:*) — jamais les deux à la fois exigés. ... + `side_effect` déclare le niveau de conséquence de l'action — "read" (aucun + effet de bord), "write" (modifie un état interne) ou "outbound" (quitte le + système : email, paiement, appel HTTP sortant, message posté...). C'est un + axe orthogonal à `permissions` : `permissions` dit QUI peut appeler, + `side_effect` dit QUEL RISQUE ça représente une fois l'appel autorisé — un + appelant légitime peut quand même déclencher quelque chose d'irréversible. + Purement déclaratif, stocké sur fn._xcore_action_side_effect : xcore n'en + fait rien lui-même, ni n'en déduit l'enforcement. L'usage prévu est qu'un + consommateur externe (ex : un pont qui expose les actions comme tools LLM) + lise cette valeur via ActionSchema.side_effect pour décider seul si une + action peut être un tool direct ou doit passer par une approbation — en + traitant toute action sans `side_effect` déclaré comme la plus risquée + (pas de valeur = pas de feu vert implicite). + Pour un schéma versionné, empilez @schema séparément (voir sa docstring) : @action("create_user", permissions=["admin"]) @schema(version="2.0", input={"email": (str, ...)}) async def create_user(self, payload: dict) -> dict: ... """ + if side_effect is not None and side_effect not in _VALID_SIDE_EFFECTS: + raise ValueError( + f"side_effect invalide : {side_effect!r} — attendu l'un de " + f"{sorted(_VALID_SIDE_EFFECTS)} ou None" + ) def decorator(fn: Callable) -> Callable: fn._xcore_action = name fn._xcore_action_permissions = permissions or [] fn._xcore_action_permission_groups = permission_groups or [] + fn._xcore_action_side_effect = side_effect return fn return decorator diff --git a/xcore/sdk/mixin/ipc.py b/xcore/sdk/mixin/ipc.py index 5fc13821..e77f8745 100644 --- a/xcore/sdk/mixin/ipc.py +++ b/xcore/sdk/mixin/ipc.py @@ -33,7 +33,16 @@ def _build_action_map(self) -> None: self._action_map_built = True def _register_schemas(self, plugin_name: str) -> None: - """Enregistre tous les schémas @schema de ce plugin dans le SchemaRegistry.""" + """ + Enregistre une ActionSchema par méthode @action de ce plugin — schéma + (@schema, optionnel) ET permissions (@action(permissions=..., + permission_groups=...), optionnelles elles aussi) dans le même + SchemaRegistry. Une action sans l'un ou l'autre y apparaît quand même + (champs vides) : le registre reste le catalogue complet de TOUTES les + actions du plugin, pas seulement celles qui ont un @schema — sinon un + consommateur externe qui ne lirait que ce registre perdrait + silencieusement les permissions des actions sans schéma déclaré. + """ from xcore.kernel.schema.registry import ActionSchema, schema_registry for attr_name in dir(self.__class__): @@ -41,20 +50,31 @@ def _register_schemas(self, plugin_name: str) -> None: if not callable(method): continue action_name = getattr(method, "_xcore_action", None) - schema_meta = getattr(method, "_xcore_schema", None) - if action_name and schema_meta: - schema_registry.register( - ActionSchema( - plugin=plugin_name, - action=action_name, - version=schema_meta["version"], - input=schema_meta["input"], - output=schema_meta["output"], - deprecated_fields=schema_meta["deprecated_fields"], - breaking_since=schema_meta["breaking_since"], - description=schema_meta["description"], + if not action_name: + continue + + schema_meta = getattr(method, "_xcore_schema", None) or {} + schema_registry.register( + ActionSchema( + plugin=plugin_name, + action=action_name, + version=schema_meta.get("version", ""), + input=schema_meta.get("input", {}), + output=schema_meta.get("output", {}), + deprecated_fields=schema_meta.get("deprecated_fields", {}), + breaking_since=schema_meta.get("breaking_since"), + description=schema_meta.get("description", ""), + input_json_schema=schema_meta.get("input_json_schema", {}), + output_json_schema=schema_meta.get("output_json_schema", {}), + permissions=getattr(method, "_xcore_action_permissions", None) + or [], + permission_groups=getattr( + method, "_xcore_action_permission_groups", None ) + or [], + side_effect=getattr(method, "_xcore_action_side_effect", None), ) + ) async def handle(self, action_name: str, payload: dict) -> dict: from xcore.kernel.api.contract import error