A few days ago I asked how you stop someone calling IgnoreQueryFilters() in a multi-tenant app. Thanks to everyone who answered; a lot of you said "turn the rule into a check, not a guideline."
Here's the first layer I added: an architecture test that scans the source and fails if it finds a bypass.
public class QueryFilterGuardTests
{
private static readonly string[] Forbidden =
{ "IgnoreQueryFilters", "FromSql", "ExecuteSql" };
[Fact]
public void Source_Code_Never_Bypasses_Tenant_Filters_Or_Uses_Raw_Sql()
{
var src = Path.Combine(RepoLocator.FindRoot(), "src");
var sep = Path.DirectorySeparatorChar;
var offences = Directory
.EnumerateFiles(src, "*.cs", SearchOption.AllDirectories)
.Where(p => !p.Contains($"{sep}obj{sep}")
&& !p.Contains($"{sep}bin{sep}")
&& !p.Contains($"{sep}Migrations{sep}"))
.SelectMany(p => File.ReadLines(p)
.Select((line, i) => (p, line, n: i + 1)))
.Where(x => Forbidden.Any(w => x.line.Contains(w)))
.Select(x => $"{Path.GetRelativePath(src, x.p)}:{x.n} -> {x.line.Trim()}")
.ToList();
Assert.True(offences.Count == 0,
"Forbidden calls found:\n" + string.Join("\n", offences));
}
}
Alongside it, I have isolation tests on real PostgreSQL (not in-memory) that seed two tenants and check that tenant A can't read, load by ID, or write tenant B's data.
What I know it doesn't cover (some of you pointed this out):
- It's a text match, so reflection or a creative workaround gets past it
- It's not a Roslyn analyzer, so you only find out at test time, not in the IDE
- The real backstop is Postgres RLS, which I'm working on next
Two questions:
- Is a Roslyn analyzer worth it over this for a small team, or is the test enough?
- For RLS with connection pooling, do you set
app.tenant_id in a DbConnectionInterceptor or per transaction?