Skip to content

fix(tenancy): isole réellement la base par search_path PostgreSQL - #299

Merged
NICE-DEV226 merged 5 commits into
mainfrom
fix/tenancy-search-path
Oct 13, 2026
Merged

NICE-DEV226 merged 5 commits into
mainfrom
fix/tenancy-search-path

Conversation

@NICE-DEV226

@NICE-DEV226 NICE-DEV226 commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Ce que ça remédie

isolate_db: true n'isolait rien. TenantAwareDB envoyait SET search_path en chaîne brute à SQLAlchemy 2.x : ArgumentError, avalée en debug. Sur un vrai PostgreSQL avec public, acme et beta contenant la même table, une session du tenant acme lisait la ligne de public.

  • Isolation réelle : set_config('search_path', :sp, true) (portée = transaction, valeur liée en paramètre, jamais d'interpolation), sur un tenant validé ([A-Za-z0-9_-]{1,63}, fullmatch) et cité : "tenant", public. Aucune fuite vers la requête suivante du pool ; un écouteur after_begin le ré-applique après un commit() intermédiaire. execute, fetch_* et session() sont couverts. Injection testée (a"; DROP SCHEMA public CASCADE; --).
  • Échec fermé : si le search_path n'a pas tenu (isolation_level: AUTOCOMMIT, pooler en mode statement), RuntimeError explicite au lieu d'une lecture silencieuse de public.
  • Tenants refusés : public, information_schema, pg_* (insensible à la casse), *, plus de 63 caractères, saut de ligne — pour la DB, le cache et le scheduler. X-Tenant-ID invalide → 400 {"error":"invalid_tenant"} (sans en-tête : tenant par défaut inchangé).
  • Cache : un tenant * permettait keys()/clear() sur toutes les clés ; refusé.
  • Scheduler : un job sans job_id n'était pas préfixé (deux tenants se remplaçaient) et s'exécutait avec le tenant default ; préfixé et tenant d'enregistrement repris (y compris callable objet à __call__ async).
  • Pool : pool_reset_on_return n'était jamais appliqué (la chaîne n'est pas un ResetStyle). Passé à create_async_engine, valeurs normalisées (ROLLBACK, "None", None), valeur invalide → erreur claire au démarrage.

Changements de comportement à connaître

  • Avec isolate_db: true, la base bascule de public vers le schéma du tenant. Le schéma doit exister ; sinon PostgreSQL retombe sur public. Si des tables homonymes sont créées plus tard dans un schéma de tenant, elles masqueront celles de public.
  • Un tenant invalide lève désormais ValueError (et 400 côté HTTP) ; les job_id implicites changent de forme (acme:fn).
  • Un aller-retour SQL de plus par opération sur PostgreSQL.
  • Non changé : le tenant reste lu dans l'en-tête non authentifié X-Tenant-ID.

