fix(server): trust forwarded headers only from known proxies
In TLS mode proxy the server accepted X-Forwarded-For/Proto/Host from any peer, so a client reaching the HTTP port directly could pick a new address per sign-in (defeating the 5/min/IP limit), forge audit addresses and claim HTTPS; the admin never warned (SRS-03, SRV-3). Forwarded headers now count only from TITANO_TRUSTED_PROXIES (addresses or CIDR networks; default loopback, 10/8, 172.16/12, 192.168/16, fc00::/7), and the Dashboard and Settings show a "Not via proxy" chip with a tooltip when a page did not come through a trusted proxy over HTTPS (ProxyWarning in DashboardDto and ServerSettingsDto). TITANO_PUBLIC_HTTP_PORT and TITANO_PUBLIC_HTTPS_PORT name the ports clients reach when a container's ports are published as other host ports: the admin's HTTP-to-HTTPS redirect and the LAN beacon use them instead of the bound container ports (DOCKER-4, DOCKER-5). --help lists TITANO_LOG_LEVEL, the new variables and the container's PUID, PGID and TZ (DOCKER-7); a test keeps it in step with the variables the server reads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
17 files changed
+340
-22
No files matched your search
@@ -288,6 +288,8 @@
|
||||
<data name="Admin.Settings.Network" xml:space="preserve"><value>Network and TLS</value></data>
|
||||
<data name="Admin.Settings.PemMissing" xml:space="preserve"><value>The PEM file was not found; enter its full path on the server.</value><comment>long</comment></data>
|
||||
<data name="Admin.Settings.PemOnly.Tip" xml:space="preserve"><value>Used only in Own certificate mode</value></data>
|
||||
<data name="Admin.Settings.ProxyBypassed" xml:space="preserve"><value>Not via proxy</value></data>
|
||||
<data name="Admin.Settings.ProxyBypassed.Tip" xml:space="preserve"><value>TLS mode is Reverse proxy, but this page did not come through a trusted proxy over HTTPS. Open it through your proxy, or add the proxy's address to TITANO_TRUSTED_PROXIES.</value></data>
|
||||
<data name="Admin.Settings.Restart" xml:space="preserve"><value>Restart required</value></data>
|
||||
<data name="Admin.Settings.Restart.Tip" xml:space="preserve"><value>Saved ports, TLS, workers, chunk size or job history apply after a restart</value></data>
|
||||
<data name="Admin.Settings.Server" xml:space="preserve"><value>Server</value></data>
|
||||
|
||||
@@ -288,6 +288,8 @@
|
||||
<data name="Admin.Settings.Network" xml:space="preserve"><value>Rete e TLS</value></data>
|
||||
<data name="Admin.Settings.PemMissing" xml:space="preserve"><value>File PEM non trovato; inserisci il percorso completo sul server.</value></data>
|
||||
<data name="Admin.Settings.PemOnly.Tip" xml:space="preserve"><value>Usato solo in modalità Certificato proprio</value></data>
|
||||
<data name="Admin.Settings.ProxyBypassed" xml:space="preserve"><value>Senza proxy</value></data>
|
||||
<data name="Admin.Settings.ProxyBypassed.Tip" xml:space="preserve"><value>La modalità TLS è Reverse proxy, ma questa pagina non è arrivata da un proxy attendibile in HTTPS. Aprila tramite il proxy o aggiungi l'indirizzo del proxy a TITANO_TRUSTED_PROXIES.</value></data>
|
||||
<data name="Admin.Settings.Restart" xml:space="preserve"><value>Riavvio richiesto</value></data>
|
||||
<data name="Admin.Settings.Restart.Tip" xml:space="preserve"><value>Porte, TLS, worker, dimensione blocchi o cronologia job salvati valgono dopo un riavvio</value></data>
|
||||
<data name="Admin.Settings.Server" xml:space="preserve"><value>Server</value></data>
|
||||
|
||||
@@ -3,7 +3,8 @@ namespace Titano.Protocol;
|
||||
/// <summary>
|
||||
/// <c>GET/PUT /api/v1/server/settings</c> (admin): the editable part of the server configuration. Settings named in
|
||||
/// <see cref="Locked"/> come from environment variables and cannot be changed here; <see cref="RestartRequired"/> says
|
||||
/// that saved values (ports, TLS, workers, chunk size) wait for a restart.
|
||||
/// that saved values (ports, TLS, workers, chunk size) wait for a restart. <see cref="ProxyWarning"/> is set in
|
||||
/// responses when TLS mode is proxy and the request did not come through a trusted proxy over HTTPS (ignored when saving).
|
||||
/// </summary>
|
||||
public sealed record ServerSettingsDto(
|
||||
string ServerName,
|
||||
@@ -21,7 +22,8 @@ public sealed record ServerSettingsDto(
|
||||
int TokenLifetimeDays,
|
||||
int UploadRetentionHours,
|
||||
IReadOnlyList<string> Locked,
|
||||
bool RestartRequired);
|
||||
bool RestartRequired,
|
||||
bool ProxyWarning);
|
||||
|
||||
/// <summary>A server log file (<c>GET /api/v1/logs/files</c>).</summary>
|
||||
public sealed record LogFileDto(string Name, long Size, DateTimeOffset Modified);
|
||||
@@ -35,7 +37,10 @@ public sealed record JobCountsDto(int Queued, int Running, int Paused, int DoneT
|
||||
/// <summary>Frames committed by uploads on one UTC day.</summary>
|
||||
public sealed record UploadDayDto(DateOnly Day, long Frames, long Bytes);
|
||||
|
||||
/// <summary><c>GET /api/v1/server/dashboard</c> (admin): everything the dashboard page shows in one call (BRIEF §14.8).</summary>
|
||||
/// <summary>
|
||||
/// <c>GET /api/v1/server/dashboard</c> (admin): everything the dashboard page shows in one call (BRIEF §14.8).
|
||||
/// <see cref="ProxyWarning"/>: TLS mode is proxy and this request did not come through a trusted proxy over HTTPS.
|
||||
/// </summary>
|
||||
public sealed record DashboardDto(
|
||||
string ServerName,
|
||||
string Version,
|
||||
@@ -50,4 +55,5 @@ public sealed record DashboardDto(
|
||||
IReadOnlyList<RenderNodeDto> Nodes,
|
||||
IReadOnlyList<UploadDayDto> Uploads,
|
||||
IReadOnlyList<AuditEntryDto> Activity,
|
||||
IReadOnlyList<JobDto> ActiveJobs);
|
||||
IReadOnlyList<JobDto> ActiveJobs,
|
||||
bool ProxyWarning);
|
||||
@@ -1,12 +1,12 @@
|
||||
// Dashboard (mockup Admin.html, BRIEF §14.8): storage, archive, jobs, render nodes, charts, activity, active jobs.
|
||||
import { t, plural, applyStrings, culture } from "../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, columns, toast, errorText, emptyState, redraw, fitColumns } from "../ui.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, columns, toast, errorText, emptyState, redraw, fitColumns, PROXY_WARNING } from "../ui.js";
|
||||
import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders } from "../jobs.js";
|
||||
import { activityText } from "../audit.js";
|
||||
|
||||
const SCAN_BUTTON = `<button class="btn small" data-scan data-i18n="Admin.Archive.Scan" data-i18n-title="Admin.Archive.Scan.Tip"></button>`;
|
||||
|
||||
export async function render(root, { api, setMeta, onEvent }) {
|
||||
export async function render(root, { api, setMeta, actions, onEvent }) {
|
||||
let timer = null;
|
||||
const refresh = () => {
|
||||
clearTimeout(timer);
|
||||
@@ -28,6 +28,8 @@ export async function render(root, { api, setMeta, onEvent }) {
|
||||
const tls = `Admin.Settings.Tls.${d.tlsMode.charAt(0).toUpperCase()}${d.tlsMode.slice(1)}`;
|
||||
setMeta(t("Admin.Dashboard.Meta", formatDuration(d.uptimeSeconds), d.database, t(tls),
|
||||
t(d.discovery ? "Admin.Dashboard.DiscoveryOn" : "Admin.Dashboard.DiscoveryOff")));
|
||||
actions.innerHTML = d.proxyWarning ? PROXY_WARNING : "";
|
||||
applyStrings(actions);
|
||||
const a = d.archive;
|
||||
const used = a.capacityBytes > 0 ? (a.capacityBytes - a.freeBytes) / a.capacityBytes : 0;
|
||||
const online = d.nodes.filter((n) => n.state !== "offline");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, limits, language, retention. Values fixed by environment
|
||||
// variables are read-only here; ports, TLS, workers, chunk size and job history apply at the next restart.
|
||||
import { t, applyStrings, languages } from "../i18n.js";
|
||||
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, markInvalid, clearInvalid, invalidText, escapeReverts } from "../ui.js";
|
||||
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, markInvalid, clearInvalid, invalidText, escapeReverts, PROXY_WARNING } from "../ui.js";
|
||||
|
||||
/** Setting → environment variable that can fix it (BRIEF §14.9). */
|
||||
const VARIABLES = {
|
||||
@@ -46,7 +46,8 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
${field("discovery", `<span class="inline"><input type="checkbox" name="discovery" ${settings.discovery ? "checked" : ""} ${lock("discovery")}></span>`)}
|
||||
</section>
|
||||
<section class="panel" aria-labelledby="network-title">
|
||||
<h2 id="network-title" data-i18n="Admin.Settings.Network"></h2>
|
||||
<div class="panel-head"><h2 id="network-title" data-i18n="Admin.Settings.Network"></h2>
|
||||
${settings.proxyWarning ? PROXY_WARNING : ""}</div>
|
||||
${number("httpPort", settings.httpPort, 'min="1" max="65535"')}
|
||||
${number("httpsPort", settings.httpsPort, 'min="1" max="65535"')}
|
||||
${field("tlsMode", `<select class="input" name="tlsMode" ${lock("tlsMode")}>${["auto", "pem", "proxy"].map((m) =>
|
||||
|
||||
@@ -97,6 +97,9 @@ export function fitColumns(table) {
|
||||
|
||||
window.addEventListener("resize", () => document.querySelectorAll(".table[data-levels]").forEach(fitColumns));
|
||||
|
||||
/** Chip of the Dashboard and Settings: TLS mode is proxy, but this page did not come through a trusted proxy over HTTPS (BRIEF §14.2). */
|
||||
export const PROXY_WARNING = `<span class="chip warn" data-i18n="Admin.Settings.ProxyBypassed" data-i18n-title="Admin.Settings.ProxyBypassed.Tip"></span>`;
|
||||
|
||||
/** An empty state: one sentence and one button (BRIEF §0.2). */
|
||||
export function emptyState(sentenceKey, button = "") {
|
||||
return `<div class="empty"><span data-i18n="${attr(sentenceKey)}"></span>${button}</div>`;
|
||||
|
||||
@@ -3,6 +3,7 @@ using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Hosting;
|
||||
using Titano.Server.Jobs;
|
||||
using Titano.Server.Security;
|
||||
using Titano.Server.Storage;
|
||||
@@ -18,7 +19,8 @@ public static class AdminEndpoints
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
api.MapGet("/server/dashboard", DashboardAsync).Requires(Permissions.ManageArchive | Permissions.ManageUsers);
|
||||
api.MapGet("/server/settings", (ServerSettingsStore store) => Results.Json(store.Current(), ProtocolJson.Default.ServerSettingsDto))
|
||||
api.MapGet("/server/settings", (HttpContext context, ServerSettingsStore store, ServerOptions options) =>
|
||||
Results.Json(store.Current() with { ProxyWarning = AdminPanel.BypassesProxy(context, options) }, ProtocolJson.Default.ServerSettingsDto))
|
||||
.Requires(Permissions.ManageArchive);
|
||||
api.MapPut("/server/settings", SaveSettingsAsync).Requires(Permissions.ManageArchive);
|
||||
api.MapGet("/audit", AuditAsync).Requires(Permissions.ManageUsers | Permissions.ManageArchive);
|
||||
@@ -65,11 +67,13 @@ public static class AdminEndpoints
|
||||
[.. nodes.Select(n => Dto.Node(n, names.GetValueOrDefault(n.UserId, string.Empty)))],
|
||||
[.. uploads.Select(u => new UploadDayDto(u.Day, u.Count, u.Bytes))],
|
||||
[.. activity.Items.Select(Dto.Audit)],
|
||||
[.. running.Items.Concat(queued.Items.OrderByDescending(j => j.Priority).ThenBy(j => j.Created)).Take(10).Select(Dto.Job)]),
|
||||
[.. running.Items.Concat(queued.Items.OrderByDescending(j => j.Priority).ThenBy(j => j.Created)).Take(10).Select(Dto.Job)],
|
||||
AdminPanel.BypassesProxy(context, options)),
|
||||
ProtocolJson.Default.DashboardDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, AuditLog audit)
|
||||
private static async Task<IResult> SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, ServerOptions options,
|
||||
AuditLog audit)
|
||||
{
|
||||
switch (store.Save(request))
|
||||
{
|
||||
@@ -79,7 +83,7 @@ public static class AdminEndpoints
|
||||
return ApiErrors.BadRequest(context, code, setting, setting);
|
||||
}
|
||||
await audit.WriteAsync(caller, context, "server_settings", "server", null, request.ServerName);
|
||||
return Results.Json(store.Current(), ProtocolJson.Default.ServerSettingsDto);
|
||||
return Results.Json(store.Current() with { ProxyWarning = AdminPanel.BypassesProxy(context, options) }, ProtocolJson.Default.ServerSettingsDto);
|
||||
}
|
||||
|
||||
/// <summary>The audit log, newest first; <c>action</c> may list several actions separated by commas (<c>login,login_failed</c>).</summary>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Titano.Data;
|
||||
@@ -45,15 +46,27 @@ public sealed class ServerOptions
|
||||
("TITANO_DB_SSLMODE", nameof(DbSslMode), (o, v) => o.DbSslMode = v),
|
||||
("TITANO_HTTP_PORT", nameof(HttpPort), (o, v) => o.HttpPort = Int("TITANO_HTTP_PORT", v)),
|
||||
("TITANO_HTTPS_PORT", nameof(HttpsPort), (o, v) => o.HttpsPort = Int("TITANO_HTTPS_PORT", v)),
|
||||
("TITANO_PUBLIC_HTTP_PORT", nameof(PublicHttpPort), (o, v) => o.PublicHttpPort = Int("TITANO_PUBLIC_HTTP_PORT", v)),
|
||||
("TITANO_PUBLIC_HTTPS_PORT", nameof(PublicHttpsPort), (o, v) => o.PublicHttpsPort = Int("TITANO_PUBLIC_HTTPS_PORT", v)),
|
||||
("TITANO_TLS_MODE", nameof(TlsMode), (o, v) => o.TlsMode = Enum.Parse<TlsMode>(v, ignoreCase: true)),
|
||||
("TITANO_TLS_CERT", nameof(TlsCert), (o, v) => o.TlsCert = v),
|
||||
("TITANO_TLS_KEY", nameof(TlsKey), (o, v) => o.TlsKey = v),
|
||||
("TITANO_TRUSTED_PROXIES", nameof(TrustedProxies), (o, v) => o.TrustedProxies = v),
|
||||
("TITANO_LANG", nameof(Language), (o, v) => o.Language = v),
|
||||
("TITANO_WORKERS", nameof(Workers), (o, v) => o.Workers = Math.Max(1, Int("TITANO_WORKERS", v))),
|
||||
("TITANO_DISCOVERY", nameof(Discovery), (o, v) => o.Discovery = bool.Parse(v)),
|
||||
("TITANO_LOG_LEVEL", nameof(LogLevel), (o, v) => o.LogLevel = Enum.Parse<LogLevel>(v, ignoreCase: true)),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Reverse proxies whose <c>X-Forwarded-*</c> headers count in TLS mode proxy: loopback and the private networks a
|
||||
/// compose or Unraid proxy container connects from (RFC 1918, IPv6 unique local).
|
||||
/// </summary>
|
||||
public const string DefaultTrustedProxies = "127.0.0.0/8, ::1/128, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7";
|
||||
|
||||
/// <summary>The environment variables the server reads (<c>--help</c> lists them all).</summary>
|
||||
public static IEnumerable<string> EnvironmentVariables => Variables.Select(v => v.Variable).Prepend("TITANO_DATA_PATH");
|
||||
|
||||
public string ServerName { get; set; } = "Titano Server";
|
||||
public string ArchivePath { get; set; } = OperatingSystem.IsWindows() ? @"C:\TitanoArchive" : "/archive";
|
||||
public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Titano Server") : "/data";
|
||||
@@ -72,9 +85,26 @@ public sealed class ServerOptions
|
||||
public string DbSslMode { get; set; } = "prefer";
|
||||
public int HttpPort { get; set; } = 8080;
|
||||
public int HttpsPort { get; set; } = 8443;
|
||||
|
||||
/// <summary>
|
||||
/// Port clients reach the HTTP listener on, when it differs from <see cref="HttpPort"/> (a container port published
|
||||
/// as another host port); advertised by LAN discovery. Null: <see cref="HttpPort"/>.
|
||||
/// </summary>
|
||||
public int? PublicHttpPort { get; set; }
|
||||
|
||||
/// <summary>Port clients reach the HTTPS listener on (admin redirect, LAN discovery). Null: <see cref="HttpsPort"/>.</summary>
|
||||
public int? PublicHttpsPort { get; set; }
|
||||
|
||||
public TlsMode TlsMode { get; set; } = TlsMode.Auto;
|
||||
public string? TlsCert { get; set; }
|
||||
public string? TlsKey { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Addresses or networks (CIDR), separated by commas or spaces, of the reverse proxies trusted in TLS mode proxy.
|
||||
/// Forwarded headers from any other peer are ignored, so a client that reaches the HTTP port directly cannot choose
|
||||
/// the address the sign-in rate limit and the audit log see.
|
||||
/// </summary>
|
||||
public string TrustedProxies { get; set; } = DefaultTrustedProxies;
|
||||
public string Language { get; set; } = "en";
|
||||
public int Workers { get; set; } = Math.Max(1, Environment.ProcessorCount / 2);
|
||||
public bool Discovery { get; set; } = true;
|
||||
@@ -192,12 +222,38 @@ public sealed class ServerOptions
|
||||
// Port 0 asks the OS for a free port (used by the in-process test host).
|
||||
if (HttpPort is < 0 or > 65535 || HttpsPort is < 0 or > 65535)
|
||||
throw new InvalidOperationException("Ports must be between 0 and 65535.");
|
||||
if (PublicHttpPort is < 1 or > 65535 || PublicHttpsPort is < 1 or > 65535)
|
||||
throw new InvalidOperationException("TITANO_PUBLIC_HTTP_PORT and TITANO_PUBLIC_HTTPS_PORT must be between 1 and 65535.");
|
||||
try
|
||||
{
|
||||
TrustedProxyNetworks();
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
throw new InvalidOperationException($"TITANO_TRUSTED_PROXIES must list IP addresses or networks such as 172.16.0.0/12: {ex.Message}", ex);
|
||||
}
|
||||
if (ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024)
|
||||
throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB.");
|
||||
if (MaxUploadBytes < 1 || TokenLifetimeDays < 1 || JobHistoryDays < 1 || UploadRetentionHours < 1)
|
||||
throw new InvalidOperationException("Upload size, token lifetime, job history and upload retention must be positive.");
|
||||
}
|
||||
|
||||
/// <summary>The parsed <see cref="TrustedProxies"/>; a single address is a network of one.</summary>
|
||||
/// <exception cref="FormatException">An entry is neither an IP address nor a network in CIDR notation.</exception>
|
||||
public IReadOnlyList<IPNetwork> TrustedProxyNetworks()
|
||||
{
|
||||
var networks = new List<IPNetwork>();
|
||||
foreach (var entry in TrustedProxies.Split([',', ';', ' ', '\t'], StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (IPNetwork.TryParse(entry, out var network)) networks.Add(network);
|
||||
else if (!entry.Contains('/', StringComparison.Ordinal) && IPAddress.TryParse(entry, out var address)
|
||||
&& (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6 || address.ScopeId == 0))
|
||||
networks.Add(new IPNetwork(address, address.GetAddressBytes().Length * 8));
|
||||
else throw new FormatException($"'{entry}' is neither an address nor a network.");
|
||||
}
|
||||
return networks;
|
||||
}
|
||||
|
||||
/// <summary>TITANO_DB is <c>postgres</c>, <c>sqlite</c> or a complete connection string (<c>Host=…</c> / <c>Data Source=…</c>).</summary>
|
||||
private void ApplyDatabase(string value)
|
||||
{
|
||||
|
||||
@@ -47,14 +47,14 @@ public sealed class ServerSettingsStore(ServerOptions options)
|
||||
|| !string.Equals(request.TlsMode, options.TlsMode.ToString(), StringComparison.OrdinalIgnoreCase)
|
||||
|| request.TlsCert != options.TlsCert || request.TlsKey != options.TlsKey || request.Workers != options.Workers
|
||||
|| request.ChunkSizeBytes != options.ChunkSizeBytes || request.JobHistoryDays != options.JobHistoryDays;
|
||||
_saved = request with { ServerName = request.ServerName.Trim(), Locked = [.. options.Locked], RestartRequired = restart };
|
||||
_saved = request with { ServerName = request.ServerName.Trim(), Locked = [.. options.Locked], RestartRequired = restart, ProxyWarning = false };
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static ServerSettingsDto Snapshot(ServerOptions o, bool restartRequired) => new(
|
||||
o.ServerName, o.HttpPort, o.HttpsPort, o.TlsMode.ToString().ToLowerInvariant(), o.TlsCert, o.TlsKey, o.Language, o.Workers, o.Discovery,
|
||||
o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours, [.. o.Locked], restartRequired);
|
||||
o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours, [.. o.Locked], restartRequired, ProxyWarning: false);
|
||||
|
||||
private static string? Validate(ServerSettingsDto r)
|
||||
{
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||
@@ -7,7 +8,9 @@ namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Serves the embedded admin panel at <c>/admin</c>. Requests over plain HTTP from another machine are redirected to
|
||||
/// the HTTPS listener, because the session cookie is <c>Secure</c> (BRIEF §14.2) and would not survive plain HTTP.
|
||||
/// the HTTPS listener, on the port clients reach it on (<see cref="ServerOptions.PublicHttpsPort"/> when a container
|
||||
/// port is published as another host port), because the session cookie is <c>Secure</c> (BRIEF §14.2) and would not
|
||||
/// survive plain HTTP.
|
||||
/// </summary>
|
||||
public static class AdminPanel
|
||||
{
|
||||
@@ -33,14 +36,22 @@ public static class AdminPanel
|
||||
});
|
||||
}
|
||||
|
||||
private static string? HttpsLocation(HttpContext context, ServerOptions options, IServer server)
|
||||
/// <summary>
|
||||
/// True when TLS mode is proxy but this request did not reach the server through a trusted proxy over HTTPS (BRIEF
|
||||
/// §14.2: the admin warns). The server has no HTTPS listener in that mode, so a request is HTTPS only when a proxy
|
||||
/// listed in <see cref="ServerOptions.TrustedProxies"/> forwarded it as such.
|
||||
/// </summary>
|
||||
public static bool BypassesProxy(HttpContext context, ServerOptions options) =>
|
||||
options.TlsMode == TlsMode.Proxy && !context.Request.IsHttps;
|
||||
|
||||
internal static string? HttpsLocation(HttpContext context, ServerOptions options, IServer server)
|
||||
{
|
||||
if (context.Request.IsHttps || options.TlsMode == TlsMode.Proxy) return null;
|
||||
if (context.Connection.RemoteIpAddress is { } remote && IPAddress.IsLoopback(remote)) return null;
|
||||
foreach (var address in server.Features.Get<IServerAddressesFeature>()?.Addresses ?? [])
|
||||
{
|
||||
if (!address.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var port = address[(address.LastIndexOf(':') + 1)..].TrimEnd('/');
|
||||
var port = options.PublicHttpsPort?.ToString(CultureInfo.InvariantCulture) ?? address[(address.LastIndexOf(':') + 1)..].TrimEnd('/');
|
||||
return $"https://{context.Request.Host.Host}:{port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -12,7 +12,8 @@ namespace Titano.Server.Hosting;
|
||||
/// <summary>
|
||||
/// LAN discovery (BRIEF §14.9, <c>TITANO_DISCOVERY</c>): every few seconds a <see cref="DiscoveryBeacon"/> is broadcast on
|
||||
/// UDP port <see cref="DiscoveryBeacon.Port"/> of every IPv4 network, so clients can offer this server on first run.
|
||||
/// Switching discovery off in the settings stops it without a restart.
|
||||
/// Switching discovery off in the settings stops it without a restart. In a container the broadcasts reach the LAN
|
||||
/// only with host networking; on a bridge network they stay on the bridge.
|
||||
/// </summary>
|
||||
public sealed class DiscoveryBeaconService(ServerOptions options, ServerState state, IServer server, ILogger<DiscoveryBeaconService> logger) : BackgroundService
|
||||
{
|
||||
@@ -51,12 +52,15 @@ public sealed class DiscoveryBeaconService(ServerOptions options, ServerState st
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The beacon for the ports Kestrel actually listens on (HTTPS 0 when TLS is terminated elsewhere).</summary>
|
||||
/// <summary>
|
||||
/// The beacon for the ports clients reach: the public ports when set, else the ports Kestrel actually listens on
|
||||
/// (HTTPS 0 when TLS is terminated elsewhere).
|
||||
/// </summary>
|
||||
public DiscoveryBeacon CreateBeacon() => new(
|
||||
options.ServerName,
|
||||
SystemEndpoints.Version,
|
||||
BoundPort(Uri.UriSchemeHttp) ?? options.HttpPort,
|
||||
state.TlsFingerprint is null ? 0 : BoundPort(Uri.UriSchemeHttps) ?? options.HttpsPort,
|
||||
options.PublicHttpPort ?? BoundPort(Uri.UriSchemeHttp) ?? options.HttpPort,
|
||||
state.TlsFingerprint is null ? 0 : options.PublicHttpsPort ?? BoundPort(Uri.UriSchemeHttps) ?? options.HttpsPort,
|
||||
state.TlsFingerprint);
|
||||
|
||||
public async Task SendOnceAsync(UdpClient udp, IEnumerable<IPEndPoint> targets, CancellationToken cancellationToken)
|
||||
|
||||
@@ -36,7 +36,16 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
TITANO_ARCHIVE_PATH TITANO_DATA_PATH TITANO_SERVER_NAME TITANO_ADMIN_USER TITANO_ADMIN_PASSWORD
|
||||
TITANO_DB (postgres | sqlite | connection string) TITANO_DB_HOST TITANO_DB_PORT TITANO_DB_NAME TITANO_DB_USER
|
||||
TITANO_DB_PASSWORD TITANO_DB_SSLMODE TITANO_HTTP_PORT TITANO_HTTPS_PORT TITANO_TLS_MODE (auto | pem | proxy)
|
||||
TITANO_TLS_CERT TITANO_TLS_KEY TITANO_LANG TITANO_WORKERS TITANO_DISCOVERY
|
||||
TITANO_TLS_CERT TITANO_TLS_KEY TITANO_LANG TITANO_WORKERS
|
||||
TITANO_LOG_LEVEL (Trace | Debug | Information | Warning | Error)
|
||||
TITANO_DISCOVERY LAN beacon (true | false); in a container it needs host networking
|
||||
TITANO_PUBLIC_HTTP_PORT, TITANO_PUBLIC_HTTPS_PORT
|
||||
ports clients reach when the container's ports are published as other host ports
|
||||
(admin redirect to HTTPS, LAN beacon)
|
||||
TITANO_TRUSTED_PROXIES proxy mode: addresses or networks (CIDR) whose X-Forwarded-* headers count
|
||||
(default: loopback, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7)
|
||||
|
||||
Container image only: PUID, PGID (user and group the server runs as, owners of /data), TZ (local time zone)
|
||||
""";
|
||||
|
||||
public static ServerCommandLine Parse(IReadOnlyList<string> args)
|
||||
|
||||
@@ -106,11 +106,15 @@ public static class ServerHost
|
||||
services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));
|
||||
if (options.TlsMode == TlsMode.Proxy)
|
||||
{
|
||||
// Only the configured proxies may say who the client is: a client that reaches the HTTP port directly would
|
||||
// otherwise pick its own address for the sign-in rate limit and the audit log, and claim HTTPS.
|
||||
var trusted = options.TrustedProxyNetworks();
|
||||
services.Configure<ForwardedHeadersOptions>(f =>
|
||||
{
|
||||
f.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
|
||||
f.KnownIPNetworks.Clear();
|
||||
f.KnownProxies.Clear();
|
||||
foreach (var network in trusted) f.KnownIPNetworks.Add(network);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,19 @@ public sealed class DiscoveryTests(TestContext context)
|
||||
Assert.Equal((await info.ReadAsync(ProtocolJson.Default.ServerInfo)).TlsFingerprint, beacon.TlsFingerprint);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheBeaconAdvertisesThePortsClientsReach()
|
||||
{
|
||||
// Container ports published as other host ports: a client on the LAN must use the host's.
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.PublicHttpPort = 18080;
|
||||
o.PublicHttpsPort = 18443;
|
||||
});
|
||||
var beacon = server.Services.GetRequiredService<DiscoveryBeaconService>().CreateBeacon();
|
||||
Assert.Equal((18080, 18443), (beacon.HttpPort, beacon.HttpsPort));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ForeignDatagramsAreIgnored()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Server.Tests.Hosting;
|
||||
|
||||
/// <summary>TLS mode proxy (BRIEF §14.2): forwarded headers count only from trusted proxies, and the admin warns otherwise.</summary>
|
||||
[Category("server")]
|
||||
public sealed class ProxyModeTests(TestContext context)
|
||||
{
|
||||
/// <summary>A documentation network (RFC 5737) the test client never connects from.</summary>
|
||||
private const string ElsewhereOnly = "192.0.2.0/24";
|
||||
|
||||
[Test]
|
||||
public async Task AClientOutsideTheTrustedProxiesCannotChooseItsAddress()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.TrustedProxies = ElsewhereOnly;
|
||||
o.LoginAttemptsPerMinute = 5;
|
||||
});
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
using var failed = await LoginAsync(server, "user" + i, $"203.0.113.{i + 1}");
|
||||
await failed.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
|
||||
}
|
||||
// A new X-Forwarded-For per attempt does not buy a new budget: the limit stays on the real address.
|
||||
using var limited = await LoginAsync(server, "admin", "203.0.113.99");
|
||||
await limited.ExpectErrorAsync(HttpStatusCode.TooManyRequests, "rate_limited");
|
||||
|
||||
var audit = await server.Database.Audit.ListAsync(null, "login_failed", 50, null, context.Cancellation);
|
||||
Assert.Count(5, audit.Items);
|
||||
Assert.True(audit.Items.All(e => IsLoopback(e.RemoteAddress)), string.Join(", ", audit.Items.Select(e => e.RemoteAddress)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ATrustedProxyReportsTheClientAddress()
|
||||
{
|
||||
// The default trusts loopback and the private networks a compose or Unraid proxy container connects from.
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.LoginAttemptsPerMinute = 5;
|
||||
});
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
using var failed = await LoginAsync(server, "user" + i, $"203.0.113.{i + 1}");
|
||||
await failed.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
|
||||
}
|
||||
var audit = await server.Database.Audit.ListAsync(null, "login_failed", 50, null, context.Cancellation);
|
||||
Assert.Contains("203.0.113.8", audit.Items.Select(e => e.RemoteAddress));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheAdminWarnsWhenAPageDidNotComeThroughATrustedProxyOverHttps()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.TlsMode = TlsMode.Proxy);
|
||||
var admin = await server.AdminAsync();
|
||||
Assert.True((await DashboardAsync(admin, forwardedProto: null)).ProxyWarning, "plain HTTP to the server's own port");
|
||||
Assert.False((await DashboardAsync(admin, "https")).ProxyWarning, "HTTPS through a trusted proxy");
|
||||
Assert.True((await DashboardAsync(admin, "http")).ProxyWarning, "plain HTTP through the proxy");
|
||||
Assert.True((await SettingsAsync(admin, forwardedProto: null)).ProxyWarning);
|
||||
Assert.False((await SettingsAsync(admin, "https")).ProxyWarning);
|
||||
|
||||
await using var untrusted = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.TrustedProxies = ElsewhereOnly;
|
||||
});
|
||||
var other = await untrusted.AdminAsync();
|
||||
Assert.True((await DashboardAsync(other, "https")).ProxyWarning, "a claim of HTTPS from a peer that is no trusted proxy");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OtherTlsModesNeverWarn()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var admin = await server.AdminAsync();
|
||||
Assert.False((await DashboardAsync(admin, forwardedProto: null)).ProxyWarning);
|
||||
Assert.False((await SettingsAsync(admin, forwardedProto: null)).ProxyWarning);
|
||||
}
|
||||
|
||||
private static bool IsLoopback(string? address) =>
|
||||
IPAddress.TryParse(address, out var ip) && IPAddress.IsLoopback(ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip);
|
||||
|
||||
private static async Task<HttpResponseMessage> LoginAsync(TestServer server, string username, string forwardedFor)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/auth/login")
|
||||
{
|
||||
Content = JsonContent.Create(new LoginRequest(username, "wrong-password-x", "tests"), ProtocolJson.Default.LoginRequest),
|
||||
};
|
||||
request.Headers.Add("X-Forwarded-For", forwardedFor);
|
||||
return await server.Client.SendAsync(request);
|
||||
}
|
||||
|
||||
private static async Task<DashboardDto> DashboardAsync(HttpClient admin, string? forwardedProto)
|
||||
{
|
||||
using var response = await SendAsync(admin, "/api/v1/server/dashboard", forwardedProto);
|
||||
return await response.ReadAsync(ProtocolJson.Default.DashboardDto);
|
||||
}
|
||||
|
||||
private static async Task<ServerSettingsDto> SettingsAsync(HttpClient admin, string? forwardedProto)
|
||||
{
|
||||
using var response = await SendAsync(admin, "/api/v1/server/settings", forwardedProto);
|
||||
return await response.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
|
||||
}
|
||||
|
||||
private static async Task<HttpResponseMessage> SendAsync(HttpClient client, string path, string? forwardedProto)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, path);
|
||||
if (forwardedProto is not null) request.Headers.Add("X-Forwarded-Proto", forwardedProto);
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using Titano.Data;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Hosting;
|
||||
@@ -72,4 +74,57 @@ public sealed class StartupTests(TestContext context)
|
||||
Assert.SequenceEqual(["Database", "HttpPort", "Discovery"], options.Locked);
|
||||
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["TITANO_DATA_PATH"] = root, ["TITANO_DB"] = "postgres", ["TITANO_WORKERS"] = "many" }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TrustedProxiesAreAddressesOrNetworks()
|
||||
{
|
||||
var root = context.CreateTempDirectory("proxies");
|
||||
var defaults = ServerOptions.Load(new Dictionary<string, string?> { ["TITANO_DATA_PATH"] = root, ["TITANO_DB"] = "postgres" }).TrustedProxyNetworks();
|
||||
foreach (var address in new[] { "127.0.0.1", "::1", "10.20.30.40", "172.18.0.3", "192.168.1.2", "fd00::7", "::ffff:172.17.0.2" })
|
||||
Assert.True(defaults.Any(n => n.Contains(IPAddress.Parse(address)) || n.Contains(IPAddress.Parse(address).MapToIPv4())), address);
|
||||
Assert.False(defaults.Any(n => n.Contains(IPAddress.Parse("203.0.113.5"))));
|
||||
|
||||
var options = ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["TITANO_DATA_PATH"] = root,
|
||||
["TITANO_DB"] = "postgres",
|
||||
["TITANO_TRUSTED_PROXIES"] = "10.1.2.3, 2001:db8::/32;172.20.0.5/16",
|
||||
});
|
||||
Assert.Contains("TrustedProxies", options.Locked);
|
||||
Assert.SequenceEqual(["10.1.2.3/32", "2001:db8::/32", "172.20.0.0/16"], options.TrustedProxyNetworks().Select(n => n.ToString()));
|
||||
foreach (var invalid in new[] { "proxy.lan", "10.0.0.0/33", "fe80::1%2" })
|
||||
{
|
||||
var error = Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["TITANO_DATA_PATH"] = root,
|
||||
["TITANO_DB"] = "postgres",
|
||||
["TITANO_TRUSTED_PROXIES"] = "127.0.0.1," + invalid,
|
||||
}));
|
||||
Assert.Contains(invalid, error.Message);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PublicPortsComeFromTheEnvironment()
|
||||
{
|
||||
var root = context.CreateTempDirectory("public");
|
||||
var options = ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["TITANO_DATA_PATH"] = root,
|
||||
["TITANO_DB"] = "postgres",
|
||||
["TITANO_PUBLIC_HTTP_PORT"] = "18080",
|
||||
["TITANO_PUBLIC_HTTPS_PORT"] = "18443",
|
||||
});
|
||||
Assert.Equal((18080, 18443), (options.PublicHttpPort, options.PublicHttpsPort));
|
||||
Assert.Null(ServerOptions.Load(new Dictionary<string, string?> { ["TITANO_DATA_PATH"] = root, ["TITANO_DB"] = "postgres" }).PublicHttpsPort);
|
||||
foreach (var invalid in new[] { "0", "70000", "https" })
|
||||
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["TITANO_DATA_PATH"] = root, ["TITANO_DB"] = "postgres", ["TITANO_PUBLIC_HTTPS_PORT"] = invalid }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HelpListsEveryVariable()
|
||||
{
|
||||
foreach (var variable in ServerOptions.EnvironmentVariables.Concat(["PUID", "PGID", "TZ"]))
|
||||
Assert.True(Regex.IsMatch(ServerCommandLine.Usage, $@"\b{variable}\b"), variable);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,11 @@ using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Hosting;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Server.Tests.Hosting;
|
||||
@@ -89,6 +93,31 @@ public sealed class SystemEndpointTests(TestContext context)
|
||||
Assert.Equal(HttpStatusCode.NotModified, cached.StatusCode);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PlainHttpFromAnotherMachineGoesToThePublicHttpsPort()
|
||||
{
|
||||
// The container listens on 8443, published on the host as 18443 (BRIEF §19.6: the template's ports are editable).
|
||||
await using var server = await TestServer.StartAsync(context, o => o.PublicHttpsPort = 18443);
|
||||
var kestrel = server.Services.GetRequiredService<IServer>();
|
||||
var request = AdminRequest(IPAddress.Parse("10.0.0.7"));
|
||||
Assert.Equal("https://10.0.0.5:18443/admin/?page=jobs", AdminPanel.HttpsLocation(request, server.Options, kestrel));
|
||||
|
||||
server.Options.PublicHttpsPort = null;
|
||||
Assert.Equal($"https://10.0.0.5:{Assert.NotNull(server.HttpsBase).Port}/admin/?page=jobs", AdminPanel.HttpsLocation(request, server.Options, kestrel));
|
||||
Assert.Null(AdminPanel.HttpsLocation(AdminRequest(IPAddress.Loopback), server.Options, kestrel));
|
||||
}
|
||||
|
||||
private static DefaultHttpContext AdminRequest(IPAddress from)
|
||||
{
|
||||
var request = new DefaultHttpContext();
|
||||
request.Connection.RemoteIpAddress = from;
|
||||
request.Request.Scheme = "http";
|
||||
request.Request.Host = new HostString("10.0.0.5", 18080);
|
||||
request.Request.Path = "/admin/";
|
||||
request.Request.QueryString = new QueryString("?page=jobs");
|
||||
return request;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AdminPanelRunsUnderAStrictPolicyAndIsNeverFramed()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user