Public Access
Add configuration, OIDC auth wiring and discovery endpoints (M1)
Options, JWT bearer validation, the /meta and .well-known endpoints, and a dev compose stack with Keycloak. Verified end to end: compose up, migrate, run, both discovery endpoints return correct payloads, and readiness reports the schema current. Configuration: - Strongly-typed options for Server, Oidc, Relay and Sync, all ValidateOnStart. A self-hosted server that boots half-configured and fails later per-request is far harder to diagnose than one that refuses to start and names the bad setting. - Cross-field validation the annotations cannot express: relay needs a WebSocketUrl when enabled, idle timeout must be under max session duration, item payload cap under batch cap. - Startup warnings for combinations that are individually valid but dangerous together: RequireHttpsMetadata false outside Development, and AllowEmailLinking (which turns any token bearing a victim's email into account takeover, hence default false). Auth: - JwtBearer with ClockSkew cut to 30s from the 5-minute default; five minutes of slack on a credential granting vault ciphertext access is more than any clock needs. - IncludeErrorDetails off, and a FallbackPolicy so an endpoint without an explicit policy still requires a caller rather than silently being public. Discovery, per ADR 0002: - /api/v1/meta reports versions, features and push caps. - /.well-known/dodossh-configuration is the onboarding story: the user types one server URL and the client discovers OIDC authority, client id, scopes and relay endpoint. Two environment problems found by actually running the stack: - PostgreSQL 18 changed its data mount point. Mounting /var/lib/postgresql/data — correct through 17 — makes the image refuse to start; 18+ wants a single mount at /var/lib/postgresql with the cluster in a subdirectory. - Keycloak moved to host port 18080. An unrelated Apache Tomcat on this machine holds 127.0.0.1:8080, and a loopback-specific bind beats Docker's 0.0.0.0 publish for "localhost". It presents as Keycloak 404ing every realm while its own log says the import succeeded, which is a genuinely misleading failure. Also: CA1848 is enforced, not advisory — warnings are errors, so the .editorconfig comment claiming otherwise was wrong. Startup and health logging now uses [LoggerMessage]. And a clean rebuild is back to zero warnings; the incremental build had been hiding 40 in test projects (banned Guid.NewGuid, an obsolete Testcontainers constructor, and two analyzer families that are genuinely noise under a test host). Verified: 0 warnings on a clean rebuild, 122 tests pass, format clean.
This commit is contained in:
1 parent
eaf68c86b0
commit
d3b14e6bc0
19 files changed
+941
-16
No files matched your search
@@ -0,0 +1,85 @@
|
||||
using DodoSSH.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
|
||||
namespace DodoSSH.Api.Setup;
|
||||
|
||||
/// <summary>Database wiring.</summary>
|
||||
internal static class Persistence
|
||||
{
|
||||
private const string ConnectionStringName = "Postgres";
|
||||
|
||||
internal static IServiceCollection AddDodoPersistence(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
var connectionString = configuration.GetConnectionString(ConnectionStringName)
|
||||
?? throw new InvalidOperationException(
|
||||
$"ConnectionStrings:{ConnectionStringName} is not configured.");
|
||||
|
||||
services.AddDbContext<DodoDbContext>(options => options
|
||||
.UseNpgsql(connectionString, npgsql => npgsql
|
||||
.MigrationsHistoryTable("__EFMigrationsHistory", DodoDbContext.SchemaName)
|
||||
// Retry on transient faults only. Note this is safe here because writes go
|
||||
// through explicitly-managed transactions rather than relying on the execution
|
||||
// strategy to replay ambient ones.
|
||||
.EnableRetryOnFailure(3))
|
||||
.UseSnakeCaseNamingConvention());
|
||||
|
||||
services.AddHealthChecks()
|
||||
.AddCheck<DatabaseHealthCheck>(
|
||||
"postgres",
|
||||
tags: [HealthChecks.ReadyTag, HealthChecks.StartupTag]);
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reports the database reachable and the schema current.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Pending migrations make the instance unready rather than crashing it. The API never migrates in
|
||||
/// production — a separate migrator job does — so the correct response to a schema mismatch is to
|
||||
/// stop taking traffic and say so loudly, not to attempt a repair.
|
||||
/// </remarks>
|
||||
internal sealed class DatabaseHealthCheck(DodoDbContext context, ILogger<DatabaseHealthCheck> logger)
|
||||
: IHealthCheck
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<HealthCheckResult> CheckHealthAsync(
|
||||
HealthCheckContext healthCheckContext,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!await context.Database.CanConnectAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
return HealthCheckResult.Unhealthy("Cannot connect to PostgreSQL.");
|
||||
}
|
||||
|
||||
var pending = await context.Database
|
||||
.GetPendingMigrationsAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var pendingList = pending.ToList();
|
||||
if (pendingList.Count > 0)
|
||||
{
|
||||
// Computed once and used for both the log and the health result, so this is not
|
||||
// work done only for logging.
|
||||
var pendingDescription = string.Join(", ", pendingList);
|
||||
|
||||
StartupLog.PendingMigrations(logger, pendingList.Count, pendingDescription);
|
||||
|
||||
return HealthCheckResult.Unhealthy(
|
||||
$"{pendingList.Count} migration(s) pending: {pendingDescription}");
|
||||
}
|
||||
|
||||
return HealthCheckResult.Healthy();
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException)
|
||||
{
|
||||
return HealthCheckResult.Unhealthy("PostgreSQL health check failed.", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user