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:
Claude committed 2026-10-12 09:27:31 +00:00
1 parent 047cddfe7b
commit 5ec59a2e96
17 files changed
+340 -22

No files matched your search

@@ -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()
{