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
3 changes: 3 additions & 0 deletions doc/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]

### Fixed
- **Root `tenancy:` section now reaches the plugin supervisor** (`XcoreConfig.__post_init__` shares it with `plugins.tenancy`). Before, `tenancy.enabled`/`enforce_ipc` were always read as defaults there. **Behavior change**: with `tenancy.enabled: true` and `enforce_ipc: true`, `allowed_callers` is now really enforced (deny-by-default): a plugin without `allowed_callers` (or with an empty list) refuses every incoming plugin-to-plugin call (`ipc_denied`); a boot warning lists these plugins. Also now effective at runtime: tenant ContextVar propagation in dispatch and the tenant-aware service wrappers (`isolate_cache`/`isolate_db`/`isolate_scheduler`).
- **`TenantAwareScheduler`**: `@scheduler.cron` / `@scheduler.interval` are now prefixed and tenant-bound like `add_job`, so a plugin's cron jobs are released on unload/reload when `isolate_scheduler: true`.
- **`TenantAwareCache.get_or_set`** no longer leaks values between tenants (key was not prefixed).
- **`RoutedPlugin.RouterIn()`**: restored as a deprecated alias of `get_router()` (`DeprecationWarning`); the rename in 2.5.x broke plugins still calling `self.RouterIn()`.
- **`TrustedBase.call_plugin()`**: propagates the current request tenant (`_current_tenant_id` ContextVar) instead of the frozen `ctx.tenant_id`, so nested plugin calls keep their tenant when `tenancy.enabled=true`. Falls back to `ctx.tenant_id` when no tenant is set.

Expand Down
121 changes: 121 additions & 0 deletions tests/unit/kernel/test_enforce_ipc_wiring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""enforce_ipc / tenancy racine doivent atteindre le superviseur (vraie config)."""

from types import SimpleNamespace

from xcore.configurations.loader import ConfigLoader
from xcore.kernel.context import KernelContext
from xcore.kernel.events.bus import EventBus
from xcore.kernel.runtime.supervisor import PluginSupervisor
from xcore.kernel.tenancy.services import _current_tenant_id
from xcore.services.container import ServiceContainer

_YAML = """
app:
name: t
secret_key: test-secret-key-for-testing-min32chars
plugins:
directory: {plugins}
strict_trusted: false
interval: 0
tenancy:
enabled: true
enforce_ipc: true
"""


def _add(sup, name, handler):
sup._loader._handlers[name] = handler
sup._permissions.grant_all(name)


class _Handler:
def __init__(self, allowed, seen=None):
self.manifest = SimpleNamespace(allowed_callers=allowed)
self._seen = seen

async def call(self, action, payload):
if self._seen is not None:
self._seen.append(_current_tenant_id.get())
return {"status": "ok"}


async def _boot(tmp_path):
plugins = tmp_path / "plugins"
plugins.mkdir()
cfg_file = tmp_path / "xcore.yaml"
cfg_file.write_text(_YAML.format(plugins=plugins))
cfg = ConfigLoader.load(cfg_file)
ctx = KernelContext(
config=cfg.plugins,
services=ServiceContainer(cfg.services),
events=EventBus(),
)
sup = PluginSupervisor(ctx)
await sup.boot()
return sup


async def test_config_racine_tenancy_atteint_les_plugins(tmp_path):
sup = await _boot(tmp_path)
t = sup._ctx.config.tenancy
assert t.enabled is True and t.enforce_ipc is True


async def test_ipc_denied_si_caller_non_autorise(tmp_path):
sup = await _boot(tmp_path)
_add(sup, "target", _Handler(["x"]))
denied = await sup.call("target", "ping", {}, caller="intruder")
assert denied["status"] == "error" and denied["code"] == "ipc_denied"
ok = await sup.call("target", "ping", {}, caller="x")
assert ok["status"] == "ok"


async def test_deny_by_default_sans_allowed_callers(tmp_path):
"""Changement voulu : enforce_ipc + allowed_callers vide => refus."""
sup = await _boot(tmp_path)
_add(sup, "legacy", _Handler([]))
res = await sup.call("legacy", "ping", {}, caller="any")
assert res["code"] == "ipc_denied"


async def test_tenant_propage_quand_tenancy_activee(tmp_path):
seen: list = []
sup = await _boot(tmp_path)
_add(sup, "t", _Handler(["*"], seen))
await sup.call("t", "ping", {}, caller="a", tenant_id="acme")
assert seen == ["acme"]


def test_warning_liste_les_plugins_sans_allowed_callers(monkeypatch):
from xcore.kernel.runtime import supervisor as sup_mod

class _Loader:
_m = {"open": ["*"], "closed": [], "none": None}

def get_manifest(self, n):
return SimpleNamespace(allowed_callers=self._m[n])

class _Log:
def __init__(self):
self.calls = []

def warning(self, msg, **kw):
self.calls.append((msg, kw))

log = _Log()
monkeypatch.setattr(sup_mod, "logger", log)
sup = PluginSupervisor.__new__(PluginSupervisor)
sup._loader = _Loader()
sup._warn_plugins_without_allowed_callers(["open", "closed", "none"])
assert log.calls[0][1] == {"plugins": ["closed", "none"]}
log.calls.clear()
sup._warn_plugins_without_allowed_callers(["open"])
assert log.calls == []


def test_xcoreconfig_construite_a_la_main_partage_la_tenancy_racine():
from xcore.configurations.sections import TenancyConfig, XcoreConfig

cfg = XcoreConfig(tenancy=TenancyConfig(enabled=True, enforce_ipc=True))
assert cfg.plugins.tenancy is cfg.tenancy
assert cfg.plugins.tenancy.enabled is True
48 changes: 48 additions & 0 deletions tests/unit/kernel/test_plugin_gc_scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,51 @@ async def test_get_service_after_boot_is_still_tenant_aware(

assert isinstance(lm._instance.db, TenantAwareDB)
assert lm._instance.db is not raw_db


class TestSchedulerReleasedWithIsolateScheduler:
"""isolate_scheduler=true : les jobs (add_job ET @cron/@interval) sont retirés."""

BODY = """
sch = self.get_service("scheduler")
sch.add_job(self.tick, "interval", job_id="viaadd", seconds=3600)