Tests

  • 23 nouveaux tests, tous rouges avant correctif (tests/unit/kernel/test_tenancy_isolation_real.py). 50 sessions concurrentes sur 52 schémas, pool de 5 : 0 fuite.
  • Suite unitaire : 1429 passés / 11 ignorés (tests PostgreSQL sans XCORE_TEST_PG_URL), 1 échec préexistant sur main (test_extensions.py::test_init_loads_extension). Avec un PostgreSQL réel : 1439 passés. isort / black OK.
  • TestTenantAwareDB réécrit (les mocks vérifiaient la chaîne SQL brute) sur SQLite réel.
  • CI : le job test de ci.yml gagne un service postgres:16 + XCORE_TEST_PG_URL + pip install asyncpg pour exécuter ces tests ; modification non exécutée avant cette PR (si asyncpg n'a pas de wheel pour une version de Python de la matrice, ce job le dira).

Summary by Sourcery

Garantir l’isolation effective des tenants PostgreSQL et renforcer la validation ainsi que la propagation du contexte tenant dans les composants associés.

New Features:

  • Isoler réellement les requêtes PostgreSQL par schéma tenant avec une portée transactionnelle et une vérification de persistance du search_path.
  • Propager le tenant enregistré aux jobs planifiés et préfixer également les identifiants implicites afin d’éviter les collisions entre tenants.

Bug Fixes:

  • Empêcher les fuites de données vers le schéma public lorsque l’isolation PostgreSQL échoue ou que le mode de connexion ne la garantit pas.
  • Valider et refuser les tenants invalides ou réservés dans la base, le cache, le scheduler et les requêtes HTTP.
  • Empêcher les opérations de cache globales via le tenant *.
  • Corriger l’application de pool_reset_on_return et rejeter les valeurs de configuration invalides.

Enhancements:

  • Prendre en charge les requêtes SQL brutes avec SQLAlchemy 2.x tout en conservant la compatibilité avec les adaptateurs non PostgreSQL.

CI:

  • Ajouter un service PostgreSQL et le pilote asyncpg au job CI afin d’exécuter les tests d’isolation réels.

Tests:

  • Ajouter une couverture PostgreSQL réelle de l’isolation entre tenants, de la persistance après commit, de l’absence de fuite via le pool, des modes d’isolation incompatibles, de la validation des tenants, du cache et du scheduler.

TenantAwareDB envoyait le SET search_path en chaîne brute : SQLAlchemy 2.x
lève ArgumentError, l'exception était avalée en debug et isolate_db n'isolait
rien, sans alerte. Désormais :
- search_path posé via set_config(..., true) avec paramètre lié sur un
  identifiant validé (fullmatch, 1 à 63 car.) puis cité : portée transaction,
  donc aucune fuite vers la requête suivante du pool, ré-appliqué après un
  commit intermédiaire (after_begin) ;
- une erreur sur PostgreSQL est propagée ; SQLite, MySQL et MongoDB sont
  ignorés explicitement (détection du dialecte) ;
- execute/fetch_* acceptent une chaîne (convertie en text()) ;
- le tenant est validé aussi pour le cache et le scheduler : un tenant "*"
  (en-tête X-Tenant-ID) permettait cache.clear()/keys() sur tous les tenants ;
- scheduler : un job sans job_id est préfixé par le tenant (sinon deux
  tenants se remplaçaient) et s'exécute avec le ContextVar du tenant
  d'enregistrement.

Risque connu, inchangé : le tenant provient d'un en-tête HTTP non
authentifié (TenantMiddleware) ; tout client peut choisir son tenant. Aucune
injection SQL possible via tenant_id (regex stricte + paramètre lié).
Le schéma du tenant doit exister, sinon PostgreSQL retombe sur public.
La chaîne affectée directement à pool._reset_on_return n'était égale à aucune
valeur ResetStyle : le pool n'effectuait plus aucun reset au retour de
connexion (ni rollback, ni commit). L'option native est maintenant transmise
au moteur, qui la convertit et rejette les valeurs invalides au démarrage.
…ntrée

- AUTOCOMMIT (isolation_level ou execution_options) : set_config local était
  perdu sans erreur et les requêtes lisaient public. Le search_path est
  maintenant relu dans la même transaction ; s'il n'a pas persisté, une
  RuntimeError explicite est levée (fail-closed, valable aussi derrière un
  pooler en mode statement). Choix assumé : pas de set_config de session, qui
  fuirait entre requêtes du pool.
- tenants réservés refusés pour DB, cache et scheduler : public,
  information_schema, pg_* (insensible à la casse).
- TenantMiddleware renvoie 400 JSON (invalid_tenant) dès l'entrée quand
  l'en-tête ou le sous-domaine est invalide ; l'absence d'en-tête garde le
  tenant par défaut, et rien ne change si la tenancy est désactivée.
- pool_reset_on_return normalisé (casse, none/null/false, true) et validé au
  démarrage pour les adaptateurs sync et async.
- scheduler : un callable objet à __call__ async conserve le tenant
  d'enregistrement.
Copilot AI balanced review requested due to automatic review settings October 13, 2026 17:47
@sourcery-ai

sourcery-ai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Cette PR rend l’isolation multi-tenant PostgreSQL effective en configurant et vérifiant search_path par transaction, refuse les configurations ou identifiants dangereux, propage correctement le tenant au cache et au scheduler, corrige le reset du pool SQLAlchemy et ajoute une couverture d’intégration PostgreSQL exécutée en CI.

Sequence diagram for PostgreSQL tenant-isolated database access

sequenceDiagram
    participant Caller
    participant TenantAwareDB
    participant AsyncSession
    participant PostgreSQL

    Caller->>TenantAwareDB: execute(query)
    TenantAwareDB->>AsyncSession: _set_tenant_schema(sess)
    TenantAwareDB->>PostgreSQL: set_config('search_path', :sp, true)
    PostgreSQL-->>TenantAwareDB: transaction-scoped search_path
    TenantAwareDB->>PostgreSQL: current_setting('search_path')
    PostgreSQL-->>TenantAwareDB: tenant_schema, public
    TenantAwareDB->>PostgreSQL: execute(query)
    PostgreSQL-->>Caller: tenant-scoped result
    AsyncSession-->>PostgreSQL: commit or rollback
    PostgreSQL-->>AsyncSession: transaction ends, search_path discarded
Loading

Sequence diagram for tenant validation and request rejection

sequenceDiagram
    actor Client
    participant Middleware
    participant TenantValidation
    participant Handler

    Client->>Middleware: HTTP request with X-Tenant-ID
    Middleware->>TenantValidation: _validate_tenant(tenant_id)
    alt invalid or reserved tenant
        TenantValidation-->>Middleware: ValueError
        Middleware-->>Client: 400 {error: invalid_tenant}
    else valid tenant
        TenantValidation-->>Middleware: validated tenant
        Middleware->>Handler: call_next(request)
        Handler-->>Client: response
    end
Loading

Sequence diagram for tenant-aware scheduled job execution

sequenceDiagram
    participant Application
    participant TenantAwareScheduler
    participant Scheduler
    participant Job
    participant ContextVar

    Application->>TenantAwareScheduler: add_job(func)
    TenantAwareScheduler->>TenantAwareScheduler: _validate_tenant(tenant_id)
    TenantAwareScheduler->>Scheduler: add_job(_bind_tenant(func, tenant), job_id)
    Scheduler-->>Application: registered tenant-prefixed job
    Scheduler->>Job: invoke wrapped callable
    Job->>ContextVar: set tenant
    Job-->>Job: access tenant-aware DB or cache
    Job->>ContextVar: reset tenant
Loading

File-Level Changes

Change Details Files
Remplacer le SET search_path SQL brut par une isolation PostgreSQL transactionnelle, vérifiée et fail-closed.
  • Valider strictement les tenants et refuser les schémas réservés ou les valeurs injectables.
  • Appliquer set_config('search_path', :sp, true) avec paramètre lié, vérifier la persistance et réappliquer après les débuts de transaction.
  • Couvrir les opérations execute, fetch_* et session, tout en conservant un comportement ignoré sur les dialectes non PostgreSQL.
  • Convertir les chaînes SQL en expressions SQLAlchemy 2.x et propager les erreurs PostgreSQL au lieu de les avaler.
xcore/kernel/tenancy/services.py
tests/unit/kernel/test_tenancy.py
tests/unit/kernel/test_tenancy_isolation_real.py
Renforcer la propagation et la validation de l’identité du tenant aux frontières HTTP, cache et scheduler.
  • Retourner HTTP 400 avec invalid_tenant pour un tenant d’en-tête ou de sous-domaine invalide.
  • Empêcher les opérations globales du cache via le tenant * et valider le tenant à chaque usage.
  • Préfixer aussi les identifiants de jobs implicites et restaurer le tenant d’enregistrement lors de l’exécution, y compris pour les callables async.
xcore/kernel/tenancy/middleware.py
xcore/kernel/tenancy/services.py
tests/unit/kernel/test_tenancy_isolation_real.py
Corriger la configuration du reset des connexions SQLAlchemy afin qu’elle soit réellement transmise au pool.
  • Normaliser les valeurs YAML booléennes, nulles et textuelles vers les styles SQLAlchemy supportés.
  • Lever une erreur claire pour les valeurs invalides et transmettre la configuration à create_async_engine/create_async_engine selon l’adaptateur.
  • Ajouter des tests du comportement ROLLBACK, COMMIT et NONE sur SQLite et PostgreSQL.
xcore/services/database/adapters/_utils.py
xcore/services/database/adapters/async_sql.py
xcore/services/database/adapters/sql.py
tests/unit/kernel/test_tenancy_isolation_real.py
Ajouter une couverture d’intégration PostgreSQL réelle et l’exécuter en CI.
  • Provisionner PostgreSQL 16 et installer asyncpg dans le job de tests.
  • Tester l’isolation entre schémas, l’absence de fuite dans le pool, les commits intermédiaires, l’AUTOCOMMIT, l’injection, le cache, le scheduler et le middleware.
  • Remplacer les mocks SQLAlchemy obsolètes par des tests SQLite réels pour le comportement générique.
.github/workflows/ci.yml
tests/unit/kernel/test_tenancy.py
tests/unit/kernel/test_tenancy_isolation_real.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@gitguardian

gitguardian Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

️✅ There are no secrets present in this pull request anymore.

If these secrets were true positive and are still valid, we highly recommend you to revoke them.
While these secrets were previously flagged, we no longer have a reference to the
specific commits where they were detected. Once a secret has been leaked into a git
repository, you should consider it compromised, even if it was deleted immediately.
Find here more information about risks.


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

@github-actions

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

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.

Hey - I've found 8 issues

Fixed security issues:

  • SQL injection from untrusted request data interpolated into raw SQL strings (link)
Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="xcore/kernel/tenancy/middleware.py" line_range="63" />
<code_context>
+                        "detail": "Identifiant de tenant invalide ou réservé.",
+                    },
+                )
+        tenant_id = requested or self._cfg.default_tenant
         request.state.tenant_id = tenant_id
         return await call_next(request)
