Public Access
Add HTTP integration harness and the sync authorization matrix (M1)
27 end-to-end tests over the real HTTP pipeline, against a PostgreSQL container and a stubbed identity provider. This closes the gap the previous commit flagged. Authentication is genuinely exercised, not bypassed. StubIdentityProvider serves real OIDC discovery and JWKS via WireMock and signs tokens with a real RSA key, so the application's own JwtBearer pipeline validates issuer, audience, signature, lifetime and claims. A TestAuthHandler that short-circuits authentication would hide exactly the claim-mapping mistakes that cause real authorization holes. Proven by rejecting: no token, a foreign signing key, the wrong audience, the wrong issuer, and an expired token. Authorization denials — the tests that matter most: - Another user's vault is 404, not 403, for both pull and push. A distinct "exists but forbidden" answer is an existence oracle for other tenants' vault ids. - A denied push writes nothing: no host row and no change-log entry. A denial that still mutated state would be worse than no check at all. - A team vault is denied until M3 rather than falling through to a permissive default. Behaviour covered: push/pull round trip, cursor advance (and that an empty pull does not rewind the cursor, which would replay history), tampered cursor rejection, stale-version conflict returning server state without overwriting, operation-id replay reported Duplicate and applied once, a mixed batch applying the good and reporting the bad, relay field enforcement both ways, delete clearing the relay address, tombstones carrying no payload, and JIT provisioning happening exactly once. Two configuration problems found by running it: - appsettings.json carried empty-string placeholders for the connection string and OIDC authority. Under minimal hosting those beat anything a test registers via ConfigureAppConfiguration, because Program.cs adds its own sources after that callback runs. Removed them outright — an empty placeholder turns "not configured" into "configured as empty", which defeats failing fast. Tests now use DODOSSH_ environment variables, which Program.cs adds last. - My first fix for minting an expired test token derived notBefore from the expiry, which put nbf fourteen minutes in the future for normal tokens and made every valid token 401. It needs the earlier of now-1min and exp-1min. Verified: 0 warnings on a clean rebuild, 173 tests pass (up from 146), format clean.
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
using System.Net.Http.Headers;
|
||||
using DodoSSH.Infrastructure;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Testcontainers.PostgreSql;
|
||||
using Xunit;
|
||||
|
||||
namespace DodoSSH.Api.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Hosts the API in-process against a real PostgreSQL container and a stubbed identity provider.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// One container and one host per assembly. Tests therefore use distinct users and vaults rather
|
||||
/// than assuming an empty database.
|
||||
/// </remarks>
|
||||
public sealed class ApiFixture : WebApplicationFactory<Program>, IAsyncLifetime
|
||||
{
|
||||
private readonly PostgreSqlContainer container = new PostgreSqlBuilder("postgres:18-alpine")
|
||||
.WithDatabase("dodossh")
|
||||
.WithUsername("postgres")
|
||||
.WithPassword("test")
|
||||
.Build();
|
||||
|
||||
/// <summary>The stubbed identity provider.</summary>
|
||||
public StubIdentityProvider IdentityProvider { get; } = new();
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask InitializeAsync()
|
||||
{
|
||||
await container.StartAsync();
|
||||
|
||||
await using var scope = Services.CreateAsyncScope();
|
||||
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
|
||||
await database.Database.MigrateAsync();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
await base.DisposeAsync();
|
||||
await container.DisposeAsync();
|
||||
IdentityProvider.Dispose();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(builder);
|
||||
|
||||
builder.UseEnvironment("Testing");
|
||||
|
||||
// Environment variables rather than ConfigureAppConfiguration. Under minimal hosting the
|
||||
// application's own configuration sources are added inside Program.cs after this callback
|
||||
// runs, so an appsettings.json value would win over anything registered here. Program.cs
|
||||
// adds AddEnvironmentVariables("DODOSSH_") last, which makes these authoritative.
|
||||
var settings = new Dictionary<string, string?>(StringComparer.Ordinal)
|
||||
{
|
||||
["DODOSSH_ConnectionStrings__Postgres"] = container.GetConnectionString(),
|
||||
["DODOSSH_Server__PublicBaseUrl"] = "http://localhost",
|
||||
["DODOSSH_Oidc__Authority"] = IdentityProvider.Authority,
|
||||
["DODOSSH_Oidc__Audience"] = StubIdentityProvider.Audience,
|
||||
["DODOSSH_Oidc__ClientId"] = "dodossh-desktop",
|
||||
|
||||
// The stub serves plaintext HTTP on a loopback port.
|
||||
["DODOSSH_Oidc__RequireHttpsMetadata"] = "false",
|
||||
|
||||
["DODOSSH_Relay__Enabled"] = "false",
|
||||
|
||||
// Fixed so cursors stay valid for the lifetime of the test host.
|
||||
["DODOSSH_Sync__CursorSigningKey"] = Convert.ToBase64String(new byte[32]),
|
||||
};
|
||||
|
||||
foreach (var (name, value) in settings)
|
||||
{
|
||||
Environment.SetEnvironmentVariable(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Creates a client carrying a valid token for the given subject.</summary>
|
||||
public HttpClient CreateClientFor(string subject, string? email = null)
|
||||
{
|
||||
var client = CreateClient();
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
|
||||
"Bearer",
|
||||
IdentityProvider.MintToken(subject, email));
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
/// <summary>Creates a client carrying the supplied raw token.</summary>
|
||||
public HttpClient CreateClientWithToken(string token)
|
||||
{
|
||||
var client = CreateClient();
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
return client;
|
||||
}
|
||||
|
||||
/// <summary>Opens a database scope for arranging state and asserting on it.</summary>
|
||||
public AsyncServiceScope CreateScope() => Services.CreateAsyncScope();
|
||||
}
|
||||
|
||||
/// <summary>Shares one host and container across every test class in the assembly.</summary>
|
||||
[CollectionDefinition(Name)]
|
||||
public sealed class ApiCollection : ICollectionFixture<ApiFixture>
|
||||
{
|
||||
/// <summary>Collection name.</summary>
|
||||
public const string Name = "api";
|
||||
}
|
||||
Reference in New Issue
Block a user