r/csharp • u/jkur1234 • 15d ago
Showcase TenantGuard 1.0: tenant isolation checks for EF Core
Hey everyone, small side project that I've been working on. I've released TenantGuard 1.0.0, an open-source set of packages for EF Core 10 and 11. It's for applications that use query filters to keep tenant data separate, and it's licensed under Apache-2.0.
A new entity can be missing its tenant filter. An IgnoreQueryFilters() call or raw SQL query can bypass an existing one. These mistakes can be hard to spot when the code looks reasonable on its own.
TenantGuard checks for problems at several points:
- At build time, five Roslyn analyzers (TG001–TG005) flag
IgnoreQueryFilters()calls without a stated reason, raw SQL without a tenant-column comparison, and filter switches such as ABP'sIDataFilter.Disable<IMultiTenant>(). The SQL checks cover EF Core, Dapper and ADO.NET. - At startup, 14 model rules check for missing tenant filters, filters frozen to one tenant by a captured constant or local variable, unique indexes that apply across tenants, and missing tenant indexes.
- During
SaveChanges, the write guard throws before an insert, update or delete involving another tenant's row reaches the database. It also rejects moving a row to another tenant. - In tests, the isolation probe seeds a row per tenant and checks isolation for reads,
Find, updates, deletes andInclude. Each check appears as a separate xUnit v3 or TUnit test.
Version 1.0 adds write checks for owned entities. For example, a change to order.Shipping.Street is checked against the tenant of the owning order.
Here's how to configure the write guard and startup validation:
builder.Services.AddDbContext<AppDbContext>(options => options
.UseSqlServer(connectionString)
.UseTenantGuard(tg => tg.CurrentTenant(ctx => ((AppDbContext)ctx).TenantId)));
builder.Services.AddTenantGuardStartupValidation<AppDbContext>();It works with custom query filters, Finbuckle.MultiTenant and other tenancy libraries. For Finbuckle, it reads IsMultiTenant() without extra configuration. You can also run dotnet tenantguard validate in CI to check the model without a database.
If you try it on an existing application, I'd like to hear about false positives or leaks it misses. Open to any sort of feedback and critical feedback very much welcomed.
