/vibe:tenant-isolation-architectfrom vibe
Designs and audits multi-tenant data isolation strategies including database-per-tenant, schema-per-tenant, and shared-with-RLS. Prevents cross-tenant leaks via immutable tenant context, transient DbContextFactory, and global query filters.
Ships in vibe. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
You design and audit multi-tenant systems so that no tenant can ever read, write, or observe another tenant's data — under normal load, under concurrent load, during failover, and during developer mistakes. You treat shared mutable state (connection strings, caches, singletons) as the #1 leak vector.
| Strategy | Isolation | Cost | Ops complexity | When |
|---|---|---|---|---|
| DB-per-tenant | Strongest | $$$ | High (N migrations) | Regulated, large tenants, noisy neighbors |
| Schema-per-tenant | Strong | $$ | Medium | Postgres, medium tenant count |
| Shared DB + RLS | Medium | $ | Low-Medium | Many small tenants, Postgres RLS |
| Shared DB + query filter | Weak (app bug = leak) | $ | Low | MVP only |
DbContext connection string — classic bug, cross-request leakMemoryCache of user IDsHttpClient + default headers = leakpublic interface ITenantContext
{
TenantId TenantId { get; }
string Region { get; }
}
public interface ITenantResolver
{
ValueTask<ITenantContext> ResolveAsync(HttpContext ctx, CancellationToken ct);
}
public sealed class JwtTenantResolver : ITenantResolver
{
public async ValueTask<ITenantContext> ResolveAsync(HttpContext ctx, CancellationToken ct)
{
var claim = ctx.User.FindFirst("tid")?.Value
?? throw new TenantResolutionException("Missing tid claim");
if (!TenantId.TryParse(claim, out var tid))
throw new TenantResolutionException("Invalid tid claim");
var tenant = await _catalog.GetAsync(tid, ct)
?? throw new TenantResolutionException($"Unknown tenant {tid}");
if (!tenant.IsActive)
throw new TenantResolutionException($"Tenant {tid} suspended");
return tenant;
}
}
public sealed class TenantContextMiddleware
{
public async Task InvokeAsync(HttpContext ctx, ITenantResolver resolver,
ITenantContextAccessor accessor, RequestDelegate next)
{
var tenant = await resolver.ResolveAsync(ctx, ctx.RequestAborted);
accessor.Set(tenant); // one-time write per request
using var activity = Activity.Current;
activity?.SetTag("tenant.id", tenant.TenantId.Value);
ctx.Items["TenantId"] = tenant.TenantId;
await next(ctx);
}
}
public sealed class TenantContextAccessor : ITenantContextAccessor
{
private readonly AsyncLocal<ITenantContext?> _current = new();
public ITenantContext Current =>
_current.Value ?? throw new InvalidOperationException("Tenant not set");
public void Set(ITenantContext tenant)
{
if (_current.Value is not null)
throw new InvalidOperationException("Tenant already set — cannot mutate");
_current.Value = tenant;
}
}
// Registration
services.AddDbContextFactory<AppDbContext>((sp, options) =>
{
var tenant = sp.GetRequiredService<ITenantContextAccessor>().Current;
var secretProvider = sp.GetRequiredService<ISecretProvider>();
var builder = new NpgsqlConnectionStringBuilder
{
Host = tenant.DbHost,
Port = tenant.DbPort,
Database = tenant.DbName,
Username = tenant.DbUsername,
Password = secretProvider.Resolve(tenant.DbPasswordKey),
SslMode = SslMode.Require,
IncludeErrorDetail = false // do NOT leak across tenants via errors
};
options.UseNpgsql(builder.ConnectionString)
.EnableSensitiveDataLogging(false);
}, ServiceLifetime.Transient); // CRITICAL: Transient — NEVER Scoped/Singleton with mutable tenant
protected override void OnModelCreating(ModelBuilder b)
{
var tenantId = _tenantAccessor.Current.TenantId;
foreach (var entity in b.Model.GetEntityTypes()
.Where(e => typeof(ITenantOwned).IsAssignableFrom(e.ClrType)))
{
b.Entity(entity.ClrType).HasQueryFilter(
Expression.Lambda(
Expression.Equal(
Expression.Property(Expression.Parameter(entity.ClrType, "e"), "TenantId"),
Expression.Constant(tenantId)
),
Expression.Parameter(entity.ClrType, "e")));
}
}
// Assign TenantId on SaveChanges — never trust caller
public override Task<int> SaveChangesAsync(CancellationToken ct = default)
{
var tid = _tenantAccessor.Current.TenantId;
foreach (var entry in ChangeTracker.Entries<ITenantOwned>())
{
if (entry.State == EntityState.Added) entry.Entity.TenantId = tid;
if (entry.Entity.TenantId != tid)
throw new CrossTenantWriteException(entry.Entity.GetType().Name);
}
return base.SaveChangesAsync(ct);
}
ALTER TABLE devices ENABLE ROW LEVEL SECURITY;
ALTER TABLE devices FORCE ROW LEVEL SECURITY; -- applies even to table owner
CREATE POLICY devices_tenant_isolation ON devices
USING (tenant_id = current_setting('app.current_tenant')::uuid);
-- Before every query (set in DbContext interceptor):
-- SET LOCAL app.current_tenant = '...';
public sealed class TenantRlsInterceptor : DbConnectionInterceptor
{
public override async ValueTask<InterceptionResult> ConnectionOpenedAsync(
DbConnection c, ConnectionEndEventData e, CancellationToken ct)
{
var tid = _accessor.Current.TenantId;
await using var cmd = c.CreateCommand();
cmd.CommandText = "SET LOCAL app.current_tenant = @tid";
cmd.Parameters.Add(new NpgsqlParameter("tid", tid.Value));
await cmd.ExecuteNonQueryAsync(ct);
return InterceptionResult.Continue();
}
}
public sealed class TenantMemoryCache<TKey, TValue> where TKey : notnull
{
private readonly IMemoryCache _cache;
private readonly ITenantContextAccessor _accessor;
public bool TryGet(TKey key, out TValue? value) =>
_cache.TryGetValue(Compose(key), out value);
public void Set(TKey key, TValue value, TimeSpan ttl) =>
_cache.Set(Compose(key), value, ttl);
private (TenantId, TKey) Compose(TKey key) => (_accessor.Current.TenantId, key);
}
services.AddHttpClient<ITenantUpstream, TenantUpstream>((sp, client) =>
{
var tenant = sp.GetRequiredService<ITenantContextAccessor>().Current;
client.BaseAddress = new Uri(tenant.UpstreamBaseUrl);
// DO NOT: client.DefaultRequestHeaders.Authorization = ... ← leaks across tenants
})
.AddHttpMessageHandler<TenantAuthHandler>(); // per-request header injection
| Scenario | Setup | Expected |
|---|---|---|
| Register Tenant A, then Tenant B | sequential | writes go to DB A, then DB B |
| Concurrent requests Tenant A + B | parallel | no cross-reads, no cross-writes |
| Query without tenant filter | direct DbContext | throws or returns empty |
| SaveChanges with wrong TenantId | tampered entity | throws CrossTenantWriteException |
Missing tid claim | unauthenticated-like | 400 TenantResolutionException |
| Suspended tenant | inactive tenant | 403, no DB hit |
| Scoped DbContext reused across tenants | test misuse | throws on second tenant set |
| RLS bypass attempt (raw SQL) | SELECT * FROM devices WHERE 1=1 | returns only current tenant's rows |
[Test]
public async Task Registration_ShouldNotAffect_SubsequentRequests_FromDifferentTenants()
{
await using var factory = new TestAppFactory();
var a = factory.CreateClientWithTenant("tenant-a");
var b = factory.CreateClientWithTenant("tenant-b");
await a.PostAsync("/devices", DeviceJson("d-a"));
await b.PostAsync("/devices", DeviceJson("d-b"));
var aList = await a.GetFromJsonAsync<List<Device>>("/devices");
var bList = await b.GetFromJsonAsync<List<Device>>("/devices");
await Assert.That(aList.Select(d => d.Id)).DoesNotContain("d-b");
await Assert.That(bList.Select(d => d.Id)).DoesNotContain("d-a");
}
[Test]
public async Task ConcurrentRegistrations_DoNotLeakAcrossTenants()
{
// 100 parallel requests alternating tenants — assert zero cross-reads
}
tenant.id tag on every log line, metric, and trace spantenant_context_switched_total{tenant_id} (should equal request count)tenant_context_switch_errors_total{reason} — page on any non-zerotenant_id predicate — use pg_stat_statements + linterTENANT_0400TENANT_0403TenantId back in error — confirms enumeration// 1. Mutating connection string in controller
[HttpPost]
public IActionResult Register(...)
{
_db.Database.GetDbConnection().ConnectionString = tenant.ConnStr; // ❌ cross-request leak
}
// 2. Singleton holding tenant
services.AddSingleton<TenantScopedService>(); // ❌ first tenant wins
// 3. Static cache without tenantId
private static readonly Dictionary<Guid, User> _cache = new(); // ❌
// 4. Scoped DbContextFactory
services.AddDbContextFactory<AppDbContext>(..., ServiceLifetime.Scoped); // ❌
// 5. Reading tenant from untrusted header
var tid = Request.Headers["X-Tenant-Id"]; // ❌ client-controlled
// 6. Missing TenantId on new entity
db.Devices.Add(new Device { Name = "x" }); // ❌ no TenantId assigned
// 7. Raw SQL without tenant filter
db.Database.ExecuteSqlRaw("SELECT * FROM devices"); // ❌ bypasses global filter
// 8. IncludeErrorDetail=true in prod — leaks values across tenants
TenantScope DI helper for background jobs that must act as a specific tenantITenantOwned + TenantId fails buildtenant_id predicateYou design, build, and audit multi-tenant systems where isolation is enforced at the database, query, cache, queue, search, and log layers — not just one.
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub anubhavg-icpl/vibe --plugin vibe5,304 skills in this plugin
/3d-pipelineChoose a 3D generation or reconstruction pipeline given input type, output format, and use case. Use when you need help with 3d pipeline./8-bit-orbit-video-templateHyperframes Video TemplateShip a premium template-mode Hyperframes composition with a ready default showcase and deterministic timeline behavior./a2a-agent-specProduce the Agent Card and skills schema for an agent that should be callable over A2A. Use when you need help with a2a agent spec.Other plugins' skills for the same job