</code_context>
<issue_to_address>
**Clients can select another tenant**

When a caller with a valid API key sends another tenant’s valid ID in `X-Tenant-ID`, `TenantMiddleware` checks only the syntax of `X-Tenant-ID`, then the router passes it to `PluginSupervisor`, which sets the tenant `ContextVar` used by `TenantAwareDB`; a caller with a valid API key can therefore choose another tenant and read its data.

Authorize the requested tenant against the authenticated principal before passing it to the supervisor.
</issue_to_address>

### Comment 2
<location path="xcore/kernel/tenancy/services.py" line_range="211" />
<code_context>
+
+        from sqlalchemy import event, text
+
+        params = {"sp": f'"{tenant}", public'}
+        await _maybe_await(sess.execute(text(_SET_SEARCH_PATH_SQL), params))
+        # Preuve que la valeur tient : en AUTOCOMMIT (ou derrière un pooler
</code_context>
<issue_to_address>
**Tenant queries reach shared tables**

When the tenant schema or a queried table is absent, `_set_tenant_schema` puts `public` in `search_path`, and PostgreSQL skips missing schemas and resolves absent tenant tables there. Tenant-aware queries therefore read or modify shared rows instead of failing closed.

Remove `public` from the tenant search path and ensure missing tenant schemas or tables fail closed.

