Skip to content
Merged
147 changes: 147 additions & 0 deletions API.IntegrationTests/Tests/DatabaseConstraintTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
using System.Net;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Npgsql;
using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.Common.Models;
using OpenShock.Common.OpenShockDb;

namespace OpenShock.API.IntegrationTests.Tests;

/// <summary>
/// Covers behaviour that lives in the database rather than in C#: the case-insensitive email collation, the
/// username blacklist query, the native audit log column types and the check constraints.
/// </summary>
public sealed class DatabaseConstraintTests
{
[ClassDataSource<WebApplicationFactory>(Shared = SharedType.PerTestSession)]
public required WebApplicationFactory WebApplicationFactory { get; init; }

[Test]
public async Task Email_LookupIgnoresCase()
{
var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, "dbemaillookup", "dbemaillookup@test.org", "SecurePassword123#");

await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();

var found = await db.Users.Where(u => u.Email == "DbEmailLookup@Test.ORG").Select(u => u.Id).ToListAsync();

await Assert.That(found).IsEquivalentTo([userId]);
}

[Test]
public async Task Email_UniquenessIgnoresCase()
{
await TestHelper.CreateUserInDb(WebApplicationFactory, "dbemailunique", "dbemailunique@test.org", "SecurePassword123#");

await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();

db.Users.Add(new User
{
Name = "dbemailunique2",
Email = "DBEMAILUNIQUE@test.org",
PasswordHash = null,
ActivatedAt = DateTime.UtcNow
});

var exception = await Assert.That(() => db.SaveChangesAsync()).Throws<DbUpdateException>();
await Assert.That((exception!.InnerException as PostgresException)?.SqlState).IsEqualTo(PostgresErrorCodes.UniqueViolation);
}

[Test]
public async Task UserNameBlacklist_MatchesExactAndContainedEntries()
{
await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();

var exact = new UserNameBlacklist { Value = "ZqxExactEntry", MatchType = MatchTypeEnum.Exact };
var contains = new UserNameBlacklist { Value = "Zqx_Part", MatchType = MatchTypeEnum.Contains };
var percent = new UserNameBlacklist { Value = "Zqx%Pct", MatchType = MatchTypeEnum.Contains };
// Ends in a sigma, which lower() would turn into a final ς that no longer matches the mid-word σ below
var sigma = new UserNameBlacklist { Value = "ΖΚΞΟΣ", MatchType = MatchTypeEnum.Contains };
// Precomposed é, matched below against e followed by a combining acute accent
var accent = new UserNameBlacklist { Value = "ZqxCaf\u00E9", MatchType = MatchTypeEnum.Contains };
db.UserNameBlacklists.AddRange(exact, contains, percent, sigma, accent);
await db.SaveChangesAsync();

try
{
async Task<Guid[]> Matching(string username) =>
await db.UserNameBlacklists.Matching(username).Select(x => x.Id).ToArrayAsync();

await Assert.That(await Matching("zqxexactentry")).IsEquivalentTo([exact.Id]);
// An exact entry is not a substring match
await Assert.That(await Matching("xzqxexactentryx")).IsEmpty();
await Assert.That(await Matching("some_ZQX_PART_name")).IsEquivalentTo([contains.Id]);
// The underscore in the entry is literal, not a single character wildcard
await Assert.That(await Matching("somezqxxpartname")).IsEmpty();
// The percent sign is literal too, not a wildcard
await Assert.That(await Matching("a_zqx%pct_b")).IsEquivalentTo([percent.Id]);
await Assert.That(await Matching("zqxanythingpct")).IsEmpty();
// Case folding is context independent, so the entry still matches as a prefix of a longer name
await Assert.That(await Matching("ΖΚΞΟΣΑ")).IsEquivalentTo([sigma.Id]);
await Assert.That(await Matching("ζκξοσα")).IsEquivalentTo([sigma.Id]);
// Canonically equivalent accents match whichever way they are written
await Assert.That(await Matching("xxZQXCAFE\u0301yy")).IsEquivalentTo([accent.Id]);
}
finally
{
Guid[] ids = [exact.Id, contains.Id, percent.Id, sigma.Id, accent.Id];
await db.UserNameBlacklists.Where(x => ids.Contains(x.Id)).ExecuteDeleteAsync();
}
}

