feat(backend): add PostgreSQL schema, RLS policies, and multi-tenant middleware
- Add EF Core migrations for initial schema (clubs, members, work_items, shifts, shift_signups) - Implement RLS policies with SET LOCAL for tenant isolation - Add Finbuckle multi-tenant middleware with ClaimStrategy + HeaderStrategy fallback - Create TenantValidationMiddleware to enforce JWT claims match X-Tenant-Id header - Add tenant-aware DB interceptors (SaveChangesTenantInterceptor, TenantDbConnectionInterceptor) - Configure AppDbContext with tenant scoping and RLS support - Add test infrastructure: CustomWebApplicationFactory, TestAuthHandler, DatabaseFixture - Write TDD integration tests for multi-tenant isolation and RLS enforcement - Add health check null safety for connection string Tasks: 7 (PostgreSQL schema + migrations + RLS), 8 (Finbuckle multi-tenancy + validation), 12 (test infrastructure)
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Testcontainers.PostgreSql;
|
||||
using WorkClub.Infrastructure.Data;
|
||||
|
||||
namespace WorkClub.Tests.Integration.Infrastructure;
|
||||
|
||||
public class CustomWebApplicationFactory<TProgram> : WebApplicationFactory<TProgram> where TProgram : class
|
||||
{
|
||||
private readonly PostgreSqlContainer _postgresContainer = new PostgreSqlBuilder()
|
||||
.WithImage("postgres:16-alpine")
|
||||
.WithDatabase("workclub_test")
|
||||
.WithUsername("test")
|
||||
.WithPassword("test")
|
||||
.Build();
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
// Start container (async wait)
|
||||
_postgresContainer.StartAsync().GetAwaiter().GetResult();
|
||||
|
||||
builder.ConfigureAppConfiguration((context, config) =>
|
||||
{
|
||||
// Override connection string for tests
|
||||
config.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["ConnectionStrings:DefaultConnection"] = _postgresContainer.GetConnectionString()
|
||||
});
|
||||
});
|
||||
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
// Remove existing DbContext registration
|
||||
var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
|
||||
if (descriptor != null)
|
||||
{
|
||||
services.Remove(descriptor);
|
||||
}
|
||||
|
||||
// Add Testcontainers DbContext
|
||||
services.AddDbContext<AppDbContext>(options =>
|
||||
options.UseNpgsql(_postgresContainer.GetConnectionString()));
|
||||
|
||||
// Replace authentication with TestAuthHandler
|
||||
services.RemoveAll<IAuthenticationSchemeProvider>();
|
||||
services.AddAuthentication(defaultScheme: "Test")
|
||||
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", options => { });
|
||||
|
||||
// Build service provider and ensure database created
|
||||
var sp = services.BuildServiceProvider();
|
||||
using var scope = sp.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
db.Database.EnsureCreated();
|
||||
});
|
||||
|
||||
builder.UseEnvironment("Test");
|
||||
}
|
||||
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
await _postgresContainer.DisposeAsync();
|
||||
await base.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace WorkClub.Tests.Integration.Infrastructure;
|
||||
|
||||
[CollectionDefinition("Database collection")]
|
||||
public class DatabaseCollection : ICollectionFixture<DatabaseFixture>
|
||||
{
|
||||
}
|
||||
|
||||
public class DatabaseFixture : IAsyncLifetime
|
||||
{
|
||||
public Task InitializeAsync()
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task DisposeAsync()
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace WorkClub.Tests.Integration.Infrastructure;
|
||||
|
||||
public abstract class IntegrationTestBase : IClassFixture<CustomWebApplicationFactory<Program>>, IAsyncLifetime
|
||||
{
|
||||
protected readonly HttpClient Client;
|
||||
protected readonly CustomWebApplicationFactory<Program> Factory;
|
||||
|
||||
protected IntegrationTestBase(CustomWebApplicationFactory<Program> factory)
|
||||
{
|
||||
Factory = factory;
|
||||
Client = factory.CreateClient();
|
||||
}
|
||||
|
||||
protected void AuthenticateAs(string email, Dictionary<string, string> clubs)
|
||||
{
|
||||
var clubsJson = JsonSerializer.Serialize(clubs);
|
||||
Client.DefaultRequestHeaders.Remove("X-Test-Clubs");
|
||||
Client.DefaultRequestHeaders.Add("X-Test-Clubs", clubsJson);
|
||||
|
||||
Client.DefaultRequestHeaders.Remove("X-Test-Email");
|
||||
Client.DefaultRequestHeaders.Add("X-Test-Email", email);
|
||||
}
|
||||
|
||||
protected void SetTenant(string tenantId)
|
||||
{
|
||||
Client.DefaultRequestHeaders.Remove("X-Tenant-Id");
|
||||
Client.DefaultRequestHeaders.Add("X-Tenant-Id", tenantId);
|
||||
}
|
||||
|
||||
public virtual Task InitializeAsync() => Task.CompletedTask;
|
||||
|
||||
public virtual Task DisposeAsync() => Task.CompletedTask;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace WorkClub.Tests.Integration.Infrastructure;
|
||||
|
||||
public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
||||
{
|
||||
public TestAuthHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder)
|
||||
: base(options, logger, encoder)
|
||||
{
|
||||
}
|
||||
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var clubsClaim = Context.Request.Headers["X-Test-Clubs"].ToString();
|
||||
var emailClaim = Context.Request.Headers["X-Test-Email"].ToString();
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, "test-user"),
|
||||
new Claim(ClaimTypes.Email, string.IsNullOrEmpty(emailClaim) ? "test@test.com" : emailClaim),
|
||||
};
|
||||
|
||||
if (!string.IsNullOrEmpty(clubsClaim))
|
||||
{
|
||||
claims.Add(new Claim("clubs", clubsClaim));
|
||||
}
|
||||
|
||||
var identity = new ClaimsIdentity(claims, "Test");
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
var ticket = new AuthenticationTicket(principal, "Test");
|
||||
|
||||
return Task.FromResult(AuthenticateResult.Success(ticket));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user