Also at `xcore/kernel/tenancy/services.py:173`, `xcore/kernel/tenancy/services.py:212`.
</issue_to_address>

### Comment 3
<location path="xcore/kernel/tenancy/services.py" line_range="211" />
<code_context>
+
+        from sqlalchemy import event, text
+
+        params = {"sp": f'"{tenant}", public'}
+        await _maybe_await(sess.execute(text(_SET_SEARCH_PATH_SQL), params))
+        # Preuve que la valeur tient : en AUTOCOMMIT (ou derrière un pooler
</code_context>
<issue_to_address>
**Temporary tables shadow tenant tables**

When a tenant creates a temporary table and another tenant reuses that pooled connection, postgreSQL searches the connection's temporary schema ahead of `search_path` when `pg_temp` is omitted. An unqualified query therefore resolves to the earlier tenant's temporary table, exposing or corrupting tenant data.

Set the search path so the connection's temporary schema cannot shadow tenant relations.
</issue_to_address>

### Comment 4
<location path="xcore/kernel/tenancy/middleware.py" line_range="63" />
<code_context>
+                        "detail": "Identifiant de tenant invalide ou réservé.",
+                    },
+                )
+        tenant_id = requested or self._cfg.default_tenant
         request.state.tenant_id = tenant_id
         return await call_next(request)
