diff --git a/API.IntegrationTests/API.IntegrationTests.csproj b/API.IntegrationTests/API.IntegrationTests.csproj
index 0d4a377d..912fd637 100644
--- a/API.IntegrationTests/API.IntegrationTests.csproj
+++ b/API.IntegrationTests/API.IntegrationTests.csproj
@@ -1,6 +1,7 @@
+
@@ -12,17 +13,6 @@
-
-
-
-
-
-
-
- <_Parameter1>$(SourceRevisionId)
-
-
-
diff --git a/API.IntegrationTests/AssemblyAttributes.cs b/API.IntegrationTests/AssemblyAttributes.cs
index b906e50c..967ee3e3 100644
--- a/API.IntegrationTests/AssemblyAttributes.cs
+++ b/API.IntegrationTests/AssemblyAttributes.cs
@@ -1,10 +1,10 @@
using OpenShock.API.IntegrationTests;
+using OpenShock.IntegrationTests.Shared;
using TUnit.Core.Interfaces;
-// Allow up to 5 minutes per test — integration tests can be slow in CI when Docker images
-// are cold-pulled and EF migrations run for the first time. The execution timer in TUnit
-// may include class-data-source initialization time for the first test that uses the factory.
-[assembly: Timeout(5 * 60_000)]
+// The containers are started (and images pulled) by the session hook below, not by the first test, so this
+// only has to cover a test's own work, including the first boot of a shared host.
+[assembly: Timeout(120_000)]
// Limit parallel test execution to avoid thread pool starvation on CI runners.
// BCrypt password hashing in login/signup endpoints is synchronous and CPU-bound;
@@ -18,7 +18,7 @@ public sealed record CiSafeParallelLimit : IParallelLimit
public int Limit => Math.Max(Environment.ProcessorCount * 2, 8);
}
-public static class ThreadPoolSetup
+public static class TestSessionSetup
{
// Running tests block on the shared host's boot, which connects to Redis synchronously and needs a free thread
[Before(TestSession)]
@@ -27,4 +27,10 @@ public static void RaiseMinThreads()
ThreadPool.GetMinThreads(out var workerThreads, out var completionPortThreads);
ThreadPool.SetMinThreads(Math.Max(workerThreads, new CiSafeParallelLimit().Limit * 2), completionPortThreads);
}
+
+ // Cold image pulls and the first migration run can take minutes on CI
+ [Before(TestSession)]
+ [Timeout(15 * 60_000)]
+ public static Task WarmUpContainers(CancellationToken cancellationToken) =>
+ Task.WhenAll(PostgresFixture.WarmUpAsync(), RedisFixture.WarmUpAsync()).WaitAsync(cancellationToken);
}
diff --git a/API.IntegrationTests/Docker/DockerNetwork.cs b/API.IntegrationTests/Docker/DockerNetwork.cs
deleted file mode 100644
index 412e5f82..00000000
--- a/API.IntegrationTests/Docker/DockerNetwork.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-using DotNet.Testcontainers.Builders;
-using DotNet.Testcontainers.Networks;
-using TUnit.Core.Interfaces;
-
-namespace OpenShock.API.IntegrationTests.Docker;
-
-public sealed class DockerNetwork : IAsyncInitializer, IAsyncDisposable
-{
- public INetwork Instance { get; } = new NetworkBuilder()
- .WithName($"tunit-{Guid.CreateVersion7():N}")
- .Build();
-
- public Task InitializeAsync() => Instance.CreateAsync();
- public ValueTask DisposeAsync() => Instance.DisposeAsync();
-}
diff --git a/API.IntegrationTests/Docker/InMemoryDatabase.cs b/API.IntegrationTests/Docker/InMemoryDatabase.cs
deleted file mode 100644
index 1ae0c5d4..00000000
--- a/API.IntegrationTests/Docker/InMemoryDatabase.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.Logging.Abstractions;
-using OpenShock.Common.OpenShockDb;
-using OpenShock.Internal.Common.Utils;
-using Testcontainers.PostgreSql;
-using TUnit.Core.Interfaces;
-
-namespace OpenShock.API.IntegrationTests.Docker;
-
-public sealed class InMemoryDatabase : IAsyncInitializer, IAsyncDisposable
-{
- [ClassDataSource(Shared = SharedType.PerTestSession)]
- public required DockerNetwork DockerNetwork { get; init; }
-
- private PostgreSqlContainer? _container;
- public PostgreSqlContainer Container
- {
- get
- {
- _container ??= new PostgreSqlBuilder(image: "timescale/timescaledb:latest-pg18") // Community edition, the schema needs it
- .WithNetwork(DockerNetwork.Instance)
- .WithName($"tunit-postgresql-{Guid.CreateVersion7()}")
- .WithDatabase("openshock")
- .WithUsername("openshock")
- .WithPassword(CryptoUtils.RandomString(32))
- .Build();
-
- return _container;
- }
- }
-
- ///
- /// Starts the container and brings the schema up to date. Migrations are applied here, once per
- /// test session, rather than by the API hosts on boot: several
- /// variants share this one database, and each boots its own host. EF's migrator is not safe to run
- /// concurrently against the same database, so letting each host migrate on startup races - two
- /// migrators both see the same pending migrations and both apply them, which fails with
- /// "type/relation/collation already exists", a duplicate key on __EFMigrationsHistory, or queries
- /// hitting a half-migrated schema. The factories set OPENSHOCK__DB__SKIPMIGRATION so this is the
- /// only migrator, matching how Cron.IntegrationTests already seeds its schema.
- ///
- public async Task InitializeAsync()
- {
- await Container.StartAsync();
-
- await using var migrationContext = new MigrationOpenShockContext(
- Container.GetConnectionString(), false, NullLoggerFactory.Instance);
- await migrationContext.Database.MigrateAsync();
- }
-
- public ValueTask DisposeAsync() => Container.DisposeAsync();
-}
diff --git a/API.IntegrationTests/Docker/InMemoryRedis.cs b/API.IntegrationTests/Docker/InMemoryRedis.cs
deleted file mode 100644
index 7671f675..00000000
--- a/API.IntegrationTests/Docker/InMemoryRedis.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-using Testcontainers.Redis;
-using TUnit.Core.Interfaces;
-
-namespace OpenShock.API.IntegrationTests.Docker;
-
-public sealed class InMemoryRedis : IAsyncInitializer, IAsyncDisposable
-{
- [ClassDataSource(Shared = SharedType.PerTestSession)]
- public required DockerNetwork DockerNetwork { get; init; }
-
- private RedisContainer? _container;
- public RedisContainer Container
- {
- get
- {
- _container ??= new RedisBuilder(image: "ghcr.io/dragonflydb/dragonfly:latest") // Same store as the compose stacks
- .WithCommand("--notify_keyspace_events=Ex")
- .WithNetwork(DockerNetwork.Instance)
- .WithName($"tunit-redis-{Guid.CreateVersion7()}")
- .Build();
-
- return _container;
- }
- }
-
- public Task InitializeAsync() => Container.StartAsync();
- public ValueTask DisposeAsync() => Container.DisposeAsync();
-}
diff --git a/API.IntegrationTests/GeoLocatedWebApplicationFactory.cs b/API.IntegrationTests/GeoLocatedWebApplicationFactory.cs
deleted file mode 100644
index 39bf8117..00000000
--- a/API.IntegrationTests/GeoLocatedWebApplicationFactory.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-using System.Net;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.TestHost;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.DependencyInjection.Extensions;
-using OpenShock.Common.Services.Geo;
-
-namespace OpenShock.API.IntegrationTests;
-
-///
-/// Variant of whose GeoIP lookup resolves every request to
-/// , so tests can place the caller without shipping a GeoLite2 database.
-///
-public sealed class GeoLocatedWebApplicationFactory : WebApplicationFactory
-{
- private readonly FakeIpEnrichmentService _enrichment = new();
-
- public GeoPoint? ClientLocation
- {
- get => _enrichment.Location;
- set => _enrichment.Location = value;
- }
-
- /// Country every request resolves to, or null for "unknown".
- public string? ClientCountryCode
- {
- get => _enrichment.CountryCode;
- set => _enrichment.CountryCode = value;
- }
-
- protected override void ConfigureWebHost(IWebHostBuilder builder)
- {
- base.ConfigureWebHost(builder);
-
- builder.ConfigureTestServices(services =>
- {
- services.RemoveAll();
- services.AddSingleton(_enrichment);
- });
- }
-
- private sealed class FakeIpEnrichmentService : IIpEnrichmentService
- {
- public GeoPoint? Location { get; set; }
- public string? CountryCode { get; set; }
-
- public IpEnrichmentData? Enrich(IPAddress ip) =>
- Location is null && CountryCode is null
- ? null
- : new IpEnrichmentData(null, null, null, CountryCode, null, Location, Location is null ? null : 20);
- }
-}
diff --git a/API.IntegrationTests/HeaderIpEnrichmentService.cs b/API.IntegrationTests/HeaderIpEnrichmentService.cs
new file mode 100644
index 00000000..5cabb881
--- /dev/null
+++ b/API.IntegrationTests/HeaderIpEnrichmentService.cs
@@ -0,0 +1,70 @@
+using System.Globalization;
+using System.Net;
+using Microsoft.AspNetCore.Http;
+using OpenShock.Common.Services.Geo;
+
+namespace OpenShock.API.IntegrationTests;
+
+///
+/// Stands in for the GeoIP lookup in the test host: a request is placed wherever its test-only headers say, and
+/// resolves to nothing without them, as production does without GeoLite2 databases. Every caller enriches the
+/// address of the request it is handling, so reading that request's headers is equivalent. Only registered by
+/// ; production never looks at these headers.
+///
+public sealed class HeaderIpEnrichmentService : IIpEnrichmentService
+{
+ /// Alpha-2 country the request resolves to.
+ public const string CountryHeader = "X-Test-Client-Country";
+
+ /// Location the request resolves to, as latitude,longitude in invariant culture.
+ public const string LocationHeader = "X-Test-Client-Location";
+
+ private readonly IHttpContextAccessor _httpContextAccessor;
+
+ public HeaderIpEnrichmentService(IHttpContextAccessor httpContextAccessor)
+ {
+ _httpContextAccessor = httpContextAccessor;
+ }
+
+ public IpEnrichmentData? Enrich(IPAddress ip)
+ {
+ var headers = _httpContextAccessor.HttpContext?.Request.Headers;
+ if (headers is null) return null;
+
+ var countryCode = headers.TryGetValue(CountryHeader, out var country) ? country.ToString() : null;
+ var location = headers.TryGetValue(LocationHeader, out var raw) ? ParseLocation(raw.ToString()) : null;
+
+ return countryCode is null && location is null
+ ? null
+ : new IpEnrichmentData(null, null, null, countryCode, null, location, location is null ? null : 20);
+ }
+
+ /// Places every request sends; null leaves that part unresolved.
+ public static HttpClient Place(HttpClient client, string? countryCode = null, GeoPoint? location = null)
+ {
+ if (countryCode is not null) client.DefaultRequestHeaders.Add(CountryHeader, countryCode);
+ if (location is { } point) client.DefaultRequestHeaders.Add(LocationHeader, Format(point));
+ return client;
+ }
+
+ /// Places a single request; null leaves that part unresolved.
+ public static HttpRequestMessage Place(HttpRequestMessage request, string? countryCode = null, GeoPoint? location = null)
+ {
+ if (countryCode is not null) request.Headers.Add(CountryHeader, countryCode);
+ if (location is { } point) request.Headers.Add(LocationHeader, Format(point));
+ return request;
+ }
+
+ private static string Format(GeoPoint point) =>
+ string.Create(CultureInfo.InvariantCulture, $"{point.Latitude},{point.Longitude}");
+
+ private static GeoPoint? ParseLocation(string value)
+ {
+ var parts = value.Split(',');
+ if (parts.Length != 2) throw new FormatException($"{LocationHeader} must be latitude,longitude, got '{value}'");
+
+ return new GeoPoint(
+ double.Parse(parts[0], CultureInfo.InvariantCulture),
+ double.Parse(parts[1], CultureInfo.InvariantCulture));
+ }
+}
diff --git a/API.IntegrationTests/Helpers/OAuthFlowCookieHelper.cs b/API.IntegrationTests/Helpers/OAuthFlowCookieHelper.cs
new file mode 100644
index 00000000..263a6a34
--- /dev/null
+++ b/API.IntegrationTests/Helpers/OAuthFlowCookieHelper.cs
@@ -0,0 +1,42 @@
+using System.Security.Claims;
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.AspNetCore.Authentication.Cookies;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Options;
+using OpenShock.API.OAuth;
+
+namespace OpenShock.API.IntegrationTests.Helpers;
+
+///
+/// There is no provider to talk to in tests. What the provider round trip leaves behind is the flow cookie, a
+/// ticket holding the provider's claims and the properties the flow was started with, so tests mint it the way
+/// the callback would.
+///
+public static class OAuthFlowCookieHelper
+{
+ public static string Mint(WebApplicationFactory factory, string provider, string externalId, string? email = null,
+ bool emailVerified = false, OAuthFlow flow = OAuthFlow.LoginOrCreate)
+ {
+ var options = factory.Services.GetRequiredService>().Get(OAuthConstants.FlowScheme);
+
+ List claims =
+ [
+ new(ClaimTypes.NameIdentifier, externalId),
+ new(ClaimTypes.Name, "external-" + externalId[..8])
+ ];
+ if (email is not null) claims.Add(new Claim(ClaimTypes.Email, email));
+ if (emailVerified) claims.Add(new Claim(OAuthConstants.ClaimEmailVerified, "true"));
+
+ var properties = new AuthenticationProperties
+ {
+ IssuedUtc = DateTimeOffset.UtcNow,
+ ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10)
+ };
+ properties.Items[".AuthScheme"] = provider;
+ OAuthUtil.SetOAuthFlow(properties, flow);
+
+ var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims, provider)), properties, OAuthConstants.FlowScheme);
+
+ return $"{options.Cookie.Name}={options.TicketDataFormat.Protect(ticket)}";
+ }
+}
diff --git a/API.IntegrationTests/Helpers/TestHelper.cs b/API.IntegrationTests/Helpers/TestHelper.cs
index 4becab7a..875517ce 100644
--- a/API.IntegrationTests/Helpers/TestHelper.cs
+++ b/API.IntegrationTests/Helpers/TestHelper.cs
@@ -8,6 +8,7 @@
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Services.Session;
using OpenShock.Common.Utils;
+using OpenShock.IntegrationTests.Shared;
using OpenShock.Internal.Common.Utils;
namespace OpenShock.API.IntegrationTests.Helpers;
@@ -172,26 +173,6 @@ public static StringContent JsonContent(object obj)
{
return new StringContent(JsonSerializer.Serialize(obj, JsonOptions), Encoding.UTF8, "application/json");
}
-
- ///
- /// Generates a unique recipient address so per-test Mailpit lookups never collide with other
- /// tests' emails. Format: {prefix}-{8hex}@test.org.
- ///
- public static string UniqueEmail(string prefix)
- {
- var suffix = Guid.NewGuid().ToString("N")[..8];
- return $"{prefix}-{suffix}@test.org";
- }
-
- ///
- /// Generates a unique username so concurrent tests in the same session never collide on the
- /// users.name unique index.
- ///
- public static string UniqueUsername(string prefix)
- {
- var suffix = Guid.NewGuid().ToString("N")[..8];
- return ($"{prefix}{suffix}").ToLowerInvariant();
- }
}
public sealed record AuthenticatedUser(Guid Id, string Username, string Email, string SessionToken);
diff --git a/API.IntegrationTests/HttpMessageHandlers/InterceptedHttpMessageHandler.cs b/API.IntegrationTests/HttpMessageHandlers/InterceptedHttpMessageHandler.cs
index 6d21c268..19307f7d 100644
--- a/API.IntegrationTests/HttpMessageHandlers/InterceptedHttpMessageHandler.cs
+++ b/API.IntegrationTests/HttpMessageHandlers/InterceptedHttpMessageHandler.cs
@@ -8,13 +8,26 @@ namespace OpenShock.API.IntegrationTests.HttpMessageHandlers;
sealed class InterceptedHttpMessageHandler : DelegatingHandler
{
+ /// The secret configures; anything else is an invalid secret.
+ public const string TurnstileSecretKey = "turnstile-secret-key";
+
private async Task HandleCloudflareTurnstileRequest(HttpRequestMessage request, CancellationToken cancellationToken)
{
var formData = request.Content is null ? string.Empty : await request.Content.ReadAsStringAsync(cancellationToken);
var parsedForm = HttpUtility.ParseQueryString(formData);
var responseToken = parsedForm["response"];
- var responseDto = responseToken switch
+ // Cloudflare rejects a request with the wrong secret whatever the token, so a test passing "valid-token"
+ // also proves the API sent the configured secret.
+ var responseDto = parsedForm["secret"] != TurnstileSecretKey ? new CloudflareTurnstileVerifyResponseDto
+ {
+ Success = false,
+ ErrorCodes = ["invalid-input-secret"],
+ ChallengeTs = DateTime.UtcNow,
+ Hostname = "invalidhost",
+ Action = "invalidaction",
+ Cdata = ""
+ } : responseToken switch
{
"valid-token" => new CloudflareTurnstileVerifyResponseDto
{
diff --git a/API.IntegrationTests/Tests/AccountAuthenticatedTests.cs b/API.IntegrationTests/Tests/AccountAuthenticatedTests.cs
index 30bd50ea..f09dd19c 100644
--- a/API.IntegrationTests/Tests/AccountAuthenticatedTests.cs
+++ b/API.IntegrationTests/Tests/AccountAuthenticatedTests.cs
@@ -2,11 +2,14 @@
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using OpenShock.API.IntegrationTests.Helpers;
+using OpenShock.IntegrationTests.Shared;
namespace OpenShock.API.IntegrationTests.Tests;
public sealed class AccountAuthenticatedTests
{
+ private const string Password = "SecurePassword123#";
+
[ClassDataSource(Shared = SharedType.PerTestSession)]
public required WebApplicationFactory WebApplicationFactory { get; init; }
@@ -15,7 +18,9 @@ public sealed class AccountAuthenticatedTests
[Test]
public async Task GetSelf_ReturnsCurrentUserInfo_WithoutLegacyWrapper()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "accself", "accself@test.org", "SecurePassword123#");
+ var username = UniqueNames.Username("accself");
+ var email = UniqueNames.Email("acc-self");
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, username, email, Password);
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
var response = await client.GetAsync("/1/account");
@@ -25,10 +30,10 @@ public async Task GetSelf_ReturnsCurrentUserInfo_WithoutLegacyWrapper()
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var root = doc.RootElement;
await Assert.That(root.TryGetProperty("data", out _)).IsFalse();
- await Assert.That(root.GetProperty("name").GetString()).IsEqualTo("accself");
- await Assert.That(root.GetProperty("email").GetString()).IsEqualTo("accself@test.org");
+ await Assert.That(root.GetProperty("id").GetGuid()).IsEqualTo(user.Id);
+ await Assert.That(root.GetProperty("name").GetString()).IsEqualTo(username);
+ await Assert.That(root.GetProperty("email").GetString()).IsEqualTo(email);
await Assert.That(root.GetProperty("hasPassword").GetBoolean()).IsTrue();
- await Assert.That(root.TryGetProperty("id", out _)).IsTrue();
await Assert.That(root.TryGetProperty("image", out _)).IsTrue();
await Assert.That(root.TryGetProperty("roles", out _)).IsTrue();
}
@@ -36,7 +41,8 @@ public async Task GetSelf_ReturnsCurrentUserInfo_WithoutLegacyWrapper()
[Test]
public async Task GetSelf_WithApiToken_ReturnsUserInfo()
{
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, "accselfapi", "accselfapi@test.org", "SecurePassword123#");
+ var username = UniqueNames.Username("accselfapi");
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, UniqueNames.Email("acc-self-api"), Password);
var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId, "AccountSelfApiToken");
using var client = TestHelper.CreateApiTokenClient(WebApplicationFactory, rawToken);
@@ -45,15 +51,16 @@ public async Task GetSelf_WithApiToken_ReturnsUserInfo()
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
- await Assert.That(doc.RootElement.GetProperty("name").GetString()).IsEqualTo("accselfapi");
+ await Assert.That(doc.RootElement.GetProperty("name").GetString()).IsEqualTo(username);
}
// --- Change Password ---
[Test]
- public async Task ChangePassword_Success()
+ public async Task ChangePassword_Success_NewPasswordSignsIn_AndTheOldOneNoLonger()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "chgpwd", "chgpwd@test.org", "OldPassword123#");
+ var email = UniqueNames.Email("chg-pwd");
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("chgpwd"), email, "OldPassword123#");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
var response = await client.PostAsync("/1/account/password", TestHelper.JsonContent(new
@@ -64,25 +71,19 @@ public async Task ChangePassword_Success()
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
- // Verify can login with new password
using var loginClient = WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
HandleCookies = false
});
- var loginResponse = await loginClient.PostAsync("/2/account/login", TestHelper.JsonContent(new
- {
- usernameOrEmail = "chgpwd@test.org",
- password = "NewPassword456#",
- turnstileResponse = "valid-token"
- }));
- await Assert.That(loginResponse.StatusCode).IsEqualTo(HttpStatusCode.OK);
+ await Assert.That((await PendingSignupHelper.PostLoginAsync(loginClient, email, "NewPassword456#")).StatusCode).IsEqualTo(HttpStatusCode.OK);
+ await Assert.That((await PendingSignupHelper.PostLoginAsync(loginClient, email, "OldPassword123#")).StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
}
[Test]
public async Task ChangePassword_WrongCurrentPassword_Returns403()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "chgpwdbad", "chgpwdbad@test.org", "CorrectPassword123#");
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("chgpwdbad"), UniqueNames.Email("chg-pwd-bad"), "CorrectPassword123#");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
var response = await client.PostAsync("/1/account/password", TestHelper.JsonContent(new
@@ -97,60 +98,35 @@ public async Task ChangePassword_WrongCurrentPassword_Returns403()
// --- Change Username ---
[Test]
- public async Task ChangeUsername_Success()
+ public async Task ChangeUsername_Success_RenamesTheAccount()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "oldname", "chguname@test.org", "SecurePassword123#");
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("oldname"), UniqueNames.Email("chg-uname"), Password);
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
+ var newName = UniqueNames.Username("newname");
var response = await client.PostAsync("/1/account/username", TestHelper.JsonContent(new
{
- username = "newname"
+ username = newName
}));
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
+ using var self = JsonDocument.Parse(await client.GetStringAsync("/1/account"));
+ await Assert.That(self.RootElement.GetProperty("name").GetString()).IsEqualTo(newName);
}
[Test]
public async Task ChangeUsername_Taken_Returns409()
{
- await TestHelper.CreateAndLoginUser(WebApplicationFactory, "takenname", "takenname@test.org", "SecurePassword123#");
- var user2 = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "wantsname", "wantsname@test.org", "SecurePassword123#");
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user2.SessionToken);
+ var takenName = UniqueNames.Username("takenname");
+ await TestHelper.CreateUserInDb(WebApplicationFactory, takenName, UniqueNames.Email("taken-name"), Password);
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("wantsname"), UniqueNames.Email("wants-name"), Password);
+ using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
var response = await client.PostAsync("/1/account/username", TestHelper.JsonContent(new
{
- username = "takenname"
+ username = takenName
}));
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict);
}
-
- // --- Unauthenticated access ---
-
- [Test]
- public async Task ChangePassword_Unauthenticated_Returns401()
- {
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.PostAsync("/1/account/password", TestHelper.JsonContent(new
- {
- currentPassword = "anything",
- newPassword = "anything"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
- }
-
- [Test]
- public async Task ChangeUsername_Unauthenticated_Returns401()
- {
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.PostAsync("/1/account/username", TestHelper.JsonContent(new
- {
- username = "anything"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
- }
}
diff --git a/API.IntegrationTests/Tests/AccountLoginTests.cs b/API.IntegrationTests/Tests/AccountLoginTests.cs
index 6ac0b7c2..acaad5ea 100644
--- a/API.IntegrationTests/Tests/AccountLoginTests.cs
+++ b/API.IntegrationTests/Tests/AccountLoginTests.cs
@@ -3,6 +3,8 @@
using Microsoft.AspNetCore.Mvc.Testing;
using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.Common.Constants;
+using OpenShock.IntegrationTests.Shared;
+using static OpenShock.API.IntegrationTests.Helpers.PendingSignupHelper;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -11,170 +13,104 @@ public sealed class AccountLoginTests
[ClassDataSource(Shared = SharedType.PerTestSession)]
public required WebApplicationFactory WebApplicationFactory { get; init; }
- // --- V1 Login (retired) ---
-
- [Test]
- public async Task V1Login_Retired_Returns410Gone()
+ private HttpClient CreateClient() => WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions
{
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.PostAsync("/1/account/login", TestHelper.JsonContent(new
- {
- email = "whatever@test.org",
- password = "SecurePassword123#"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Gone);
- }
+ AllowAutoRedirect = false,
+ HandleCookies = false
+ });
// --- V2 Login ---
[Test]
- public async Task V2Login_Success_ReturnsCookieAndBody()
+ [Arguments(true)]
+ [Arguments(false)]
+ public async Task V2Login_Success_ReturnsTheAccount_AndSetsTheSessionCookie(bool byEmail)
{
- await TestHelper.CreateUserInDb(WebApplicationFactory, "loginv2", "loginv2@test.org", "SecurePassword123#");
+ var username = UniqueNames.Username("loginv2");
+ var email = UniqueNames.Email("login-v2");
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, Password);
- using var client = WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions
- {
- AllowAutoRedirect = false,
- HandleCookies = false
- });
-
- var response = await client.PostAsync("/2/account/login", TestHelper.JsonContent(new
- {
- usernameOrEmail = "loginv2@test.org",
- password = "SecurePassword123#",
- turnstileResponse = "valid-token"
- }));
+ using var client = CreateClient();
+ var response = await PostLoginAsync(client, byEmail ? email : username, Password);
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
-
- var json = await response.Content.ReadAsStringAsync();
- using var doc = JsonDocument.Parse(json);
- var root = doc.RootElement;
- await Assert.That(root.TryGetProperty("accountId", out _)).IsTrue();
- await Assert.That(root.TryGetProperty("accountName", out _)).IsTrue();
-
- var setCookie = response.Headers.GetValues("Set-Cookie").ToArray();
- var hasSessionCookie = setCookie.Any(c => c.Contains(AuthConstants.UserSessionCookieName));
- await Assert.That(hasSessionCookie).IsTrue();
+ using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
+ await Assert.That(doc.RootElement.GetProperty("accountId").GetGuid()).IsEqualTo(userId);
+ await Assert.That(doc.RootElement.GetProperty("accountName").GetString()).IsEqualTo(username);
+ await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsTrue();
}
[Test]
public async Task V2Login_InvalidTurnstile_Returns403()
{
- await TestHelper.CreateUserInDb(WebApplicationFactory, "loginv2ts", "loginv2ts@test.org", "SecurePassword123#");
-
- using var client = WebApplicationFactory.CreateClient();
+ var email = UniqueNames.Email("login-v2-turnstile");
+ await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("loginv2ts"), email, Password);
+ using var client = CreateClient();
var response = await client.PostAsync("/2/account/login", TestHelper.JsonContent(new
{
- usernameOrEmail = "loginv2ts@test.org",
- password = "SecurePassword123#",
+ usernameOrEmail = email,
+ password = Password,
turnstileResponse = "invalid-token"
}));
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden);
- }
-
- [Test]
- public async Task V2Login_ExpiredOrDuplicateTurnstile_Returns403()
- {
- await TestHelper.CreateUserInDb(WebApplicationFactory, "loginv2tsexp", "loginv2tsexp@test.org", "SecurePassword123#");
-
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.PostAsync("/2/account/login", TestHelper.JsonContent(new
- {
- usernameOrEmail = "loginv2tsexp@test.org",
- password = "SecurePassword123#",
- turnstileResponse = "expired-token"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden);
+ await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Turnstile.Invalid");
+ await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsFalse();
}
[Test]
public async Task V2Login_InvalidCredentials_Returns401()
{
- await TestHelper.CreateUserInDb(WebApplicationFactory, "loginv2bad", "loginv2bad@test.org", "SecurePassword123#");
-
- using var client = WebApplicationFactory.CreateClient();
+ var email = UniqueNames.Email("login-v2-bad");
+ await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("loginv2bad"), email, Password);
- var response = await client.PostAsync("/2/account/login", TestHelper.JsonContent(new
- {
- usernameOrEmail = "loginv2bad@test.org",
- password = "WrongPassword!",
- turnstileResponse = "valid-token"
- }));
+ using var client = CreateClient();
+ var response = await PostLoginAsync(client, email, "WrongPassword123#");
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
- }
-
- [Test]
- public async Task V2Login_ByUsername_Success()
- {
- await TestHelper.CreateUserInDb(WebApplicationFactory, "loginbyname", "loginbyname@test.org", "SecurePassword123#");
-
- using var client = WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions
- {
- AllowAutoRedirect = false,
- HandleCookies = false
- });
-
- var response = await client.PostAsync("/2/account/login", TestHelper.JsonContent(new
- {
- usernameOrEmail = "loginbyname",
- password = "SecurePassword123#",
- turnstileResponse = "valid-token"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
+ await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsFalse();
}
// --- Unactivated account ---
+ // Told apart from wrong credentials, and only once the password is right.
[Test]
- public async Task V2Login_UnactivatedAccount_Returns401()
+ public async Task V2Login_UnactivatedAccount_CorrectPassword_ReturnsNotActivated_AndNoSession()
{
- await TestHelper.CreateUserInDb(WebApplicationFactory, "notactivated", "notactivated@test.org", "SecurePassword123#", activated: false);
+ var email = UniqueNames.Email("login-notactivated");
+ await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("loginnotactivated"), email, Password, activated: false);
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.PostAsync("/2/account/login", TestHelper.JsonContent(new
- {
- usernameOrEmail = "notactivated@test.org",
- password = "SecurePassword123#",
- turnstileResponse = "valid-token"
- }));
+ using var client = CreateClient();
+ var response = await PostLoginAsync(client, email, Password);
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
+ await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.AccountNotActivated");
+ await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsFalse();
+
+ var wrongPassword = await PostLoginAsync(client, email, "WrongPassword123#");
+ await Assert.That(await wrongPassword.Content.ReadAsStringAsync()).DoesNotContain("Account.AccountNotActivated");
}
// --- Logout ---
[Test]
- public async Task Logout_ClearsCookie()
+ public async Task Logout_EndsTheSession_AndRemovesTheCookie()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "logoutuser", "logoutuser@test.org", "SecurePassword123#");
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("logoutuser"), UniqueNames.Email("logout-user"), Password);
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
+ await Assert.That((await client.GetAsync("/1/account")).StatusCode).IsEqualTo(HttpStatusCode.OK);
var response = await client.PostAsync("/1/account/logout", null);
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
- }
-
- [Test]
- public async Task Logout_WithoutSession_StillReturnsOk()
- {
- using var client = WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions
- {
- AllowAutoRedirect = false,
- HandleCookies = false
- });
-
- var response = await client.PostAsync("/1/account/logout", null);
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
+ await Assert.That(DeletesCookie(response, AuthConstants.UserSessionCookieName)).IsTrue();
+ await Assert.That((await client.GetAsync("/1/account")).StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
+
+ // Idempotent: without a session there is nothing to end, and the cookie is still removed.
+ using var anonymous = CreateClient();
+ var again = await anonymous.PostAsync("/1/account/logout", null);
+ await Assert.That(again.StatusCode).IsEqualTo(HttpStatusCode.OK);
+ await Assert.That(DeletesCookie(again, AuthConstants.UserSessionCookieName)).IsTrue();
}
}
diff --git a/API.IntegrationTests/Tests/AccountSignupTests.cs b/API.IntegrationTests/Tests/AccountSignupTests.cs
deleted file mode 100644
index 918a3994..00000000
--- a/API.IntegrationTests/Tests/AccountSignupTests.cs
+++ /dev/null
@@ -1,145 +0,0 @@
-using System.Net;
-using Microsoft.AspNetCore.Mvc.Testing;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.DependencyInjection;
-using OpenShock.API.IntegrationTests.Helpers;
-using OpenShock.Common.Constants;
-using OpenShock.Common.OpenShockDb;
-
-namespace OpenShock.API.IntegrationTests.Tests;
-
-public sealed class AccountSignupTests
-{
- [ClassDataSource(Shared = SharedType.PerTestSession)]
- public required WebApplicationFactory WebApplicationFactory { get; init; }
-
- // --- V1 Signup (retired) ---
-
- [Test]
- public async Task V1Signup_Retired_Returns410Gone()
- {
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.PostAsync("/1/account/signup", TestHelper.JsonContent(new
- {
- username = "v1retired",
- password = "SecurePassword123#",
- email = "v1retired@test.org"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Gone);
- }
-
- // --- V2 Signup ---
-
- [Test]
- public async Task V2Signup_Success_CreatesUser()
- {
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
- {
- username = "v2user",
- password = "SecurePassword123#",
- email = "v2user@test.org",
- turnstileResponse = "valid-token"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
-
- // The account exists once the mailed code is entered in the browser that signed up.
- var pending = (await PendingSignupHelper.FindByEmailAsync(WebApplicationFactory, "v2user@test.org")).Single();
- var code = await PendingSignupHelper.MailCodeAsync(WebApplicationFactory, pending.Id);
- var cookie = PendingSignupHelper.ReadSetCookie(response, AuthConstants.SignupBrowserSecureCookieName);
- using var browser = WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions { HandleCookies = false });
- var activated = await PendingSignupHelper.PostActivateAsync(browser, code, cookie);
- await Assert.That(activated.StatusCode).IsEqualTo(HttpStatusCode.OK);
-
- await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
- var db = scope.ServiceProvider.GetRequiredService();
- var user = await db.Users.FirstOrDefaultAsync(u => u.Email == "v2user@test.org");
- await Assert.That(user).IsNotNull();
- }
-
- [Test]
- public async Task V2Signup_InvalidTurnstile_Returns403()
- {
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
- {
- username = "v2blocked",
- password = "SecurePassword123#",
- email = "v2blocked@test.org",
- turnstileResponse = "invalid-token"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden);
- }
-
- [Test, DependsOn(nameof(V2Signup_Success_CreatesUser))]
- public async Task V2Signup_DuplicateEmail_Returns409()
- {
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
- {
- username = "v2userDifferent",
- password = "SecurePassword123#",
- email = "v2user@test.org", // same email
- turnstileResponse = "valid-token"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict);
- }
-
- [Test, DependsOn(nameof(V2Signup_Success_CreatesUser))]
- public async Task V2Signup_DuplicateUsername_Returns409()
- {
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
- {
- username = "v2user", // same username
- password = "SecurePassword123#",
- email = "v2different@test.org",
- turnstileResponse = "valid-token"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict);
- }
-
- // --- Validation ---
-
- [Test]
- public async Task V2Signup_EmptyUsername_Returns400()
- {
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
- {
- username = "",
- password = "SecurePassword123#",
- email = "emptyusername@test.org",
- turnstileResponse = "valid-token"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest);
- }
-
- [Test]
- public async Task V2Signup_EmptyPassword_Returns400()
- {
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
- {
- username = "validname",
- password = "",
- email = "emptypass@test.org",
- turnstileResponse = "valid-token"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest);
- }
-}
diff --git a/API.IntegrationTests/Tests/AccountTests.cs b/API.IntegrationTests/Tests/AccountTests.cs
deleted file mode 100644
index f33926d1..00000000
--- a/API.IntegrationTests/Tests/AccountTests.cs
+++ /dev/null
@@ -1,78 +0,0 @@
-using System.Net;
-using System.Text.Json;
-using Microsoft.AspNetCore.Mvc.Testing;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.DependencyInjection;
-using OpenShock.API.IntegrationTests.Helpers;
-using OpenShock.Common.Constants;
-using OpenShock.Common.OpenShockDb;
-
-namespace OpenShock.API.IntegrationTests.Tests;
-
-public sealed class AccountTests
-{
- [ClassDataSource(Shared = SharedType.PerTestSession)]
- public required WebApplicationFactory WebApplicationFactory { get; init; }
-
- [Test]
- public async Task CreateAccount_ShouldAdd_NewUserToDatabase()
- {
- using var client = WebApplicationFactory.CreateClient();
-
- var requestBody = new
- {
- username = "Bob",
- password = "SecurePassword123#",
- email = "bob@example.com",
- turnstileresponse = "valid-token"
- };
-
-
- var response = await client.PostAsJsonAsync("/2/account/signup", requestBody);
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
-
- // The account exists once the mailed code is entered in the browser that signed up.
- var pending = (await PendingSignupHelper.FindByEmailAsync(WebApplicationFactory, "bob@example.com")).Single();
- var code = await PendingSignupHelper.MailCodeAsync(WebApplicationFactory, pending.Id);
- var cookie = PendingSignupHelper.ReadSetCookie(response, AuthConstants.SignupBrowserSecureCookieName);
- using var browser = WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions { HandleCookies = false });
- var activated = await PendingSignupHelper.PostActivateAsync(browser, code, cookie);
- await Assert.That(activated.StatusCode).IsEqualTo(HttpStatusCode.OK);
-
- await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
- var db = scope.ServiceProvider.GetRequiredService();
-
- var user = await db.Users.FirstOrDefaultAsync(u => u.Email == "bob@example.com");
-
- await Assert.That(user).IsNotNull();
- }
-
- [Test, DependsOn(nameof(CreateAccount_ShouldAdd_NewUserToDatabase))]
- public async Task CheckUsername()
- {
- using var client = WebApplicationFactory.CreateClient();
-
- var requestBody = new { username = "Bob" };
-
- var response = await client.PostAsJsonAsync("/1/account/username/check", requestBody);
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
-
- var mediaType = response.Content.Headers.ContentType?.MediaType;
- await Assert.That(mediaType).IsEqualTo("application/json");
-
- var json = await response.Content.ReadAsStringAsync();
- using var doc = JsonDocument.Parse(json);
-
- var root = doc.RootElement;
-
- // Validate Availability
- var availability = root.GetProperty("availability").GetString();
- await Assert.That(availability).IsEqualTo("Taken");
-
- // Validate Error
- var error = root.GetProperty("error").GetString();
- await Assert.That(error).IsNull();
- }
-}
diff --git a/API.IntegrationTests/Tests/AdminUserLifecycleTests.cs b/API.IntegrationTests/Tests/AdminUserLifecycleTests.cs
index 57cf05e5..8160c16b 100644
--- a/API.IntegrationTests/Tests/AdminUserLifecycleTests.cs
+++ b/API.IntegrationTests/Tests/AdminUserLifecycleTests.cs
@@ -4,6 +4,7 @@
using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.Common.Models;
using OpenShock.Common.OpenShockDb;
+using OpenShock.IntegrationTests.Shared;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -16,8 +17,8 @@ public sealed class AdminUserLifecycleTests
public async Task Admin_CanDeactivateAndReactivateAUser()
{
using var admin = await CreateAdminClient("adminlcdeact");
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("adminlcdeactu"),
- TestHelper.UniqueEmail("adminlcdeactu"), "SecurePassword123#");
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("adminlcdeactu"),
+ UniqueNames.Email("adminlcdeactu"), "SecurePassword123#");
var deactivate =
await admin.PutAsync($"/1/admin/users/{userId}/deactivate?deleteLater=false&reason=test", null);
@@ -33,8 +34,8 @@ public async Task Admin_CanDeactivateAndReactivateAUser()
public async Task Admin_CanDeleteAUser()
{
using var admin = await CreateAdminClient("adminlcdelete");
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("adminlcdeleteu"),
- TestHelper.UniqueEmail("adminlcdeleteu"), "SecurePassword123#");
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("adminlcdeleteu"),
+ UniqueNames.Email("adminlcdeleteu"), "SecurePassword123#");
var response = await admin.DeleteAsync($"/1/admin/users/{userId}?reason=test");
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
@@ -49,7 +50,7 @@ public async Task Admin_CannotDeleteAnotherAdmin()
{
using var admin = await CreateAdminClient("adminlcpriv");
var otherAdmin = await TestHelper.CreateAndLoginUser(WebApplicationFactory,
- TestHelper.UniqueUsername("adminlcprivo"), TestHelper.UniqueEmail("adminlcprivo"), "SecurePassword123#");
+ UniqueNames.Username("adminlcprivo"), UniqueNames.Email("adminlcprivo"), "SecurePassword123#");
await SetRoles(otherAdmin.Id, [RoleType.Admin]);
var response = await admin.DeleteAsync($"/1/admin/users/{otherAdmin.Id}");
@@ -61,10 +62,52 @@ public async Task Admin_CannotDeleteAnotherAdmin()
await Assert.That(await db.Users.AnyAsync(u => u.Id == otherAdmin.Id)).IsTrue();
}
+ [Test]
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task NonAdminSession_IsRefusedOnAdminEndpoints(bool staff)
+ {
+ var caller = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("adminlcnonadm"),
+ UniqueNames.Email("adminlcnonadm"), "SecurePassword123#");
+ if (staff) await SetRoles(caller.Id, [RoleType.Staff]);
+ var targetId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("adminlcnonadmt"),
+ UniqueNames.Email("adminlcnonadmt"), "SecurePassword123#");
+ using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, caller.SessionToken);
+
+ var response = await client.DeleteAsync($"/1/admin/users/{targetId}?reason=test");
+
+ await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden);
+ await Assert.That(await UserExists(targetId)).IsTrue();
+ }
+
+ [Test]
+ public async Task AdminsApiToken_IsRefusedOnAdminEndpoints()
+ {
+ var admin = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("adminlctoken"),
+ UniqueNames.Email("adminlctoken"), "SecurePassword123#");
+ await SetRoles(admin.Id, [RoleType.Admin]);
+ var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, admin.Id, "AdminsToken", [.. Enum.GetValues()]);
+ var targetId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("adminlctokent"),
+ UniqueNames.Email("adminlctokent"), "SecurePassword123#");
+ using var client = TestHelper.CreateApiTokenClient(WebApplicationFactory, rawToken);
+
+ var response = await client.DeleteAsync($"/1/admin/users/{targetId}?reason=test");
+
+ await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
+ await Assert.That(await UserExists(targetId)).IsTrue();
+ }
+
+ private async Task UserExists(Guid userId)
+ {
+ await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ return await db.Users.AnyAsync(u => u.Id == userId);
+ }
+
private async Task CreateAdminClient(string prefix)
{
- var admin = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername(prefix),
- TestHelper.UniqueEmail(prefix), "SecurePassword123#");
+ var admin = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix),
+ UniqueNames.Email(prefix), "SecurePassword123#");
await SetRoles(admin.Id, [RoleType.Admin]);
return TestHelper.CreateAuthenticatedClient(WebApplicationFactory, admin.SessionToken);
}
diff --git a/API.IntegrationTests/Tests/AdminUsersViewTests.cs b/API.IntegrationTests/Tests/AdminUsersViewTests.cs
index 05d43a13..3207541c 100644
--- a/API.IntegrationTests/Tests/AdminUsersViewTests.cs
+++ b/API.IntegrationTests/Tests/AdminUsersViewTests.cs
@@ -2,6 +2,7 @@
using Microsoft.Extensions.DependencyInjection;
using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.Common.OpenShockDb;
+using OpenShock.IntegrationTests.Shared;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -21,7 +22,7 @@ public sealed class AdminUsersViewTests
[Test]
public async Task PasswordHashType_ForPasswordUser_MapsToBCrypt()
{
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, "adminviewbcrypt", "adminviewbcrypt@test.org", "SecurePassword123#");
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("adminviewbcrypt"), UniqueNames.Email("adminviewbcrypt"), "SecurePassword123#");
await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService();
@@ -43,8 +44,8 @@ public async Task PasswordHashType_ForOAuthOnlyUser_IsNull()
db.Users.Add(new User
{
Id = userId,
- Name = "adminviewoauth",
- Email = "adminviewoauth@test.org",
+ Name = UniqueNames.Username("adminviewoauth"),
+ Email = UniqueNames.Email("adminviewoauth"),
PasswordHash = null,
ActivatedAt = DateTime.UtcNow
});
diff --git a/API.IntegrationTests/Tests/AuthorizationTests.cs b/API.IntegrationTests/Tests/AuthorizationTests.cs
index 1d01a555..cafb1685 100644
--- a/API.IntegrationTests/Tests/AuthorizationTests.cs
+++ b/API.IntegrationTests/Tests/AuthorizationTests.cs
@@ -5,6 +5,7 @@
using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.Common.Constants;
using OpenShock.Common.OpenShockDb;
+using OpenShock.IntegrationTests.Shared;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -14,6 +15,8 @@ namespace OpenShock.API.IntegrationTests.Tests;
///
public sealed class AuthorizationTests
{
+ private const string Password = "SecurePassword123#";
+
[ClassDataSource(Shared = SharedType.PerTestSession)]
public required WebApplicationFactory WebApplicationFactory { get; init; }
@@ -22,6 +25,7 @@ public sealed class AuthorizationTests
[Test]
[Arguments("/1/devices")]
[Arguments("/1/shockers/shared")]
+ [Arguments("/1/shares/links")]
[Arguments("/1/tokens")]
[Arguments("/1/sessions/self")]
[Arguments("/1/users/self")]
@@ -35,37 +39,37 @@ public async Task ProtectedEndpoint_NoAuth_Returns401(string url)
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
}
- [Test]
- public async Task ProtectedPostEndpoint_NoAuth_Returns401()
- {
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.PostAsync("/1/devices", null);
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
- }
-
// --- API Token on session-only endpoints ---
[Test]
- public async Task ApiToken_OnSessionOnlyEndpoint_Returns401()
+ [Arguments("GET", "/1/sessions/self")]
+ [Arguments("GET", "/1/account/profile")]
+ [Arguments("POST", "/1/tokens")]
+ public async Task ApiToken_OnSessionOnlyEndpoint_Returns401(string method, string url)
{
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, "apitoksess", "apitoksess@test.org", "SecurePassword123#");
- var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId, "SessionOnlyTest");
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("apitoksess"), UniqueNames.Email("apitoksess"), Password);
+ var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId, "SessionOnlyTest", [.. Enum.GetValues()]);
using var client = TestHelper.CreateApiTokenClient(WebApplicationFactory, rawToken);
- // Sessions endpoint requires UserSessionCookie only
- var response = await client.GetAsync("/1/sessions/self");
+ using var request = new HttpRequestMessage(new HttpMethod(method), url);
+ if (method == "POST")
+ {
+ request.Content = TestHelper.JsonContent(new { name = "MintedByToken", permissions = new[] { "shockers.use" } });
+ }
+ var response = await client.SendAsync(request);
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
+ await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ await Assert.That(await db.ApiTokens.AnyAsync(t => t.UserId == userId && t.Id != tokenId)).IsFalse();
}
- // --- Session cookie on hub-only endpoint ---
+ // --- Credentials of the wrong kind ---
[Test]
public async Task SessionCookie_OnHubOnlyEndpoint_Returns401()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "sesshub", "sesshub@test.org", "SecurePassword123#");
+ var user = await CreateUser("sesshub");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
// Device self endpoint requires HubToken
@@ -74,13 +78,26 @@ public async Task SessionCookie_OnHubOnlyEndpoint_Returns401()
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
}
+ [Test]
+ public async Task HubToken_OnSessionOnlyEndpoint_Returns401()
+ {
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("hubwrong"), UniqueNames.Email("hubwrong"), Password);
+ var (_, hubToken) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, userId, "WrongHub");
+ using var client = TestHelper.CreateHubTokenClient(WebApplicationFactory, hubToken);
+
+ // Tokens endpoint requires UserSessionCookie, not HubToken
+ var response = await client.GetAsync("/1/tokens");
+
+ await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
+ }
+
// --- Cross-user isolation: devices ---
[Test]
public async Task CrossUser_CannotSeeOtherUsersDevices()
{
- var user1 = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "isoown1", "isoown1@test.org", "SecurePassword123#");
- var user2 = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "isoown2", "isoown2@test.org", "SecurePassword123#");
+ var user1 = await CreateUser("isoown1");
+ var user2 = await CreateUser("isoown2");
var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user1.Id, "PrivateHub");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user2.SessionToken);
@@ -92,8 +109,8 @@ public async Task CrossUser_CannotSeeOtherUsersDevices()
[Test]
public async Task CrossUser_CannotEditOtherUsersDevices()
{
- var user1 = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "isoedit1", "isoedit1@test.org", "SecurePassword123#");
- var user2 = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "isoedit2", "isoedit2@test.org", "SecurePassword123#");
+ var user1 = await CreateUser("isoedit1");
+ var user2 = await CreateUser("isoedit2");
var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user1.Id, "SecureHub");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user2.SessionToken);
@@ -103,19 +120,21 @@ public async Task CrossUser_CannotEditOtherUsersDevices()
}));
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
+ await Assert.That(await GetDeviceName(deviceId)).IsEqualTo("SecureHub");
}
[Test]
public async Task CrossUser_CannotDeleteOtherUsersDevices()
{
- var user1 = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "isodel1", "isodel1@test.org", "SecurePassword123#");
- var user2 = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "isodel2", "isodel2@test.org", "SecurePassword123#");
+ var user1 = await CreateUser("isodel1");
+ var user2 = await CreateUser("isodel2");
var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user1.Id, "ProtectedHub");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user2.SessionToken);
var response = await client.DeleteAsync($"/1/devices/{deviceId}");
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
+ await Assert.That(await GetDeviceName(deviceId)).IsEqualTo("ProtectedHub");
}
// --- Cross-user isolation: tokens ---
@@ -123,8 +142,8 @@ public async Task CrossUser_CannotDeleteOtherUsersDevices()
[Test]
public async Task CrossUser_CannotSeeOtherUsersTokens()
{
- var user1 = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "isotok1", "isotok1@test.org", "SecurePassword123#");
- var user2 = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "isotok2", "isotok2@test.org", "SecurePassword123#");
+ var user1 = await CreateUser("isotok1");
+ var user2 = await CreateUser("isotok2");
// Create a token for user1 via authenticated client
using var client1 = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user1.SessionToken);
@@ -149,12 +168,15 @@ public async Task CrossUser_CannotSeeOtherUsersTokens()
// token's permissions must bind even when a valid session cookie rides along.
[Test]
- public async Task SessionCookieAndRestrictedApiToken_TokenPermissionMissing_Returns403()
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task SessionCookieAndRestrictedApiToken_TokenPermissionMissing_Returns403(bool cookieOfAnotherUser)
{
- var owner = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "combown", "combown@test.org", "SecurePassword123#");
+ var owner = await CreateUser("combown");
+ var cookieUser = cookieOfAnotherUser ? await CreateUser("combxoth") : owner;
var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, owner.Id, "ComboHub");
var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, owner.Id, "NoDevicesEdit", [PermissionType.Shockers_Use]);
- using var client = CreateSessionAndApiTokenClient(owner.SessionToken, rawToken);
+ using var client = CreateSessionAndApiTokenClient(cookieUser.SessionToken, rawToken);
var response = await client.PatchAsync($"/1/devices/{deviceId}", TestHelper.JsonContent(new { name = "Renamed" }));
@@ -163,28 +185,17 @@ public async Task SessionCookieAndRestrictedApiToken_TokenPermissionMissing_Retu
}
[Test]
- public async Task OtherUsersSessionCookieAndRestrictedApiToken_TokenPermissionMissing_Returns403()
+ [Arguments(false)]
+ [Arguments(true)]
+ public async Task SessionCookieAndPermittedApiToken_ActsAsTheTokensOwner(bool cookieOfAnotherUser)
{
- var owner = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "combxown", "combxown@test.org", "SecurePassword123#");
- var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "combxoth", "combxoth@test.org", "SecurePassword123#");
- var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, owner.Id, "ComboCrossHub");
- var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, owner.Id, "NoDevicesEdit", [PermissionType.Shockers_Use]);
- using var client = CreateSessionAndApiTokenClient(other.SessionToken, rawToken);
-
- var response = await client.PatchAsync($"/1/devices/{deviceId}", TestHelper.JsonContent(new { name = "Renamed" }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden);
- await Assert.That(await GetDeviceName(deviceId)).IsEqualTo("ComboCrossHub");
- }
-
- [Test]
- public async Task SessionCookieAndPermittedApiToken_Returns200()
- {
- var owner = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "combok", "combok@test.org", "SecurePassword123#");
+ var owner = await CreateUser("combok");
+ var cookieUser = cookieOfAnotherUser ? await CreateUser("combokoth") : owner;
var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, owner.Id, "ComboOkHub");
var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, owner.Id, "DevicesEdit", [PermissionType.Devices_Edit]);
- using var client = CreateSessionAndApiTokenClient(owner.SessionToken, rawToken);
+ using var client = CreateSessionAndApiTokenClient(cookieUser.SessionToken, rawToken);
+ // The device belongs to the token's owner, so this only finds it when the token's owner is the acting user.
var response = await client.PatchAsync($"/1/devices/{deviceId}", TestHelper.JsonContent(new { name = "Renamed" }));
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
@@ -194,7 +205,7 @@ public async Task SessionCookieAndPermittedApiToken_Returns200()
[Test]
public async Task SessionCookieAndApiTokenWithoutDevicesAuth_DoesNotExposeHubToken()
{
- var owner = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "combauth", "combauth@test.org", "SecurePassword123#");
+ var owner = await CreateUser("combauth");
var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, owner.Id, "ComboAuthHub");
var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, owner.Id, "NoDevicesAuth", [PermissionType.Devices_Edit]);
using var client = CreateSessionAndApiTokenClient(owner.SessionToken, rawToken);
@@ -207,6 +218,21 @@ public async Task SessionCookieAndApiTokenWithoutDevicesAuth_DoesNotExposeHubTok
await Assert.That(token.ValueKind).IsEqualTo(JsonValueKind.Null);
}
+ // --- Invalid session token ---
+
+ [Test]
+ public async Task InvalidSessionToken_Returns401()
+ {
+ using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, "totally-invalid-session-token-abc123");
+
+ var response = await client.GetAsync("/1/devices");
+
+ await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
+ }
+
+ private Task CreateUser(string prefix) =>
+ TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), Password);
+
private HttpClient CreateSessionAndApiTokenClient(string sessionToken, string apiToken)
{
var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, sessionToken);
@@ -220,16 +246,4 @@ private async Task GetDeviceName(Guid deviceId)
var db = scope.ServiceProvider.GetRequiredService();
return await db.Devices.Where(x => x.Id == deviceId).Select(x => x.Name).SingleAsync();
}
-
- // --- Invalid session token ---
-
- [Test]
- public async Task InvalidSessionToken_Returns401()
- {
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, "totally-invalid-session-token-abc123");
-
- var response = await client.GetAsync("/1/devices");
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
- }
}
diff --git a/API.IntegrationTests/Tests/AutomationTokenTests.cs b/API.IntegrationTests/Tests/AutomationTokenTests.cs
index 2dc11310..5568a9b9 100644
--- a/API.IntegrationTests/Tests/AutomationTokenTests.cs
+++ b/API.IntegrationTests/Tests/AutomationTokenTests.cs
@@ -8,6 +8,7 @@
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Services.AutomationTokens;
using OpenShock.Common.Utils;
+using OpenShock.IntegrationTests.Shared;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -30,15 +31,9 @@ public async Task Signup_WithTurnstileToken_BypassesTurnstileAndLinksAccount()
{
var (tokenId, secret) = await CreateAutomationTokenInDb();
using var client = CreateAutomationClient(secret);
- var email = TestHelper.UniqueEmail("autosignup");
+ var email = UniqueNames.Email("autosignup");
- var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
- {
- username = TestHelper.UniqueUsername("autosignup"),
- password = Password,
- email,
- turnstileResponse = "invalid-token"
- }));
+ var response = await PostSignupWithInvalidTurnstileAsync(client, "autosignup", email);
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
@@ -59,99 +54,74 @@ public async Task Signup_WithTurnstileToken_BypassesTurnstileAndLinksAccount()
await Assert.That(await HasUsedAuditAsync(db, user.Id)).IsTrue();
}
- [Test]
- public async Task Signup_WithUnknownToken_StillRequiresTurnstile()
+ public enum IgnoredTokenCase
{
- using var client = CreateAutomationClient(IAutomationTokenService.GenerateSecret());
-
- var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
- {
- username = TestHelper.UniqueUsername("autounknown"),
- password = Password,
- email = TestHelper.UniqueEmail("autounknown"),
- turnstileResponse = "invalid-token"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden);
+ UnknownSecret,
+ RateLimitOnlyToken,
+ PrivilegedSession,
+ PrivilegedApiToken
}
+ // Each case is a different reason the middleware does not honor the header, so Turnstile still applies.
[Test]
- public async Task Signup_WithRateLimitOnlyToken_StillRequiresTurnstile()
+ [Arguments(IgnoredTokenCase.UnknownSecret)]
+ [Arguments(IgnoredTokenCase.RateLimitOnlyToken)]
+ [Arguments(IgnoredTokenCase.PrivilegedSession)]
+ [Arguments(IgnoredTokenCase.PrivilegedApiToken)]
+ public async Task Signup_WithTokenThatIsNotHonored_StillRequiresTurnstile(IgnoredTokenCase @case)
{
- var (_, secret) = await CreateAutomationTokenInDb([AutomationTokenType.RateLimit]);
- using var client = CreateAutomationClient(secret);
-
- var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
+ HttpClient client;
+ switch (@case)
{
- username = TestHelper.UniqueUsername("autoratelimit"),
- password = Password,
- email = TestHelper.UniqueEmail("autoratelimit"),
- turnstileResponse = "invalid-token"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden);
- }
-
- // --- Privileged callers (middleware) ---
-
- [Test]
- public async Task PrivilegedSession_TokenIsRefused()
- {
- var (_, secret) = await CreateAutomationTokenInDb();
- var staff = await CreateUserWithRoles("autostaffsession", [RoleType.Staff]);
-
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, staff.SessionToken);
- client.DefaultRequestHeaders.Add(AuthConstants.AutomationTokenHeaderName, secret);
-
- var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
+ case IgnoredTokenCase.UnknownSecret:
+ client = CreateAutomationClient(IAutomationTokenService.GenerateSecret());
+ break;
+ case IgnoredTokenCase.RateLimitOnlyToken:
+ {
+ var (_, secret) = await CreateAutomationTokenInDb([AutomationTokenType.RateLimit]);
+ client = CreateAutomationClient(secret);
+ break;
+ }
+ case IgnoredTokenCase.PrivilegedSession:
+ {
+ var (_, secret) = await CreateAutomationTokenInDb();
+ var staff = await CreateUserWithRoles("autostaffsession", [RoleType.Staff]);
+ client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, staff.SessionToken);
+ client.DefaultRequestHeaders.Add(AuthConstants.AutomationTokenHeaderName, secret);
+ break;
+ }
+ case IgnoredTokenCase.PrivilegedApiToken:
+ {
+ var (_, secret) = await CreateAutomationTokenInDb();
+ var staff = await CreateUserWithRoles("autostaffapi", [RoleType.Staff]);
+ var (_, apiToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, staff.Id);
+ client = TestHelper.CreateApiTokenClient(WebApplicationFactory, apiToken);
+ client.DefaultRequestHeaders.Add(AuthConstants.AutomationTokenHeaderName, secret);
+ break;
+ }
+ default:
+ throw new ArgumentOutOfRangeException(nameof(@case), @case, null);
+ }
+
+ using (client)
{
- username = TestHelper.UniqueUsername("autostaffsessionsignup"),
- password = Password,
- email = TestHelper.UniqueEmail("autostaffsessionsignup"),
- turnstileResponse = "invalid-token"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden);
- }
-
- [Test]
- public async Task PrivilegedApiToken_TokenIsRefused()
- {
- var (_, secret) = await CreateAutomationTokenInDb();
- var staff = await CreateUserWithRoles("autostaffapi", [RoleType.Staff]);
- var (_, apiToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, staff.Id);
-
- using var client = TestHelper.CreateApiTokenClient(WebApplicationFactory, apiToken);
- client.DefaultRequestHeaders.Add(AuthConstants.AutomationTokenHeaderName, secret);
-
- var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
- {
- username = TestHelper.UniqueUsername("autostaffapisignup"),
- password = Password,
- email = TestHelper.UniqueEmail("autostaffapisignup"),
- turnstileResponse = "invalid-token"
- }));
+ var response = await PostSignupWithInvalidTurnstileAsync(client, "autoignored");
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden);
+ await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden);
+ }
}
[Test]
public async Task NormalApiToken_TokenIsHonored()
{
var (_, secret) = await CreateAutomationTokenInDb();
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("autonormalapi"), TestHelper.UniqueEmail("autonormalapi"), Password);
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("autonormalapi"), UniqueNames.Email("autonormalapi"), Password);
var (_, apiToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId);
using var client = TestHelper.CreateApiTokenClient(WebApplicationFactory, apiToken);
client.DefaultRequestHeaders.Add(AuthConstants.AutomationTokenHeaderName, secret);
- var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
- {
- username = TestHelper.UniqueUsername("autonormalapisignup"),
- password = Password,
- email = TestHelper.UniqueEmail("autonormalapisignup"),
- turnstileResponse = "invalid-token"
- }));
+ var response = await PostSignupWithInvalidTurnstileAsync(client, "autonormalapisignup");
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
}
@@ -162,8 +132,8 @@ public async Task NormalApiToken_TokenIsHonored()
public async Task Login_ForNormalAccount_BypassesTurnstileAndAudits()
{
var (_, secret) = await CreateAutomationTokenInDb();
- var email = TestHelper.UniqueEmail("autologin");
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("autologin"), email, Password);
+ var email = UniqueNames.Email("autologin");
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("autologin"), email, Password);
using var client = CreateAutomationClient(secret);
var response = await client.PostAsync("/2/account/login", TestHelper.JsonContent(new
@@ -225,8 +195,8 @@ public async Task PasswordReset_ForPrivilegedAccount_ReturnsOkWithoutStartingRes
public async Task PasswordReset_ForNormalAccount_StartsResetAndAudits()
{
var (_, secret) = await CreateAutomationTokenInDb();
- var email = TestHelper.UniqueEmail("autoreset");
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("autoreset"), email, Password);
+ var email = UniqueNames.Email("autoreset");
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("autoreset"), email, Password);
using var client = CreateAutomationClient(secret);
var response = await client.PostAsync("/2/account/password-reset", TestHelper.JsonContent(new
@@ -342,7 +312,7 @@ public async Task Delete_DeletesTokenAndTheAccountsItCreated()
{
var (tokenId, _) = await CreateAutomationTokenInDb();
var createdId = await CreateUserCreatedByToken(tokenId, "autodelcreated", []);
- var unrelatedId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("autodelunrelated"), TestHelper.UniqueEmail("autodelunrelated"), Password);
+ var unrelatedId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("autodelunrelated"), UniqueNames.Email("autodelunrelated"), Password);
using var client = await CreateAdminClient("autodelete");
var response = await client.DeleteAsync($"/1/admin/automationTokens/{tokenId}");
@@ -358,6 +328,16 @@ public async Task Delete_DeletesTokenAndTheAccountsItCreated()
// --- Helpers ---
+ /// Signs up with a Turnstile response the test server rejects, so it only succeeds when an automation token lifts Turnstile.
+ private static Task PostSignupWithInvalidTurnstileAsync(HttpClient client, string prefix, string? email = null) =>
+ client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
+ {
+ username = UniqueNames.Username(prefix),
+ password = Password,
+ email = email ?? UniqueNames.Email(prefix),
+ turnstileResponse = "invalid-token"
+ }));
+
private HttpClient CreateAutomationClient(string secret)
{
var client = WebApplicationFactory.CreateClient();
@@ -385,7 +365,7 @@ private HttpClient CreateAutomationClient(string secret)
private async Task CreateUserWithRoles(string prefix, List roles)
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername(prefix), TestHelper.UniqueEmail(prefix), Password);
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), Password);
await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService();
@@ -396,7 +376,7 @@ private async Task CreateUserWithRoles(string prefix, List CreateUserCreatedByToken(Guid tokenId, string prefix, List roles)
{
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername(prefix), TestHelper.UniqueEmail(prefix), Password);
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), Password);
await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService();
diff --git a/API.IntegrationTests/Tests/ControlStatChangesTests.cs b/API.IntegrationTests/Tests/ControlStatChangesTests.cs
index 48d260f7..4de7f07e 100644
--- a/API.IntegrationTests/Tests/ControlStatChangesTests.cs
+++ b/API.IntegrationTests/Tests/ControlStatChangesTests.cs
@@ -7,6 +7,7 @@
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Services.AutomationTokens;
using OpenShock.Common.Utils;
+using OpenShock.IntegrationTests.Shared;
using static OpenShock.API.IntegrationTests.Helpers.ControlLogHelper;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -39,7 +40,7 @@ public async Task InitialSync_ReportsEveryRequestedUser_WithReceivedAndGivenTota
var idle = await CreateUser("chgidle");
var notRequested = await CreateUser("chgother");
var shockerId = await CreateShocker(WebApplicationFactory, owner, "Changes");
- var at = new DateTime(2026, 3, 1, 12, 0, 0, DateTimeKind.Utc);
+ var at = MaterializedPast;
await Insert(WebApplicationFactory,
[
@@ -78,7 +79,7 @@ public async Task Since_OnlyReportsUsersWithRecentActivity()
var quietShockerId = await CreateShocker(WebApplicationFactory, quiet, "Quiet");
// Old activity only, outside of any lookback
- var old = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc);
+ var old = MaterializedPast;
await Insert(WebApplicationFactory,
Log(owner, shockerId, owner, old), Log(owner, shockerId, owner, old), Log(owner, shockerId, owner, old),
Log(quiet, quietShockerId, quiet, old));
@@ -110,7 +111,7 @@ public async Task Since_AtMinValue_ReportsUsersWithAnyActivity()
var owner = await CreateUser("chgmin");
var idle = await CreateUser("chgminidle");
var shockerId = await CreateShocker(WebApplicationFactory, owner, "MinValue");
- var at = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc);
+ var at = MaterializedPast;
await Insert(WebApplicationFactory, Log(owner, shockerId, owner, at), Log(owner, shockerId, owner, at));
await RefreshControlStats(WebApplicationFactory);
@@ -155,7 +156,7 @@ public async Task DeletedOwners_AreLeftOutOfGivenTotals()
var controller = await CreateUser("chgdelctl");
var shockerId = await CreateShocker(WebApplicationFactory, owner, "Deleted");
await Insert(WebApplicationFactory,
- Log(owner, shockerId, controller, new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc)));
+ Log(owner, shockerId, controller, MaterializedPast));
await RefreshControlStats(WebApplicationFactory);
await using (var scope = WebApplicationFactory.Services.CreateAsyncScope())
@@ -172,6 +173,12 @@ await Insert(WebApplicationFactory,
await Assert.That(user.GetProperty("given").GetArrayLength()).IsEqualTo(0);
}
+ ///
+ /// Old enough to be materialized by , outside the refresh policy's 3 day window and
+ /// the late write window, well within the logs' one year retention.
+ ///
+ private static DateTime MaterializedPast => DateTime.UtcNow.Date.AddDays(-30).AddHours(12);
+
/// Moves the users' logs out of the change lookback, as if written long ago.
private async Task Backdate(params Guid[] ownerIds)
{
@@ -193,7 +200,7 @@ private static async Task Post(HttpClient client, object body)
}
private Task CreateUser(string prefix) => TestHelper.CreateUserInDb(WebApplicationFactory,
- TestHelper.UniqueUsername(prefix), TestHelper.UniqueEmail(prefix), Password);
+ UniqueNames.Username(prefix), UniqueNames.Email(prefix), Password);
private async Task CreateTokenClient(List types)
{
diff --git a/API.IntegrationTests/Tests/ControlStatsTests.cs b/API.IntegrationTests/Tests/ControlStatsTests.cs
index 9f82738e..3e8ebc9f 100644
--- a/API.IntegrationTests/Tests/ControlStatsTests.cs
+++ b/API.IntegrationTests/Tests/ControlStatsTests.cs
@@ -4,6 +4,7 @@
using Microsoft.Extensions.DependencyInjection;
using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.Common.OpenShockDb;
+using OpenShock.IntegrationTests.Shared;
using static OpenShock.API.IntegrationTests.Helpers.ControlLogHelper;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -18,8 +19,8 @@ public sealed class ControlStatsTests
[Test]
public async Task SendControl_IsCountedInStats_RightAway()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("stats"),
- TestHelper.UniqueEmail("stats"), Password);
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("stats"),
+ UniqueNames.Email("stats"), Password);
var shockerId = await CreateShocker(WebApplicationFactory, user.Id, "Stats Shocker");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
@@ -57,7 +58,11 @@ await Assert.That(shock.GetProperty("averageIntensity").GetDouble())
await Assert.That(controller.GetProperty("userId").GetGuid()).IsEqualTo(user.Id);
await Assert.That(controller.GetProperty("user").GetProperty("name").GetString()).IsEqualTo(user.Username);
- await Assert.That(received.GetProperty("days").GetArrayLength()).IsEqualTo(1);
+ // One day, or two when the run straddles UTC midnight
+ var days = received.GetProperty("days").EnumerateArray().ToArray();
+ await Assert.That(days.Length).IsBetween(1, 2);
+ await Assert.That(days.Sum(d => d.GetProperty("stats").EnumerateArray().Sum(s => s.GetProperty("count").GetInt64())))
+ .IsEqualTo(3);
// Controlling your own shocker counts as given too
var given = doc.RootElement.GetProperty("given");
@@ -68,10 +73,10 @@ await Assert.That(given.GetProperty("owners").EnumerateArray().Single().GetPrope
}
[Test]
- public async Task LiveControlBursts_CountOnce_WithWeightedAverageAndPeakIntensity()
+ public async Task LiveControl_IsCountedSeparately_WithRecordedPeakIntensity()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("statslive"),
- TestHelper.UniqueEmail("statslive"), Password);
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("statslive"),
+ UniqueNames.Email("statslive"), Password);
var shockerId = await CreateShocker(WebApplicationFactory, user.Id, "Live");
var now = DateTime.UtcNow;
@@ -93,8 +98,8 @@ await Assert.That(live.GetProperty("averageIntensity").GetDouble())
[Test]
public async Task Insert_RetriedWithSameIds_IsCountedOnce()
{
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("statsretry"),
- TestHelper.UniqueEmail("statsretry"), Password);
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("statsretry"),
+ UniqueNames.Email("statsretry"), Password);
var shockerId = await CreateShocker(WebApplicationFactory, userId, "Retry");
ShockerControlLog[] logs = [Log(userId, shockerId, userId, DateTime.UtcNow, live: true)];
@@ -111,8 +116,8 @@ await Assert.That(await db.ControlStats.Where(x => x.ShockerId == shockerId).Sum
[Test]
public async Task Insert_ForOwnerDeletedBeforeFlush_IsDropped()
{
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("statsgone"),
- TestHelper.UniqueEmail("statsgone"), Password);
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("statsgone"),
+ UniqueNames.Email("statsgone"), Password);
var shockerId = await CreateShocker(WebApplicationFactory, userId, "Gone");
await using (var scope = WebApplicationFactory.Services.CreateAsyncScope())
@@ -130,8 +135,8 @@ await Assert
[Test]
public async Task DeletingShockers_KeepsTheirStats_CombinedIntoOneEntry()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("statsdel"),
- TestHelper.UniqueEmail("statsdel"), Password);
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("statsdel"),
+ UniqueNames.Email("statsdel"), Password);
var shockerA = await CreateShocker(WebApplicationFactory, user.Id, "A");
var shockerB = await CreateShocker(WebApplicationFactory, user.Id, "B");
var kept = await CreateShocker(WebApplicationFactory, user.Id, "Kept");
@@ -168,10 +173,10 @@ await Assert
[Test]
public async Task DeletingAController_KeepsTheirStats()
{
- var owner = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("statsctlown"),
- TestHelper.UniqueEmail("statsctlown"), Password);
- var controllerId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("statsctl"),
- TestHelper.UniqueEmail("statsctl"), Password);
+ var owner = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("statsctlown"),
+ UniqueNames.Email("statsctlown"), Password);
+ var controllerId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("statsctl"),
+ UniqueNames.Email("statsctl"), Password);
var shockerId = await CreateShocker(WebApplicationFactory, owner.Id, "Controlled");
await Insert(WebApplicationFactory, Log(owner.Id, shockerId, controllerId, DateTime.UtcNow));
@@ -196,15 +201,15 @@ await Assert
[Test]
public async Task DeletingTheOwner_DeletesTheirLogs_AndTheirStatsForControllers()
{
- var ownerId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("statsownd"),
- TestHelper.UniqueEmail("statsownd"), Password);
+ var ownerId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("statsownd"),
+ UniqueNames.Email("statsownd"), Password);
var controller = await TestHelper.CreateAndLoginUser(WebApplicationFactory,
- TestHelper.UniqueUsername("statsownctl"),
- TestHelper.UniqueEmail("statsownctl"), Password);
+ UniqueNames.Username("statsownctl"),
+ UniqueNames.Email("statsownctl"), Password);
var shockerId = await CreateShocker(WebApplicationFactory, ownerId, "Owned");
await Insert(WebApplicationFactory,
- Log(ownerId, shockerId, controller.Id, new DateTime(2026, 2, 1, 12, 0, 0, DateTimeKind.Utc)),
+ Log(ownerId, shockerId, controller.Id, MaterializedPast),
Log(ownerId, shockerId, controller.Id, DateTime.UtcNow));
await RefreshControlStats(WebApplicationFactory);
@@ -226,49 +231,51 @@ await Insert(WebApplicationFactory,
[Test]
public async Task Stats_GroupsDaysInRequestedTimeZone_AndFiltersRange()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("statstz"),
- TestHelper.UniqueEmail("statstz"), Password);
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("statstz"),
+ UniqueNames.Email("statstz"), Password);
var shockerId = await CreateShocker(WebApplicationFactory, user.Id, "Tz");
+ var day = MaterializedPast.Date;
await Insert(WebApplicationFactory,
- // 23:00 UTC on Jan 1 is already Jan 2 in Berlin (UTC+1)
- Log(user.Id, shockerId, user.Id, new DateTime(2026, 1, 1, 23, 0, 0, DateTimeKind.Utc)),
- Log(user.Id, shockerId, user.Id, new DateTime(2026, 1, 5, 12, 0, 0, DateTimeKind.Utc)));
+ // 23:00 UTC is already the next day in Berlin, in summer (UTC+2) as in winter (UTC+1)
+ Log(user.Id, shockerId, user.Id, day.AddHours(23)),
+ Log(user.Id, shockerId, user.Id, day.AddDays(4).AddHours(12)));
await RefreshControlStats(WebApplicationFactory);
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
using (var utc = await GetStats(client))
- await Assert.That(Days(utc)).IsEquivalentTo(new[] { "2026-01-01", "2026-01-05" });
+ await Assert.That(Days(utc)).IsEquivalentTo(new[] { Date(day), Date(day.AddDays(4)) });
using (var berlin = await GetStats(client, "?tz=Europe/Berlin"))
- await Assert.That(Days(berlin)).IsEquivalentTo(new[] { "2026-01-02", "2026-01-05" });
+ await Assert.That(Days(berlin)).IsEquivalentTo(new[] { Date(day.AddDays(1)), Date(day.AddDays(4)) });
- using (var ranged = await GetStats(client, "?tz=Europe/Berlin&from=2026-01-02&to=2026-01-02"))
- await Assert.That(Days(ranged)).IsEquivalentTo(new[] { "2026-01-02" });
+ using (var ranged = await GetStats(client, $"?tz=Europe/Berlin&from={Date(day.AddDays(1))}&to={Date(day.AddDays(1))}"))
+ await Assert.That(Days(ranged)).IsEquivalentTo(new[] { Date(day.AddDays(1)) });
}
[Test]
public async Task Stats_HalfHourOffsetTimeZone_SplitsDaysAtLocalMidnight()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("statskol"),
- TestHelper.UniqueEmail("statskol"), Password);
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("statskol"),
+ UniqueNames.Email("statskol"), Password);
var shockerId = await CreateShocker(WebApplicationFactory, user.Id, "Kolkata");
+ var day = MaterializedPast.Date;
await Insert(WebApplicationFactory,
- // Midnight in Kolkata (UTC+5:30) is 18:30 UTC, in the middle of an hour
- Log(user.Id, shockerId, user.Id, new DateTime(2026, 1, 1, 18, 15, 0, DateTimeKind.Utc)),
- Log(user.Id, shockerId, user.Id, new DateTime(2026, 1, 1, 18, 45, 0, DateTimeKind.Utc)),
- Log(user.Id, shockerId, user.Id, new DateTime(2026, 1, 1, 18, 50, 0, DateTimeKind.Utc)));
+ // Midnight in Kolkata (UTC+5:30, no DST) is 18:30 UTC, in the middle of an hour
+ Log(user.Id, shockerId, user.Id, day.AddHours(18).AddMinutes(15)),
+ Log(user.Id, shockerId, user.Id, day.AddHours(18).AddMinutes(45)),
+ Log(user.Id, shockerId, user.Id, day.AddHours(18).AddMinutes(50)));
await RefreshControlStats(WebApplicationFactory);
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
using (var all = await GetStats(client, "?tz=Asia/Kolkata"))
- await Assert.That(Days(all)).IsEquivalentTo(new[] { "2026-01-01", "2026-01-02" });
+ await Assert.That(Days(all)).IsEquivalentTo(new[] { Date(day), Date(day.AddDays(1)) });
- using var secondDay = await GetStats(client, "?tz=Asia/Kolkata&from=2026-01-02");
- await Assert.That(Days(secondDay)).IsEquivalentTo(new[] { "2026-01-02" });
+ using var secondDay = await GetStats(client, $"?tz=Asia/Kolkata&from={Date(day.AddDays(1))}");
+ await Assert.That(Days(secondDay)).IsEquivalentTo(new[] { Date(day.AddDays(1)) });
await Assert.That(FindTotals(secondDay.RootElement.GetProperty("received").GetProperty("totals"), "Shock",
live: false)
.GetProperty("count").GetInt64()).IsEqualTo(2);
@@ -277,8 +284,8 @@ await Assert.That(FindTotals(secondDay.RootElement.GetProperty("received").GetPr
[Test]
public async Task Stats_InvalidTimeZoneOrRange_Returns400()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("statsbad"),
- TestHelper.UniqueEmail("statsbad"), Password);
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("statsbad"),
+ UniqueNames.Email("statsbad"), Password);
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
var badTz = await client.GetAsync("/1/users/self/control-stats?tz=Not/AZone");
@@ -288,13 +295,13 @@ public async Task Stats_InvalidTimeZoneOrRange_Returns400()
await Assert.That(badRange.StatusCode).IsEqualTo(HttpStatusCode.BadRequest);
}
- [Test]
- public async Task Stats_Unauthenticated_Returns401()
- {
- using var client = WebApplicationFactory.CreateClient();
- var response = await client.GetAsync("/1/users/self/control-stats");
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
- }
+ ///
+ /// Old enough to be materialized by and outside the refresh policy's 3 day
+ /// window, well within the logs' one year retention.
+ ///
+ private static DateTime MaterializedPast => DateTime.UtcNow.Date.AddDays(-30);
+
+ private static string Date(DateTime day) => day.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
private static async Task GetStats(HttpClient client, string query = "")
{
diff --git a/API.IntegrationTests/Tests/DatabaseConstraintTests.cs b/API.IntegrationTests/Tests/DatabaseConstraintTests.cs
index 4fa88d38..6ff02bae 100644
--- a/API.IntegrationTests/Tests/DatabaseConstraintTests.cs
+++ b/API.IntegrationTests/Tests/DatabaseConstraintTests.cs
@@ -5,12 +5,14 @@
using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.Common.Models;
using OpenShock.Common.OpenShockDb;
+using OpenShock.IntegrationTests.Shared;
namespace OpenShock.API.IntegrationTests.Tests;
///
/// 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.
+/// username blacklist query, the audit log metadata column, the check constraints and the control stats refresh
+/// policy.
///
public sealed class DatabaseConstraintTests
{
@@ -18,30 +20,22 @@ public sealed class DatabaseConstraintTests
public required WebApplicationFactory WebApplicationFactory { get; init; }
[Test]
- public async Task Email_LookupIgnoresCase()
+ public async Task Email_LookupAndUniquenessIgnoreCase()
{
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, "dbemaillookup", "dbemaillookup@test.org", "SecurePassword123#");
+ var email = UniqueNames.Email("dbemail");
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("dbemail"), email, "SecurePassword123#");
await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService();
- var found = await db.Users.Where(u => u.Email == "DbEmailLookup@Test.ORG").Select(u => u.Id).ToListAsync();
-
+ // The column's collation makes the lookup ignore case, the unique index's own collation the uniqueness
+ var found = await db.Users.Where(u => u.Email == email.ToUpperInvariant()).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();
db.Users.Add(new User
{
- Name = "dbemailunique2",
- Email = "DBEMAILUNIQUE@test.org",
+ Name = UniqueNames.Username("dbemail"),
+ Email = email.ToUpperInvariant(),
PasswordHash = null,
ActivatedAt = DateTime.UtcNow
});
@@ -94,11 +88,12 @@ async Task Matching(string username) =>
}
[Test]
- public async Task AuditLog_RoundTripsIpAddressAndMetadata()
+ public async Task AuditLog_MetadataKeepsItsSubtype()
{
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, "dbauditroundtrip", "dbauditroundtrip@test.org", "SecurePassword123#");
+ // Left to Npgsql's own JSON mapping, the runtime type is serialized without its discriminator and reads
+ // back as the base type
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("dbaudit"), UniqueNames.Email("dbaudit"), "SecurePassword123#");
var sessionId = Guid.CreateVersion7();
- var ipAddress = IPAddress.Parse("2001:db8::1");
await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService();
@@ -108,7 +103,7 @@ public async Task AuditLog_RoundTripsIpAddressAndMetadata()
UserId = userId,
ActorId = userId,
Action = AuditAction.Login,
- IpAddress = ipAddress,
+ IpAddress = IPAddress.Loopback,
Metadata = new LoginMetadata(sessionId),
CreatedAt = DateTime.UtcNow
};
@@ -117,14 +112,13 @@ public async Task AuditLog_RoundTripsIpAddressAndMetadata()
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 userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("dbtokenlimits"), UniqueNames.Email("dbtokenlimits"), "SecurePassword123#");
var (tokenId, _) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId);
await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
@@ -144,4 +138,18 @@ public async Task ApiToken_RejectsControlLimitsOutOfRange()
.Throws();
await Assert.That(minimumAboveMaximum!.SqlState).IsEqualTo(PostgresErrorCodes.CheckViolation);
}
+
+ [Test]
+ public async Task ControlStats_HasRefreshPolicy()
+ {
+ await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+
+ var policies = await db.Database.SqlQuery($"""
+ SELECT count(*)::int AS "Value" FROM timescaledb_information.jobs
+ WHERE proc_name = 'policy_refresh_continuous_aggregate' AND hypertable_name = 'control_stats'
+ """).SingleAsync();
+
+ await Assert.That(policies).IsEqualTo(1);
+ }
}
diff --git a/API.IntegrationTests/Tests/DeviceEndpointTests.cs b/API.IntegrationTests/Tests/DeviceEndpointTests.cs
index f3e06b4f..14a7350e 100644
--- a/API.IntegrationTests/Tests/DeviceEndpointTests.cs
+++ b/API.IntegrationTests/Tests/DeviceEndpointTests.cs
@@ -3,6 +3,7 @@
using Microsoft.Extensions.DependencyInjection;
using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.Common.OpenShockDb;
+using OpenShock.IntegrationTests.Shared;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -15,95 +16,57 @@ public sealed class DeviceEndpointTests
[ClassDataSource(Shared = SharedType.PerTestSession)]
public required WebApplicationFactory WebApplicationFactory { get; init; }
- // --- Get Device Self ---
-
[Test]
- public async Task GetDeviceSelf_ReturnsDeviceInfo()
+ public async Task GetDeviceSelf_ReturnsTheCallingHubAndOnlyItsShockers()
{
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, "hubself", "hubself@test.org", "SecurePassword123#");
- var (_, hubToken) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, userId, "MyHub");
- using var client = TestHelper.CreateHubTokenClient(WebApplicationFactory, hubToken);
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("hubself"),
+ UniqueNames.Email("hubself"), "SecurePassword123#");
+ var (deviceId, hubToken) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, userId, "MyHub");
+ var (otherDeviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, userId, "OtherHub");
+ var shockerId = await CreateShocker(deviceId, 500);
+ await CreateShocker(otherDeviceId, 501);
+ using var client = TestHelper.CreateHubTokenClient(WebApplicationFactory, hubToken);
var response = await client.GetAsync("/1/device/self");
-
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
- var json = await response.Content.ReadAsStringAsync();
- using var doc = JsonDocument.Parse(json);
+ using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var data = doc.RootElement.GetProperty("data");
+ await Assert.That(data.GetProperty("id").GetGuid()).IsEqualTo(deviceId);
await Assert.That(data.GetProperty("name").GetString()).IsEqualTo("MyHub");
- await Assert.That(data.TryGetProperty("shockers", out _)).IsTrue();
- }
-
- [Test]
- public async Task GetDeviceSelf_WithShockers_ReturnsShockerList()
- {
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, "hubshockers", "hubshockers@test.org", "SecurePassword123#");
- var (deviceId, hubToken) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, userId, "HubWithShockers");
-
- // Add a shocker to this device
- await using (var scope = WebApplicationFactory.Services.CreateAsyncScope())
- {
- var db = scope.ServiceProvider.GetRequiredService();
- db.Shockers.Add(new Shocker
- {
- Id = Guid.CreateVersion7(),
- Name = "HubShocker",
- RfId = 500,
- DeviceId = deviceId,
- Model = ShockerModelType.CaiXianlin
- });
- await db.SaveChangesAsync();
- }
-
- using var client = TestHelper.CreateHubTokenClient(WebApplicationFactory, hubToken);
-
- var response = await client.GetAsync("/1/device/self");
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
-
- var json = await response.Content.ReadAsStringAsync();
- using var doc = JsonDocument.Parse(json);
- var shockers = doc.RootElement.GetProperty("data").GetProperty("shockers");
- await Assert.That(shockers.GetArrayLength()).IsGreaterThanOrEqualTo(1);
+ var shocker = data.GetProperty("shockers").EnumerateArray().Single();
+ await Assert.That(shocker.GetProperty("id").GetGuid()).IsEqualTo(shockerId);
+ await Assert.That(shocker.GetProperty("rfId").GetInt32()).IsEqualTo(500);
}
- // --- Invalid Hub Token ---
-
[Test]
- public async Task GetDeviceSelf_InvalidToken_Returns401()
+ [Arguments(null)]
+ [Arguments("completely-invalid-token")]
+ public async Task GetDeviceSelf_MissingOrInvalidToken_Returns401(string? hubToken)
{
- using var client = TestHelper.CreateHubTokenClient(WebApplicationFactory, "completely-invalid-token");
+ using var client = hubToken is null
+ ? WebApplicationFactory.CreateClient()
+ : TestHelper.CreateHubTokenClient(WebApplicationFactory, hubToken);
var response = await client.GetAsync("/1/device/self");
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
}
- // --- Hub token on session-only endpoint should fail ---
-
- [Test]
- public async Task HubToken_OnSessionOnlyEndpoint_Returns401()
+ private async Task CreateShocker(Guid deviceId, ushort rfId)
{
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, "hubwrong", "hubwrong@test.org", "SecurePassword123#");
- var (_, hubToken) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, userId, "WrongHub");
- using var client = TestHelper.CreateHubTokenClient(WebApplicationFactory, hubToken);
-
- // Tokens endpoint requires UserSessionCookie, not HubToken
- var response = await client.GetAsync("/1/tokens");
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
- }
-
- // --- No auth ---
-
- [Test]
- public async Task GetDeviceSelf_NoAuth_Returns401()
- {
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.GetAsync("/1/device/self");
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
+ await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var shockerId = Guid.CreateVersion7();
+ db.Shockers.Add(new Shocker
+ {
+ Id = shockerId,
+ Name = "HubShocker",
+ RfId = rfId,
+ DeviceId = deviceId,
+ Model = ShockerModelType.CaiXianlin
+ });
+ await db.SaveChangesAsync();
+ return shockerId;
}
}
diff --git a/API.IntegrationTests/Tests/DevicesTests.cs b/API.IntegrationTests/Tests/DevicesTests.cs
index cf9f3603..d0f17c51 100644
--- a/API.IntegrationTests/Tests/DevicesTests.cs
+++ b/API.IntegrationTests/Tests/DevicesTests.cs
@@ -1,108 +1,57 @@
using System.Net;
using System.Text.Json;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
using OpenShock.API.IntegrationTests.Helpers;
+using OpenShock.Common.OpenShockDb;
+using OpenShock.IntegrationTests.Shared;
namespace OpenShock.API.IntegrationTests.Tests;
public sealed class DevicesTests
{
+ private const string Password = "SecurePassword123#";
+
[ClassDataSource(Shared = SharedType.PerTestSession)]
public required WebApplicationFactory WebApplicationFactory { get; init; }
- // --- List Devices ---
-
[Test]
- public async Task ListDevices_Empty_ReturnsEmptyArray()
+ public async Task ListDevices_ReturnsOnlyOwnDevices()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "devempty", "devempty@test.org", "SecurePassword123#");
+ var user = await CreateUser("devlist");
+ var other = await CreateUser("devlistoth");
+ var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id, "Mine");
+ await TestHelper.CreateDeviceInDb(WebApplicationFactory, other.Id, "Theirs");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
- var response = await client.GetAsync("/1/devices");
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
-
- var json = await response.Content.ReadAsStringAsync();
- using var doc = JsonDocument.Parse(json);
- var data = doc.RootElement.GetProperty("data");
- await Assert.That(data.GetArrayLength()).IsEqualTo(0);
+ var device = (await ListDevices(client)).Single();
+ await Assert.That(device.GetProperty("id").GetGuid()).IsEqualTo(deviceId);
+ await Assert.That(device.GetProperty("name").GetString()).IsEqualTo("Mine");
}
- // --- Create Device (V1 + V2) ---
-
[Test]
- public async Task CreateDeviceV1_Returns201()
+ [Arguments(1)]
+ [Arguments(2)]
+ public async Task CreateDevice_Returns201_AndListsTheNewHub(int version)
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "devv1create", "devv1create@test.org", "SecurePassword123#");
+ var user = await CreateUser("devcreate");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
- var response = await client.PostAsync("/1/devices", null);
-
+ var response = version == 1
+ ? await client.PostAsync("/1/devices", null)
+ : await client.PostAsync("/2/devices", TestHelper.JsonContent(new { name = "My Custom Hub" }));
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Created);
- }
- [Test]
- public async Task CreateDeviceV2_WithName_Returns201()
- {
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "devv2create", "devv2create@test.org", "SecurePassword123#");
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
-
- var response = await client.PostAsync("/2/devices", TestHelper.JsonContent(new
- {
- name = "My Custom Hub"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Created);
+ var device = (await ListDevices(client)).Single();
+ var name = device.GetProperty("name").GetString();
+ if (version == 1) await Assert.That(name).StartsWith("New Hub ");
+ else await Assert.That(name).IsEqualTo("My Custom Hub");
}
- // --- Get Device by ID ---
-
- [Test]
- public async Task GetDeviceById_Success()
- {
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "devgetone", "devgetone@test.org", "SecurePassword123#");
- var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id, "TestHub1");
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
-
- var response = await client.GetAsync($"/1/devices/{deviceId}");
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
-
- var json = await response.Content.ReadAsStringAsync();
- using var doc = JsonDocument.Parse(json);
- var data = doc.RootElement.GetProperty("data");
- await Assert.That(data.GetProperty("name").GetString()).IsEqualTo("TestHub1");
- }
-
- [Test]
- public async Task GetDeviceById_NonexistentId_Returns404()
- {
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "devget404", "devget404@test.org", "SecurePassword123#");
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
-
- var response = await client.GetAsync($"/1/devices/{Guid.CreateVersion7()}");
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
- }
-
- [Test]
- public async Task GetDeviceById_OtherUsersDevice_Returns404()
- {
- var user1 = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "devowner", "devowner@test.org", "SecurePassword123#");
- var user2 = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "devother", "devother@test.org", "SecurePassword123#");
- var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user1.Id, "OwnerHub");
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user2.SessionToken);
-
- var response = await client.GetAsync($"/1/devices/{deviceId}");
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
- }
-
- // --- Edit Device ---
-
[Test]
public async Task EditDevice_Rename_Success()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "devedit", "devedit@test.org", "SecurePassword123#");
+ var user = await CreateUser("devedit");
var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id, "OldName");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
@@ -110,117 +59,106 @@ public async Task EditDevice_Rename_Success()
{
name = "RenamedHub"
}));
-
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
- // Verify name changed
- var getResponse = await client.GetAsync($"/1/devices/{deviceId}");
- var json = await getResponse.Content.ReadAsStringAsync();
- using var doc = JsonDocument.Parse(json);
- var name = doc.RootElement.GetProperty("data").GetProperty("name").GetString();
- await Assert.That(name).IsEqualTo("RenamedHub");
- }
-
- [Test]
- public async Task EditDevice_Nonexistent_Returns404()
- {
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "devedit404", "devedit404@test.org", "SecurePassword123#");
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
-
- var response = await client.PatchAsync($"/1/devices/{Guid.CreateVersion7()}", TestHelper.JsonContent(new
- {
- name = "Whatever"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
+ using var doc = JsonDocument.Parse(await client.GetStringAsync($"/1/devices/{deviceId}"));
+ await Assert.That(doc.RootElement.GetProperty("data").GetProperty("name").GetString()).IsEqualTo("RenamedHub");
}
- // --- Delete Device ---
-
[Test]
public async Task DeleteDevice_Success()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "devdel", "devdel@test.org", "SecurePassword123#");
+ var user = await CreateUser("devdel");
var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id, "ToDelete");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
var response = await client.DeleteAsync($"/1/devices/{deviceId}");
-
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
- // Verify it no longer exists
var getResponse = await client.GetAsync($"/1/devices/{deviceId}");
await Assert.That(getResponse.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
}
[Test]
- public async Task DeleteDevice_Nonexistent_Returns404()
- {
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "devdel404", "devdel404@test.org", "SecurePassword123#");
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
-
- var response = await client.DeleteAsync($"/1/devices/{Guid.CreateVersion7()}");
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
- }
-
- // --- Regenerate Device Token ---
-
- [Test]
- public async Task RegenerateDeviceToken_ReturnsNewToken()
+ public async Task RegenerateDeviceToken_OldTokenStopsWorking_NewTokenWorks()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "devregen", "devregen@test.org", "SecurePassword123#");
+ var user = await CreateUser("devregen");
var (deviceId, originalToken) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id, "RegenHub");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
var response = await client.PutAsync($"/1/devices/{deviceId}", null);
-
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
- var newToken = await response.Content.ReadAsStringAsync();
- await Assert.That(newToken).IsNotNullOrWhiteSpace();
+ string newToken;
+ await using (var scope = WebApplicationFactory.Services.CreateAsyncScope())
+ {
+ var db = scope.ServiceProvider.GetRequiredService();
+ newToken = await db.Devices.Where(x => x.Id == deviceId).Select(x => x.Token).SingleAsync();
+ }
await Assert.That(newToken).IsNotEqualTo(originalToken);
- }
+ await Assert.That(await response.Content.ReadAsStringAsync()).Contains(newToken);
- // --- Get Device Shockers ---
+ using var oldHub = TestHelper.CreateHubTokenClient(WebApplicationFactory, originalToken);
+ await Assert.That((await oldHub.GetAsync("/1/device/self")).StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
+
+ using var newHub = TestHelper.CreateHubTokenClient(WebApplicationFactory, newToken);
+ await Assert.That((await newHub.GetAsync("/1/device/self")).StatusCode).IsEqualTo(HttpStatusCode.OK);
+ }
[Test]
- public async Task GetDeviceShockers_EmptyDevice_ReturnsEmptyList()
+ public async Task GetDeviceShockers_ReturnsTheHubsShockers()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "devshock0", "devshock0@test.org", "SecurePassword123#");
- var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id, "EmptyHub");
+ var user = await CreateUser("devshock");
+ var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id, "ShockerHub");
+ var (otherDeviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id, "OtherHub");
+ var shockerId = await CreateShockerInDb(deviceId, maxIntensity: 40);
+ await CreateShockerInDb(otherDeviceId, maxIntensity: null);
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
- var response = await client.GetAsync($"/1/devices/{deviceId}/shockers");
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
-
- var json = await response.Content.ReadAsStringAsync();
- using var doc = JsonDocument.Parse(json);
- var data = doc.RootElement.GetProperty("data");
- await Assert.That(data.GetArrayLength()).IsEqualTo(0);
+ using var doc = JsonDocument.Parse(await client.GetStringAsync($"/1/devices/{deviceId}/shockers"));
+ var shocker = doc.RootElement.GetProperty("data").EnumerateArray().Single();
+ await Assert.That(shocker.GetProperty("id").GetGuid()).IsEqualTo(shockerId);
+ await Assert.That(shocker.GetProperty("limits").GetProperty("intensity").GetInt32()).IsEqualTo(40);
}
[Test]
- public async Task GetDeviceShockers_WrongDevice_Returns404()
+ public async Task GetDeviceShockers_OtherUsersDevice_Returns404()
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "devshock404", "devshock404@test.org", "SecurePassword123#");
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
+ var owner = await CreateUser("devshockown");
+ var other = await CreateUser("devshockoth");
+ var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, owner.Id, "PrivateHub");
+ await CreateShockerInDb(deviceId, maxIntensity: null);
+ using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, other.SessionToken);
- var response = await client.GetAsync($"/1/devices/{Guid.CreateVersion7()}/shockers");
+ var response = await client.GetAsync($"/1/devices/{deviceId}/shockers");
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
}
- // --- Unauthorized ---
+ private Task CreateUser(string prefix) =>
+ TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), Password);
- [Test]
- public async Task ListDevices_Unauthenticated_Returns401()
+ private static async Task ListDevices(HttpClient client)
{
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.GetAsync("/1/devices");
+ using var doc = JsonDocument.Parse(await client.GetStringAsync("/1/devices"));
+ return doc.RootElement.GetProperty("data").EnumerateArray().Select(x => x.Clone()).ToArray();
+ }
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
+ private async Task CreateShockerInDb(Guid deviceId, byte? maxIntensity)
+ {
+ await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var shockerId = Guid.CreateVersion7();
+ db.Shockers.Add(new Shocker
+ {
+ Id = shockerId,
+ Name = "DeviceShocker",
+ RfId = 700,
+ DeviceId = deviceId,
+ Model = ShockerModelType.CaiXianlin,
+ MaxIntensity = maxIntensity
+ });
+ await db.SaveChangesAsync();
+ return shockerId;
}
}
diff --git a/API.IntegrationTests/Tests/EmailOutboxPersistenceTests.cs b/API.IntegrationTests/Tests/EmailOutboxPersistenceTests.cs
deleted file mode 100644
index f4381ef2..00000000
--- a/API.IntegrationTests/Tests/EmailOutboxPersistenceTests.cs
+++ /dev/null
@@ -1,99 +0,0 @@
-using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.DependencyInjection;
-using OpenShock.API.IntegrationTests.Helpers;
-using OpenShock.Common.OpenShockDb;
-
-namespace OpenShock.API.IntegrationTests.Tests;
-
-///
-/// Database round-trip coverage for the email_outbox row against real Postgres: that every
-/// (including the new sending/skipped enum values) and the new
-/// attempt/next-attempt columns persist and read back, and that the delivery job's claim predicate
-/// (the enum filter used by the FOR UPDATE SKIP LOCKED query) selects the right rows. The pure
-/// transition logic is covered by the Cron unit tests; this guards the persistence mapping the unit
-/// tests can't.
-///
-public sealed class EmailOutboxPersistenceTests
-{
- [ClassDataSource(Shared = SharedType.PerTestSession)]
- public required WebApplicationFactory WebApplicationFactory { get; init; }
-
- [Test]
- public async Task EveryStatus_AndAttemptColumns_RoundTripThroughPostgres()
- {
- var factory = WebApplicationFactory.Services.GetRequiredService>();
-
- foreach (var status in Enum.GetValues())
- {
- Guid id;
- await using (var db = await factory.CreateDbContextAsync())
- {
- var message = EmailOutboxMessage.Create(
- EmailType.PasswordReset, TestHelper.UniqueEmail("outbox-persist"), "Persist",
- new Dictionary { ["k"] = "v" });
- message.Status = status;
- message.AttemptCount = 3;
- message.LastError = "boom";
- message.CoalesceKey = "pwreset:round-trip";
- db.EmailOutbox.Add(message);
- await db.SaveChangesAsync();
- id = message.Id;
- }
-
- await using var verifyDb = await factory.CreateDbContextAsync();
- var loaded = await verifyDb.EmailOutbox.AsNoTracking().FirstAsync(m => m.Id == id);
-
- await Assert.That(loaded.Status).IsEqualTo(status);
- await Assert.That(loaded.AttemptCount).IsEqualTo(3);
- await Assert.That(loaded.LastError).IsEqualTo("boom");
- await Assert.That(loaded.CoalesceKey).IsEqualTo("pwreset:round-trip");
- }
- }
-
- [Test]
- public async Task ClaimPredicate_SelectsDuePendingAndLapsedSending_NotTerminalOrFuture()
- {
- var factory = WebApplicationFactory.Services.GetRequiredService>();
- var recipient = TestHelper.UniqueEmail("outbox-claim");
- var past = DateTime.UtcNow - TimeSpan.FromMinutes(5);
- var future = DateTime.UtcNow + TimeSpan.FromHours(1);
-
- var duePending = await SeedAsync(factory, recipient, EmailStatus.Pending, past);
- var lapsedSending = await SeedAsync(factory, recipient, EmailStatus.Sending, past);
- await SeedAsync(factory, recipient, EmailStatus.Pending, future); // scheduled retry, not yet due
- await SeedAsync(factory, recipient, EmailStatus.Sent, past); // terminal
-
- await using var db = await factory.CreateDbContextAsync();
-
- // The delivery job's claim predicate (enum filter + dueness), scoped to this test's recipient so
- // it never touches rows from other tests and needs no FOR UPDATE.
- var claimed = await db.EmailOutbox
- .FromSql(
- $"""
- SELECT * FROM email_outbox
- WHERE recipient = {recipient}
- AND next_attempt_at <= now()
- AND (status = {EmailStatus.Pending} OR status = {EmailStatus.Sending})
- """)
- .AsNoTracking()
- .Select(m => m.Id)
- .ToListAsync();
-
- await Assert.That(claimed).Contains(duePending);
- await Assert.That(claimed).Contains(lapsedSending);
- await Assert.That(claimed.Count).IsEqualTo(2);
- }
-
- private static async Task SeedAsync(IDbContextFactory factory, string recipient, EmailStatus status, DateTime nextAttemptAt)
- {
- await using var db = await factory.CreateDbContextAsync();
- var message = EmailOutboxMessage.Create(
- EmailType.PasswordReset, recipient, "Claim",
- new Dictionary { ["k"] = "v" });
- message.Status = status;
- message.NextAttemptAt = nextAttemptAt;
- db.EmailOutbox.Add(message);
- await db.SaveChangesAsync();
- return message.Id;
- }
-}
diff --git a/API.IntegrationTests/Tests/EmailProviderBlacklistTests.cs b/API.IntegrationTests/Tests/EmailProviderBlacklistTests.cs
index ea8a4c4b..4a9f0064 100644
--- a/API.IntegrationTests/Tests/EmailProviderBlacklistTests.cs
+++ b/API.IntegrationTests/Tests/EmailProviderBlacklistTests.cs
@@ -5,6 +5,7 @@
using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.Common.Models;
using OpenShock.Common.OpenShockDb;
+using OpenShock.IntegrationTests.Shared;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -63,7 +64,9 @@ public async Task Add_WithAnyInvalidEntry_AddsNothing(CancellationToken cancella
{
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"];
+ // Which entries are domains is EmailValidator.TryNormalizeDomain's business (EmailValidatorTests); these
+ // are the shapes it rejects that its tests do not list.
+ string[] invalid = ["@", new string('a', 250) + ".example", "under_score.example", "-leading.example", "trailing-.example", "double..dot.example"];
try
{
@@ -126,7 +129,7 @@ private async Task DeleteDomains(string suffix)
private async Task CreateAdminClient(string prefix)
{
- var admin = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername(prefix), TestHelper.UniqueEmail(prefix), "SecurePassword123#");
+ var admin = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), "SecurePassword123#");
await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService();
diff --git a/API.IntegrationTests/Tests/EmailStatusEnumTests.cs b/API.IntegrationTests/Tests/EmailStatusEnumTests.cs
new file mode 100644
index 00000000..c187ca66
--- /dev/null
+++ b/API.IntegrationTests/Tests/EmailStatusEnumTests.cs
@@ -0,0 +1,33 @@
+using System.Reflection;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using NpgsqlTypes;
+using OpenShock.Common.OpenShockDb;
+
+namespace OpenShock.API.IntegrationTests.Tests;
+
+///
+/// Every the code can write exists in the database's email_status type. The delivery
+/// flows only ever reach some of the states, so a value added without a migration would only fail in production.
+///
+public sealed class EmailStatusEnumTests
+{
+ [ClassDataSource(Shared = SharedType.PerTestSession)]
+ public required WebApplicationFactory WebApplicationFactory { get; init; }
+
+ [Test]
+ public async Task EveryEmailStatus_IsAValueOfTheDatabaseEnum()
+ {
+ var mapped = Enum.GetNames()
+ .Select(name => typeof(EmailStatus).GetField(name)!.GetCustomAttribute()!.PgName)
+ .ToHashSet();
+
+ await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var inDatabase = await db.Database
+ .SqlQueryRaw("""SELECT unnest(enum_range(NULL::email_status))::text AS "Value" """)
+ .ToListAsync();
+
+ await Assert.That(inDatabase).IsEquivalentTo(mapped);
+ }
+}
diff --git a/API.IntegrationTests/Tests/LcgAssignmentTests.cs b/API.IntegrationTests/Tests/LcgAssignmentTests.cs
index bec7ce20..744e24d9 100644
--- a/API.IntegrationTests/Tests/LcgAssignmentTests.cs
+++ b/API.IntegrationTests/Tests/LcgAssignmentTests.cs
@@ -1,235 +1,236 @@
using System.Net;
-using System.Net.Mime;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
+using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.API.Models.Response;
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Redis;
-using OpenShock.Common.Utils;
-using OpenShock.Internal.Common.Utils;
+using OpenShock.Common.Services.Geo;
+using OpenShock.IntegrationTests.Shared;
using Redis.OM.Contracts;
namespace OpenShock.API.IntegrationTests.Tests;
+///
+/// Which gateway /2/device/assignLCG hands a hub. Where loads are given, they are chosen so that the
+/// wrong pick would win on load alone: the provisioner picks randomly among equally loaded nodes, so equal loads
+/// would let a broken rule pass half the time.
+///
public sealed class LcgAssignmentTests
{
[ClassDataSource(Shared = SharedType.PerTestSession)]
public required WebApplicationFactory WebApplicationFactory { get; init; }
- private const string ParalellGateway = "gateway_assignment";
+ // Every test here wipes the whole Redis node collection
+ private const string GatewayAssignment = "gateway_assignment";
+
+ private static readonly GeoPoint Seattle = new(47.61, -122.33);
+ private static readonly GeoPoint NewYork = new(40.71, -74.01);
+ private static readonly GeoPoint Oregon = new(45.60, -121.18);
+ private static readonly GeoPoint Virginia = new(39.04, -77.49);
+ private static readonly GeoPoint Frankfurt = new(50.11, 8.68);
+ private static readonly GeoPoint Munich = new(48.14, 11.58);
+ private static readonly GeoPoint Hamburg = new(53.55, 9.99);
+ private static readonly GeoPoint Vienna = new(48.21, 16.37);
+
private Guid _userId;
- private Guid _hubId;
private string _hubToken = string.Empty;
[Before(Test)]
public async Task Setup()
{
- // Dependency Resolution
- await using var context = WebApplicationFactory.Services.CreateAsyncScope();
- var db = context.ServiceProvider.GetRequiredService();
-
- // Set up variables
- _userId = Guid.CreateVersion7();
- _hubId = Guid.CreateVersion7();
- _hubToken = CryptoUtils.RandomString(256);
-
- // Create mock data
- db.Users.Add(new User
- {
- Id = _userId,
- Name = _userId.ToString("N"),
- Email = $"{_userId}@test.org",
- PasswordHash = HashingUtils.HashPassword("password")
- });
- db.Devices.Add(new Device
- {
- Id = _hubId,
- Name = "TestHub",
- OwnerId = _userId,
- Token = _hubToken,
- CreatedAt = DateTime.UtcNow
- });
- await db.SaveChangesAsync();
+ _userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("lcg"), UniqueNames.Email("lcg"), "SecurePassword123#");
+ (_, _hubToken) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, _userId);
}
[After(Test)]
public async Task Teardown()
{
- // Dependency Resolution
- await using var context = WebApplicationFactory.Services.CreateAsyncScope();
- var db = context.ServiceProvider.GetRequiredService();
- var redisConnectionProvider = context.ServiceProvider.GetRequiredService();
- var lcgNodesCollection = redisConnectionProvider.RedisCollection(false);
+ await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var lcgNodes = scope.ServiceProvider.GetRequiredService().RedisCollection(false);
- // Data cleanup
- await db.Devices.Where(x => x.Id == _hubId).ExecuteDeleteAsync();
+ await db.Devices.Where(x => x.OwnerId == _userId).ExecuteDeleteAsync();
await db.Users.Where(x => x.Id == _userId).ExecuteDeleteAsync();
- var allLcg = await lcgNodesCollection.ToListAsync();
- await lcgNodesCollection.DeleteAsync(allLcg);
+ await lcgNodes.DeleteAsync(await lcgNodes.ToListAsync());
}
[Test]
- [NotInParallel(ParalellGateway)]
- [Arguments("US", "us1.example.com")]
- [Arguments("DE", "de1.example.com")]
- [Arguments("CA", "us1.example.com")]
- [Arguments("CA", "us1.example.com")]
- [Arguments("AT", "de1.example.com")]
- [Arguments("FR", "de1.example.com")]
- public async Task CheckBasicAssignments(string requesterCountry, string expectedHost)
- {
- await AddGateways(["US|us1.example.com", "DE|de1.example.com", "AS|as1.example.com"]);
- var response = await SendAssignRequest(requesterCountry);
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
- var mediaType = response.Content.Headers.ContentType?.MediaType;
- await Assert.That(mediaType).IsEqualTo(MediaTypeNames.Application.Json);
+ [NotInParallel(GatewayAssignment)]
+ public async Task PicksGatewayInNearestCountry_WhenRequesterCountryHasNone()
+ {
+ await AddGateway("us1.example.com", "US", null);
+ await AddGateway("de1.example.com", "DE", null);
+ await AddGateway("jp1.example.com", "JP", null);
- var data = await response.Content.ReadFromJsonAsync();
- await Assert.That(data).IsNotNull();
- await Assert.That(data!.Host).IsEqualTo(expectedHost);
+ await Assert.That(await AssignHost("AT")).IsEqualTo("de1.example.com");
}
[Test]
- [NotInParallel(ParalellGateway)]
+ [NotInParallel(GatewayAssignment)]
[Arguments("US")]
- [Arguments("DE")]
+ [Arguments("XX")] // Cloudflare's "unknown", which takes the no-country path
+ public async Task NoGateways_Returns503(string requesterCountry)
+ {
+ using var response = await SendAssignRequest(requesterCountry);
+
+ await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.ServiceUnavailable);
+ }
+
+ [Test]
+ [NotInParallel(GatewayAssignment)]
[Arguments("XX")]
- [Arguments(null)]
- public async Task CheckAnyGateway(string? requesterCountry)
+ [Arguments("DE")]
+ public async Task GatewaysOfAnotherEnvironment_AreNotAssigned(string requesterCountry)
+ {
+ await AddGateway("de-dev.example.com", "DE", null, environment: "SomethingThatDoesntExist!");
+
+ using var response = await SendAssignRequest(requesterCountry);
+
+ await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.ServiceUnavailable);
+ }
+
+ [Test]
+ [NotInParallel(GatewayAssignment)]
+ [Arguments(8080, "/gateway", 2u, "/gateway/2/ws/hub")]
+ [Arguments(443, "", 2u, "/2/ws/hub")]
+ [Arguments(443, "", 1u, "/1/ws/hub")]
+ public async Task AdvertisesGatewayPortAndPath(int port, string pathPrefix, uint schemaVersion, string expectedPath)
{
- await AddGateways(["US|us1.example.com", "DE|de1.example.com", "AS|as1.example.com"]);
- var response = await SendAssignRequest(requesterCountry);
+ await AddGateway("de1.example.com", "DE", null, port: (ushort)port, pathPrefix: pathPrefix);
+
+ using var response = await SendAssignRequest("DE", schemaVersion);
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
- var mediaType = response.Content.Headers.ContentType?.MediaType;
- await Assert.That(mediaType).IsEqualTo(MediaTypeNames.Application.Json);
var data = await response.Content.ReadFromJsonAsync();
await Assert.That(data).IsNotNull();
- await Assert.That(data!.Host).IsNotNullOrWhiteSpace();
+ await Assert.That(data!.Host).IsEqualTo("de1.example.com");
+ await Assert.That(data.Port).IsEqualTo((ushort)port);
+ await Assert.That(data.Path).IsEqualTo(expectedPath);
}
[Test]
- [NotInParallel(ParalellGateway)]
- [Arguments("US")]
- [Arguments("XX")]
- [Arguments(null)]
- public async Task CheckUnavailable(string? requesterCountry)
+ [NotInParallel(GatewayAssignment)]
+ [Arguments(47.61, -122.33, 50, 0, "us-west.example.com")] // Seattle
+ [Arguments(40.71, -74.01, 0, 50, "us-east.example.com")] // New York
+ public async Task PicksClosestGatewayWithinSameCountry_OverLoad(double latitude, double longitude, int westLoad, int eastLoad, string expectedHost)
{
- // We dont add any gateways here
- var response = await SendAssignRequest(requesterCountry);
+ // Both gateways are "US", so the country table alone ties them; coordinates break the tie, even against load
+ await AddGateway("us-west.example.com", "US", Oregon, load: (byte)westLoad);
+ await AddGateway("us-east.example.com", "US", Virginia, load: (byte)eastLoad);
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.ServiceUnavailable);
+ await Assert.That(await AssignHost("US", new GeoPoint(latitude, longitude))).IsEqualTo(expectedHost);
}
[Test]
- [NotInParallel(ParalellGateway)]
- public async Task CheckEnvironmentFilter()
- {
- await AddGateways([
- "US|us-dev.example.com",
- "DE|de-dev.example.com",
- "AS|as-dev.example.com"
- ], "SomethingThatDoesntExist!");
-
- // This sends a request with an actual environment like development or production
- var response = await SendAssignRequest("XX");
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.ServiceUnavailable);
+ [NotInParallel(GatewayAssignment)]
+ public async Task UsesCoordinatesWithoutCountryHeader()
+ {
+ await AddGateway("us-west.example.com", "US", Oregon, load: 50);
+ await AddGateway("de1.example.com", "DE", Frankfurt, load: 0);
+
+ await Assert.That(await AssignHost(null, Seattle)).IsEqualTo("us-west.example.com");
}
- private async Task AddGateways(string[] availableGateways, string? environmentOverride = null)
+ [Test]
+ [NotInParallel(GatewayAssignment)]
+ public async Task FallsBackToCountryWhenClientHasNoLocation()
{
- await using var context = WebApplicationFactory.Services.CreateAsyncScope();
- var redisConnectionProvider = context.ServiceProvider.GetRequiredService();
- var webHostEnvironment = context.ServiceProvider.GetRequiredService();
- var lcgNodesCollection = redisConnectionProvider.RedisCollection(false);
- var testGateways = availableGateways.Select(x =>
- {
- var split = x.Split('|');
- if (split.Length != 2)
- throw new ArgumentException("Invalid gateway format");
-
- var host = split[1];
- return new LcgNode
- {
- Id = host,
- Host = host,
- Port = 443,
- Country = split[0],
- Load = 0,
- Environment = environmentOverride ?? webHostEnvironment.EnvironmentName
- };
- });
+ await AddGateway("us-west.example.com", "US", Oregon, load: 0);
+ await AddGateway("de1.example.com", "DE", Frankfurt, load: 50);
+
+ await Assert.That(await AssignHost("DE")).IsEqualTo("de1.example.com");
+ }
+
+ [Test]
+ [NotInParallel(GatewayAssignment)]
+ public async Task FallsBackToCountryForGatewayWithoutLocation()
+ {
+ // A gateway that has not configured coordinates must still be assignable by country.
+ await AddGateway("us-west.example.com", "US", Oregon, load: 0);
+ await AddGateway("de1.example.com", "DE", null, load: 50);
- await lcgNodesCollection.InsertAsync(testGateways);
+ await Assert.That(await AssignHost("DE", Frankfurt)).IsEqualTo("de1.example.com");
}
- private async Task AddGatewayNode(string host, ushort port, string pathPrefix, string country)
+ [Test]
+ [NotInParallel(GatewayAssignment)]
+ public async Task MixedCoordinatesLeaveRegionUntouched()
{
- await using var context = WebApplicationFactory.Services.CreateAsyncScope();
- var redisConnectionProvider = context.ServiceProvider.GetRequiredService();
- var webHostEnvironment = context.ServiceProvider.GetRequiredService();
- var lcgNodesCollection = redisConnectionProvider.RedisCollection(false);
+ // us-east has no coordinates, so the US region can't be ranked fairly and must fall back to
+ // pure load balancing, rather than us-east winning on a 0 km same-country score.
+ await AddGateway("us-west.example.com", "US", Oregon, load: 0);
+ await AddGateway("us-east.example.com", "US", null, load: 50);
+
+ await Assert.That(await AssignHost("US", NewYork)).IsEqualTo("us-west.example.com");
+ }
+
+ [Test]
+ [NotInParallel(GatewayAssignment)]
+ [Arguments(null)]
+ [Arguments("XX")]
+ public async Task LeastLoadedWinsWithoutGeoInformation(string? requesterCountry)
+ {
+ await AddGateway("us-west.example.com", "US", Oregon, load: 80);
+ await AddGateway("de1.example.com", "DE", Frankfurt, load: 20);
+
+ await Assert.That(await AssignHost(requesterCountry)).IsEqualTo("de1.example.com");
+ }
+
+ [Test]
+ [NotInParallel(GatewayAssignment)]
+ public async Task CoordinatesDoNotCrossCountryPick()
+ {
+ // Munich is nearer Vienna than Hamburg, but coordinates only refine the country pick.
+ await AddGateway("de1.example.com", "DE", Hamburg);
+ await AddGateway("at1.example.com", "AT", Vienna);
+
+ await Assert.That(await AssignHost("DE", Munich)).IsEqualTo("de1.example.com");
+ }
+
+ private async Task AddGateway(string host, string country, GeoPoint? location, byte load = 0,
+ ushort port = 443, string pathPrefix = "", string? environment = null)
+ {
+ await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
+ var lcgNodes = scope.ServiceProvider.GetRequiredService().RedisCollection(false);
var id = host;
if (port != 443) id += ":" + port;
id += pathPrefix;
- await lcgNodesCollection.InsertAsync(new LcgNode
+ await lcgNodes.InsertAsync(new LcgNode
{
Id = id,
Host = host,
Port = port,
PathPrefix = pathPrefix,
Country = country,
- Load = 0,
- Environment = webHostEnvironment.EnvironmentName
+ Latitude = location?.Latitude,
+ Longitude = location?.Longitude,
+ Load = load,
+ Environment = environment ?? scope.ServiceProvider.GetRequiredService().EnvironmentName
});
}
- [Test]
- [NotInParallel(ParalellGateway)]
- public async Task CheckPathAndPortPropagation()
+ private async Task SendAssignRequest(string? requesterCountry, uint schemaVersion = 2, GeoPoint? clientLocation = null)
{
- // A gateway on a custom port and path prefix must be advertised verbatim, with the
- // firmware WS route appended to the prefix.
- await AddGatewayNode("de1.example.com", 8080, "/gateway", "DE");
-
- var response = await SendAssignRequest("DE", schemaVersion: 2);
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
+ var request = HeaderIpEnrichmentService.Place(
+ new HttpRequestMessage(HttpMethod.Get, $"/2/device/assignLCG?version={schemaVersion}"), location: clientLocation);
+ if (!string.IsNullOrEmpty(requesterCountry)) request.Headers.Add("CF-IPCountry", requesterCountry);
- var data = await response.Content.ReadFromJsonAsync();
- await Assert.That(data).IsNotNull();
- await Assert.That(data!.Host).IsEqualTo("de1.example.com");
- await Assert.That(data.Port).IsEqualTo((ushort)8080);
- await Assert.That(data.Path).IsEqualTo("/gateway/2/ws/hub");
+ using var client = TestHelper.CreateHubTokenClient(WebApplicationFactory, _hubToken);
+ return await client.SendAsync(request);
}
- [Test]
- [NotInParallel(ParalellGateway)]
- public async Task CheckDefaultGatewayIsBackwardCompatible()
+ private async Task AssignHost(string? requesterCountry, GeoPoint? clientLocation = null)
{
- // Default port/root path -> bare host, port 443, unprefixed route (unchanged wire shape).
- await AddGateways(["DE|de1.example.com"]);
-
- var response = await SendAssignRequest("DE", schemaVersion: 2);
+ using var response = await SendAssignRequest(requesterCountry, clientLocation: clientLocation);
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
var data = await response.Content.ReadFromJsonAsync();
await Assert.That(data).IsNotNull();
- await Assert.That(data!.Host).IsEqualTo("de1.example.com");
- await Assert.That(data.Port).IsEqualTo((ushort)443);
- await Assert.That(data.Path).IsEqualTo("/2/ws/hub");
- }
-
- private async Task SendAssignRequest(string? requesterCountry, uint schemaVersion = 1)
- {
- var httpRequest = new HttpRequestMessage(HttpMethod.Get, $"/2/device/assignLCG?version={schemaVersion}");
- httpRequest.Headers.Add("Device-Token", _hubToken);
- if (!string.IsNullOrEmpty(requesterCountry)) httpRequest.Headers.Add("CF-IPCountry", requesterCountry);
-
- using var client = WebApplicationFactory.CreateClient();
- return await client.SendAsync(httpRequest);
+ return data!.Host;
}
}
diff --git a/API.IntegrationTests/Tests/LcgCoordinateAssignmentTests.cs b/API.IntegrationTests/Tests/LcgCoordinateAssignmentTests.cs
deleted file mode 100644
index eec66213..00000000
--- a/API.IntegrationTests/Tests/LcgCoordinateAssignmentTests.cs
+++ /dev/null
@@ -1,210 +0,0 @@
-using System.Net;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.DependencyInjection;
-using OpenShock.API.Models.Response;
-using OpenShock.Common.OpenShockDb;
-using OpenShock.Common.Redis;
-using OpenShock.Common.Services.Geo;
-using OpenShock.Common.Utils;
-using OpenShock.Internal.Common.Utils;
-using Redis.OM.Contracts;
-
-namespace OpenShock.API.IntegrationTests.Tests;
-
-public sealed class LcgCoordinateAssignmentTests
-{
- [ClassDataSource(Shared = SharedType.PerTestSession)]
- public required GeoLocatedWebApplicationFactory WebApplicationFactory { get; init; }
-
- // Shares the key with LcgAssignmentTests: both suites wipe the same Redis node collection.
- private const string ParalellGateway = "gateway_assignment";
-
- private static readonly GeoPoint Seattle = new(47.61, -122.33);
- private static readonly GeoPoint NewYork = new(40.71, -74.01);
- private static readonly GeoPoint Oregon = new(45.60, -121.18);
- private static readonly GeoPoint Virginia = new(39.04, -77.49);
- private static readonly GeoPoint Frankfurt = new(50.11, 8.68);
- private static readonly GeoPoint Munich = new(48.14, 11.58);
- private static readonly GeoPoint Hamburg = new(53.55, 9.99);
- private static readonly GeoPoint Vienna = new(48.21, 16.37);
-
- private Guid _userId;
- private Guid _hubId;
- private string _hubToken = string.Empty;
-
- [Before(Test)]
- public async Task Setup()
- {
- await using var context = WebApplicationFactory.Services.CreateAsyncScope();
- var db = context.ServiceProvider.GetRequiredService();
-
- _userId = Guid.CreateVersion7();
- _hubId = Guid.CreateVersion7();
- _hubToken = CryptoUtils.RandomString(256);
-
- db.Users.Add(new User
- {
- Id = _userId,
- Name = _userId.ToString("N"),
- Email = $"{_userId}@test.org",
- PasswordHash = HashingUtils.HashPassword("password")
- });
- db.Devices.Add(new Device
- {
- Id = _hubId,
- Name = "TestHub",
- OwnerId = _userId,
- Token = _hubToken,
- CreatedAt = DateTime.UtcNow
- });
- await db.SaveChangesAsync();
- }
-
- [After(Test)]
- public async Task Teardown()
- {
- WebApplicationFactory.ClientLocation = null;
-
- await using var context = WebApplicationFactory.Services.CreateAsyncScope();
- var db = context.ServiceProvider.GetRequiredService();
- var lcgNodesCollection = context.ServiceProvider.GetRequiredService().RedisCollection(false);
-
- await db.Devices.Where(x => x.Id == _hubId).ExecuteDeleteAsync();
- await db.Users.Where(x => x.Id == _userId).ExecuteDeleteAsync();
-
- var allLcg = await lcgNodesCollection.ToListAsync();
- await lcgNodesCollection.DeleteAsync(allLcg);
- }
-
- [Test]
- [NotInParallel(ParalellGateway)]
- public async Task PicksClosestGatewayWithinSameCountry()
- {
- // Both gateways are "US", so the country table alone ties them; coordinates break the tie.
- await AddGateway("us-west.example.com", "US", Oregon);
- await AddGateway("us-east.example.com", "US", Virginia);
-
- WebApplicationFactory.ClientLocation = Seattle;
- await Assert.That(await AssignHost("US")).IsEqualTo("us-west.example.com");
-
- WebApplicationFactory.ClientLocation = NewYork;
- await Assert.That(await AssignHost("US")).IsEqualTo("us-east.example.com");
- }
-
- [Test]
- [NotInParallel(ParalellGateway)]
- public async Task UsesCoordinatesWithoutCountryHeader()
- {
- await AddGateway("us-west.example.com", "US", Oregon);
- await AddGateway("de1.example.com", "DE", Frankfurt);
-
- WebApplicationFactory.ClientLocation = Seattle;
- await Assert.That(await AssignHost(null)).IsEqualTo("us-west.example.com");
- }
-
- [Test]
- [NotInParallel(ParalellGateway)]
- public async Task FallsBackToCountryWhenClientHasNoLocation()
- {
- await AddGateway("us-west.example.com", "US", Oregon);
- await AddGateway("de1.example.com", "DE", Frankfurt);
-
- WebApplicationFactory.ClientLocation = null;
- await Assert.That(await AssignHost("DE")).IsEqualTo("de1.example.com");
- }
-
- [Test]
- [NotInParallel(ParalellGateway)]
- public async Task FallsBackToCountryForGatewayWithoutLocation()
- {
- // A gateway that has not configured coordinates must still be assignable by country.
- await AddGateway("us-west.example.com", "US", Oregon);
- await AddGateway("de1.example.com", "DE", null);
-
- WebApplicationFactory.ClientLocation = Frankfurt;
- await Assert.That(await AssignHost("DE")).IsEqualTo("de1.example.com");
- }
-
- [Test]
- [NotInParallel(ParalellGateway)]
- public async Task CoordinatesOverrideLoadWithinRegion()
- {
- // Baseline for MixedCoordinatesLeaveRegionUntouched: with full coordinates, distance wins over load.
- await AddGateway("us-west.example.com", "US", Oregon, load: 50);
- await AddGateway("us-east.example.com", "US", Virginia, load: 0);
-
- WebApplicationFactory.ClientLocation = Seattle;
- await Assert.That(await AssignHost("US")).IsEqualTo("us-west.example.com");
- }
-
- [Test]
- [NotInParallel(ParalellGateway)]
- public async Task MixedCoordinatesLeaveRegionUntouched()
- {
- // us-east has no coordinates, so the US region can't be ranked fairly and must fall back to
- // pure load balancing, rather than us-east winning on a 0 km same-country score.
- await AddGateway("us-west.example.com", "US", Oregon, load: 0);
- await AddGateway("us-east.example.com", "US", null, load: 50);
-
- WebApplicationFactory.ClientLocation = NewYork;
- await Assert.That(await AssignHost("US")).IsEqualTo("us-west.example.com");
- }
-
- [Test]
- [NotInParallel(ParalellGateway)]
- public async Task LeastLoadedWinsWithoutGeoInformation()
- {
- await AddGateway("us-west.example.com", "US", Oregon, load: 80);
- await AddGateway("de1.example.com", "DE", Frankfurt, load: 20);
-
- WebApplicationFactory.ClientLocation = null;
- await Assert.That(await AssignHost(null)).IsEqualTo("de1.example.com");
- }
-
- [Test]
- [NotInParallel(ParalellGateway)]
- public async Task CoordinatesDoNotCrossCountryPick()
- {
- // Munich is nearer Vienna than Hamburg, but coordinates only refine the country pick.
- await AddGateway("de1.example.com", "DE", Hamburg);
- await AddGateway("at1.example.com", "AT", Vienna);
-
- WebApplicationFactory.ClientLocation = Munich;
- await Assert.That(await AssignHost("DE")).IsEqualTo("de1.example.com");
- }
-
- private async Task AddGateway(string host, string country, GeoPoint? location, byte load = 0)
- {
- await using var context = WebApplicationFactory.Services.CreateAsyncScope();
- var environment = context.ServiceProvider.GetRequiredService();
- var lcgNodesCollection = context.ServiceProvider.GetRequiredService().RedisCollection(false);
-
- await lcgNodesCollection.InsertAsync(new LcgNode
- {
- Id = host,
- Host = host,
- Port = 443,
- Country = country,
- Latitude = location?.Latitude,
- Longitude = location?.Longitude,
- Load = load,
- Environment = environment.EnvironmentName
- });
- }
-
- private async Task AssignHost(string? requesterCountry)
- {
- var httpRequest = new HttpRequestMessage(HttpMethod.Get, "/2/device/assignLCG?version=2");
- httpRequest.Headers.Add("Device-Token", _hubToken);
- if (!string.IsNullOrEmpty(requesterCountry)) httpRequest.Headers.Add("CF-IPCountry", requesterCountry);
-
- using var client = WebApplicationFactory.CreateClient();
- using var response = await client.SendAsync(httpRequest);
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
-
- var data = await response.Content.ReadFromJsonAsync();
- await Assert.That(data).IsNotNull();
- return data!.Host;
- }
-}
diff --git a/API.IntegrationTests/Tests/LimitNormalizationMigrationTests.cs b/API.IntegrationTests/Tests/LimitNormalizationMigrationTests.cs
index ce9210d5..a02856d4 100644
--- a/API.IntegrationTests/Tests/LimitNormalizationMigrationTests.cs
+++ b/API.IntegrationTests/Tests/LimitNormalizationMigrationTests.cs
@@ -5,6 +5,7 @@
using Microsoft.Extensions.Logging.Abstractions;
using OpenShock.Common.Models;
using OpenShock.Common.OpenShockDb;
+using OpenShock.IntegrationTests.Shared;
using Testcontainers.PostgreSql;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -33,7 +34,9 @@ private static readonly (int Stored, int Expected)[] DurationCases =
[Test]
public async Task OutOfRangeLimits_AreWrappedOnceAndThenConstrained()
{
- await using var container = new PostgreSqlBuilder(image: "timescale/timescaledb:latest-pg18").Build();
+ await using var container = new PostgreSqlBuilder(image: ContainerImages.TimescaleDb)
+ .WithCommand(ContainerImages.TimescaleDbCommand)
+ .Build();
await container.StartAsync();
MigrationOpenShockContext CreateContext() => new(container.GetConnectionString(), false, NullLoggerFactory.Instance);
diff --git a/API.IntegrationTests/Tests/MailDisabledTests.cs b/API.IntegrationTests/Tests/MailDisabledTests.cs
index bb12eaa2..8fa757b6 100644
--- a/API.IntegrationTests/Tests/MailDisabledTests.cs
+++ b/API.IntegrationTests/Tests/MailDisabledTests.cs
@@ -4,6 +4,7 @@
using Microsoft.Extensions.DependencyInjection;
using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.Common.OpenShockDb;
+using OpenShock.IntegrationTests.Shared;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -17,14 +18,15 @@ public sealed class MailDisabledTests
public required MailDisabledWebApplicationFactory WebApplicationFactory { get; init; }
[Test]
- public async Task V2Signup_MailDisabled_ActivatesAccountAndEnqueuesNoEmail()
+ public async Task V2Signup_MailDisabled_ActivatesAccount_EnqueuesNoEmail_AndCanLogInImmediately()
{
using var client = WebApplicationFactory.CreateClient();
- var email = TestHelper.UniqueEmail("mail-disabled");
+ var email = UniqueNames.Email("mail-disabled");
+ var username = UniqueNames.Username("maildisabled");
var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
{
- username = "mailDisabledUser",
+ username,
password = "SecurePassword123#",
email,
turnstileResponse = "valid-token"
@@ -44,21 +46,14 @@ public async Task V2Signup_MailDisabled_ActivatesAccountAndEnqueuesNoEmail()
var activationMails = await db.EmailOutbox
.CountAsync(m => m.Recipient == email && m.Type == EmailType.AccountActivation);
await Assert.That(activationMails).IsEqualTo(0);
- }
-
- [Test, DependsOn(nameof(V2Signup_MailDisabled_ActivatesAccountAndEnqueuesNoEmail))]
- public async Task V2Signup_MailDisabled_AccountCanLogInImmediately()
- {
- using var client = WebApplicationFactory.CreateClient();
- var response = await client.PostAsync("/2/account/login", TestHelper.JsonContent(new
+ var login = await client.PostAsync("/2/account/login", TestHelper.JsonContent(new
{
- usernameOrEmail = "mailDisabledUser",
+ usernameOrEmail = username,
password = "SecurePassword123#",
turnstileResponse = "valid-token"
}));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
+ await Assert.That(login.StatusCode).IsEqualTo(HttpStatusCode.OK);
}
[Test]
diff --git a/API.IntegrationTests/Tests/MailTests.cs b/API.IntegrationTests/Tests/MailTests.cs
index 039ca1ad..a3ca7967 100644
--- a/API.IntegrationTests/Tests/MailTests.cs
+++ b/API.IntegrationTests/Tests/MailTests.cs
@@ -9,6 +9,7 @@
using OpenShock.Common.Constants;
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Utils;
+using OpenShock.IntegrationTests.Shared;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -16,7 +17,8 @@ namespace OpenShock.API.IntegrationTests.Tests;
/// The API's responsibility for transactional email is to write the correct
/// row (and its business row) atomically - it never sends mail. These tests assert exactly that: the right
/// outbox row is enqueued (type, recipient, coalesce key, payload) or, for rejected requests, that nothing
-/// is enqueued. Actual delivery, lazy token minting, the emailed-link flows, and newest-wins coalescing are
+/// is enqueued; and the password-reset and email-change links the Cron host mails are honoured as they
+/// should be. Actual delivery, lazy token minting, the emailed-link flows, and newest-wins coalescing are
/// the Cron host's job and are covered by Cron.IntegrationTests. Signing up and activating is covered by
/// .
///
@@ -40,33 +42,11 @@ private async Task CountOutboxAsync(string email)
// --- Password Reset ---
- [Test]
- public async Task V1PasswordReset_Retired_Returns410Gone()
- {
- using var client = WebApplicationFactory.CreateClient();
- var response = await client.PostAsync("/1/account/reset", TestHelper.JsonContent(new { email = "whatever@test.org" }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Gone);
- }
-
- [Test]
- public async Task ResetPasswordAlias_Retired_Returns410Gone()
- {
- using var client = WebApplicationFactory.CreateClient();
- var response = await client.PostAsync("/2/account/reset-password", TestHelper.JsonContent(new
- {
- email = "whatever@test.org",
- turnstileResponse = "valid-token"
- }));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Gone);
- }
-
[Test]
public async Task V2PasswordReset_EnqueuesResetOutbox()
{
- var email = TestHelper.UniqueEmail("mail-pwreset-v2");
- var username = TestHelper.UniqueUsername("mailpwresetv2");
+ var email = UniqueNames.Email("mail-pwreset-v2");
+ var username = UniqueNames.Username("mailpwresetv2");
var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "OldPassword123#");
using var client = WebApplicationFactory.CreateClient();
@@ -93,8 +73,8 @@ public async Task V2PasswordReset_EnqueuesResetOutbox()
[Test]
public async Task PasswordResetComplete_ActivatedAccount_KeepsOAuthConnectionsAndApiTokens()
{
- var email = TestHelper.UniqueEmail("mail-pwreset-recovery");
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailpwresetrecov"), email, "OldPassword123#");
+ var email = UniqueNames.Email("mail-pwreset-recovery");
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("mailpwresetrecov"), email, "OldPassword123#");
await AddOAuthConnectionAsync(userId, "discord");
await AddOAuthConnectionAsync(userId, "google");
var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId);
@@ -111,82 +91,6 @@ public async Task PasswordResetComplete_ActivatedAccount_KeepsOAuthConnectionsAn
await Assert.That((await tokenClient.GetAsync("/1/users/self")).StatusCode).IsEqualTo(HttpStatusCode.OK);
}
- // --- Disconnecting a provider must not leave an account with no way to sign in ---
-
- [Test]
- public async Task RemoveOAuthConnection_OnlyLoginMethod_Returns409_AndKeepsConnection()
- {
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailoauthlast"), TestHelper.UniqueEmail("mail-oauth-last"), "Placeholder123#");
- await AddOAuthConnectionAsync(user.Id, "discord");
- await using (var seedScope = WebApplicationFactory.Services.CreateAsyncScope())
- {
- var seedDb = seedScope.ServiceProvider.GetRequiredService();
- await seedDb.Users.Where(u => u.Id == user.Id).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null));
- }
-
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
- var response = await client.DeleteAsync("/1/account/connections/discord");
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict);
-
- await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
- var db = scope.ServiceProvider.GetRequiredService();
- await Assert.That(await db.UserOAuthConnections.AsNoTracking().CountAsync(c => c.UserId == user.Id)).IsEqualTo(1);
- }
-
- [Test]
- public async Task RemoveOAuthConnection_PasswordlessAccountWithTwo_RemovesOne_ThenKeepsTheLast()
- {
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailoauthtwo"), TestHelper.UniqueEmail("mail-oauth-two"), "Placeholder123#");
- await AddOAuthConnectionAsync(user.Id, "discord");
- await AddOAuthConnectionAsync(user.Id, "google");
- await using (var seedScope = WebApplicationFactory.Services.CreateAsyncScope())
- {
- var seedDb = seedScope.ServiceProvider.GetRequiredService();
- await seedDb.Users.Where(u => u.Id == user.Id).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null));
- }
-
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
- await Assert.That((await client.DeleteAsync("/1/account/connections/discord")).StatusCode).IsEqualTo(HttpStatusCode.NoContent);
- await Assert.That((await client.DeleteAsync("/1/account/connections/google")).StatusCode).IsEqualTo(HttpStatusCode.Conflict);
- await Assert.That((await client.DeleteAsync("/1/account/connections/discord")).StatusCode).IsEqualTo(HttpStatusCode.NotFound);
- }
-
- [Test]
- public async Task RemoveOAuthConnection_PasswordlessAccountWithTwo_RemovedAtTheSameTime_KeepsOne()
- {
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailoauthrace"), TestHelper.UniqueEmail("mail-oauth-race"), "Placeholder123#");
- await AddOAuthConnectionAsync(user.Id, "discord");
- await AddOAuthConnectionAsync(user.Id, "google");
- await using (var seedScope = WebApplicationFactory.Services.CreateAsyncScope())
- {
- var seedDb = seedScope.ServiceProvider.GetRequiredService();
- await seedDb.Users.Where(u => u.Id == user.Id).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null));
- }
-
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
- var responses = await Task.WhenAll(
- client.DeleteAsync("/1/account/connections/discord"),
- client.DeleteAsync("/1/account/connections/google"));
-
- await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.NoContent)).IsEqualTo(1);
- await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.Conflict)).IsEqualTo(1);
-
- await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
- var db = scope.ServiceProvider.GetRequiredService();
- await Assert.That(await db.UserOAuthConnections.AsNoTracking().CountAsync(c => c.UserId == user.Id)).IsEqualTo(1);
- }
-
- [Test]
- public async Task RemoveOAuthConnection_AccountWithPassword_RemovesIt()
- {
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailoauthpw"), TestHelper.UniqueEmail("mail-oauth-pw"), "OwnerPassword123#");
- await AddOAuthConnectionAsync(user.Id, "discord");
-
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
- var response = await client.DeleteAsync("/1/account/connections/discord");
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NoContent);
- }
-
// --- An email change is only confirmed from a session of the account that asked for it ---
[Test]
@@ -205,7 +109,7 @@ public async Task EmailChangeVerify_WithoutSession_Returns401_AndLeavesEmail()
public async Task EmailChangeVerify_FromAnotherAccountsSession_Returns400_AndLeavesEmail()
{
var (user, token, _) = await CreateUserWithPendingEmailChangeAsync("mail-verify-other");
- var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailverifysecond"), TestHelper.UniqueEmail("mail-verify-second"), "SecurePassword123#");
+ var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("mailverifysecond"), UniqueNames.Email("mail-verify-second"), "SecurePassword123#");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, other.SessionToken);
var response = await client.PostAsync($"/1/account/email-change/verify?token={token}", null);
@@ -214,30 +118,16 @@ public async Task EmailChangeVerify_FromAnotherAccountsSession_Returns400_AndLea
await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(user.Email);
}
- [Test]
- public async Task EmailChangeVerify_FromOwnSession_AppliesChange()
- {
- var (user, token, newEmail) = await CreateUserWithPendingEmailChangeAsync("mail-verify-own");
-
- using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
- var response = await client.PostAsync($"/1/account/email-change/verify?token={token}", null);
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
- await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(newEmail);
- }
-
// The route the verification link used before email-change/verify existed still works, under the same rule.
[Test]
- public async Task EmailChangeVerify_LegacyRoute_FromOwnSession_AppliesChange()
+ [Arguments("/1/account/email-change/verify")]
+ [Arguments("/1/account/verify-email")]
+ public async Task EmailChangeVerify_FromOwnSession_AppliesChange(string route)
{
- var (user, token, newEmail) = await CreateUserWithPendingEmailChangeAsync("mail-verify-legacy");
-
- using var anonymous = CreateCookielessClient();
- var rejected = await anonymous.PostAsync($"/1/account/verify-email?token={token}", null);
- await Assert.That(rejected.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
+ var (user, token, newEmail) = await CreateUserWithPendingEmailChangeAsync("mail-verify-own");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
- var response = await client.PostAsync($"/1/account/verify-email?token={token}", null);
+ var response = await client.PostAsync($"{route}?token={token}", null);
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(newEmail);
@@ -247,7 +137,7 @@ public async Task EmailChangeVerify_LegacyRoute_FromOwnSession_AppliesChange()
public async Task EmailChangeVerify_AddressHeldByActivatedAccount_Returns409_AndLeavesEmail()
{
var (user, token, newEmail) = await CreateUserWithPendingEmailChangeAsync("mail-verify-taken");
- await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailverifytaken"), newEmail, "HolderPassword123#");
+ await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("mailverifytaken"), newEmail, "HolderPassword123#");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
var response = await client.PostAsync($"/1/account/email-change/verify?token={token}", null);
@@ -258,8 +148,8 @@ public async Task EmailChangeVerify_AddressHeldByActivatedAccount_Returns409_And
private async Task<(AuthenticatedUser User, string Token, string NewEmail)> CreateUserWithPendingEmailChangeAsync(string prefix)
{
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername(prefix.Replace("-", "")), TestHelper.UniqueEmail(prefix + "-old"), "SecurePassword123#");
- var newEmail = TestHelper.UniqueEmail(prefix + "-new");
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix.Replace("-", "")), UniqueNames.Email(prefix + "-old"), "SecurePassword123#");
+ var newEmail = UniqueNames.Email(prefix + "-new");
var token = "email-change-" + Guid.NewGuid().ToString("N");
await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
@@ -289,8 +179,8 @@ private async Task GetEmailAsync(Guid userId)
[Test]
public async Task PasswordResetComplete_RevokesExistingSessions()
{
- var email = TestHelper.UniqueEmail("mail-pwreset-sessions");
- var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailpwresetsess"), email, "OldPassword123#");
+ var email = UniqueNames.Email("mail-pwreset-sessions");
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("mailpwresetsess"), email, "OldPassword123#");
var response = await CompleteSeededPasswordResetAsync(user.Id);
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
@@ -323,10 +213,14 @@ public async Task PasswordResetComplete_RevokesExistingSessions()
private async Task CompleteSeededPasswordResetAsync(Guid userId)
{
var (resetId, secret) = await SeedPasswordResetAsync(userId);
+ return await CompletePasswordResetAsync(resetId, secret);
+ }
+ private async Task CompletePasswordResetAsync(Guid resetId, string secret, string password = "NewPassword123#")
+ {
using var client = WebApplicationFactory.CreateClient();
return await client.PostAsync($"/1/account/password-reset/{resetId}/{secret}/complete",
- TestHelper.JsonContent(new { password = "NewPassword123#" }));
+ TestHelper.JsonContent(new { password }));
}
private async Task AddOAuthConnectionAsync(Guid userId, string provider)
@@ -344,42 +238,47 @@ private async Task AddOAuthConnectionAsync(Guid userId, string provider)
}
[Test]
- public async Task PasswordResetComplete_LegacyRecoverRoute_Returns410Gone()
+ public async Task PasswordResetCheck_OnlyTheRightSecretOfAnOpenReset_IsValid()
{
- using var client = WebApplicationFactory.CreateClient();
-
- var response = await client.PostAsync(
- $"/1/account/recover/{Guid.CreateVersion7()}/somesecret",
- TestHelper.JsonContent(new { password = "LegacyNewPassword456#" }));
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("mailpwresetcheck"), UniqueNames.Email("mail-pwreset-check"), "OldPassword123#");
+ var (resetId, secret) = await SeedPasswordResetAsync(userId);
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Gone);
+ using var client = WebApplicationFactory.CreateClient();
+ await Assert.That((await client.GetAsync($"/1/account/password-reset/{resetId}/{secret}")).StatusCode).IsEqualTo(HttpStatusCode.OK);
+ await Assert.That((await client.GetAsync($"/1/account/password-reset/{resetId}/{secret}-wrong")).StatusCode).IsEqualTo(HttpStatusCode.NotFound);
+ await Assert.That((await client.GetAsync($"/1/account/password-reset/{Guid.CreateVersion7()}/{secret}")).StatusCode).IsEqualTo(HttpStatusCode.NotFound);
}
[Test]
- public async Task PasswordResetCheck_LegacyHeadRecoverRoute_Returns410Gone()
+ public async Task PasswordResetComplete_WrongSecret_Returns404_AndKeepsThePassword()
{
- using var client = WebApplicationFactory.CreateClient();
+ var email = UniqueNames.Email("mail-pwreset-wrongsecret");
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("mailpwresetwrong"), email, "OldPassword123#");
+ var (resetId, secret) = await SeedPasswordResetAsync(userId);
- var response = await client.SendAsync(new HttpRequestMessage(
- HttpMethod.Head, $"/1/account/recover/{Guid.CreateVersion7()}/somesecret"));
+ var response = await CompletePasswordResetAsync(resetId, secret + "-wrong");
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Gone);
+ await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
+ await Assert.That(await response.Content.ReadAsStringAsync()).Contains("PasswordReset.NotFound");
+ using var client = CreateCookielessClient();
+ await Assert.That((await PendingSignupHelper.PostLoginAsync(client, email, "OldPassword123#")).StatusCode).IsEqualTo(HttpStatusCode.OK);
}
[Test]
- public async Task PasswordResetCheck_InvalidToken_Returns404()
+ public async Task PasswordResetComplete_UsedLink_CannotBeUsedAgain()
{
- var email = TestHelper.UniqueEmail("mail-pwreset-check-invalid");
- var username = TestHelper.UniqueUsername("mailpwresetcheckinvalid");
- await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "OldPassword123#");
-
- using var client = WebApplicationFactory.CreateClient();
+ var email = UniqueNames.Email("mail-pwreset-reuse");
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("mailpwresetreuse"), email, "OldPassword123#");
+ var (resetId, secret) = await SeedPasswordResetAsync(userId);
- var bogusId = Guid.CreateVersion7();
- const string bogusSecret = "thisisnotarealtokenatallzz";
+ await Assert.That((await CompletePasswordResetAsync(resetId, secret)).StatusCode).IsEqualTo(HttpStatusCode.OK);
- var response = await client.GetAsync($"/1/account/password-reset/{bogusId}/{bogusSecret}");
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
+ var again = await CompletePasswordResetAsync(resetId, secret, "AnotherPassword123#");
+ await Assert.That(again.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
+ using var client = CreateCookielessClient();
+ await Assert.That((await client.GetAsync($"/1/account/password-reset/{resetId}/{secret}")).StatusCode).IsEqualTo(HttpStatusCode.NotFound);
+ await Assert.That((await PendingSignupHelper.PostLoginAsync(client, email, "NewPassword123#")).StatusCode).IsEqualTo(HttpStatusCode.OK);
+ await Assert.That((await PendingSignupHelper.PostLoginAsync(client, email, "AnotherPassword123#")).StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
}
// --- Change Email ---
@@ -387,9 +286,9 @@ public async Task PasswordResetCheck_InvalidToken_Returns404()
[Test]
public async Task ChangeEmail_EnqueuesVerificationAndNotice()
{
- var oldEmail = TestHelper.UniqueEmail("mail-chgemail-notice-old");
- var newEmail = TestHelper.UniqueEmail("mail-chgemail-notice-new");
- var username = TestHelper.UniqueUsername("mailchgemailnotice");
+ var oldEmail = UniqueNames.Email("mail-chgemail-notice-old");
+ var newEmail = UniqueNames.Email("mail-chgemail-notice-new");
+ var username = UniqueNames.Username("mailchgemailnotice");
const string password = "SecurePassword123#";
var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, username, oldEmail, password);
@@ -423,9 +322,9 @@ public async Task ChangeEmail_EnqueuesVerificationAndNotice()
[Test]
public async Task ChangeEmail_WrongPassword_Returns403_AndEnqueuesNothing()
{
- var oldEmail = TestHelper.UniqueEmail("mail-chgemail-badpwd-old");
- var newEmail = TestHelper.UniqueEmail("mail-chgemail-badpwd-new");
- var username = TestHelper.UniqueUsername("mailchgemailbadpwd");
+ var oldEmail = UniqueNames.Email("mail-chgemail-badpwd-old");
+ var newEmail = UniqueNames.Email("mail-chgemail-badpwd-new");
+ var username = UniqueNames.Username("mailchgemailbadpwd");
var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, username, oldEmail, "CorrectPassword123#");
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
@@ -447,8 +346,8 @@ public async Task ChangeEmail_WrongPassword_Returns403_AndEnqueuesNothing()
[Test]
public async Task ChangeEmail_Unchanged_Returns400_AndEnqueuesNothing()
{
- var email = TestHelper.UniqueEmail("mail-chgemail-unchanged");
- var username = TestHelper.UniqueUsername("mailchgemailunchanged");
+ var email = UniqueNames.Email("mail-chgemail-unchanged");
+ var username = UniqueNames.Username("mailchgemailunchanged");
const string password = "SecurePassword123#";
var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, username, email, password);
@@ -470,10 +369,10 @@ public async Task ChangeEmail_Unchanged_Returns400_AndEnqueuesNothing()
[Test]
public async Task ChangeEmail_AlreadyInUse_Returns409()
{
- var takenEmail = TestHelper.UniqueEmail("mail-chgemail-taken-existing");
- var ownEmail = TestHelper.UniqueEmail("mail-chgemail-taken-own");
- var takenUser = TestHelper.UniqueUsername("mailchgemailtaken1");
- var ownUser = TestHelper.UniqueUsername("mailchgemailtaken2");
+ var takenEmail = UniqueNames.Email("mail-chgemail-taken-existing");
+ var ownEmail = UniqueNames.Email("mail-chgemail-taken-own");
+ var takenUser = UniqueNames.Username("mailchgemailtaken1");
+ var ownUser = UniqueNames.Username("mailchgemailtaken2");
const string password = "SecurePassword123#";
await TestHelper.CreateUserInDb(WebApplicationFactory, takenUser, takenEmail, password);
diff --git a/API.IntegrationTests/Tests/MetadataTests.cs b/API.IntegrationTests/Tests/MetadataTests.cs
index 7035afe8..214fdd28 100644
--- a/API.IntegrationTests/Tests/MetadataTests.cs
+++ b/API.IntegrationTests/Tests/MetadataTests.cs
@@ -1,15 +1,21 @@
using System.Net;
using System.Text.Json;
+using OpenShock.API.IntegrationTests.Helpers;
+using OpenShock.IntegrationTests.Shared;
namespace OpenShock.API.IntegrationTests.Tests;
+///
+/// GET /1 is how the frontend learns how this instance is configured, so its fields are checked against
+/// the configuration boots with.
+///
public sealed class MetadataTests
{
[ClassDataSource(Shared = SharedType.PerTestSession)]
public required WebApplicationFactory WebApplicationFactory { get; init; }
-
+
[Test]
- public async Task GetMetadata_ShouldMatchBackendInfoResponseContract()
+ public async Task GetMetadata_ReportsInstanceConfiguration()
{
using var client = WebApplicationFactory.CreateClient();
@@ -17,69 +23,27 @@ public async Task GetMetadata_ShouldMatchBackendInfoResponseContract()
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
- var mediaType = response.Content.Headers.ContentType?.MediaType;
- await Assert.That(mediaType).IsEqualTo("application/json");
-
- var json = await response.Content.ReadAsStringAsync();
- using var doc = JsonDocument.Parse(json);
-
- var root = doc.RootElement;
-
- // Validate Message
- var message = root.GetProperty("message").GetString();
- await Assert.That(message).IsEqualTo("OpenShock");
-
- // Fetch data
- var data = root.GetProperty("data");
-
- // Validate Version
- var version = data.GetProperty("version").GetString();
- await Assert.That(version).IsNotNullOrWhiteSpace();
-
- // Validate Commit
- var commit = data.GetProperty("commit").GetString();
- await Assert.That(commit).Matches("[a-fA-F0-9]{4,64}");
-
- // Validate CurrentTime
- var currentTime = data.GetProperty("currentTime").GetDateTimeOffset();
- await Assert.That(currentTime).IsBetween(
- DateTimeOffset.UtcNow.AddSeconds(-5),
- DateTimeOffset.UtcNow.AddSeconds(5)
- );
-
- // Validate FrontendUrl
- var frontendUrlStr = data.GetProperty("frontendUrl").GetString();
- await Assert.That(Uri.TryCreate(frontendUrlStr, UriKind.Absolute, out _))
- .IsTrue();
-
- // Validate ShortLinkUrl
- var shortLinkUrlStr = data.GetProperty("shortLinkUrl").GetString();
- await Assert.That(Uri.TryCreate(shortLinkUrlStr, UriKind.Absolute, out _))
- .IsTrue();
-
- // Validate TurnstileSiteKey (nullable, can be null or string)
- var turnstileSiteKeyProp = data.GetProperty("turnstileSiteKey");
- if (turnstileSiteKeyProp.ValueKind is not JsonValueKind.Null)
- {
- var turnstileSiteKey = turnstileSiteKeyProp.GetString();
- await Assert.That(turnstileSiteKey).IsNotNullOrWhiteSpace();
- }
+ using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
+ await Assert.That(doc.RootElement.GetProperty("message").GetString()).IsEqualTo("OpenShock");
+
+ var data = doc.RootElement.GetProperty("data");
+ await Assert.That(new Uri(data.GetProperty("frontendUrl").GetString()!)).IsEqualTo(new Uri("https://openshock.app"));
+ await Assert.That(new Uri(data.GetProperty("shortLinkUrl").GetString()!)).IsEqualTo(new Uri("https://openshock.app"));
+ await Assert.That(data.GetProperty("turnstileSiteKey").GetString()).IsEqualTo("turnstile-site-key");
+ await Assert.That(data.GetProperty("oAuthProviders").EnumerateArray().Select(p => p.GetString()!).ToArray())
+ .IsEquivalentTo(["discord"]);
+ await Assert.That(data.GetProperty("isMailEnabled").GetBoolean()).IsTrue();
+ await Assert.That(data.GetProperty("isUserAuthenticated").GetBoolean()).IsFalse();
+ }
- // Validate OAuthProviders (string[])
- var oauthProviders = data.GetProperty("oAuthProviders");
- await Assert.That(oauthProviders.ValueKind).IsEqualTo(JsonValueKind.Array);
- foreach (var provider in oauthProviders.EnumerateArray())
- {
- var p = provider.GetString();
- await Assert.That(p).IsNotNullOrWhiteSpace();
- }
+ [Test]
+ public async Task GetMetadata_WithSession_ReportsUserAuthenticated()
+ {
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("metadata"), UniqueNames.Email("metadata"), "SecurePassword123#");
+ using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
- // Validate IsMailEnabled (bool)
- var isMailEnabled = data.GetProperty("isMailEnabled").GetBoolean();
- await Assert.That(isMailEnabled).IsTrue(); // The test host configures a mail type
+ using var doc = JsonDocument.Parse(await client.GetStringAsync("/1"));
- // Validate IsUserAuthenticated (bool)
- var isUserAuthenticated = data.GetProperty("isUserAuthenticated").GetBoolean();
- await Assert.That(isUserAuthenticated).IsIn(true, false);
+ await Assert.That(doc.RootElement.GetProperty("data").GetProperty("isUserAuthenticated").GetBoolean()).IsTrue();
}
}
diff --git a/API.IntegrationTests/Tests/OAuthConnectionTests.cs b/API.IntegrationTests/Tests/OAuthConnectionTests.cs
new file mode 100644
index 00000000..6e3aead5
--- /dev/null
+++ b/API.IntegrationTests/Tests/OAuthConnectionTests.cs
@@ -0,0 +1,91 @@
+using System.Net;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using OpenShock.API.IntegrationTests.Helpers;
+using OpenShock.Common.OpenShockDb;
+using OpenShock.IntegrationTests.Shared;
+
+namespace OpenShock.API.IntegrationTests.Tests;
+
+///
+/// Disconnecting a provider must not leave an account with no way to sign in.
+///
+public sealed class OAuthConnectionTests
+{
+ [ClassDataSource(Shared = SharedType.PerTestSession)]
+ public required WebApplicationFactory WebApplicationFactory { get; init; }
+
+ [Test]
+ public async Task RemoveOAuthConnection_PasswordlessAccountWithTwo_RemovesOne_ThenKeepsTheLast()
+ {
+ var user = await CreatePasswordlessUserAsync("oauthtwo", "discord", "google");
+
+ using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
+ await Assert.That((await client.DeleteAsync("/1/account/connections/discord")).StatusCode).IsEqualTo(HttpStatusCode.NoContent);
+ await Assert.That((await client.DeleteAsync("/1/account/connections/google")).StatusCode).IsEqualTo(HttpStatusCode.Conflict);
+ await Assert.That((await client.DeleteAsync("/1/account/connections/discord")).StatusCode).IsEqualTo(HttpStatusCode.NotFound);
+
+ await Assert.That(await GetProvidersAsync(user.Id)).IsEquivalentTo(["google"]);
+ }
+
+ [Test]
+ public async Task RemoveOAuthConnection_PasswordlessAccountWithTwo_RemovedAtTheSameTime_KeepsOne()
+ {
+ var user = await CreatePasswordlessUserAsync("oauthrace", "discord", "google");
+
+ using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
+ var responses = await Task.WhenAll(
+ client.DeleteAsync("/1/account/connections/discord"),
+ client.DeleteAsync("/1/account/connections/google"));
+
+ await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.NoContent)).IsEqualTo(1);
+ await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.Conflict)).IsEqualTo(1);
+ await Assert.That((await GetProvidersAsync(user.Id)).Count).IsEqualTo(1);
+ }
+
+ [Test]
+ public async Task RemoveOAuthConnection_AccountWithPassword_RemovesIt()
+ {
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("oauthpw"), UniqueNames.Email("oauth-pw"), "OwnerPassword123#");
+ await AddOAuthConnectionAsync(user.Id, "discord");
+
+ using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);
+ var response = await client.DeleteAsync("/1/account/connections/discord");
+
+ await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NoContent);
+ await Assert.That(await GetProvidersAsync(user.Id)).IsEmpty();
+ }
+
+ private async Task CreatePasswordlessUserAsync(string prefix, params string[] providers)
+ {
+ var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), "Placeholder123#");
+ foreach (var provider in providers) await AddOAuthConnectionAsync(user.Id, provider);
+
+ await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ await db.Users.Where(u => u.Id == user.Id).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null));
+
+ return user;
+ }
+
+ private async Task AddOAuthConnectionAsync(Guid userId, string provider)
+ {
+ await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ db.UserOAuthConnections.Add(new UserOAuthConnection
+ {
+ UserId = userId,
+ ProviderKey = provider,
+ ExternalId = Guid.CreateVersion7().ToString(),
+ DisplayName = "external"
+ });
+ await db.SaveChangesAsync();
+ }
+
+ private async Task> GetProvidersAsync(Guid userId)
+ {
+ await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ return await db.UserOAuthConnections.AsNoTracking().Where(c => c.UserId == userId).Select(c => c.ProviderKey).ToListAsync();
+ }
+}
diff --git a/API.IntegrationTests/Tests/OAuthFlowTests.cs b/API.IntegrationTests/Tests/OAuthFlowTests.cs
index 670cfe2f..5705b8d9 100644
--- a/API.IntegrationTests/Tests/OAuthFlowTests.cs
+++ b/API.IntegrationTests/Tests/OAuthFlowTests.cs
@@ -11,6 +11,7 @@
using OpenShock.API.OAuth;
using OpenShock.Common.Constants;
using OpenShock.Common.OpenShockDb;
+using OpenShock.IntegrationTests.Shared;
using static OpenShock.API.IntegrationTests.Helpers.PendingSignupHelper;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -33,23 +34,13 @@ public sealed class OAuthFlowTests
// --- handoff ---
- [Test]
- public async Task Handoff_IdentityNobodyKnows_GoesToTheSignupForm()
- {
- using var client = CreateClient();
- var response = await HandoffAsync(client, MintFlowCookie(NewExternalId()));
-
- await AssertSentBackToSignupAsync(response, pending: false);
- await Assert.That(SetsCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsFalse();
- }
-
// Over HTTPS the flow cookie only counts under its __Host- name, which a browser accepts from this
// host alone. Under the plain name it is what a sibling subdomain could have planted.
[Test]
public async Task Handoff_FlowCookieWithoutHostPrefix_IsIgnored()
{
var externalId = NewExternalId();
- var email = TestHelper.UniqueEmail("oauth-handoff-planted");
+ var email = UniqueNames.Email("oauth-handoff-planted");
await CreatePendingOAuthSignupAsync(email, "oauthhandoffplanted", externalId);
var planted = MintFlowCookie(externalId).Replace(OAuthConstants.FlowSecureCookieName + "=", OAuthConstants.FlowCookieName + "=");
@@ -68,7 +59,7 @@ public async Task Handoff_FlowCookieWithoutHostPrefix_IsIgnored()
public async Task Handoff_IdentityWithAPendingSignup_HoldsTheSignup_MailsACode_AndIsNotSignedIn()
{
var externalId = NewExternalId();
- var email = TestHelper.UniqueEmail("oauth-handoff-pending");
+ var email = UniqueNames.Email("oauth-handoff-pending");
var pendingId = await CreatePendingOAuthSignupAsync(email, "oauthhandoffpending", externalId);
using var client = CreateClient();
@@ -92,7 +83,7 @@ public async Task Handoff_IdentityWithAPendingSignup_HoldsTheSignup_MailsACode_A
[Test]
public async Task Handoff_AnotherIdentity_DoesNotGetToHoldSomeoneElsesSignup()
{
- var email = TestHelper.UniqueEmail("oauth-handoff-otherid");
+ var email = UniqueNames.Email("oauth-handoff-otherid");
await CreatePendingOAuthSignupAsync(email, "oauthhandoffotherid", NewExternalId());
using var client = CreateClient();
@@ -109,10 +100,10 @@ public async Task Handoff_AnotherIdentity_DoesNotGetToHoldSomeoneElsesSignup()
public async Task SignupFinalize_EmailTheProviderDidNotVerify_StartsAPendingSignup_WithoutAnAccountOrSession()
{
var externalId = NewExternalId();
- var email = TestHelper.UniqueEmail("oauth-finalize-unverified");
+ var email = UniqueNames.Email("oauth-finalize-unverified");
using var client = CreateClient();
- var response = await FinalizeAsync(client, MintFlowCookie(externalId, email: TestHelper.UniqueEmail("oauth-finalize-provider"), emailVerified: true), email, TestHelper.UniqueUsername("oauthfinunver"));
+ var response = await FinalizeAsync(client, MintFlowCookie(externalId, email: UniqueNames.Email("oauth-finalize-provider"), emailVerified: true), email, UniqueNames.Username("oauthfinunver"));
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsFalse();
@@ -134,10 +125,10 @@ public async Task SignupFinalize_EmailTheProviderDidNotVerify_StartsAPendingSign
public async Task SignupFinalize_EmailTheProviderVerified_CreatesTheAccount_AndSignsIn()
{
var externalId = NewExternalId();
- var email = TestHelper.UniqueEmail("oauth-finalize-verified");
+ var email = UniqueNames.Email("oauth-finalize-verified");
using var client = CreateClient();
- var response = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, TestHelper.UniqueUsername("oauthfinver"));
+ var response = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, UniqueNames.Username("oauthfinver"));
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsTrue();
@@ -154,11 +145,11 @@ public async Task SignupFinalize_EmailTheProviderVerified_CreatesTheAccount_AndS
public async Task SignupFinalize_PendingSignup_NewEmail_ReplacesIt_AndTheOldCodeNoLongerWorks()
{
var externalId = NewExternalId();
- var oldEmail = TestHelper.UniqueEmail("oauth-finalize-move");
- var username = TestHelper.UniqueUsername("oauthfinmove");
+ var oldEmail = UniqueNames.Email("oauth-finalize-move");
+ var username = UniqueNames.Username("oauthfinmove");
var oldPendingId = await CreatePendingOAuthSignupAsync(oldEmail, username, externalId, uniqueUsername: false);
var oldCode = await MailCodeAsync(WebApplicationFactory, oldPendingId);
- var victimEmail = TestHelper.UniqueEmail("oauth-finalize-victim");
+ var victimEmail = UniqueNames.Email("oauth-finalize-victim");
using var client = CreateClient();
var response = await FinalizeAsync(client, MintFlowCookie(externalId), victimEmail, username);
@@ -188,9 +179,9 @@ public async Task SignupFinalize_PendingSignup_NewEmail_ReplacesIt_AndTheOldCode
[Test]
public async Task SignupFinalize_UsernameOfAnotherPendingSignupStartedWithinTheHour_Returns409()
{
- var username = TestHelper.UniqueUsername("oauthfinreserved");
- await CreatePendingOAuthSignupAsync(TestHelper.UniqueEmail("oauth-finalize-reserved"), username, NewExternalId(), uniqueUsername: false);
- var email = TestHelper.UniqueEmail("oauth-finalize-reserved-other");
+ var username = UniqueNames.Username("oauthfinreserved");
+ await CreatePendingOAuthSignupAsync(UniqueNames.Email("oauth-finalize-reserved"), username, NewExternalId(), uniqueUsername: false);
+ var email = UniqueNames.Email("oauth-finalize-reserved-other");
using var client = CreateClient();
var response = await FinalizeAsync(client, MintFlowCookie(NewExternalId(), email: email, emailVerified: true), email, username);
@@ -200,31 +191,13 @@ public async Task SignupFinalize_UsernameOfAnotherPendingSignupStartedWithinTheH
}
[Test]
- public async Task SignupFinalize_PendingSignup_EmailTheProviderVerified_ReplacesItWithAnAccount()
- {
- var externalId = NewExternalId();
- var pendingId = await CreatePendingOAuthSignupAsync(TestHelper.UniqueEmail("oauth-finalize-replace"), "oauthfinreplace", externalId);
- var email = TestHelper.UniqueEmail("oauth-finalize-replace-verified");
-
- using var client = CreateClient();
- var response = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, TestHelper.UniqueUsername("oauthfinrepl"));
-
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
- await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsTrue();
-
- var user = await FindUserByEmailAsync(WebApplicationFactory, email);
- await Assert.That(user!.ActivatedAt).IsNotNull();
- await Assert.That(await FindAsync(WebApplicationFactory, pendingId)).IsNull();
- }
-
- [Test]
- public async Task SignupFinalize_PendingSignup_UsernameTaken_KeepsThePendingSignup()
+ public async Task SignupFinalize_PendingSignup_UsernameTaken_KeepsThePendingSignup_AndARetryReplacesItWithAnAccount()
{
var externalId = NewExternalId();
- var pendingId = await CreatePendingOAuthSignupAsync(TestHelper.UniqueEmail("oauth-finalize-keep"), "oauthfinkeep", externalId);
- var takenUsername = TestHelper.UniqueUsername("oauthfintaken");
- await TestHelper.CreateUserInDb(WebApplicationFactory, takenUsername, TestHelper.UniqueEmail("oauth-finalize-taken"), "TakenPassword123#");
- var email = TestHelper.UniqueEmail("oauth-finalize-keep-verified");
+ var pendingId = await CreatePendingOAuthSignupAsync(UniqueNames.Email("oauth-finalize-keep"), "oauthfinkeep", externalId);
+ var takenUsername = UniqueNames.Username("oauthfintaken");
+ await TestHelper.CreateUserInDb(WebApplicationFactory, takenUsername, UniqueNames.Email("oauth-finalize-taken"), "TakenPassword123#");
+ var email = UniqueNames.Email("oauth-finalize-keep-verified");
using var client = CreateClient();
var response = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, takenUsername);
@@ -232,22 +205,26 @@ public async Task SignupFinalize_PendingSignup_UsernameTaken_KeepsThePendingSign
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict);
await Assert.That(await FindAsync(WebApplicationFactory, pendingId)).IsNotNull();
- // The flow is still open, so the signup can be retried with another username.
- var retry = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, TestHelper.UniqueUsername("oauthfinretry"));
+ // The flow is still open, so the signup can be retried with another username. The provider verified
+ // the address, so the retry replaces the pending signup with an activated account and signs in.
+ var retry = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, UniqueNames.Username("oauthfinretry"));
await Assert.That(retry.StatusCode).IsEqualTo(HttpStatusCode.OK);
+ await Assert.That(SetsCookie(retry, AuthConstants.UserSessionCookieName)).IsTrue();
await Assert.That(await FindAsync(WebApplicationFactory, pendingId)).IsNull();
+ var user = await FindUserByEmailAsync(WebApplicationFactory, email);
+ await Assert.That(user!.ActivatedAt).IsNotNull();
}
[Test]
public async Task SignupFinalize_IdentityOfAnAccount_Returns409()
{
var externalId = NewExternalId();
- var email = TestHelper.UniqueEmail("oauth-finalize-linked");
+ var email = UniqueNames.Email("oauth-finalize-linked");
using var client = CreateClient();
- var created = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, TestHelper.UniqueUsername("oauthfinlinked"));
+ var created = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, UniqueNames.Username("oauthfinlinked"));
await Assert.That(created.StatusCode).IsEqualTo(HttpStatusCode.OK);
- var response = await FinalizeAsync(client, MintFlowCookie(externalId), TestHelper.UniqueEmail("oauth-finalize-linked-new"), TestHelper.UniqueUsername("oauthfinlinked2"));
+ var response = await FinalizeAsync(client, MintFlowCookie(externalId), UniqueNames.Email("oauth-finalize-linked-new"), UniqueNames.Username("oauthfinlinked2"));
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict);
}
@@ -258,7 +235,7 @@ public async Task SignupFinalize_IdentityOfAnAccount_Returns409()
public async Task Handoff_IdentityOfAnAccountLeftUnactivated_IsNotSignedIn_AndIsToldWhy()
{
var externalId = NewExternalId();
- var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("oauthunactivated"), TestHelper.UniqueEmail("oauth-unactivated"), Password, activated: false);
+ var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("oauthunactivated"), UniqueNames.Email("oauth-unactivated"), Password, activated: false);
await using (var scope = WebApplicationFactory.Services.CreateAsyncScope())
{
var db = scope.ServiceProvider.GetRequiredService();
@@ -282,11 +259,11 @@ public async Task Handoff_IdentityOfAnAccountLeftUnactivated_IsNotSignedIn_AndIs
public async Task SignupSomeoneElseStartedOnMyAddress_NeverBecomesMyAccount_AndDoesNotKeepMeFromSigningUp()
{
var attackerExternalId = NewExternalId();
- var victimEmail = TestHelper.UniqueEmail("oauth-takeover-victim");
+ var victimEmail = UniqueNames.Email("oauth-takeover-victim");
// The attacker signs up through the provider, typing the victim's address.
using var client = CreateClient();
- var attackerSignup = await FinalizeAsync(client, MintFlowCookie(attackerExternalId, email: TestHelper.UniqueEmail("oauth-takeover-attacker"), emailVerified: true), victimEmail, TestHelper.UniqueUsername("oauthtakeover"));
+ var attackerSignup = await FinalizeAsync(client, MintFlowCookie(attackerExternalId, email: UniqueNames.Email("oauth-takeover-attacker"), emailVerified: true), victimEmail, UniqueNames.Username("oauthtakeover"));
await Assert.That(attackerSignup.StatusCode).IsEqualTo(HttpStatusCode.OK);
var attackerPending = (await FindByEmailAsync(WebApplicationFactory, victimEmail)).Single();
@@ -295,7 +272,7 @@ public async Task SignupSomeoneElseStartedOnMyAddress_NeverBecomesMyAccount_AndD
await Assert.That((await PostActivateAsync(client, attackerCode, cookie: null)).StatusCode).IsEqualTo(HttpStatusCode.BadRequest);
// ...and the address is still free for them to sign up with, which they do, and complete.
- var victimSignup = await PostSignupAsync(client, victimEmail, TestHelper.UniqueUsername("oauthvictim"), "VictimPassword123#");
+ var victimSignup = await PostSignupAsync(client, victimEmail, UniqueNames.Username("oauthvictim"), "VictimPassword123#");
await Assert.That(victimSignup.StatusCode).IsEqualTo(HttpStatusCode.OK);
var victimPending = (await FindByEmailAsync(WebApplicationFactory, victimEmail)).Single(p => p.Id != attackerPending.Id);
var victimCode = await MailCodeAsync(WebApplicationFactory, victimPending.Id);
@@ -321,7 +298,7 @@ public async Task SignupSomeoneElseStartedOnMyAddress_NeverBecomesMyAccount_AndD
await Assert.That(late.StatusCode).IsEqualTo(HttpStatusCode.BadRequest);
// ...and the address cannot be signed up with again.
- var again = await FinalizeAsync(client, MintFlowCookie(attackerExternalId), victimEmail, TestHelper.UniqueUsername("oauthtakeover2"));
+ var again = await FinalizeAsync(client, MintFlowCookie(attackerExternalId), victimEmail, UniqueNames.Username("oauthtakeover2"));
await Assert.That(again.StatusCode).IsEqualTo(HttpStatusCode.Conflict);
}
@@ -392,7 +369,7 @@ private static async Task AssertSentBackToSignupAsync(HttpResponseMessage respon
/// A signup started through the provider with an address it did not verify, with no mail queued yet.
private Task CreatePendingOAuthSignupAsync(string email, string username, string externalId, bool uniqueUsername = true)
- => CreateInDbAsync(WebApplicationFactory, email, uniqueUsername ? TestHelper.UniqueUsername(username) : username, password: null, oauthProvider: Provider, oauthExternalId: externalId);
+ => CreateInDbAsync(WebApplicationFactory, email, uniqueUsername ? UniqueNames.Username(username) : username, password: null, oauthProvider: Provider, oauthExternalId: externalId);
private async Task CountOutboxAsync(string email)
{
diff --git a/API.IntegrationTests/Tests/PendingSignupsMigrationTests.cs b/API.IntegrationTests/Tests/PendingSignupsMigrationTests.cs
index 25b3f553..d4ef3d25 100644
--- a/API.IntegrationTests/Tests/PendingSignupsMigrationTests.cs
+++ b/API.IntegrationTests/Tests/PendingSignupsMigrationTests.cs
@@ -1,9 +1,11 @@
+using System.Net;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.Extensions.Logging.Abstractions;
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Utils;
+using OpenShock.IntegrationTests.Shared;
using Testcontainers.PostgreSql;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -19,7 +21,9 @@ public sealed class PendingSignupsMigrationTests
[Test]
public async Task NeverActivatedAccounts_BecomePendingSignups_AndTheRestIsLeftAlone()
{
- await using var container = new PostgreSqlBuilder(image: "timescale/timescaledb:latest-pg18").Build();
+ await using var container = new PostgreSqlBuilder(image: ContainerImages.TimescaleDb)
+ .WithCommand(ContainerImages.TimescaleDbCommand)
+ .Build();
await container.StartAsync();
MigrationOpenShockContext CreateContext() => new(container.GetConnectionString(), false, NullLoggerFactory.Instance);
@@ -30,6 +34,7 @@ public async Task NeverActivatedAccounts_BecomePendingSignups_AndTheRestIsLeftAl
var staff = Guid.CreateVersion7();
var deactivated = Guid.CreateVersion7();
var ownsHub = Guid.CreateVersion7();
+ var ownsApiToken = Guid.CreateVersion7();
var twoIdentities = Guid.CreateVersion7();
var noCredential = Guid.CreateVersion7();
var invited = Guid.CreateVersion7();
@@ -46,6 +51,7 @@ public async Task NeverActivatedAccounts_BecomePendingSignups_AndTheRestIsLeftAl
NewUser(staff, "migratestaff", passwordHash, isActivated: false, RoleType.Staff),
NewUser(deactivated, "migratedeactivated", passwordHash, isActivated: false),
NewUser(ownsHub, "migratehub", passwordHash, isActivated: false),
+ NewUser(ownsApiToken, "migrateapitoken", passwordHash, isActivated: false),
NewUser(twoIdentities, "migratetwoidentities", passwordHash: null, isActivated: false),
// Nothing to resume a signup with, so there is nothing to move it to.
NewUser(noCredential, "migratenocredential", passwordHash: null, isActivated: false),
@@ -59,6 +65,7 @@ public async Task NeverActivatedAccounts_BecomePendingSignups_AndTheRestIsLeftAl
new UserOAuthConnection { UserId = twoIdentities, ProviderKey = "google", ExternalId = "migrate-two-google", DisplayName = "Second" });
db.UserDeactivations.Add(new UserDeactivation { DeactivatedUserId = deactivated, DeactivatedByUserId = deactivated, DeleteLater = false });
db.Devices.Add(new Device { Id = Guid.CreateVersion7(), OwnerId = ownsHub, Name = "Hub", Token = "pending-signups-migration-token" });
+ db.ApiTokens.Add(new ApiToken { Id = Guid.CreateVersion7(), UserId = ownsApiToken, Name = "Token", TokenHash = HashingUtils.HashToken("pending-signups-migration-api-token"), CreatedByIp = IPAddress.Loopback, Permissions = [PermissionType.Shockers_Use] });
await db.SaveChangesAsync();
// The table the migration drops, with the link that was mailed for one of the accounts.
@@ -80,6 +87,7 @@ await db.Database.ExecuteSqlAsync(
await Assert.That(users).Contains(staff);
await Assert.That(users).Contains(deactivated);
await Assert.That(users).Contains(ownsHub);
+ await Assert.That(users).Contains(ownsApiToken);
await Assert.That(users).Contains(twoIdentities);
await Assert.That(users).Contains(noCredential);
await Assert.That(users).Contains(invited);
diff --git a/API.IntegrationTests/Tests/PublicShareControlTests.cs b/API.IntegrationTests/Tests/PublicShareControlTests.cs
new file mode 100644
index 00000000..36a4edef
--- /dev/null
+++ b/API.IntegrationTests/Tests/PublicShareControlTests.cs
@@ -0,0 +1,169 @@
+using System.Net;
+using System.Text.Json;
+using Microsoft.AspNetCore.Http.Connections;
+using Microsoft.AspNetCore.SignalR.Client;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using OpenShock.API.IntegrationTests.Helpers;
+using OpenShock.Common.Models.WebSocket.User;
+using OpenShock.Common.OpenShockDb;
+using OpenShock.IntegrationTests.Shared;
+using static OpenShock.API.IntegrationTests.Helpers.ControlLogHelper;
+
+namespace OpenShock.API.IntegrationTests.Tests;
+
+public sealed class PublicShareControlTests
+{
+ private const string Password = "SecurePassword123#";
+
+ [ClassDataSource(Shared = SharedType.PerTestSession)]
+ public required WebApplicationFactory WebApplicationFactory { get; init; }
+
+ [Test]
+ public async Task GuestControl_IsClampedToTheTighterOfShareAndShockerLimits()
+ {
+ var (owner, shareId, shockerId) = await CreateShareWithShocker("pscclamp");
+ using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken);
+
+ var shockerLimits = await ownerClient.PutAsync($"/1/shockers/{shockerId}/permissions", TestHelper.JsonContent(new
+ {
+ permissions = new { shock = true, vibrate = true, sound = true, live = true },
+ limits = new { intensity = 30, duration = 5000 }
+ }));
+ await Assert.That(shockerLimits.StatusCode).IsEqualTo(HttpStatusCode.OK);
+ await EditShareShocker(ownerClient, shareId, shockerId, shock: true, vibrate: true, intensity: 60, duration: 1000);
+
+ await using var connection = await ConnectGuestAsync(shareId);
+ await connection.InvokeAsync("Control", new[] { Shock(shockerId, ControlType.Shock, 90, 8000) });
+
+ var log = (await Logs(shockerId)).Single();
+ await Assert.That(log.Intensity).IsEqualTo((byte)30);
+ await Assert.That(log.Duration).IsEqualTo(1000u);
+ await Assert.That(log.ControlledByUserId).IsNull();
+ }
+
+ [Test]
+ [Arguments(true)]
+ [Arguments(false)]
+ public async Task GuestControl_TypeDisallowedByShareOrShocker_IsNotSent(bool disallowedByShare)
+ {
+ var (owner, shareId, shockerId) = await CreateShareWithShocker("pscperm");
+ using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken);
+
+ if (disallowedByShare)
+ {
+ await EditShareShocker(ownerClient, shareId, shockerId, shock: false, vibrate: true, intensity: null, duration: null);
+ }
+ else
+ {
+ var response = await ownerClient.PutAsync($"/1/shockers/{shockerId}/permissions", TestHelper.JsonContent(new
+ {
+ permissions = new { shock = false, vibrate = true, sound = true, live = true },
+ limits = new { intensity = (int?)null, duration = (int?)null }
+ }));
+ await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
+ }
+
+ await using var connection = await ConnectGuestAsync(shareId);
+ await connection.InvokeAsync("Control", new[] { Shock(shockerId, ControlType.Shock, 50, 1000) });
+ await connection.InvokeAsync("Control", new[] { Shock(shockerId, ControlType.Vibrate, 50, 1000) });
+
+ var logs = await Logs(shockerId);
+ await Assert.That(logs.Select(x => x.Type).ToArray()).IsEquivalentTo(new[] { ControlType.Vibrate });
+ }
+
+ [Test]
+ [Arguments(true)]
+ [Arguments(false)]
+ public async Task GuestControl_PausedShareShockerOrShocker_IsNotSent(bool pauseInShare)
+ {
+ var (owner, shareId, shockerId) = await CreateShareWithShocker("pscpause");
+ using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken);
+ await using var connection = await ConnectGuestAsync(shareId);
+
+ await connection.InvokeAsync("Control", new[] { Shock(shockerId, ControlType.Vibrate, 50, 1000) });
+ await Assert.That((await Logs(shockerId)).Length).IsEqualTo(1);
+
+ var pause = await ownerClient.PostAsync(
+ pauseInShare ? $"/1/shares/links/{shareId}/{shockerId}/pause" : $"/1/shockers/{shockerId}/pause",
+ TestHelper.JsonContent(new { pause = true }));
+ await Assert.That(pause.StatusCode).IsEqualTo(HttpStatusCode.OK);
+
+ await connection.InvokeAsync("Control", new[] { Shock(shockerId, ControlType.Vibrate, 50, 1000) });
+ await Assert.That((await Logs(shockerId)).Length).IsEqualTo(1);
+ }
+
+ private static Control Shock(Guid shockerId, ControlType type, byte intensity, ushort duration) => new()
+ {
+ Id = shockerId,
+ Type = type,
+ Intensity = intensity,
+ Duration = duration
+ };
+
+ private async Task<(AuthenticatedUser Owner, Guid ShareId, Guid ShockerId)> CreateShareWithShocker(string prefix)
+ {
+ var owner = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix),
+ UniqueNames.Email(prefix), Password);
+ var shockerId = await CreateShocker(WebApplicationFactory, owner.Id, "Shared");
+
+ using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken);
+ var created = await client.PostAsync("/1/shares/links", TestHelper.JsonContent(new { name = "control share" }));
+ await Assert.That(created.StatusCode).IsEqualTo(HttpStatusCode.OK);
+ using var json = JsonDocument.Parse(await created.Content.ReadAsStringAsync());
+ var shareId = json.RootElement.GetProperty("data").GetGuid();
+
+ var added = await client.PostAsync($"/1/shares/links/{shareId}/{shockerId}", null);
+ await Assert.That(added.StatusCode).IsEqualTo(HttpStatusCode.OK);
+
+ return (owner, shareId, shockerId);
+ }
+
+ private static async Task EditShareShocker(HttpClient ownerClient, Guid shareId, Guid shockerId, bool shock, bool vibrate,
+ int? intensity, int? duration)
+ {
+ var response = await ownerClient.PatchAsync($"/1/shares/links/{shareId}/{shockerId}", TestHelper.JsonContent(new
+ {
+ permissions = new { shock, vibrate, sound = true, live = false },
+ limits = new { intensity, duration },
+ cooldown = (int?)null
+ }));
+ await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
+ }
+
+ private async Task Logs(Guid shockerId)
+ {
+ await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ return await db.ShockerControlLogs.AsNoTracking().Where(x => x.ShockerId == shockerId).ToArrayAsync();
+ }
+
+ /// Connects as a guest and waits until the hub admitted the connection (it sends Welcome after its checks).
+ private async Task ConnectGuestAsync(Guid shareId)
+ {
+ var server = WebApplicationFactory.Server;
+ var connection = new HubConnectionBuilder()
+ .WithUrl(new Uri(server.BaseAddress, $"/1/hubs/share/link/{shareId}?name=Guest"), options =>
+ {
+ options.Transports = HttpTransportType.WebSockets;
+ options.SkipNegotiation = true;
+ options.WebSocketFactory = async (context, cancellationToken) =>
+ await server.CreateWebSocketClient().ConnectAsync(context.Uri, cancellationToken);
+ })
+ .Build();
+
+ var welcomed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ connection.On("Welcome", _ => welcomed.TrySetResult());
+ try
+ {
+ await connection.StartAsync();
+ await welcomed.Task.WaitAsync(TimeSpan.FromSeconds(30));
+ return connection;
+ }
+ catch
+ {
+ await connection.DisposeAsync();
+ throw;
+ }
+ }
+}
diff --git a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs
index feca254f..29f836b8 100644
--- a/API.IntegrationTests/Tests/PublicSharePasswordTests.cs
+++ b/API.IntegrationTests/Tests/PublicSharePasswordTests.cs
@@ -1,3 +1,4 @@
+using OpenShock.IntegrationTests.Shared;
using StackExchange.Redis;
using System.Net;
using System.Text.Json;
@@ -11,7 +12,6 @@
using OpenShock.Common.Models.WebSocket.User;
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Services.PublicShareAccess;
-using OpenShock.Common.Services.Session;
namespace OpenShock.API.IntegrationTests.Tests;
@@ -96,17 +96,6 @@ public async Task OwnList_ShowsWhetherAShareHasAPassword()
// --- Unlocking ---
- [Test]
- public async Task Unlock_WithWrongPassword_Returns401()
- {
- var (_, shareId) = await CreateShareWithShocker("pwwrong", Password);
- using var visitor = WebApplicationFactory.CreateClient();
-
- var response = await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock",
- TestHelper.JsonContent(new { password = "nope-nope" }));
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
- }
-
[Test]
public async Task Unlock_AfterTooManyWrongPasswords_IsLockedOutEvenWithTheRightOne()
{
@@ -138,20 +127,6 @@ public async Task Unlock_ParallelWrongPasswords_NeverGetPastTheLimit()
await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.TooManyRequests)).IsEqualTo(10);
}
- [Test]
- public async Task Unlock_WrongPassword_StartsAnExpiringLockoutWindow()
- {
- var (_, shareId) = await CreateShareWithShocker("pwwindow", Password);
- using var visitor = WebApplicationFactory.CreateClient();
-
- await visitor.PostAsync($"/1/public/shares/links/{shareId}/unlock", TestHelper.JsonContent(new { password = "nope-nope" }));
-
- var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase();
- var ttl = await redis.KeyTimeToLiveAsync($"public-share-unlock-failures:{shareId}");
- await Assert.That(ttl).IsNotNull();
- await Assert.That(ttl!.Value).IsLessThanOrEqualTo(PublicShareAccessService.FailedAttemptWindow);
- }
-
[Test]
public async Task Unlock_CorrectPasswords_DoNotCountTowardsTheLockout()
{
@@ -275,23 +250,12 @@ public async Task RemovingThePassword_OpensTheShare()
await Assert.That(share.GetProperty("passwordRequired").GetBoolean()).IsFalse();
}
- [Test]
- public async Task SettingAPassword_ThatIsTooShort_Returns400()
- {
- var (owner, shareId) = await CreateShareWithShocker("pwshort", password: null);
- using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken);
-
- var response = await ownerClient.PutAsync($"/1/shares/links/{shareId}/password",
- TestHelper.JsonContent(new { password = "abc" }));
- await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest);
- }
-
[Test]
public async Task SettingThePassword_OfSomeoneElsesShare_Returns404()
{
var (_, shareId) = await CreateShareWithShocker("pwforeign", password: null);
- var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("pwforeigno"),
- TestHelper.UniqueEmail("pwforeigno"), "SecurePassword123#");
+ var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("pwforeigno"),
+ UniqueNames.Email("pwforeigno"), "SecurePassword123#");
using var otherClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, other.SessionToken);
var response = await otherClient.PutAsync($"/1/shares/links/{shareId}/password",
@@ -299,22 +263,6 @@ public async Task SettingThePassword_OfSomeoneElsesShare_Returns404()
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
}
- [Test]
- public async Task Profile_DefaultShare_SaysWhetherItIsPasswordProtected()
- {
- var (owner, shareId) = await CreateShareWithShocker("pwprofile", Password);
- using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken);
- var profile = await ownerClient.PutAsync("/1/account/profile",
- TestHelper.JsonContent(new
- { isPublic = true, socials = Array.Empty