Path: redb-identity/tests/redb.Identity.Tests/Security/ClientChosenAddressHandlerTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Security/ClientChosenAddressHandlerTests.cs
----
using System.Net;
using System.Net.Sockets;
using AwesomeAssertions;
using redb.Identity.Core.Services;
using Xunit;
namespace redb.Identity.Tests.Security;
///
/// The connection of the client-chosen-address clients goes only to an address the handler's own resolution approved:
/// a name that would answer a public address to the guard's pre-check and a loopback one to the connection is refused
/// at the connection; approved addresses are tried in order; IPv4-mapped forms are judged as IPv4; a proxy endpoint is
/// not subject to the address rule.
///
public sealed class ClientChosenAddressHandlerTests
{
/// A loopback TCP server that counts connections and answers every request 200.
private sealed class CountingServer : IDisposable
{
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
private int _connections;
public int Port { get; }
public int Connections => Volatile.Read(ref _connections);
public CountingServer()
{
_listener.Start();
Port = ((IPEndPoint)_listener.LocalEndpoint).Port;
_ = Task.Run(AcceptAsync);
}
private async Task AcceptAsync()
{
while (true)
{
TcpClient client;
try { client = await _listener.AcceptTcpClientAsync(); } catch { return; }
Interlocked.Increment(ref _connections);
_ = Task.Run(async () =>
{
using (client)
{
var stream = client.GetStream();
var buffer = new byte[4096];
try { await stream.ReadAsync(buffer); } catch { return; }
var answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"u8.ToArray();
await stream.WriteAsync(answer);
}
});
}
}
public void Dispose() => _listener.Stop();
}
private static ClientChosenAddressHandler.Resolver Answers(params string[] addresses) =>
(_, _) => Task.FromResult(addresses.Select(IPAddress.Parse).ToArray());
[Fact]
public async Task A_name_that_resolves_to_loopback_at_connection_time_is_refused()
{
using var server = new CountingServer();
// The guard's pre-check would have seen a public address for this name; the connection resolves it again here
// and gets loopback, as a rebinding name would answer.
using var http = new HttpClient(ClientChosenAddressHandler.Create(false, Answers("127.0.0.1")));
var act = () => http.GetAsync($"http://rebind.test:{server.Port}/jwks");
(await act.Should().ThrowAsync()).Which.ToString().Should().Contain("non-public");
await Task.Delay(50);
server.Connections.Should().Be(0);
}
[Fact]
public async Task With_private_targets_allowed_the_approved_address_is_connected()
{
using var server = new CountingServer();
using var http = new HttpClient(ClientChosenAddressHandler.Create(true, Answers("127.0.0.1")));
var response = await http.GetAsync($"http://keys.test:{server.Port}/jwks");
response.StatusCode.Should().Be(HttpStatusCode.OK);
server.Connections.Should().Be(1);
}
[Fact]
public async Task Approved_addresses_are_tried_in_order_until_one_connects()
{
using var server = new CountingServer();
// ::1 has nothing listening on that port (the server binds IPv4 loopback only), so it is refused first.
using var http = new HttpClient(ClientChosenAddressHandler.Create(true, Answers("::1", "127.0.0.1")));
var response = await http.GetAsync($"http://dual.test:{server.Port}/jwks");
response.StatusCode.Should().Be(HttpStatusCode.OK);
server.Connections.Should().Be(1);
}
[Theory]
[InlineData("::ffff:127.0.0.1")]
[InlineData("203.0.113.10", "::ffff:10.0.0.1")] // one non-public answer refuses the name
[InlineData("203.0.113.10", "169.254.169.254")]
public async Task Mapped_and_mixed_answers_get_the_guard_rule(params string[] answers)
{
using var http = new HttpClient(ClientChosenAddressHandler.Create(false, Answers(answers)));
var act = () => http.GetAsync("http://mixed.test:9/jwks");
(await act.Should().ThrowAsync()).Which.ToString().Should().Contain("non-public");
}
[Fact]
public async Task A_literal_loopback_address_is_refused_without_resolution()
{
var resolved = false;
using var http = new HttpClient(ClientChosenAddressHandler.Create(false, (_, _) => { resolved = true; return Task.FromResult(Array.Empty()); }));
var act = () => http.GetAsync("http://127.0.0.1:9/jwks");
await act.Should().ThrowAsync();
resolved.Should().BeFalse();
}
[Fact]
public async Task A_proxy_endpoint_is_not_subject_to_the_address_rule()
{
using var proxy = new CountingServer();
var handler = ClientChosenAddressHandler.Create(false, Answers("127.0.0.1"));
handler.Proxy = new WebProxy($"http://127.0.0.1:{proxy.Port}");
handler.UseProxy = true;
using var http = new HttpClient(handler);
// The target is not resolved by Identity here: the proxy (on loopback, as proxies often are on private
// addresses) receives the request and its policy decides where it goes.
var response = await http.GetAsync("http://target.test/jwks");
response.StatusCode.Should().Be(HttpStatusCode.OK);
proxy.Connections.Should().Be(1);
}
[Theory]
[InlineData("loopback.test.")] // trailing dot
[InlineData("LOOPBACK.TEST")] // upper case
public async Task Other_spellings_of_a_name_that_resolves_to_loopback_are_refused(string host)
{
using var server = new CountingServer();
using var http = new HttpClient(ClientChosenAddressHandler.Create(false, Answers("127.0.0.1")));
var act = () => http.GetAsync($"http://{host}:{server.Port}/jwks");
await act.Should().ThrowAsync();
await Task.Delay(50);
server.Connections.Should().Be(0);
}
[Fact]
public async Task With_a_proxy_configured_a_bypassed_host_is_checked_as_the_target()
{
using var proxy = new CountingServer();
using var target = new CountingServer();
var handler = ClientChosenAddressHandler.Create(false, Answers("127.0.0.1"));
handler.Proxy = new WebProxy($"http://127.0.0.1:{proxy.Port}", BypassOnLocal: false, BypassList: [@"bypassed\.test"]);
handler.UseProxy = true;
using var http = new HttpClient(handler);
var act = () => http.GetAsync($"http://bypassed.test:{target.Port}/jwks");
await act.Should().ThrowAsync();
await Task.Delay(50);
target.Connections.Should().Be(0);
proxy.Connections.Should().Be(0);
}
[Fact]
public async Task The_connect_phase_ends_at_the_client_timeout()
{
// 203.0.113.10 (TEST-NET-3) is not routed: the connect either hangs until the timeout or fails at once.
using var http = new HttpClient(ClientChosenAddressHandler.Create(false, Answers("203.0.113.10")))
{
Timeout = TimeSpan.FromMilliseconds(300),
};
var started = DateTime.UtcNow;
var act = () => http.GetAsync("http://unroutable.test:81/jwks");
await act.Should().ThrowAsync().Where(e => e is TaskCanceledException || e is HttpRequestException);
(DateTime.UtcNow - started).Should().BeLessThan(TimeSpan.FromSeconds(5));
}
}