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:
@@ -0,0 +1,67 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace DodoSSH.Api.Setup;
|
||||
|
||||
/// <summary>Authentication and authorization wiring.</summary>
|
||||
/// <remarks>
|
||||
/// The API validates bearer access tokens only. It never runs a browser flow itself: the desktop
|
||||
/// app is a public client using Authorization Code with PKCE and a loopback redirect, and it talks
|
||||
/// to the identity provider directly.
|
||||
/// </remarks>
|
||||
internal static class Auth
|
||||
{
|
||||
/// <summary>Policy requiring an authenticated caller.</summary>
|
||||
internal const string AuthenticatedPolicy = "Authenticated";
|
||||
|
||||
/// <summary>Policy requiring a caller who has completed key enrollment.</summary>
|
||||
internal const string EnrolledPolicy = "Enrolled";
|
||||
|
||||
internal static IServiceCollection AddDodoAuthentication(this IServiceCollection services)
|
||||
{
|
||||
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
// Bound late so options validation has already run and the values are known good.
|
||||
var oidc = services.BuildServiceProvider().GetRequiredService<IOptions<OidcOptions>>().Value;
|
||||
|
||||
options.Authority = oidc.Authority;
|
||||
options.Audience = oidc.Audience;
|
||||
options.RequireHttpsMetadata = oidc.RequireHttpsMetadata;
|
||||
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
RequireSignedTokens = true,
|
||||
RequireExpirationTime = true,
|
||||
|
||||
// 30 seconds, not the 5-minute default. A five-minute grace period on a
|
||||
// credential that grants vault ciphertext access is far more slack than any
|
||||
// sane clock needs.
|
||||
ClockSkew = TimeSpan.FromSeconds(30),
|
||||
};
|
||||
|
||||
// Tokens are the one thing that must never reach a log or a trace.
|
||||
options.IncludeErrorDetails = false;
|
||||
});
|
||||
|
||||
services.AddAuthorization(options =>
|
||||
{
|
||||
options.AddPolicy(AuthenticatedPolicy, policy => policy.RequireAuthenticatedUser());
|
||||
|
||||
// Enrollment state lives in the database, so the real handler arrives with the
|
||||
// enrollment feature. Registered now so endpoint groups can reference the policy name
|
||||
// and the endpoint-inventory test has something to assert against.
|
||||
options.AddPolicy(EnrolledPolicy, policy => policy.RequireAuthenticatedUser());
|
||||
|
||||
// Deny by default: an endpoint without an explicit policy still requires a caller.
|
||||
options.FallbackPolicy = options.GetPolicy(AuthenticatedPolicy);
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace DodoSSH.Api.Setup;
|
||||
|
||||
/// <summary>Binds and validates strongly-typed options.</summary>
|
||||
/// <remarks>
|
||||
/// Every section uses <c>ValidateOnStart</c>. 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 says
|
||||
/// which setting is wrong.
|
||||
/// </remarks>
|
||||
internal static class Configuration
|
||||
{
|
||||
internal static IServiceCollection AddDodoOptions(this IServiceCollection services)
|
||||
{
|
||||
services.AddOptions<ServerOptions>()
|
||||
.BindConfiguration(ServerOptions.SectionName)
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddOptions<OidcOptions>()
|
||||
.BindConfiguration(OidcOptions.SectionName)
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddOptions<SyncOptions>()
|
||||
.BindConfiguration(SyncOptions.SectionName)
|
||||
.ValidateDataAnnotations()
|
||||
.Validate(
|
||||
options => options.MaxItemPayloadBytes <= options.MaxPayloadBytes,
|
||||
"Sync:MaxItemPayloadBytes must not exceed Sync:MaxPayloadBytes.")
|
||||
.Validate(
|
||||
options => options.DefaultPullLimit <= options.MaxPullLimit,
|
||||
"Sync:DefaultPullLimit must not exceed Sync:MaxPullLimit.")
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddOptions<RelayOptions>()
|
||||
.BindConfiguration(RelayOptions.SectionName)
|
||||
.ValidateDataAnnotations()
|
||||
.Validate(
|
||||
options => !options.Enabled || !string.IsNullOrWhiteSpace(options.WebSocketUrl),
|
||||
"Relay:WebSocketUrl is required when Relay:Enabled is true.")
|
||||
.Validate(
|
||||
options => options.IdleTimeout < options.MaxSessionDuration,
|
||||
"Relay:IdleTimeout must be shorter than Relay:MaxSessionDuration.")
|
||||
.ValidateOnStart();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Warns about configuration that is individually valid but dangerous in combination.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// These cannot be hard failures — each is legitimate in some deployment — but silently
|
||||
/// accepting them produces subtly broken security properties that nobody notices.
|
||||
/// </remarks>
|
||||
internal static WebApplication WarnOnRiskyConfiguration(this WebApplication app)
|
||||
{
|
||||
var logger = app.Services.GetRequiredService<ILoggerFactory>().CreateLogger("DodoSSH.Startup");
|
||||
var oidc = app.Services.GetRequiredService<IOptions<OidcOptions>>().Value;
|
||||
|
||||
if (!oidc.RequireHttpsMetadata && !app.Environment.IsDevelopment())
|
||||
{
|
||||
StartupLog.InsecureMetadataOutsideDevelopment(logger);
|
||||
}
|
||||
|
||||
if (oidc.AllowEmailLinking)
|
||||
{
|
||||
StartupLog.EmailLinkingEnabled(logger);
|
||||
}
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace DodoSSH.Api.Setup;
|
||||
|
||||
/// <summary>Identity provider settings.</summary>
|
||||
/// <remarks>
|
||||
/// Provider-agnostic by design. Claim names differ between providers — Keycloak nests roles at
|
||||
/// <c>realm_access.roles</c>, Entra uses <c>roles</c> and <c>groups</c>, Auth0 namespaces them,
|
||||
/// Authentik uses <c>groups</c> — so the mapping is configuration rather than code.
|
||||
/// </remarks>
|
||||
public sealed class OidcOptions
|
||||
{
|
||||
/// <summary>Configuration section name.</summary>
|
||||
public const string SectionName = "Oidc";
|
||||
|
||||
/// <summary>Issuer URL. Discovery and JWKS are fetched from here.</summary>
|
||||
[Required]
|
||||
[Url]
|
||||
public string Authority { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Expected audience of access tokens.</summary>
|
||||
[Required]
|
||||
public string Audience { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Public client identifier the desktop app uses.</summary>
|
||||
[Required]
|
||||
public string ClientId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Scopes the client should request.</summary>
|
||||
public IList<string> Scopes { get; } = ["openid", "profile", "email", "offline_access"];
|
||||
|
||||
/// <summary>
|
||||
/// Registered loopback redirect pattern. RFC 8252: a native client uses a loopback redirect on
|
||||
/// an ephemeral port with the system browser, never a custom scheme and never an embedded
|
||||
/// browser, so the user can see the real address bar.
|
||||
/// </summary>
|
||||
public string LoopbackRedirectPattern { get; set; } = "http://127.0.0.1:*/callback";
|
||||
|
||||
/// <summary>Whether HTTPS metadata is required. Only ever false for local development.</summary>
|
||||
public bool RequireHttpsMetadata { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Whether a new identity-provider subject may be linked to an existing account by matching
|
||||
/// email.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Defaults to false, and must stay that way. If an attacker can obtain a token from any
|
||||
/// configured provider carrying a victim's email address, email linking hands them the
|
||||
/// victim's account.
|
||||
/// </remarks>
|
||||
public bool AllowEmailLinking { get; set; }
|
||||
|
||||
/// <summary>Claim type holding the user's email.</summary>
|
||||
public string EmailClaim { get; set; } = "email";
|
||||
|
||||
/// <summary>Claim type holding the user's display name.</summary>
|
||||
public string NameClaim { get; set; } = "name";
|
||||
}
|
||||
|
||||
/// <summary>Relay settings. See ADR 0004.</summary>
|
||||
public sealed class RelayOptions
|
||||
{
|
||||
/// <summary>Configuration section name.</summary>
|
||||
public const string SectionName = "Relay";
|
||||
|
||||
/// <summary>Whether this deployment offers a relay at all.</summary>
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
/// <summary>Public WebSocket URL clients should dial. Required when enabled.</summary>
|
||||
public string? WebSocketUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether RFC1918 and other private ranges may be dialled.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Defaults to true, unlike a typical SSRF allow-list, because reaching private
|
||||
/// infrastructure is the entire purpose of a self-hosted SSH tool. The control that matters is
|
||||
/// the ACL: only hosts in a vault the caller holds Connect on can be dialled at all. Loopback,
|
||||
/// link-local and cloud metadata ranges are denied unconditionally and are not configurable.
|
||||
/// </remarks>
|
||||
public bool AllowPrivateNetworks { get; set; } = true;
|
||||
|
||||
/// <summary>Maximum concurrent sessions per user.</summary>
|
||||
[Range(1, 1000)]
|
||||
public int MaxConcurrentSessionsPerUser { get; set; } = 10;
|
||||
|
||||
/// <summary>Maximum concurrent sessions per node.</summary>
|
||||
[Range(1, 100_000)]
|
||||
public int MaxConcurrentSessionsTotal { get; set; } = 200;
|
||||
|
||||
/// <summary>Maximum session lifetime.</summary>
|
||||
public TimeSpan MaxSessionDuration { get; set; } = TimeSpan.FromHours(12);
|
||||
|
||||
/// <summary>Idle timeout.</summary>
|
||||
public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromMinutes(10);
|
||||
|
||||
/// <summary>Timeout for the outbound TCP connect.</summary>
|
||||
public TimeSpan ConnectTimeout { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>Ticket lifetime. Deliberately tiny: single-use and single-host.</summary>
|
||||
public TimeSpan TicketLifetime { get; set; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>How long to keep draining live sessions during shutdown.</summary>
|
||||
public TimeSpan DrainTimeout { get; set; } = TimeSpan.FromSeconds(30);
|
||||
}
|
||||
|
||||
/// <summary>Sync protocol limits.</summary>
|
||||
public sealed class SyncOptions
|
||||
{
|
||||
/// <summary>Configuration section name.</summary>
|
||||
public const string SectionName = "Sync";
|
||||
|
||||
/// <summary>Maximum operations in one push. Enforced before the transaction opens.</summary>
|
||||
[Range(1, 10_000)]
|
||||
public int MaxOperationsPerPush { get; set; } = 500;
|
||||
|
||||
/// <summary>Maximum total ciphertext in one push.</summary>
|
||||
[Range(1024, 1024L * 1024 * 1024)]
|
||||
public long MaxPayloadBytes { get; set; } = 8L * 1024 * 1024;
|
||||
|
||||
/// <summary>Maximum ciphertext for a single item.</summary>
|
||||
[Range(1024, 1024L * 1024 * 1024)]
|
||||
public long MaxItemPayloadBytes { get; set; } = 256L * 1024;
|
||||
|
||||
/// <summary>Default page size for a pull.</summary>
|
||||
[Range(1, 10_000)]
|
||||
public int DefaultPullLimit { get; set; } = 200;
|
||||
|
||||
/// <summary>Maximum page size for a pull.</summary>
|
||||
[Range(1, 10_000)]
|
||||
public int MaxPullLimit { get; set; } = 1000;
|
||||
|
||||
/// <summary>How long tombstones are retained before collection.</summary>
|
||||
[Range(1, 3650)]
|
||||
public int TombstoneRetentionDays { get; set; } = 90;
|
||||
|
||||
/// <summary>
|
||||
/// Key used to sign sync cursors, base64.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Cursors are integrity-tagged so a tampered one is rejected rather than silently
|
||||
/// mis-serving. Generated per deployment; losing it only invalidates in-flight cursors, since
|
||||
/// clients simply resync from the beginning.
|
||||
/// </remarks>
|
||||
public string? CursorSigningKey { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Server identity and client compatibility.</summary>
|
||||
public sealed class ServerOptions
|
||||
{
|
||||
/// <summary>Configuration section name.</summary>
|
||||
public const string SectionName = "Server";
|
||||
|
||||
/// <summary>Public base URL clients should use for API calls.</summary>
|
||||
[Required]
|
||||
[Url]
|
||||
public string PublicBaseUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Oldest client version this server will serve.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Self-hosted means version skew is normal, not exceptional. A client below this must be
|
||||
/// shown a clear remediation screen rather than failing obscurely mid-sync.
|
||||
/// </remarks>
|
||||
public string? MinClientVersion { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using DodoSSH.Api.Features.Meta;
|
||||
|
||||
namespace DodoSSH.Api.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// The single, explicit list of every endpoint module.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Deliberately not reflection-based discovery. Explicit registration gives predictable startup,
|
||||
/// survives trimming, and makes every route greppable — and a route that silently disappears
|
||||
/// because an assembly was not scanned is a genuinely nasty failure. The cost is one line per
|
||||
/// module.
|
||||
/// </remarks>
|
||||
internal static class EndpointRegistration
|
||||
{
|
||||
internal static WebApplication MapDodoEndpoints(this WebApplication app)
|
||||
{
|
||||
app.MapMetaEndpoints();
|
||||
|
||||
// Registered as each feature lands:
|
||||
// Identity — /me, enrollment, key rotation, devices
|
||||
// Directory — public-key lookup
|
||||
// Vaults — grants, rekey, ACL
|
||||
// Sync — pull and push
|
||||
// Relay — tickets and the WebSocket
|
||||
// Teams, Audit, Admin
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
namespace DodoSSH.Api.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Source-generated log messages for startup and health.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <c>[LoggerMessage]</c> rather than <c>ILogger</c> extension calls: allocation-free, and the
|
||||
/// event ids and message templates become a stable, greppable inventory instead of string literals
|
||||
/// scattered through wiring code.
|
||||
/// </remarks>
|
||||
internal static partial class StartupLog
|
||||
{
|
||||
[LoggerMessage(
|
||||
EventId = 1001,
|
||||
Level = LogLevel.Warning,
|
||||
Message = "Oidc:RequireHttpsMetadata is false outside Development. Token signing keys are "
|
||||
+ "being fetched over plaintext HTTP, so anyone on the network path can serve their "
|
||||
+ "own keys and mint tokens this server will accept.")]
|
||||
internal static partial void InsecureMetadataOutsideDevelopment(ILogger logger);
|
||||
|
||||
[LoggerMessage(
|
||||
EventId = 1002,
|
||||
Level = LogLevel.Warning,
|
||||
Message = "Oidc:AllowEmailLinking is enabled. A token from any configured provider "
|
||||
+ "carrying a victim's email address will be linked to that victim's existing account. "
|
||||
+ "Only enable this when every configured provider verifies email ownership.")]
|
||||
internal static partial void EmailLinkingEnabled(ILogger logger);
|
||||
|
||||
[LoggerMessage(
|
||||
EventId = 1010,
|
||||
Level = LogLevel.Critical,
|
||||
Message = "Database schema is out of date: {PendingCount} migration(s) pending "
|
||||
+ "({PendingMigrations}). Readiness will fail until the migrator has run.")]
|
||||
internal static partial void PendingMigrations(
|
||||
ILogger logger,
|
||||
int pendingCount,
|
||||
string pendingMigrations);
|
||||
}
|
||||
Reference in New Issue
Block a user