skip to content

How would you test that an EF Core 10 tenant filter cannot leak another tenant's forum posts, including through code paths that skip filters?

level: seniorimportance: should knowfreq 28%

answer

  1. two tenants seeded, two contexts
  2. assert with a fresh context per tenant
  3. ToQueryString shows the filter predicate
  4. SqlQuery and ExecuteSql are not filtered
  5. Find returns tracked entities first

basics

~20 s

Seed two tenants in a real database, query through tenant A's context and assert no tenant B row appears via LINQ, Include, FromSql or ExecuteUpdate. Separately test paths filters never reach, like Database.SqlQuery, and every IgnoreQueryFilters call.

solid answer

~50 s

I write integration tests against a real PostgreSQL database (a container), seed posts and comments for tenants A and B, and create one context per tenant the way the app does. Each test runs a code path through the A context and asserts no B row comes back: plain LINQ, `Include` of comments, navigation projections, `FromSql` on `db.Posts`, and `ExecuteUpdateAsync`, which must change only A's rows. A cheap unit-level check calls `ToQueryString()` on key queries and asserts the tenant predicate is present. Then I cover what filters never touch: `Database.SqlQuery<T>`, `ExecuteSql` and raw ADO.NET must carry their own tenant condition, so each gets a two-tenant test. `Find` returns an already-tracked entity without querying, so tests use fresh contexts. Finally, every `IgnoreQueryFilters` call is listed and gets a test proving the tenant filter survives, using EF Core 10 keyed ignores.

code

csharp · 8 lines
csharp
[Fact]
public void Post_queries_include_tenant_predicate()
{
    using var db = _fixture.CreateContext(TenantA);
    var sql = db.Posts.Where(p => p.ThreadId == 1).ToQueryString();

    Assert.Contains("\"TenantId\" = @", sql);
}

go deeper

for a junior

Know that a tenant filter is checked by seeding two tenants and asserting one tenant's context never returns the other's rows.

for a middle

Explain which EF paths apply the filter, which raw paths do not, and why tests need a real database and fresh contexts.

for a senior

Build a two-tenant integration suite covering raw SQL, bulk updates and every IgnoreQueryFilters call, plus ToQueryString guards.

for a principal

Treat tenant isolation as a security control with defence in depth, such as database row-level security, and make bypasses auditable.

## What must be proven A tenant filter is a security boundary. The test suite must show two things: every EF query path applies it, and every path that **cannot** apply it has its own tenant condition. Unit tests that mock the `DbContext` prove nothing here, because the filter is applied during query translation; tests must run real queries. ## Test setup 1. Run PostgreSQL in a container for the test session, apply migrations, and seed **two tenants** with overlapping data: threads, posts (some soft-deleted) and comments with identical titles in both. 2. Build contexts exactly as the app does, with the tenant supplied through the same `ITenantContext` abstraction, so the test exercises the real filter wiring. 3. Use a **fresh context** for every assertion. A context that seeded or loaded data has tracked entities, and `Find` returns a tracked instance without querying, which can make a leak look like a pass or a pass look like a leak. ## Paths EF filters, each worth one test | Path | Assertion | |---|---| | `db.Posts.Where(...)` | only tenant A rows | | `db.Threads.Include(t => t.Posts)` | included posts are A's | | projection over a navigation (`t.Posts.Count()`) | counts only A's posts | | `db.Posts.FromSql(...)` | the filter wraps the raw SQL | | `db.Posts.Where(...).ExecuteUpdateAsync(...)` | B's rows unchanged afterwards | | `db.Posts.Find(id)` with B's id, fresh context | returns null | A fast companion check runs without executing anything: call `ToQueryString()` on representative queries and assert the tenant predicate appears. It catches a filter that was removed or overwritten, for example by a second unnamed `HasQueryFilter` call before EF Core 10's named filters. ```csharp [Fact] public async Task Posts_of_other_tenant_are_invisible() { await using var db = _fixture.CreateContext(TenantA); var titles = await db.Posts.Select(p => p.Title).ToListAsync(); Assert.DoesNotContain(titles, t => t.StartsWith("B:")); } ``` ## Paths filters never reach These must carry their own tenant condition, and each needs a two-tenant test: - `Database.SqlQuery<T>` and `SqlQueryRaw<T>`: the result type is not a filtered entity; - `Database.ExecuteSql` and `ExecuteSqlRaw`: plain commands; - Dapper or ADO.NET code using the same connection; - reports built on database views mapped as keyless types without their own filter. ## Explicit bypasses `IgnoreQueryFilters()` without arguments removes the tenant filter too. Treat every call as a finding to justify: 1. Search the codebase for `IgnoreQueryFilters` and keep a list. 2. Where only soft delete should be skipped, use EF Core 10's `IgnoreQueryFilters(["SoftDelete"])` with named filters, and add a test that tenant B's deleted posts stay hidden from tenant A's moderators. 3. Where a cross-tenant query is legitimate, such as a platform-admin report, give it a separate test that documents the intent. ## Keeping the suite honest - Run the two-tenant tests in CI on every change to the model or to query code. - Seed data so that a missing filter **would** return rows; a test against an empty tenant B proves nothing. - Add a new path to the table whenever a new raw-SQL call or bypass appears in review.

  • Why can a test that reuses the seeding context miss a tenant leak?
    The seeding context tracks every entity it inserted. `Find` returns tracked instances without querying, and query results are resolved against tracked entities, so assertions may reflect what the context remembers rather than what the filtered SQL returns. A fresh context per assertion forces every check through a real, filtered query.
  • How do you test a moderator query that uses IgnoreQueryFilters(["SoftDelete"]) in EF Core 10?
    Seed deleted and live posts for both tenants, run the moderator query through tenant A's context, and assert two things: tenant A's deleted posts appear, proving the soft-delete filter was skipped, and no tenant B post appears, proving the tenant filter survived. A misspelt key fails the first assertion; a parameterless bypass fails the second.

  • Mocking DbSet<Post> proves the tenant filter works.
  • Database.SqlQuery<T> results are filtered by the tenant filter.
  • IgnoreQueryFilters() keeps tenant filters and skips only soft delete.
  • A test against an empty second tenant shows isolation.
  • Find always queries the database, so it is filtered.

Assumes EF Core 10, whose IgnoreQueryFilters overload with filter keys lets a bypass keep the tenant filter; on EF Core 8 and 9 any bypass removed it.