</code_context>
<issue_to_address>
**Invalid defaults turn requests into errors**

When a request omits the tenant header and subdomain and `default_tenant` is malformed or reserved, `TenantMiddleware` assigns `default_tenant` without validating it, so tenant-aware services raise `ValueError` and otherwise ordinary requests become server errors.

Validate the configured default tenant before assigning it to the request.
</issue_to_address>

### Comment 5
<location path="xcore/kernel/tenancy/services.py" line_range="292-293" />
<code_context>
+        getattr(func, "__call__", None)
+    ):
+
+        @functools.wraps(func)
+        async def _async_wrapper(*a: Any, **k: Any) -> Any:
+            token = _current_tenant_id.set(tenant)
+            try:
</code_context>
<issue_to_address>
**Async callable objects cannot be wrapped**

When `TenantAwareScheduler.add_job` receives an async callable object without `__name__`, `_bind_tenant` applies `functools.wraps(func)` to the callable instance, which has no `__name__`; it raises `AttributeError` before the scheduler receives the job.

Wrap callable instances without requiring function-only attributes such as `__name__`.
</issue_to_address>

### Comment 6
<location path="xcore/services/database/adapters/async_sql.py" line_range="80-84" />
<code_context>
             engine_kwargs.pop("pool_timeout", None)
             engine_kwargs.pop("pool_recycle", None)
             engine_kwargs.pop("pool_pre_ping", None)
+        else:
+            # Option native du pool : SQLAlchemy convertit "rollback"/"commit"/
+            # "none" en ResetStyle. Affecter la chaîne à pool._reset_on_return
+            # n'est comparé à aucune des valeurs attendues => plus aucun reset.
+            engine_kwargs["pool_reset_on_return"] = normalize_pool_reset(
+                self._pool_reset_on_return
+            )
</code_context>
<issue_to_address>
**SQLite reset settings are ignored**

When an async SQLite adapter uses a non-default or invalid `pool_reset_on_return` value, the SQLite branch skips `normalize_pool_reset` and does not pass the setting to the engine. Invalid values are accepted and configured reset behavior is ignored.

Normalize and pass `pool_reset_on_return` in the async SQLite branch.
</issue_to_address>

### Comment 7
<location path="xcore/kernel/tenancy/middleware.py" line_range="50" />
<code_context>
+        requested = request.headers.get(self._cfg.header) or (
+            self._from_subdomain(request) if self._cfg.subdomain else None
         )
+        if requested:
+            # Valeur fournie par le client (non authentifiée) : rejet immédiat
+            # plutôt qu'une ValueError tardive dans DB/cache/scheduler.
</code_context>
<issue_to_address>
**Empty tenant headers select the default**

When the client sends an empty tenant header and no usable subdomain tenant is selected, `requested` is falsey, so `TenantMiddleware` skips `_validate_tenant` and selects the configured default instead of returning the promised 400 response.

Treat an explicitly supplied empty tenant header as invalid and return the 400 response.

Also at `xcore/kernel/tenancy/middleware.py:47-49`.
</issue_to_address>

### Comment 8
<location path="xcore/kernel/tenancy/services.py" line_range="237-240" />
<code_context>
             yield sess

-    async def execute(self, query: str, *args, **kwargs) -> Any:
+    async def execute(self, query: Any, *args, **kwargs) -> Any:
         async with self._db.session() as sess:
             await self._set_tenant_schema(sess)
-            return await sess.execute(query, *args, **kwargs)
+            return await sess.execute(_as_statement(query), *args, **kwargs)

-    async def fetch_one(self, query: str, *args, **kwargs) -> Any:
</code_context>
<issue_to_address>
**Legacy tenancy tests fail**

When the integration test suite runs the unchanged tenancy tests, `TenantAwareDB.execute` now turns SQL strings into `TextClause` objects, but the existing integration tests still search their recorded `execute` arguments for string fragments from the removed `SET search_path` SQL. The fake sessions also lack `get_bind()`, so schema setup is skipped and the tests fail instead of validating the new behavior.