[Test]
public async Task AuditLog_RoundTripsIpAddressAndMetadata()
{
var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, "dbauditroundtrip", "dbauditroundtrip@test.org", "SecurePassword123#");
var sessionId = Guid.CreateVersion7();
var ipAddress = IPAddress.Parse("2001:db8::1");

await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();

var entry = new UserAuditLog
{
UserId = userId,
ActorId = userId,
Action = AuditAction.Login,
IpAddress = ipAddress,
Metadata = new LoginMetadata(sessionId),
CreatedAt = DateTime.UtcNow
};
db.UserAuditLogs.Add(entry);
await db.SaveChangesAsync();

var stored = await db.UserAuditLogs.AsNoTracking().FirstAsync(x => x.Id == entry.Id);

await Assert.That(stored.IpAddress).IsEqualTo(ipAddress);
await Assert.That(stored.Metadata).IsEqualTo(new LoginMetadata(sessionId));
}

[Test]
public async Task ApiToken_RejectsControlLimitsOutOfRange()
{
var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, "dbtokenlimits", "dbtokenlimits@test.org", "SecurePassword123#");
var (tokenId, _) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId);

await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();

var aboveMaximum = await Assert.That(() => db.ApiTokens
.Where(t => t.Id == tokenId)
.ExecuteUpdateAsync(s => s.SetProperty(t => t.ShockerControlIntensityMax, (byte)101)))
.Throws<PostgresException>();
await Assert.That(aboveMaximum!.SqlState).IsEqualTo(PostgresErrorCodes.CheckViolation);

var minimumAboveMaximum = await Assert.That(() => db.ApiTokens
.Where(t => t.Id == tokenId)
.ExecuteUpdateAsync(s => s
.SetProperty(t => t.ShockerControlIntensityMin, (byte)60)
.SetProperty(t => t.ShockerControlIntensityMax, (byte)40)))
.Throws<PostgresException>();
await Assert.That(minimumAboveMaximum!.SqlState).IsEqualTo(PostgresErrorCodes.CheckViolation);
}
}
137 changes: 137 additions & 0 deletions API.IntegrationTests/Tests/EmailProviderBlacklistTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
using System.Net;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.Common.Models;
using OpenShock.Common.OpenShockDb;

namespace OpenShock.API.IntegrationTests.Tests;

/// <summary>
/// Covers adding to the email provider blacklist: entries are validated up front, so one bad line in a large
/// paste rejects the request instead of failing halfway, and the whole list goes to the database in one insert.
/// </summary>
public sealed class EmailProviderBlacklistTests
{
[ClassDataSource<WebApplicationFactory>(Shared = SharedType.PerTestSession)]
public required WebApplicationFactory WebApplicationFactory { get; init; }

[Test]
public async Task Add_NormalizesEntriesAndSkipsExisting(CancellationToken cancellationToken)
{
var suffix = Guid.NewGuid().ToString("N")[..12];
var first = $"zqx-{suffix}-a.example";
var second = $"zqx-{suffix}-b.example";
using var client = await CreateAdminClient("blacklistadd");

try
{
var response = await client.PostAsync("/1/admin/blacklist/emailProviders", TestHelper.JsonContent(new
{
// A full address, different case, a trailing dot, padding, blank lines and a repeat all fold together
domains = new[] { $"someone@{first.ToUpperInvariant()}", $" {first}. ", "", " ", second, second }
}), cancellationToken);

await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
using (var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken)))
{
await Assert.That(json.RootElement.GetProperty("submitted").GetInt32()).IsEqualTo(2);
await Assert.That(json.RootElement.GetProperty("added").GetInt32()).IsEqualTo(2);
}
// Adding again only reports the new one
var third = $"zqx-{suffix}-c.example";
var again = await client.PostAsync("/1/admin/blacklist/emailProviders",
TestHelper.JsonContent(new { domains = new[] { first, third } }), cancellationToken);
await Assert.That(again.StatusCode).IsEqualTo(HttpStatusCode.OK);
using (var json = JsonDocument.Parse(await again.Content.ReadAsStringAsync(cancellationToken)))
{
await Assert.That(json.RootElement.GetProperty("added").GetInt32()).IsEqualTo(1);
await Assert.That(json.RootElement.GetProperty("alreadyListed").GetInt32()).IsEqualTo(1);
}

await Assert.That(await ListedDomains(suffix)).IsEquivalentTo([first, second, third]);
}
finally
{
await DeleteDomains(suffix);
}
}

