-
+
+ ${settings.proxyWarning ? PROXY_WARNING : ""}
${number("httpPort", settings.httpPort, 'min="1" max="65535"')}
${number("httpsPort", settings.httpsPort, 'min="1" max="65535"')}
${field("tlsMode", `${["auto", "pem", "proxy"].map((m) =>
diff --git a/src/Titano.Server/Admin/web/ui.js b/src/Titano.Server/Admin/web/ui.js
index 5210c44d..d6ea000e 100644
--- a/src/Titano.Server/Admin/web/ui.js
+++ b/src/Titano.Server/Admin/web/ui.js
@@ -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 = ` `;
+
/** An empty state: one sentence and one button (BRIEF §0.2). */
export function emptyState(sentenceKey, button = "") {
return ` ${button}
`;
diff --git a/src/Titano.Server/Api/AdminEndpoints.cs b/src/Titano.Server/Api/AdminEndpoints.cs
index fe761f11..baaaca3c 100644
--- a/src/Titano.Server/Api/AdminEndpoints.cs
+++ b/src/Titano.Server/Api/AdminEndpoints.cs
@@ -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 SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, AuditLog audit)
+ private static async Task 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);
}
/// The audit log, newest first; action may list several actions separated by commas (login,login_failed ).
diff --git a/src/Titano.Server/Configuration/ServerOptions.cs b/src/Titano.Server/Configuration/ServerOptions.cs
index 1252c328..ba20b354 100644
--- a/src/Titano.Server/Configuration/ServerOptions.cs
+++ b/src/Titano.Server/Configuration/ServerOptions.cs
@@ -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(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(v, ignoreCase: true)),
];
+ ///
+ /// Reverse proxies whose X-Forwarded-* headers count in TLS mode proxy: loopback and the private networks a
+ /// compose or Unraid proxy container connects from (RFC 1918, IPv6 unique local).
+ ///
+ 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";
+
+ /// The environment variables the server reads (--help lists them all).
+ public static IEnumerable 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;
+
+ ///
+ /// Port clients reach the HTTP listener on, when it differs from (a container port published
+ /// as another host port); advertised by LAN discovery. Null: .
+ ///
+ public int? PublicHttpPort { get; set; }
+
+ /// Port clients reach the HTTPS listener on (admin redirect, LAN discovery). Null: .
+ public int? PublicHttpsPort { get; set; }
+
public TlsMode TlsMode { get; set; } = TlsMode.Auto;
public string? TlsCert { get; set; }
public string? TlsKey { get; set; }
+
+ ///
+ /// 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.
+ ///
+ 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.");
}
+ /// The parsed ; a single address is a network of one.
+ /// An entry is neither an IP address nor a network in CIDR notation.
+ public IReadOnlyList TrustedProxyNetworks()
+ {
+ var networks = new List();
+ 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;
+ }
+
/// TITANO_DB is postgres , sqlite or a complete connection string (Host=… / Data Source=… ).
private void ApplyDatabase(string value)
{
diff --git a/src/Titano.Server/Configuration/ServerSettingsStore.cs b/src/Titano.Server/Configuration/ServerSettingsStore.cs
index 5d830471..7b107f76 100644
--- a/src/Titano.Server/Configuration/ServerSettingsStore.cs
+++ b/src/Titano.Server/Configuration/ServerSettingsStore.cs
@@ -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)
{
diff --git a/src/Titano.Server/Hosting/AdminPanel.cs b/src/Titano.Server/Hosting/AdminPanel.cs
index d92fde09..21dda701 100644
--- a/src/Titano.Server/Hosting/AdminPanel.cs
+++ b/src/Titano.Server/Hosting/AdminPanel.cs
@@ -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;
///
/// Serves the embedded admin panel at /admin . Requests over plain HTTP from another machine are redirected to
-/// the HTTPS listener, because the session cookie is Secure (BRIEF §14.2) and would not survive plain HTTP.
+/// the HTTPS listener, on the port clients reach it on ( when a container
+/// port is published as another host port), because the session cookie is Secure (BRIEF §14.2) and would not
+/// survive plain HTTP.
///
public static class AdminPanel
{
@@ -33,14 +36,22 @@ public static class AdminPanel
});
}
- private static string? HttpsLocation(HttpContext context, ServerOptions options, IServer server)
+ ///
+ /// 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 forwarded it as such.
+ ///
+ 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()?.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;
diff --git a/src/Titano.Server/Hosting/DiscoveryBeaconService.cs b/src/Titano.Server/Hosting/DiscoveryBeaconService.cs
index 3f2e8f29..8ca27538 100644
--- a/src/Titano.Server/Hosting/DiscoveryBeaconService.cs
+++ b/src/Titano.Server/Hosting/DiscoveryBeaconService.cs
@@ -12,7 +12,8 @@ namespace Titano.Server.Hosting;
///
/// LAN discovery (BRIEF §14.9, TITANO_DISCOVERY ): every few seconds a is broadcast on
/// UDP 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.
///
public sealed class DiscoveryBeaconService(ServerOptions options, ServerState state, IServer server, ILogger logger) : BackgroundService
{
@@ -51,12 +52,15 @@ public sealed class DiscoveryBeaconService(ServerOptions options, ServerState st
}
}
- /// The beacon for the ports Kestrel actually listens on (HTTPS 0 when TLS is terminated elsewhere).
+ ///
+ /// 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).
+ ///
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 targets, CancellationToken cancellationToken)
diff --git a/src/Titano.Server/Hosting/ServerCommandLine.cs b/src/Titano.Server/Hosting/ServerCommandLine.cs
index a4751919..e27f4392 100644
--- a/src/Titano.Server/Hosting/ServerCommandLine.cs
+++ b/src/Titano.Server/Hosting/ServerCommandLine.cs
@@ -36,7 +36,16 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList args)
diff --git a/src/Titano.Server/Hosting/ServerHost.cs b/src/Titano.Server/Hosting/ServerHost.cs
index 0913d48d..2ce1a1c0 100644
--- a/src/Titano.Server/Hosting/ServerHost.cs
+++ b/src/Titano.Server/Hosting/ServerHost.cs
@@ -106,11 +106,15 @@ public static class ServerHost
services.Configure(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(f =>
{
f.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
f.KnownIPNetworks.Clear();
f.KnownProxies.Clear();
+ foreach (var network in trusted) f.KnownIPNetworks.Add(network);
});
}
diff --git a/tests/Titano.Server.Tests/Hosting/DiscoveryTests.cs b/tests/Titano.Server.Tests/Hosting/DiscoveryTests.cs
index f2e5dc3a..fb07cce7 100644
--- a/tests/Titano.Server.Tests/Hosting/DiscoveryTests.cs
+++ b/tests/Titano.Server.Tests/Hosting/DiscoveryTests.cs
@@ -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().CreateBeacon();
+ Assert.Equal((18080, 18443), (beacon.HttpPort, beacon.HttpsPort));
+ }
+
[Test]
public void ForeignDatagramsAreIgnored()
{
diff --git a/tests/Titano.Server.Tests/Hosting/ProxyModeTests.cs b/tests/Titano.Server.Tests/Hosting/ProxyModeTests.cs
new file mode 100644
index 00000000..fa5ce42f
--- /dev/null
+++ b/tests/Titano.Server.Tests/Hosting/ProxyModeTests.cs
@@ -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;
+
+/// TLS mode proxy (BRIEF §14.2): forwarded headers count only from trusted proxies, and the admin warns otherwise.
+[Category("server")]
+public sealed class ProxyModeTests(TestContext context)
+{
+ /// A documentation network (RFC 5737) the test client never connects from.
+ 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 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 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 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 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);
+ }
+}
diff --git a/tests/Titano.Server.Tests/Hosting/StartupTests.cs b/tests/Titano.Server.Tests/Hosting/StartupTests.cs
index 9ee621cb..a8bde8ef 100644
--- a/tests/Titano.Server.Tests/Hosting/StartupTests.cs
+++ b/tests/Titano.Server.Tests/Hosting/StartupTests.cs
@@ -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(() => ServerOptions.Load(new Dictionary { ["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 { ["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
+ {
+ ["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(() => ServerOptions.Load(new Dictionary
+ {
+ ["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
+ {
+ ["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 { ["TITANO_DATA_PATH"] = root, ["TITANO_DB"] = "postgres" }).PublicHttpsPort);
+ foreach (var invalid in new[] { "0", "70000", "https" })
+ Assert.Throws(() => ServerOptions.Load(new Dictionary { ["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);
+ }
}
diff --git a/tests/Titano.Server.Tests/Hosting/SystemEndpointTests.cs b/tests/Titano.Server.Tests/Hosting/SystemEndpointTests.cs
index 689b52f2..a939bb37 100644
--- a/tests/Titano.Server.Tests/Hosting/SystemEndpointTests.cs
+++ b/tests/Titano.Server.Tests/Hosting/SystemEndpointTests.cs
@@ -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();
+ 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()
{