Rewrite the integration tests to provide a PostgreSQL-like session and assert the new `set_config` behavior, or otherwise update their fakes and assertions for `TextClause` arguments.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 8 findings to address first, and the middleware accepts the client-supplied tenant header as the tenant identity, and the new database routing makes that value select a PostgreSQL schema; a caller could request another tenant’s schema and read its rows. Reverting stops future routing but cannot retract data already exposed, and the tenant-selection policy itself is the trust boundary.

Blocking findings: xcore/kernel/tenancy/middleware.py:63, xcore/kernel/tenancy/services.py:211, xcore/kernel/tenancy/services.py:211, xcore/kernel/tenancy/middleware.py:63, xcore/kernel/tenancy/services.py:293, and 3 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

"detail": "Identifiant de tenant invalide ou réservé.",
},
)
tenant_id = requested or self._cfg.default_tenant

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.

🟠 High · Clients can select another tenant

When a caller with a valid API key sends another tenant’s valid ID in X-Tenant-ID, TenantMiddleware checks only the syntax of X-Tenant-ID, then the router passes it to PluginSupervisor, which sets the tenant ContextVar used by TenantAwareDB; a caller with a valid API key can therefore choose another tenant and read its data.

Authorize the requested tenant against the authenticated principal before passing it to the supervisor.

Prompt for AI agents
In `xcore/kernel/tenancy/middleware.py` at line 63:

**Clients can select another tenant**

When a caller with a valid API key sends another tenant’s valid ID in `X-Tenant-ID`, `TenantMiddleware` checks only the syntax of `X-Tenant-ID`, then the router passes it to `PluginSupervisor`, which sets the tenant `ContextVar` used by `TenantAwareDB`; a caller with a valid API key can therefore choose another tenant and read its data.

Authorize the requested tenant against the authenticated principal before passing it to the supervisor.


from sqlalchemy import event, text

params = {"sp": f'"{tenant}", public'}

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.

🔴 Critical · Tenant queries reach shared tables

When the tenant schema or a queried table is absent, _set_tenant_schema puts public in search_path, and PostgreSQL skips missing schemas and resolves absent tenant tables there. Tenant-aware queries therefore read or modify shared rows instead of failing closed.

Remove public from the tenant search path and ensure missing tenant schemas or tables fail closed.

Also at xcore/kernel/tenancy/services.py:173, xcore/kernel/tenancy/services.py:212.

Prompt for AI agents
In `xcore/kernel/tenancy/services.py` at line 211:

**Tenant queries reach shared tables**

When the tenant schema or a queried table is absent, `_set_tenant_schema` puts `public` in `search_path`, and PostgreSQL skips missing schemas and resolves absent tenant tables there. Tenant-aware queries therefore read or modify shared rows instead of failing closed.

Remove `public` from the tenant search path and ensure missing tenant schemas or tables fail closed.

Also at `xcore/kernel/tenancy/services.py:173`, `xcore/kernel/tenancy/services.py:212`.


from sqlalchemy import event, text

params = {"sp": f'"{tenant}", public'}

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.

🟠 High · Temporary tables shadow tenant tables

When a tenant creates a temporary table and another tenant reuses that pooled connection, postgreSQL searches the connection's temporary schema ahead of search_path when pg_temp is omitted. An unqualified query therefore resolves to the earlier tenant's temporary table, exposing or corrupting tenant data.

Set the search path so the connection's temporary schema cannot shadow tenant relations.

Prompt for AI agents
In `xcore/kernel/tenancy/services.py` at line 211:

**Temporary tables shadow tenant tables**

When a tenant creates a temporary table and another tenant reuses that pooled connection, postgreSQL searches the connection's temporary schema ahead of `search_path` when `pg_temp` is omitted. An unqualified query therefore resolves to the earlier tenant's temporary table, exposing or corrupting tenant data.

Set the search path so the connection's temporary schema cannot shadow tenant relations.

"detail": "Identifiant de tenant invalide ou réservé.",
},
)
tenant_id = requested or self._cfg.default_tenant

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 · Invalid defaults turn requests into errors