[Test]
public async Task Add_WithAnyInvalidEntry_AddsNothing(CancellationToken cancellationToken)
{
var suffix = Guid.NewGuid().ToString("N")[..12];
using var client = await CreateAdminClient("blacklistinvalid");
string[] invalid = ["localhost", "127.0.0.1", "not a domain", "@", new string('a', 250) + ".example", "under_score.example", "-leading.example", "trailing-.example", "double..dot.example", "two-dots.example..", "user@", "1.2.3.4", "münchen.example"];

try
{
var response = await client.PostAsync("/1/admin/blacklist/emailProviders", TestHelper.JsonContent(new
{
domains = invalid.Prepend($"zqx-{suffix}-valid.example").ToArray()
}), cancellationToken);

await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest);
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken));
await Assert.That(json.RootElement.GetProperty("invalidCount").GetInt32()).IsEqualTo(invalid.Length);
var echoed = json.RootElement.GetProperty("invalidEntries").EnumerateArray().Select(x => x.GetString()!).ToArray();
await Assert.That(echoed).IsEquivalentTo(invalid);

await Assert.That(await ListedDomains(suffix)).IsEmpty();
}
finally
{
await DeleteDomains(suffix);
}
}

[Test]
public async Task Add_TensOfThousandsInOneRequest(CancellationToken cancellationToken)
{
var suffix = Guid.NewGuid().ToString("N")[..12];
using var client = await CreateAdminClient("blacklistbulk");
var domains = Enumerable.Range(0, 50_000).Select(i => $"zqx-{suffix}-{i}.example").ToArray();

try
{
var response = await client.PostAsync("/1/admin/blacklist/emailProviders",
TestHelper.JsonContent(new { domains }), cancellationToken);

await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken));
await Assert.That(json.RootElement.GetProperty("added").GetInt32()).IsEqualTo(domains.Length);
}
finally
{
await DeleteDomains(suffix);
}
}

private async Task<string[]> ListedDomains(string suffix)
{
await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();
var prefix = $"zqx-{suffix}-";
return await db.EmailProviderBlacklists.Where(x => x.Domain.StartsWith(prefix)).Select(x => x.Domain).ToArrayAsync();
}

private async Task DeleteDomains(string suffix)
{
await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();
var prefix = $"zqx-{suffix}-";
await db.EmailProviderBlacklists.Where(x => x.Domain.StartsWith(prefix)).ExecuteDeleteAsync();
}

private async Task<HttpClient> CreateAdminClient(string prefix)
{
var admin = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername(prefix), TestHelper.UniqueEmail(prefix), "SecurePassword123#");

await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();
await db.Users.Where(u => u.Id == admin.Id).ExecuteUpdateAsync(s => s.SetProperty(u => u.Roles, [RoleType.Admin]));

return TestHelper.CreateAuthenticatedClient(WebApplicationFactory, admin.SessionToken);
}
}
Loading