Files
Chronos/tests/Chronos.Server.Tests/Hosting/ProxyModeTests.cs
T
Alby96andClaude Opus 5.5 5f27a86406
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s
refactor!: rename Titano to Chronos and move CI and releases to Gitea
The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout. The release cross-compiles the Windows programs, checks their
  icon, version and DPI manifest, packs installers and zips, publishes the
  Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only
  tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow) and
  pe-check.

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 11:34:48 +02:00

187 lines
9.1 KiB
C#

using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Chronos.Core.Localization;
using Chronos.Protocol;
using Chronos.Server.Api;
using Chronos.Server.Configuration;
using Chronos.Testing;
namespace Chronos.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, where a proxy on the same machine (and this test) 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 ByDefaultAMachineOfTheHomeNetworkIsNoProxy()
{
// The machines of a home network reach the HTTP port directly from private addresses, also through Docker's
// port publishing (which keeps the client's address): none of them may choose its own address.
await using var server = await TestServer.StartAsync(context, o => o.TlsMode = TlsMode.Proxy);
foreach (var peer in new[] { "192.168.1.50", "10.0.0.7", "172.17.0.1", "fd00::7" })
Assert.Equal((peer, false), await ForwardAsync(server, peer));
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "127.0.0.1"));
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "::ffff:127.0.0.1"));
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "::1"));
}
[Test]
public async Task AProxyNetworkCountsOnceListed()
{
await using var server = await TestServer.StartAsync(context, o =>
{
o.TlsMode = TlsMode.Proxy;
o.TrustedProxies = "172.18.0.0/16";
});
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "172.18.0.5"));
Assert.Equal(("192.168.1.50", false), await ForwardAsync(server, "192.168.1.50"));
}
[Test]
public void AnAdminSignInThroughAnUntrustedProxyNamesTheSetting()
{
// The warning chip needs a session first: the sign-in refusal itself points at CHRONOS_TRUSTED_PROXIES.
var request = new DefaultHttpContext();
request.Connection.RemoteIpAddress = IPAddress.Parse("172.18.0.5");
request.Request.Scheme = "http";
Assert.Equal("proxy_untrusted", AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
Assert.Equal("https_required", AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Auto }));
Assert.Contains("CHRONOS_TRUSTED_PROXIES", Loc.L("Server.Error.ProxyUntrusted"));
request.Request.Scheme = "https";
Assert.Null(AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
request.Request.Scheme = "http";
request.Connection.RemoteIpAddress = IPAddress.Loopback;
Assert.Null(AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
}
[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);
}
/// <summary>
/// Runs the server's own forwarded-headers step on a request from <paramref name="peer"/> that claims to forward a
/// client at 203.0.113.7 over HTTPS: the address and scheme the rest of the server then sees.
/// </summary>
private static async Task<(string? Address, bool Https)> ForwardAsync(TestServer server, string peer)
{
var request = new DefaultHttpContext();
request.Connection.RemoteIpAddress = IPAddress.Parse(peer);
request.Request.Scheme = "http";
request.Request.Headers["X-Forwarded-For"] = "203.0.113.7";
request.Request.Headers["X-Forwarded-Proto"] = "https";
var forwarded = new ForwardedHeadersMiddleware(_ => Task.CompletedTask, NullLoggerFactory.Instance,
server.Services.GetRequiredService<IOptions<ForwardedHeadersOptions>>());
await forwarded.Invoke(request);
var address = request.Connection.RemoteIpAddress;
return ((address is { IsIPv4MappedToIPv6: true } ? address.MapToIPv4() : address)?.ToString(), request.Request.IsHttps);
}
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);
}
}