When a request omits the tenant header and subdomain and default_tenant is malformed or reserved, TenantMiddleware assigns default_tenant without validating it, so tenant-aware services raise ValueError and otherwise ordinary requests become server errors.

Validate the configured default tenant before assigning it to the request.

Prompt for AI agents
In `xcore/kernel/tenancy/middleware.py` at line 63:

**Invalid defaults turn requests into errors**

When a request omits the tenant header and subdomain and `default_tenant` is malformed or reserved, `TenantMiddleware` assigns `default_tenant` without validating it, so tenant-aware services raise `ValueError` and otherwise ordinary requests become server errors.

Validate the configured default tenant before assigning it to the request.

Comment on lines +292 to +293
@functools.wraps(func)
async def _async_wrapper(*a: Any, **k: Any) -> Any:

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 · Async callable objects cannot be wrapped

When TenantAwareScheduler.add_job receives an async callable object without __name__, _bind_tenant applies functools.wraps(func) to the callable instance, which has no __name__; it raises AttributeError before the scheduler receives the job.

Wrap callable instances without requiring function-only attributes such as __name__.

Prompt for AI agents
In `xcore/kernel/tenancy/services.py` at lines 292-293:

**Async callable objects cannot be wrapped**

When `TenantAwareScheduler.add_job` receives an async callable object without `__name__`, `_bind_tenant` applies `functools.wraps(func)` to the callable instance, which has no `__name__`; it raises `AttributeError` before the scheduler receives the job.

Wrap callable instances without requiring function-only attributes such as `__name__`.

