Files
Chronos/tests/Titano.Data.Tests/Postgres/PgWireTests.cs
T
Claude ec247a96e1 test(data): PostgreSQL MD5, cleartext, trust and TLS tests can run, and must where TLS is set up
BRIEF §6.3 requires every authentication method and TLS mode against the
PostgreSQL service containers, but the MD5, cleartext and trust tests always
skipped in CI (no roles) and the TLS tests skipped at run time because the
official images start with TLS off. .github/scripts/postgres-ci-setup.sh prepares
a server container: a role per method with its pg_hba line ahead of the image's
SCRAM line (the MD5 password stored as MD5), and TLS with a self-signed
certificate for localhost and 127.0.0.1, enabled with ALTER SYSTEM and a reload
whose rejected lines fail the script. With TITANO_TEST_PG_TLS=1 a server that
refuses TLS fails the TLS tests instead of skipping them, and a new test checks
that verify-full accepts the server whose certificate chains to
TITANO_TEST_PG_ROOT_CERT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 10:06:10 +00:00

324 lines
16 KiB
C#

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Security.Authentication;
using Titano.Data.Postgres;
using Titano.Data.Tests.Infrastructure;
using Titano.Testing;
namespace Titano.Data.Tests.Postgres;
/// <summary>
/// Protocol-level tests against a live server (TITANO_TEST_PG). Optional: TITANO_TEST_PG_MD5/_CLEARTEXT/_TRUST (roles
/// of the other authentication methods), TITANO_TEST_PG_TLS=1 (the server offers TLS) and TITANO_TEST_PG_ROOT_CERT (the
/// PEM its certificate chains to). CI sets them all up (.github/scripts/postgres-ci-setup.sh).
/// </summary>
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PgWireTests(TestContext context) : DatabaseTest(context)
{
protected override Backend Backend => Backend.Postgres;
private async Task<PostgresDatabase> OpenAsync(string? extra = null) =>
(PostgresDatabase)Own(DatabaseFactory.Open(await NewOptionsAsync(extraPostgres: extra)));
/// <summary>A server without TLS skips the TLS tests, unless it was set up with TLS (<see cref="PgTestServer.TlsVariable"/>).</summary>
[DoesNotReturn]
private static void WithoutTls(DatabaseConnectionException refusal)
{
if (PgTestServer.TlsExpected) Assert.Fail($"{PgTestServer.TlsVariable} says the server offers TLS, but it refused: {refusal.Message}");
TestContext.Skip("server has no TLS");
}
private async Task<string> AuthenticateAsync(string connectionString)
{
var database = Own(new PostgresDatabase(PostgresSettings.Parse(connectionString)));
await using var session = await database.OpenAsync(Ct);
return (await session.ScalarAsync<string>("SELECT current_user", [], Ct))!;
}
[Test]
public async Task ScramSha256Login()
{
var settings = PostgresSettings.Parse(PgTestServer.ConnectionString);
Assert.Equal(settings.Username, await AuthenticateAsync(PgTestServer.ConnectionString));
}
[Test]
public async Task Md5Login() =>
Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("TITANO_TEST_PG_MD5")));
[Test]
public async Task CleartextLogin() =>
Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("TITANO_TEST_PG_CLEARTEXT")));
[Test]
public async Task TrustLogin() =>
Assert.NotNull(await AuthenticateAsync(PgTestServer.Optional("TITANO_TEST_PG_TRUST")));
[Test]
public async Task WrongPasswordIsRejected()
{
var wrong = PgTestServer.With(PgTestServer.ConnectionString, "Password=definitely-wrong");
var error = await Assert.ThrowsAsync<PostgresException>(() => AuthenticateAsync(wrong));
Assert.Equal("28P01", error.SqlState);
Assert.Equal("FATAL", error.Severity);
}
[Test]
public async Task TlsIsNegotiatedWhenRequired()
{
PostgresDatabase database;
try
{
database = await OpenAsync("SslMode=Require");
await using var probe = await database.OpenAsync(Ct);
}
catch (DatabaseConnectionException ex) when (ex.Message.Contains("does not support TLS", StringComparison.Ordinal))
{
WithoutTls(ex);
return;
}
await using var session = await database.OpenAsync(Ct);
Assert.True(await session.ScalarAsync<bool>("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()", [], Ct));
var plain = await OpenAsync("SslMode=Disable");
await using var plainSession = await plain.OpenAsync(Ct);
Assert.False(await plainSession.ScalarAsync<bool>("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()", [], Ct));
}
[Test]
public async Task VerifyFullRejectsAnUntrustedCertificate()
{
var database = await OpenAsync("SslMode=VerifyFull");
try
{
await using var session = await database.OpenAsync(Ct);
Assert.Fail("A self-signed server certificate must not pass verify-full.");
}
catch (DatabaseConnectionException ex) when (ex.Message.Contains("does not support TLS", StringComparison.Ordinal))
{
WithoutTls(ex);
}
catch (AuthenticationException)
{
}
}
[Test]
public async Task VerifyFullAcceptsACertificateThatChainsToTheConfiguredRoot()
{
var root = PgTestServer.Optional("TITANO_TEST_PG_ROOT_CERT");
var database = await OpenAsync($"SslMode=VerifyFull;Root Certificate={root}");
await using var session = await database.OpenAsync(Ct);
Assert.True(await session.ScalarAsync<bool>("SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()", [], Ct));
}
[Test]
public async Task DecodesEveryMappedResultType()
{
await using var session = await (await OpenAsync()).OpenAsync(Ct);
var row = await session.QuerySingleAsync(
"SELECT 'txt'::text, 'vc'::varchar(5), 'bp'::bpchar(4), 7::int2, -8::int4, 9000000000::int8, 1.5::float4, " +
"-2.25::float8, 'Infinity'::float8, true, '\\x00ff10'::bytea, '2026-09-28 18:30:15.123456+02'::timestamptz, " +
"'2024-02-29 23:59:58.5'::timestamp, '2026-01-31'::date, '0190a8b4-5c4e-7a1b-9c3d-0123456789ab'::uuid, " +
"'{\"k\": 1}'::json, '{\"k\": [true]}'::jsonb, 12345678901234567890.123::numeric, NULL::int4", [], Ct);
Assert.Equal("txt", row.GetString(0));
Assert.Equal("vc", row.GetString(1));
Assert.Equal("bp ", row.GetString(2));
Assert.Equal(7, row.GetInt32(3));
Assert.Equal(-8, row.GetInt32(4));
Assert.Equal(9000000000L, row.GetInt64(5));
Assert.Equal(1.5, row.GetDouble(6));
Assert.Equal(-2.25, row.GetDouble(7));
Assert.Equal(double.PositiveInfinity, row.GetDouble(8));
Assert.True(row.GetBool(9));
Assert.BytesEqual(new byte[] { 0, 0xFF, 0x10 }, row.GetBytes(10));
Assert.Equal(new DateTimeOffset(2026, 9, 28, 16, 30, 15, 123, TimeSpan.Zero).AddTicks(4560), row.GetDateTimeOffset(11));
Assert.Equal(new DateTime(2024, 2, 29, 23, 59, 58, 500), row.GetDateTime(12));
Assert.Equal(new DateTime(2026, 1, 31), row.GetDateTime(13));
Assert.Equal(Guid.Parse("0190a8b4-5c4e-7a1b-9c3d-0123456789ab"), row.GetGuid(14));
Assert.Equal("{\"k\": 1}", row.GetString(15));
Assert.Equal("{\"k\": [true]}", row.GetString(16));
Assert.Equal("12345678901234567890.123", row.GetString(17));
Assert.True(row.IsNull(18));
}
[Test]
public async Task ByteaTravelsInBinary()
{
await using var session = await (await OpenAsync()).OpenAsync(Ct);
await session.ExecuteScriptAsync("CREATE TABLE blobs (id integer PRIMARY KEY, data bytea)", Ct);
var all = Enumerable.Range(0, 256).Select(i => (byte)i).ToArray();
var large = new byte[1 << 20];
new Random(7).NextBytes(large);
await session.ExecuteAsync("INSERT INTO blobs VALUES ($1, $2), ($3, $4), ($5, $6)", [1, all, 2, large, 3, Array.Empty<byte>()], Ct);
var readAll = await session.ScalarAsync<byte[]>("SELECT data FROM blobs WHERE id = 1", [], Ct);
var readLarge = await session.ScalarAsync<byte[]>("SELECT data FROM blobs WHERE id = 2", [], Ct);
Assert.BytesEqual(all, readAll);
Assert.BytesEqual(large, readLarge);
Assert.Equal(0, (await session.ScalarAsync<byte[]>("SELECT data FROM blobs WHERE id = 3", [], Ct))!.Length);
Assert.Equal(1L << 20, await session.ScalarAsync<long>("SELECT length(data) FROM blobs WHERE id = $1", [2], Ct));
}
[Test]
public async Task ListenReceivesNotifications()
{
var database = await OpenAsync();
var listener = Own(await database.CreateListenerAsync(Ct));
var received = new TaskCompletionSource<PgNotification>(TaskCreationOptions.RunContinuationsAsynchronously);
listener.Notification += (_, n) => received.TrySetResult(n);
await listener.ListenAsync("titano_jobs", Ct);
await using (var session = await database.OpenAsync(Ct))
await session.ExecuteAsync("SELECT pg_notify($1, $2)", ["titano_jobs", "wake ✓"], Ct);
var notification = await received.Task.WaitAsync(TimeSpan.FromSeconds(5), Ct);
Assert.Equal("titano_jobs", notification.Channel);
Assert.Equal("wake ✓", notification.Payload);
await listener.UnlistenAsync("titano_jobs", Ct);
await Assert.ThrowsAsync<PostgresException>(() => listener.ListenAsync("", Ct));
await listener.ListenAsync("still_usable", Ct);
}
[Test]
public async Task ServerErrorsMapToTypedExceptions()
{
await using var session = await (await OpenAsync()).OpenAsync(Ct);
await session.ExecuteScriptAsync("CREATE TABLE u (id integer PRIMARY KEY, code text CONSTRAINT u_code_key UNIQUE)", Ct);
await session.ExecuteAsync("INSERT INTO u VALUES ($1, $2)", [1, "a"], Ct);
var unique = await Assert.ThrowsAsync<PostgresException>(() => session.ExecuteAsync("INSERT INTO u VALUES ($1, $2)", [2, "a"], Ct));
Assert.Equal("23505", unique.SqlState);
Assert.Equal("ERROR", unique.Severity);
Assert.Equal("u_code_key", unique.ConstraintName);
Assert.Equal("u", unique.TableName);
Assert.NotNull(unique.Detail);
Assert.True(unique.IsUniqueViolation);
var syntax = await Assert.ThrowsAsync<PostgresException>(() => session.ExecuteAsync("SELECT * FROM u WHER id = 1", [], Ct));
Assert.Equal("42601", syntax.SqlState);
Assert.Equal(22, syntax.Position);
Assert.Equal(1, await session.ScalarAsync<int>("SELECT 1", [], Ct));
}
[Test]
public async Task CommitOfAnAbortedTransactionThrows()
{
await using var session = await (await OpenAsync()).OpenAsync(Ct);
await session.ExecuteScriptAsync("CREATE TABLE a (id integer PRIMARY KEY)", Ct);
var tx = await session.BeginAsync(Ct);
await session.ExecuteAsync("INSERT INTO a VALUES ($1)", [1], Ct);
await Assert.ThrowsAsync<PostgresException>(() => session.ExecuteAsync("INSERT INTO a VALUES ($1)", [1], Ct));
await Assert.ThrowsAsync<InvalidOperationException>(() => tx.CommitAsync(Ct));
Assert.False(session.InTransaction);
Assert.Equal(0L, await session.ScalarAsync<long>("SELECT count(*) FROM a", [], Ct));
}
[Test]
public async Task PoolReusesConnectionsAndHandsOutDistinctOnesConcurrently()
{
var database = await OpenAsync("Maximum Pool Size=3;Timeout=2");
int first;
await using (var s = await database.OpenAsync(Ct)) first = await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct);
await using (var s = await database.OpenAsync(Ct)) Assert.Equal(first, await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct));
var sessions = new List<IDbSession>();
for (var i = 0; i < 3; i++) sessions.Add(await database.OpenAsync(Ct));
var pids = new HashSet<int>();
foreach (var s in sessions) pids.Add(await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct));
Assert.Equal(3, pids.Count);
var watch = Stopwatch.StartNew();
await Assert.ThrowsAsync<DatabaseConnectionException>(() => database.OpenAsync(Ct));
Assert.InRange(watch.Elapsed.TotalSeconds, 1.5, 5);
foreach (var s in sessions) await s.DisposeAsync();
}
[Test]
public async Task ReadsRecoverFromATerminatedBackend()
{
var database = await OpenAsync("Maximum Pool Size=2");
int victim;
await using (var s = await database.OpenAsync(Ct)) victim = await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct);
var killer = Own(new PostgresDatabase(PostgresSettings.Parse(PgTestServer.ConnectionString)));
await using (var k = await killer.OpenAsync(Ct))
Assert.True(await k.ScalarAsync<bool>("SELECT pg_terminate_backend($1)", [victim], Ct));
await Task.Delay(200, Ct);
await using (var s = await database.OpenAsync(Ct))
{
var pid = await s.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct);
Assert.NotEqual(victim, pid);
Assert.Equal(2, await s.ScalarAsync<int>("SELECT 1 + 1", [], Ct));
}
}
[Test]
public async Task WritesOnABrokenConnectionFailWithoutRetry()
{
var database = await OpenAsync("Maximum Pool Size=1");
await using var session = await database.OpenAsync(Ct);
await session.ExecuteScriptAsync("CREATE TABLE w (id integer)", Ct);
var pid = await session.ScalarAsync<int>("SELECT pg_backend_pid()", [], Ct);
var killer = Own(new PostgresDatabase(PostgresSettings.Parse(PgTestServer.ConnectionString)));
await using (var k = await killer.OpenAsync(Ct)) await k.ExecuteAsync("SELECT pg_terminate_backend($1)", [pid], Ct);
await Task.Delay(200, Ct);
var error = await Assert.ThrowsAsync<DatabaseException>(() => session.ExecuteAsync("INSERT INTO w VALUES ($1)", [1], Ct));
Assert.True(error.IsTransient);
}
[Test]
public async Task StatementCacheEvictsAndSurvivesSchemaChanges()
{
await using var session = await (await OpenAsync("Statement Cache Size=2")).OpenAsync(Ct);
await session.ExecuteScriptAsync("CREATE TABLE c (a integer); INSERT INTO c VALUES (1)", Ct);
for (var i = 0; i < 5; i++) Assert.Equal(i, await session.ScalarAsync<int>($"SELECT {i} + 0 * $1", [i], Ct));
// Evicted statements are closed with the next command: the cache size plus the counting statement remain.
Assert.LessOrEqual(await session.ScalarAsync<long>("SELECT count(*) FROM pg_prepared_statements", [], Ct), 3);
var first = await session.QuerySingleAsync("SELECT * FROM c", [], Ct);
Assert.Equal(1, first.FieldCount);
await session.ExecuteScriptAsync("ALTER TABLE c ADD COLUMN b text DEFAULT 'x'", Ct);
var second = await session.QuerySingleAsync("SELECT * FROM c", [], Ct);
Assert.Equal(2, second.FieldCount);
Assert.Equal("x", second.GetString("b"));
}
[Test]
public async Task ACommandCannotStartWhileARowStreamIsOpen()
{
await using var session = await (await OpenAsync()).OpenAsync(Ct);
var rows = session.QueryAsync("SELECT generate_series(1, 1000)", [], Ct).GetAsyncEnumerator(Ct);
Assert.True(await rows.MoveNextAsync());
await Assert.ThrowsAsync<InvalidOperationException>(() => session.ExecuteAsync("SELECT 1", [], Ct));
await rows.DisposeAsync();
Assert.Equal(1, await session.ScalarAsync<int>("SELECT 1", [], Ct));
}
[Test]
public async Task DisposingABusySessionInATransactionFreesItsPoolSlot()
{
var database = await OpenAsync("Maximum Pool Size=1;Timeout=3");
var session = await database.OpenAsync(Ct);
await session.ExecuteScriptAsync("CREATE TABLE t (id integer)", Ct);
var tx = await session.BeginAsync(Ct);
await session.ExecuteAsync("INSERT INTO t VALUES ($1)", [1], Ct);
var rows = session.QueryAsync("SELECT generate_series(1, 1000)", [], Ct).GetAsyncEnumerator(Ct);
Assert.True(await rows.MoveNextAsync());
await tx.DisposeAsync();
Assert.True(session.InTransaction, "a busy session cannot roll back yet");
await session.DisposeAsync();
await using var next = await database.OpenAsync(Ct);
Assert.Equal(0L, await next.ScalarAsync<long>("SELECT count(*) FROM t", [], Ct));
}
[Test]
public async Task NoticesAndScriptsDoNotDisturbTheSession()
{
await using var session = await (await OpenAsync()).OpenAsync(Ct);
await session.ExecuteScriptAsync("DO $$ BEGIN RAISE NOTICE 'hello from the server'; END $$; CREATE TABLE n (id integer)", Ct);
Assert.Equal(1, await session.ExecuteAsync("INSERT INTO n VALUES ($1)", [1], Ct));
await Assert.ThrowsAsync<PostgresException>(() => session.ExecuteScriptAsync("SELECT 1; SELECT * FROM missing_table; SELECT 2", Ct));
Assert.Equal(1L, await session.ScalarAsync<long>("SELECT count(*) FROM n", [], Ct));
}
}