@sch.cron("0 * * * *")
async def viacron():
return 1

@sch.interval(seconds=3600)
async def viainterval():
return 1
"""

def _tenancy(self):
return SimpleNamespace(
enabled=True,
isolate_db=False,
isolate_cache=False,
isolate_scheduler=True,
)

def _ids(self, scheduler):
return sorted(j["id"] for j in scheduler.jobs() if "p" in j["id"])

async def test_unload_removes_every_job(self, scheduler, tmp_path):
ctx, container, registry = _kernel(scheduler, tenancy=self._tenancy())
lm = LifecycleManager(_manifest(tmp_path, "p", self.BODY), ctx)
await lm.load()
assert len(self._ids(scheduler)) == 3

await lm.unload()
assert self._ids(scheduler) == []
assert not [j for j in scheduler_module._JOB_REGISTRY if "p" in j]

async def test_reload_does_not_accumulate(self, scheduler, tmp_path):
ctx, container, registry = _kernel(scheduler, tenancy=self._tenancy())
lm = LifecycleManager(_manifest(tmp_path, "p", self.BODY), ctx)
await lm.load()
for _ in range(2):
await lm.reload()
assert len(self._ids(scheduler)) == 3
await lm.unload()
assert self._ids(scheduler) == []
22 changes: 22 additions & 0 deletions tests/unit/kernel/test_tenancy.py
Original file line number Diff line number Diff line change
Expand Up @@ -644,3 +644,25 @@ def test_partial_config_uses_defaults(self):
assert cfg.enabled is True
assert cfg.header == "X-Tenant-ID"
assert cfg.isolate_cache is True


async def test_tenant_cache_get_or_set_isole_les_tenants():
from xcore.kernel.tenancy.services import TenantAwareCache
from xcore.services.cache.backends.memory import MemoryBackend
from xcore.services.cache.service import CacheService

raw = CacheService.__new__(CacheService)
raw._backend = MemoryBackend()
a = TenantAwareCache(raw, tenant_id="a")
b = TenantAwareCache(raw, tenant_id="b")

async def va():
return "valeur-a"

async def vb():
return "valeur-b"

assert await a.get_or_set("k", va) == "valeur-a"
assert await b.get_or_set("k", vb) == "valeur-b"
assert await a.get("k") == "valeur-a"
assert await b.get("k") == "valeur-b"
5 changes: 5 additions & 0 deletions xcore/configurations/sections.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,3 +405,8 @@ class XcoreConfig:
raw: dict[str, Any] = field(default_factory=dict)
middleware: list[MiddlewareConfig] = field(default_factory=list)
cors: CORSConfig = field(default_factory=CORSConfig)

def __post_init__(self) -> None:
# Source de vérité unique : la section racine `tenancy:` est celle lue
# par le superviseur via `plugins.tenancy` (même objet partagé).
self.plugins.tenancy = self.tenancy
19 changes: 18 additions & 1 deletion xcore/kernel/runtime/supervisor.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,11 @@ async def boot(self) -> None:
)
# IPC auth en premier : bloque avant tout le reste
tenancy = getattr(self._config, "tenancy", None)
enforce_ipc = bool(tenancy and tenancy.enabled and tenancy.enforce_ipc)
self._pipeline.add_middleware(
IPCAuthMiddleware(
self._loader,
enforce=tenancy.enforce_ipc if tenancy and tenancy.enabled else False,
enforce=enforce_ipc,
),
first=True,
)
Expand All @@ -156,6 +157,8 @@ async def boot(self) -> None:
# Les handlers réactifs existent toujours pour les load/reload individuels,
# mais ici on garantit que tout est prêt avant la fin du boot.
loaded_names = report.get("loaded", [])
if enforce_ipc:
self._warn_plugins_without_allowed_callers(loaded_names)
if loaded_names:
self._load_permissions(loaded_names)
self._register_rate_limits(loaded_names)
Expand Down Expand Up @@ -190,6 +193,20 @@ async def boot(self) -> None:

return self

def _warn_plugins_without_allowed_callers(self, plugin_names: list[str]) -> None:
"""enforce_ipc est deny-by-default : signale les plugins injoignables en IPC."""
closed = [
n
for n in plugin_names
if not getattr(self._loader.get_manifest(n), "allowed_callers", None)
]
if closed:
logger.warning(
"enforce_ipc actif : ces plugins n'ont pas d'allowed_callers, "
"tout appel IPC entrant sera refusé (ipc_denied)",
plugins=sorted(closed),
)

def _register_rate_limits(self, plugin_names: list[str]) -> None:
"""Enregistre les rate limits de chaque plugin dans le RateLimiterRegistry."""
from ..sandbox.limits import RateLimitConfig as LimitsRateLimitConfig
Expand Down
27 changes: 27 additions & 0 deletions xcore/kernel/tenancy/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,13 @@ async def clear(self, pattern: str = "*") -> int:
await self._cache.delete(k)
return len(matched)

async def get_or_set(self, key: str, factory: Any, ttl: int | None = None) -> Any:
value = await self.get(key)
if value is None:
value = await factory() if callable(factory) else factory
await self.set(key, value, ttl=ttl)
return value

async def mget(self, keys: list[str]) -> dict[str, Any]:
prefixed = [self._k(k) for k in keys]
raw = await self._cache.mget(prefixed) if hasattr(self._cache, "mget") else {}
Expand Down Expand Up @@ -357,6 +364,26 @@ def add_job(
_bind_tenant(func, self._tenant), *args, **kwargs
)

def cron(self, expression: str, job_id: str | None = None):
"""@scheduler.cron : même préfixage tenant que add_job (sinon le job
n'est pas retrouvable par remove_job / le ramasse-miette du plugin)."""

def decorator(fn: Any) -> Any:
raw_id = job_id or getattr(fn, "__name__", None)
self._scheduler.cron(expression, job_id=self._jid(raw_id))(
_bind_tenant(fn, self._tenant)
)
return fn

return decorator

def interval(self, **kwargs) -> Any:
def decorator(fn: Any) -> Any:
self.add_job(fn, "interval", **kwargs)
return fn

return decorator

def remove_job(self, job_id: str) -> None:
self._scheduler.remove_job(self._jid(job_id))

Expand Down
Loading