Comment on lines +80 to +84
else:
# Option native du pool : SQLAlchemy convertit "rollback"/"commit"/
# "none" en ResetStyle. Affecter la chaîne à pool._reset_on_return
# n'est comparé à aucune des valeurs attendues => plus aucun reset.
engine_kwargs["pool_reset_on_return"] = normalize_pool_reset(

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 · SQLite reset settings are ignored

When an async SQLite adapter uses a non-default or invalid pool_reset_on_return value, the SQLite branch skips normalize_pool_reset and does not pass the setting to the engine. Invalid values are accepted and configured reset behavior is ignored.

Normalize and pass pool_reset_on_return in the async SQLite branch.

Prompt for AI agents
In `xcore/services/database/adapters/async_sql.py` at lines 80-84:

**SQLite reset settings are ignored**

When an async SQLite adapter uses a non-default or invalid `pool_reset_on_return` value, the SQLite branch skips `normalize_pool_reset` and does not pass the setting to the engine. Invalid values are accepted and configured reset behavior is ignored.

Normalize and pass `pool_reset_on_return` in the async SQLite branch.

requested = request.headers.get(self._cfg.header) or (
self._from_subdomain(request) if self._cfg.subdomain else None
)
if requested:

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 · Empty tenant headers select the default

When the client sends an empty tenant header and no usable subdomain tenant is selected, requested is falsey, so TenantMiddleware skips _validate_tenant and selects the configured default instead of returning the promised 400 response.

Treat an explicitly supplied empty tenant header as invalid and return the 400 response.

Also at xcore/kernel/tenancy/middleware.py:47-49.

Prompt for AI agents
In `xcore/kernel/tenancy/middleware.py` at line 50:

**Empty tenant headers select the default**

When the client sends an empty tenant header and no usable subdomain tenant is selected, `requested` is falsey, so `TenantMiddleware` skips `_validate_tenant` and selects the configured default instead of returning the promised 400 response.

Treat an explicitly supplied empty tenant header as invalid and return the 400 response.

Also at `xcore/kernel/tenancy/middleware.py:47-49`.

Comment thread xcore/kernel/tenancy/services.py Resolved
Service postgres:16 et XCORE_TEST_PG_URL sur le job de tests ; asyncpg est
installé à la demande (absent des dépendances du projet).
Deux tests de TestDBTenantIsolation vérifiaient l'ancienne chaîne SQL brute
`SET search_path TO "acme"` envoyée sur n'importe quel backend. Le search_path
n'est plus posé que sur PostgreSQL, via set_config(..., true) et un paramètre
lié. Le faux backend se déclare PostgreSQL et les assertions portent sur
l'appel set_config et sa valeur liée.

Ces tests n'avaient pas été relancés (seul tests/unit l'avait été) et faisaient
échouer « Quick Test » et la porte de PR. Ils échouent sur l'ancien code.
Copilot AI balanced review requested due to automatic review settings October 13, 2026 17:52
@NICE-DEV226
NICE-DEV226 force-pushed the fix/tenancy-search-path branch from 8a8dfaf to ebbf4e8 Compare October 13, 2026 17:52

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@NICE-DEV226
NICE-DEV226 merged commit 17058d3 into main Oct 13, 2026
25 checks passed
NICE-DEV226 added a commit that referenced this pull request Oct 13, 2026
…entrée de session (#301)

## Ce que ça remédie

**Régression introduite par #299** : sur PostgreSQL avec `isolate_db:
true`, tout plugin qui fait `async with session.begin():` échouait
(`InvalidRequestError: A transaction is already begun`, HTTP 500).
`TenantAwareDB._set_tenant_schema` exécutait `set_config` puis
`current_setting` **à l'entrée de `session()`**, ce qui déclenchait
l'autobegin de SQLAlchemy avant que le plugin n'ouvre sa propre
transaction. Avec `isolate_db: false` tout passait. Idiome courant dans
les plugins ERP (xstock, xsales, xpurchase…). Mes tests de #299 ne
couvraient pas ce cas.

## Correctif

`_set_tenant_schema` n'exécute plus aucun SQL à l'entrée de la session :
il attache un écouteur `after_begin` qui pose `set_config('search_path',
:sp, true)` et relit `current_setting` **au début de chaque
transaction** (autobegin, `begin()` du plugin, après commit ou
rollback). Toutes les garanties de #299 sont conservées : isolation dans
la même transaction que les requêtes du plugin, **échec fermé**
(`RuntimeError`) si le `search_path` n'a pas tenu (AUTOCOMMIT, pooler en
mode statement), aucune fuite entre requêtes du pool. Si l'adaptateur a
déjà ouvert la transaction (option `execution_options`), le
`search_path` est posé immédiatement via `run_sync`.

## Tests

- Sur PostgreSQL réel, rouges avant correctif : `session.begin()` du
plugin, 50 sessions concurrentes de tenants différents sur un pool de 5
(mêlant `begin()`, commit/rollback et requête simple : 0 fuite),
AUTOCOMMIT toujours refusé avec `begin()`.
- Suite unitaire + intégration : 1469 passés / 15 ignorés (tests
PostgreSQL sans `XCORE_TEST_PG_URL`, exécutés par le job CI qui a un
service `postgres`), 2 échecs `test_xworker::test_build_app_*` (module
`dateutil` absent de l'environnement de test), identiques sans ce
changement. `isort` / `black` OK.
- 3 tests de #299 supposaient du SQL exécuté à l'entrée de la session :
adaptés pour passer par l'écouteur ; un test vérifie qu'aucun `execute`
n'a lieu à l'entrée.

## À savoir

- Le `search_path` est posé à la première requête de la transaction,
plus à l'entrée de session : plus de SQL implicite avant le premier
`execute` du plugin.
- Non couvert : un plugin qui appelle `begin()` sur une session que
l'adaptateur a déjà fait autobégin (cas `execution_options`) échoue
toujours ; comportement de l'adaptateur déjà présent avec `isolate_db:
false`.

## Summary by Sourcery

Defer tenant search-path setup to transaction start so explicit plugin
transactions work without compromising database isolation.

Bug Fixes:
- Prevent tenant session initialization from implicitly opening a
transaction, allowing plugins to start explicit transactions with
`session.begin()` without errors.
- Reapply and validate the tenant-specific PostgreSQL `search_path` at
the start of every transaction while preserving fail-closed isolation
behavior.

Enhancements:
- Handle sessions whose transaction was already opened by the adapter
while retaining tenant schema isolation.

Tests:
- Update tenancy unit and integration tests for deferred `after_begin`
schema setup, explicit plugin transactions, transaction boundaries,
concurrent pooled sessions, and AUTOCOMMIT rejection.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants