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(), defaultPublicShareId = shareId })); - await Assert.That(profile.IsSuccessStatusCode).IsTrue(); - - using var visitor = WebApplicationFactory.CreateClient(); - var json = await GetJson(visitor, $"/1/public/users/{owner.Username}", unlockToken: null, unwrapData: false); - await Assert.That(json.GetProperty("defaultPublicShare").GetProperty("passwordProtected").GetBoolean()) - .IsTrue(); - } - // --- The hub --- [Test] @@ -331,18 +279,6 @@ public async Task Hub_WithoutToken_IsRejected() await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); } - [Test] - public async Task Hub_WithToken_ConnectsAndCanCall() - { - var (_, shareId) = await CreateShareWithShocker("pwhubok", Password); - using var visitor = WebApplicationFactory.CreateClient(); - var token = await Unlock(visitor, shareId, Password); - - await using var connection = await ConnectAsync(shareId, token); - await connection.InvokeAsync("Control", Array.Empty()); - await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); - } - [Test] public async Task Hub_OwnerConnectsWithoutToken() { @@ -444,14 +380,12 @@ public async Task Hub_LoggedInVisitor_IsClosedOnLogout() { var (_, shareId) = await CreateShareWithShocker("pwhublogout", password: null); var visitor = await TestHelper.CreateAndLoginUser(WebApplicationFactory, - TestHelper.UniqueUsername("pwhublogoutv"), TestHelper.UniqueEmail("pwhublogoutv"), "SecurePassword123#"); + UniqueNames.Username("pwhublogoutv"), UniqueNames.Email("pwhublogoutv"), "SecurePassword123#"); await using var connection = await ConnectAsync(shareId, unlockToken: null, sessionToken: visitor.SessionToken); - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - await scope.ServiceProvider.GetRequiredService() - .DeleteSessionByTokenAsync(visitor.SessionToken); - } + using var visitorClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, visitor.SessionToken); + var logout = await visitorClient.PostAsync("/1/account/logout", null); + await Assert.That(logout.StatusCode).IsEqualTo(HttpStatusCode.OK); await AssertConnectionClosesAsync(connection); } @@ -461,7 +395,7 @@ public async Task Hub_DeactivatingTheOwner_ClosesGuestsAndLoggedInVisitors() { var (owner, shareId) = await CreateShareWithShocker("pwhubownerdeact", password: null); var visitor = await TestHelper.CreateAndLoginUser(WebApplicationFactory, - TestHelper.UniqueUsername("pwhubownerdeactv"), TestHelper.UniqueEmail("pwhubownerdeactv"), "SecurePassword123#"); + UniqueNames.Username("pwhubownerdeactv"), UniqueNames.Email("pwhubownerdeactv"), "SecurePassword123#"); await using var guestConnection = await ConnectAsync(shareId, unlockToken: null); await using var visitorConnection = await ConnectAsync(shareId, unlockToken: null, sessionToken: visitor.SessionToken); @@ -480,8 +414,8 @@ await scope.ServiceProvider.GetRequiredService() private async Task<(AuthenticatedUser Owner, Guid ShareId)> CreateShareWithShocker(string prefix, string? password, string? slug = null) { - var owner = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername(prefix), - TestHelper.UniqueEmail(prefix), "SecurePassword123#"); + var owner = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), + UniqueNames.Email(prefix), "SecurePassword123#"); var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, owner.Id, "pw hub"); var shockerId = Guid.CreateVersion7(); @@ -512,8 +446,7 @@ await scope.ServiceProvider.GetRequiredService() private Task GetShare(HttpClient client, Guid shareId, string? unlockToken) => GetJson(client, $"/1/public/shares/links/{shareId}", unlockToken); - private static async Task GetJson(HttpClient client, string path, string? unlockToken, - bool unwrapData = true) + private static async Task GetJson(HttpClient client, string path, string? unlockToken) { using var request = new HttpRequestMessage(HttpMethod.Get, path); if (unlockToken is not null) request.Headers.Add(AuthConstants.PublicShareUnlockHeaderName, unlockToken); @@ -522,8 +455,7 @@ private static async Task GetJson(HttpClient client, string path, s await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); - var root = unwrapData ? json.RootElement.GetProperty("data") : json.RootElement; - return root.Clone(); + return json.RootElement.GetProperty("data").Clone(); } private static async Task Unlock(HttpClient client, Guid shareId, string password) diff --git a/API.IntegrationTests/Tests/PublicShareProfileTests.cs b/API.IntegrationTests/Tests/PublicShareProfileTests.cs index a210867d..9362ddfa 100644 --- a/API.IntegrationTests/Tests/PublicShareProfileTests.cs +++ b/API.IntegrationTests/Tests/PublicShareProfileTests.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; @@ -14,17 +15,17 @@ public sealed class PublicShareProfileTests private async Task<(AuthenticatedUser User, HttpClient Client)> CreateUser(string prefix) { - var username = TestHelper.UniqueUsername(prefix); - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, username, TestHelper.UniqueEmail(prefix), "SecurePassword123#"); + var username = UniqueNames.Username(prefix); + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, username, UniqueNames.Email(prefix), "SecurePassword123#"); return (user, TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken)); } - private static async Task CreateShare(HttpClient client, string name, string? slug) => - await client.PostAsync("/1/shares/links", TestHelper.JsonContent(new { name, slug })); + private static async Task CreateShare(HttpClient client, string name, string? slug, string? password = null) => + await client.PostAsync("/1/shares/links", TestHelper.JsonContent(new { name, slug, password })); - private static async Task CreateShareId(HttpClient client, string name, string? slug) + private static async Task CreateShareId(HttpClient client, string name, string? slug, string? password = null) { - var response = await CreateShare(client, name, slug); + var response = await CreateShare(client, name, slug, password); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); return doc.RootElement.GetProperty("data").GetGuid(); @@ -58,16 +59,10 @@ public async Task CreateWithSlug_ResolvesBySlug_CaseInsensitive() } [Test] - [Arguments("a")] - [Arguments("-abc")] - [Arguments("abc-")] - [Arguments("a--b")] - [Arguments("with space")] - [Arguments("emojié")] - public async Task CreateWithInvalidSlug_Returns400(string slug) + public async Task CreateWithInvalidSlug_Returns400() { var (_, client) = await CreateUser("sluginv"); - var response = await CreateShare(client, "Bad", slug); + var response = await CreateShare(client, "Bad", "a--b"); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); } @@ -84,15 +79,6 @@ public async Task DuplicateSlug_SameOwner_Returns409_OtherOwnerAllowed() await CreateShareId(otherClient, "Other", "mine"); } - [Test] - public async Task UnknownSlug_Returns404() - { - var (user, _) = await CreateUser("slugnf"); - using var anon = WebApplicationFactory.CreateClient(); - var response = await anon.GetAsync($"/1/public/shares/links/by-slug/{user.Username}/nope"); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); - } - [Test] public async Task ExpiredShare_ReleasesSlug() { @@ -125,6 +111,10 @@ public async Task EditShare_SetsAndClearsSlug() var bySlug = await anon.GetAsync($"/1/public/shares/links/by-slug/{user.Username}/edited"); await Assert.That(bySlug.StatusCode).IsEqualTo(HttpStatusCode.OK); + // Saving the share with the slug it already has is not a conflict with itself + var keep = await client.PutAsync($"/1/shares/links/{shareId}", TestHelper.JsonContent(new { name = "Renamed", expiresOn = (DateTime?)null, slug = "edited" })); + await Assert.That(keep.StatusCode).IsEqualTo(HttpStatusCode.OK); + var clear = await client.PutAsync($"/1/shares/links/{shareId}", TestHelper.JsonContent(new { name = "Renamed", expiresOn = (DateTime?)null, slug = (string?)null })); await Assert.That(clear.StatusCode).IsEqualTo(HttpStatusCode.OK); @@ -132,16 +122,6 @@ public async Task EditShare_SetsAndClearsSlug() await Assert.That(gone.StatusCode).IsEqualTo(HttpStatusCode.NotFound); } - [Test] - public async Task EditShare_KeepingOwnSlug_Succeeds() - { - var (_, client) = await CreateUser("slugkeep"); - var shareId = await CreateShareId(client, "Keep", "keep"); - - var edit = await client.PutAsync($"/1/shares/links/{shareId}", TestHelper.JsonContent(new { name = "Keep 2", expiresOn = (DateTime?)null, slug = "keep" })); - await Assert.That(edit.StatusCode).IsEqualTo(HttpStatusCode.OK); - } - [Test] public async Task EditShare_OtherUser_Returns404() { @@ -172,7 +152,7 @@ public async Task Profile_PrivateByDefault() public async Task Profile_Public_ShowsDetailsAndDefaultShare() { var (user, client) = await CreateUser("profpub"); - var shareId = await CreateShareId(client, "Main", "main"); + var shareId = await CreateShareId(client, "Main", "main", password: "hunter22"); var put = await PutProfile(client, new { @@ -199,6 +179,7 @@ public async Task Profile_Public_ShowsDetailsAndDefaultShare() await Assert.That(profile.GetProperty("profile").GetProperty("socials")[1].GetProperty("platform").GetString()).IsEqualTo("Bluesky"); await Assert.That(profile.GetProperty("defaultPublicShare").GetProperty("id").GetGuid()).IsEqualTo(shareId); await Assert.That(profile.GetProperty("defaultPublicShare").GetProperty("slug").GetString()).IsEqualTo("main"); + await Assert.That(profile.GetProperty("defaultPublicShare").GetProperty("passwordProtected").GetBoolean()).IsTrue(); var share = (await ReadJson(await anon.GetAsync($"/1/public/shares/links/{shareId}"))).GetProperty("data"); await Assert.That(share.GetProperty("author").GetProperty("profile").GetProperty("pronouns").GetString()).IsEqualTo("they/them"); @@ -235,22 +216,10 @@ public async Task Profile_DefaultShareOfOtherUser_Returns400() } [Test] - [Arguments("Website", "javascript:alert(1)")] - [Arguments("Website", "not a url")] - [Arguments("Discord", "has space")] - [Arguments("X", "https://x.com/someone")] - public async Task Profile_InvalidSocial_Returns400(string platform, string value) + public async Task Profile_InvalidSocial_Returns400() { var (_, client) = await CreateUser("profsoc"); - var put = await PutProfile(client, new { isPublic = true, socials = new[] { new { platform, value } } }); - await Assert.That(put.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - } - - [Test] - public async Task Profile_UnknownSocialPlatform_Returns400() - { - var (_, client) = await CreateUser("profsocu"); - var put = await PutProfile(client, new { isPublic = true, socials = new[] { new { platform = "MySpace", value = "tom" } } }); + var put = await PutProfile(client, new { isPublic = true, socials = new[] { new { platform = "Website", value = "javascript:alert(1)" } } }); await Assert.That(put.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); } @@ -271,15 +240,4 @@ public async Task Profile_DeletingDefaultShare_ClearsDefault() var profile = await ReadJson(await anon.GetAsync($"/1/public/users/{user.Username}")); await Assert.That(profile.GetProperty("defaultPublicShare").ValueKind).IsEqualTo(JsonValueKind.Null); } - - [Test] - public async Task Profile_RequiresSession_ApiTokenRejected() - { - var (user, _) = await CreateUser("proftok"); - var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "profile", [PermissionType.Publicshares_Edit]); - using var tokenClient = TestHelper.CreateApiTokenClient(WebApplicationFactory, rawToken); - - var response = await tokenClient.GetAsync("/1/account/profile"); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); - } } diff --git a/API.IntegrationTests/Tests/PublicTests.cs b/API.IntegrationTests/Tests/PublicTests.cs deleted file mode 100644 index 8c9388f5..00000000 --- a/API.IntegrationTests/Tests/PublicTests.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System.Net; -using System.Text; -using System.Text.Json; - -namespace OpenShock.API.IntegrationTests.Tests; - -public sealed class PublicTests -{ - [ClassDataSource(Shared = SharedType.PerTestSession)] - public required WebApplicationFactory WebApplicationFactory { get; init; } - - // --- Metadata / Version --- - - [Test] - public async Task GetMetadataV1_ReturnsValidResponse() - { - using var client = WebApplicationFactory.CreateClient(); - - var response = await client.GetAsync("/1"); - - 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 data = doc.RootElement.GetProperty("data"); - await Assert.That(data.GetProperty("version").GetString()).IsNotNullOrWhiteSpace(); - await Assert.That(data.GetProperty("currentTime").GetDateTimeOffset()).IsBetween( - DateTimeOffset.UtcNow.AddSeconds(-10), - DateTimeOffset.UtcNow.AddSeconds(10)); - } - - // --- Public Stats --- - - [Test] - public async Task GetStats_ReturnsDevicesOnlineCount() - { - using var client = WebApplicationFactory.CreateClient(); - - var response = await client.GetAsync("/1/public/stats"); - - 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"); - var devicesOnline = data.GetProperty("devicesOnline").GetInt64(); - await Assert.That(devicesOnline).IsGreaterThanOrEqualTo(0); - } - - // --- Check Username (public endpoint) --- - - [Test] - public async Task CheckUsername_Available_ReturnsAvailable() - { - using var client = WebApplicationFactory.CreateClient(); - - using var content = new StringContent( - JsonSerializer.Serialize(new { username = "totallyuniquename123" }), - Encoding.UTF8, - "application/json"); - - var response = await client.PostAsync("/1/account/username/check", content); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - - var json = await response.Content.ReadAsStringAsync(); - using var doc = JsonDocument.Parse(json); - var availability = doc.RootElement.GetProperty("availability").GetString(); - await Assert.That(availability).IsEqualTo("Available"); - } -} diff --git a/API.IntegrationTests/Tests/RateLimiterTests.cs b/API.IntegrationTests/Tests/RateLimiterTests.cs deleted file mode 100644 index 2094867b..00000000 --- a/API.IntegrationTests/Tests/RateLimiterTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Net; -using OpenShock.API.IntegrationTests.Helpers; - -namespace OpenShock.API.IntegrationTests.Tests; - -/// -/// Smoke tests that the rate limiter middleware is registered and policies are configured. -/// Rate limiting is disabled in the test server (NoLimiter policies) to avoid interference -/// between tests. Detailed rate limiter behavior is covered by unit tests. -/// -public sealed class RateLimiterTests -{ - [ClassDataSource(Shared = SharedType.PerTestSession)] - public required WebApplicationFactory WebApplicationFactory { get; init; } - - [Test] - public async Task AuthEndpoint_WithRateLimiterPolicy_DoesNotReturn500() - { - using var client = WebApplicationFactory.CreateClient(); - - // The "auth" rate limiter policy is applied to login/signup endpoints. - // Verify the policy is correctly registered (no 500 from missing policy). - var response = await client.PostAsync("/2/account/login", TestHelper.JsonContent(new - { - usernameOrEmail = "ratelimitertest@test.org", - password = "SomePassword123#", - turnstileResponse = "valid-token" - })); - - await Assert.That(response.StatusCode).IsNotEqualTo(HttpStatusCode.InternalServerError); - } - - [Test] - public async Task GlobalEndpoint_WithRateLimiterMiddleware_DoesNotReturn500() - { - using var client = WebApplicationFactory.CreateClient(); - - // Verify that the global rate limiter middleware doesn't cause errors. - var response = await client.GetAsync("/1"); - - await Assert.That(response.StatusCode).IsNotEqualTo(HttpStatusCode.InternalServerError); - } -} diff --git a/API.IntegrationTests/Tests/RegistrationDisabledTests.cs b/API.IntegrationTests/Tests/RegistrationDisabledTests.cs index 79acf11d..618ecdce 100644 --- a/API.IntegrationTests/Tests/RegistrationDisabledTests.cs +++ b/API.IntegrationTests/Tests/RegistrationDisabledTests.cs @@ -1,12 +1,15 @@ using System.Net; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Testing; using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.IntegrationTests.Shared; +using static OpenShock.API.IntegrationTests.Helpers.PendingSignupHelper; namespace OpenShock.API.IntegrationTests.Tests; /// -/// Verifies that all account-creation endpoints refuse with 403 Signup.RegistrationDisabled -/// when registration is disabled. +/// Verifies that both account-creation endpoints, the signup form and the OAuth signup finalize, refuse with +/// 403 Signup.RegistrationDisabled when registration is disabled. /// public sealed class RegistrationDisabledTests { @@ -16,13 +19,15 @@ public sealed class RegistrationDisabledTests [Test] public async Task V2Signup_RegistrationDisabled_Returns403WithProblemType() { + var email = UniqueNames.Email("disabled-v2"); using var client = WebApplicationFactory.CreateClient(); + // Refused before Turnstile is even looked at. var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new { - username = "disabledv2", - password = "SecurePassword123#", - email = "disabledv2@test.org", + username = UniqueNames.Username("disabledv2"), + password = Password, + email, turnstileResponse = "invalid-token" })); @@ -31,5 +36,33 @@ public async Task V2Signup_RegistrationDisabled_Returns403WithProblemType() var problem = await response.Content.ReadFromJsonAsync(); await Assert.That(problem).IsNotNull(); await Assert.That(problem!.Type).IsEqualTo("Signup.RegistrationDisabled"); + await Assert.That(await FindByEmailAsync(WebApplicationFactory, email)).IsEmpty(); + } + + // A provider-verified address would otherwise create the account and sign in on the spot. + [Test] + public async Task OAuthSignupFinalize_RegistrationDisabled_Returns403WithProblemType_AndCreatesNoAccount() + { + const string provider = "discord"; + var email = UniqueNames.Email("disabled-oauth"); + var flowCookie = OAuthFlowCookieHelper.Mint(WebApplicationFactory, provider, Guid.NewGuid().ToString("N"), email, emailVerified: true); + + using var client = WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + HandleCookies = false + }); + using var request = new HttpRequestMessage(HttpMethod.Post, $"/1/oauth/{provider}/signup-finalize") + { + Content = TestHelper.JsonContent(new { email, username = UniqueNames.Username("disabledoauth") }) + }; + request.Headers.Add("Cookie", flowCookie); + var response = await client.SendAsync(request); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + var problem = await response.Content.ReadFromJsonAsync(); + await Assert.That(problem!.Type).IsEqualTo("Signup.RegistrationDisabled"); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + await Assert.That(await FindByEmailAsync(WebApplicationFactory, email)).IsEmpty(); } } diff --git a/API.IntegrationTests/Tests/RetiredRoutesTests.cs b/API.IntegrationTests/Tests/RetiredRoutesTests.cs new file mode 100644 index 00000000..70310bbd --- /dev/null +++ b/API.IntegrationTests/Tests/RetiredRoutesTests.cs @@ -0,0 +1,31 @@ +using System.Net; +using OpenShock.API.IntegrationTests.Helpers; + +namespace OpenShock.API.IntegrationTests.Tests; + +/// +/// Routes old clients may still call answer 410 Gone, so they are told the route moved instead of a bare 404. +/// +public sealed class RetiredRoutesTests +{ + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required WebApplicationFactory WebApplicationFactory { get; init; } + + [Test] + [Arguments("POST", "/1/account/signup")] + [Arguments("POST", "/1/account/login")] + [Arguments("POST", "/1/account/reset")] + [Arguments("POST", "/2/account/reset-password")] + [Arguments("POST", "/1/account/recover/0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b/somesecret")] + [Arguments("HEAD", "/1/account/recover/0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b/somesecret")] + public async Task RetiredRoute_Returns410Gone(string method, string path) + { + using var client = WebApplicationFactory.CreateClient(); + using var request = new HttpRequestMessage(new HttpMethod(method), path); + if (method == "POST") request.Content = TestHelper.JsonContent(new { }); + + var response = await client.SendAsync(request); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Gone); + } +} diff --git a/API.IntegrationTests/Tests/SessionsTests.cs b/API.IntegrationTests/Tests/SessionsTests.cs index a1891184..602b1ca3 100644 --- a/API.IntegrationTests/Tests/SessionsTests.cs +++ b/API.IntegrationTests/Tests/SessionsTests.cs @@ -1,6 +1,7 @@ using System.Net; using System.Text.Json; using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.IntegrationTests.Shared; namespace OpenShock.API.IntegrationTests.Tests; @@ -9,77 +10,43 @@ public sealed class SessionsTests [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } - // --- Get Self Session --- - - [Test] - public async Task GetSelfSession_ReturnsSessionInfo() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "sessself", "sessself@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.GetAsync("/1/sessions/self"); - - 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("id", out _)).IsTrue(); - await Assert.That(root.GetProperty("ip").ValueKind).IsEqualTo(JsonValueKind.String); - await Assert.That(IPAddress.TryParse(root.GetProperty("ip").GetString(), out _)).IsTrue(); - } - - // --- Delete Session --- - [Test] - public async Task DeleteSession_Nonexistent_Returns404() + public async Task DeleteSession_OwnSession_EndsIt() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "sessdel404", "sessdel404@test.org", "SecurePassword123#"); + var user = await CreateUser("sessdel"); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - var response = await client.DeleteAsync($"/1/sessions/{Guid.CreateVersion7()}"); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); - } - - [Test] - public async Task DeleteSession_OwnSession_Success() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "sessdel", "sessdel@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - // Get self session to get session ID var selfResponse = await client.GetAsync("/1/sessions/self"); await Assert.That(selfResponse.StatusCode).IsEqualTo(HttpStatusCode.OK); - var selfJson = await selfResponse.Content.ReadAsStringAsync(); - using var selfDoc = JsonDocument.Parse(selfJson); - var sessionId = selfDoc.RootElement.GetProperty("id").GetString(); + using var selfDoc = JsonDocument.Parse(await selfResponse.Content.ReadAsStringAsync()); + var sessionId = selfDoc.RootElement.GetProperty("id").GetGuid(); + await Assert.That(IPAddress.TryParse(selfDoc.RootElement.GetProperty("ip").GetString(), out _)).IsTrue(); - // Delete it var response = await client.DeleteAsync($"/1/sessions/{sessionId}"); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + var afterwards = await client.GetAsync("/1/sessions/self"); + await Assert.That(afterwards.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); } - // --- Unauthenticated --- - [Test] - public async Task GetSelfSession_Unauthenticated_Returns401() + public async Task DeleteSession_OfAnotherUser_Returns404AndKeepsIt() { - using var client = WebApplicationFactory.CreateClient(); + var victim = await CreateUser("sessvictim"); + var attacker = await CreateUser("sessattacker"); + using var victimClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, victim.SessionToken); + using var attackerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, attacker.SessionToken); - var response = await client.GetAsync("/1/sessions/self"); + using var selfDoc = JsonDocument.Parse(await victimClient.GetStringAsync("/1/sessions/self")); + var victimSessionId = selfDoc.RootElement.GetProperty("id").GetGuid(); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); - } + var response = await attackerClient.DeleteAsync($"/1/sessions/{victimSessionId}"); - [Test] - public async Task DeleteSession_Unauthenticated_Returns401() - { - using var client = WebApplicationFactory.CreateClient(); - - var response = await client.DeleteAsync($"/1/sessions/{Guid.CreateVersion7()}"); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); + var victimAfterwards = await victimClient.GetAsync("/1/sessions/self"); + await Assert.That(victimAfterwards.StatusCode).IsEqualTo(HttpStatusCode.OK); } + + private Task CreateUser(string prefix) => + TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), "SecurePassword123#"); } diff --git a/API.IntegrationTests/Tests/ShareCodeTests.cs b/API.IntegrationTests/Tests/ShareCodeTests.cs new file mode 100644 index 00000000..e1ccd2af --- /dev/null +++ b/API.IntegrationTests/Tests/ShareCodeTests.cs @@ -0,0 +1,131 @@ +using System.Net; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.Common.Constants; +using OpenShock.Common.OpenShockDb; +using OpenShock.IntegrationTests.Shared; +using static OpenShock.API.IntegrationTests.Helpers.ControlLogHelper; + +namespace OpenShock.API.IntegrationTests.Tests; + +public sealed class ShareCodeTests +{ + private const string Password = "SecurePassword123#"; + + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required WebApplicationFactory WebApplicationFactory { get; init; } + + [Test] + public async Task LinkShareCode_CopiesPermissionsLimitsAndPause_AndConsumesTheCode() + { + var owner = await CreateUser("sharecodeowner"); + var recipient = await CreateUser("sharecoderecip"); + var shockerId = await CreateShocker(WebApplicationFactory, owner.Id, "Coded"); + var shareCodeId = await CreateShareCode(shockerId, new ShockerShareCode + { + Id = Guid.CreateVersion7(), + ShockerId = shockerId, + AllowShock = false, + AllowVibrate = true, + AllowSound = false, + AllowLiveControl = true, + MaxIntensity = 40, + MaxDuration = 2000, + IsPaused = true + }); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, recipient.SessionToken); + var response = await client.PostAsync($"/1/shares/code/{shareCodeId}", null); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var share = await db.UserShares.AsNoTracking().SingleAsync(x => x.ShockerId == shockerId); + await Assert.That(share.SharedWithUserId).IsEqualTo(recipient.Id); + await Assert.That(share.AllowShock).IsFalse(); + await Assert.That(share.AllowVibrate).IsTrue(); + await Assert.That(share.AllowSound).IsFalse(); + await Assert.That(share.AllowLiveControl).IsTrue(); + await Assert.That(share.MaxIntensity).IsEqualTo((byte)40); + await Assert.That(share.MaxDuration).IsEqualTo((ushort)2000); + await Assert.That(share.IsPaused).IsTrue(); + await Assert.That(await db.ShockerShareCodes.AnyAsync(x => x.Id == shareCodeId)).IsFalse(); + } + + [Test] + public async Task LinkShareCode_OwnCode_Returns400() + { + var owner = await CreateUser("sharecodeself"); + var shockerId = await CreateShocker(WebApplicationFactory, owner.Id, "Mine"); + var shareCodeId = await CreateShareCode(shockerId, null); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + var response = await client.PostAsync($"/1/shares/code/{shareCodeId}", null); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.UserShares.AnyAsync(x => x.ShockerId == shockerId)).IsFalse(); + await Assert.That(await db.ShockerShareCodes.AnyAsync(x => x.Id == shareCodeId)).IsTrue(); + } + + [Test] + public async Task LinkShareCode_ShockerAtShareLimit_Returns409() + { + var owner = await CreateUser("sharecapowner"); + var recipient = await CreateUser("sharecaprecip"); + var shockerId = await CreateShocker(WebApplicationFactory, owner.Id, "Popular"); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var users = Enumerable.Range(0, ApiHardLimits.MaxUserSharesPerShocker).Select(_ => + { + var name = UniqueNames.Username("sharecapfill"); + return new User { Id = Guid.CreateVersion7(), Name = name, Email = $"{name}@test.org", PasswordHash = "x" }; + }).ToArray(); + db.Users.AddRange(users); + db.UserShares.AddRange(users.Select(u => new UserShare + { + SharedWithUserId = u.Id, + ShockerId = shockerId, + AllowShock = true, + AllowVibrate = true, + AllowSound = true, + AllowLiveControl = true, + IsPaused = false + })); + await db.SaveChangesAsync(); + } + + var shareCodeId = await CreateShareCode(shockerId, null); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, recipient.SessionToken); + var response = await client.PostAsync($"/1/shares/code/{shareCodeId}", null); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + } + + private Task CreateUser(string prefix) => + TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), Password); + + private async Task CreateShareCode(Guid shockerId, ShockerShareCode? code) + { + code ??= new ShockerShareCode + { + Id = Guid.CreateVersion7(), + ShockerId = shockerId, + AllowShock = true, + AllowVibrate = true, + AllowSound = true, + AllowLiveControl = true, + IsPaused = false + }; + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.ShockerShareCodes.Add(code); + await db.SaveChangesAsync(); + return code.Id; + } +} diff --git a/API.IntegrationTests/Tests/ShareLimitTests.cs b/API.IntegrationTests/Tests/ShareLimitTests.cs deleted file mode 100644 index 76d0179b..00000000 --- a/API.IntegrationTests/Tests/ShareLimitTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Net; -using Microsoft.Extensions.DependencyInjection; -using OpenShock.API.IntegrationTests.Helpers; -using OpenShock.Common.Constants; -using OpenShock.Common.OpenShockDb; -using static OpenShock.API.IntegrationTests.Helpers.ControlLogHelper; - -namespace OpenShock.API.IntegrationTests.Tests; - -public sealed class ShareLimitTests -{ - private const string Password = "SecurePassword123#"; - - [ClassDataSource(Shared = SharedType.PerTestSession)] - public required WebApplicationFactory WebApplicationFactory { get; init; } - - [Test] - public async Task LinkShareCode_ShockerAtShareLimit_Returns409() - { - var owner = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("sharecapowner"), - TestHelper.UniqueEmail("sharecapowner"), Password); - var recipient = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("sharecaprecip"), - TestHelper.UniqueEmail("sharecaprecip"), Password); - var shockerId = await CreateShocker(WebApplicationFactory, owner.Id, "Popular"); - var shareCodeId = Guid.CreateVersion7(); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - var db = scope.ServiceProvider.GetRequiredService(); - var users = Enumerable.Range(0, ApiHardLimits.MaxUserSharesPerShocker).Select(_ => - { - var name = TestHelper.UniqueUsername("sharecapfill"); - return new User { Id = Guid.CreateVersion7(), Name = name, Email = $"{name}@test.org", PasswordHash = "x" }; - }).ToArray(); - db.Users.AddRange(users); - db.UserShares.AddRange(users.Select(u => new UserShare - { - SharedWithUserId = u.Id, - ShockerId = shockerId, - AllowShock = true, - AllowVibrate = true, - AllowSound = true, - AllowLiveControl = true, - IsPaused = false - })); - db.ShockerShareCodes.Add(new ShockerShareCode - { - Id = shareCodeId, - ShockerId = shockerId, - AllowShock = true, - AllowVibrate = true, - AllowSound = true, - AllowLiveControl = true, - IsPaused = false - }); - await db.SaveChangesAsync(); - } - - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, recipient.SessionToken); - var response = await client.PostAsync($"/1/shares/code/{shareCodeId}", null); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); - } -} diff --git a/API.IntegrationTests/Tests/ShareLinksTests.cs b/API.IntegrationTests/Tests/ShareLinksTests.cs index b0d326b5..fc97e105 100644 --- a/API.IntegrationTests/Tests/ShareLinksTests.cs +++ b/API.IntegrationTests/Tests/ShareLinksTests.cs @@ -1,181 +1,62 @@ using System.Net; using System.Text.Json; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; using OpenShock.Common.Constants; using OpenShock.Common.OpenShockDb; +using OpenShock.IntegrationTests.Shared; +using static OpenShock.API.IntegrationTests.Helpers.ControlLogHelper; namespace OpenShock.API.IntegrationTests.Tests; public sealed class ShareLinksTests { + private const string Password = "SecurePassword123#"; + [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } - // --- List share links --- - - [Test] - public async Task ListShareLinks_Empty_ReturnsEmptyArray() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "sharelinklist", "sharelinklist@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.GetAsync("/1/shares/links"); - 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); - } - - // --- Create share link --- - - [Test] - public async Task CreateShareLink_Success() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "sharelinkcreat", "sharelinkcreat@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.PostAsync("/1/shares/links", TestHelper.JsonContent(new - { - name = "My Public Share" - })); - - 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(Guid.TryParse(data.GetString(), out _)).IsTrue(); - } - - [Test] - public async Task CreateShareLink_ThenListContainsIt() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "sharelinkcrls", "sharelinkcrls@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - await client.PostAsync("/1/shares/links", TestHelper.JsonContent(new - { - name = "Test Share" - })); - - var response = await client.GetAsync("/1/shares/links"); - var json = await response.Content.ReadAsStringAsync(); - using var doc = JsonDocument.Parse(json); - var data = doc.RootElement.GetProperty("data"); - await Assert.That(data.GetArrayLength()).IsGreaterThanOrEqualTo(1); - } - - // --- Delete share link --- - [Test] - public async Task DeleteShareLink_Success() + public async Task DeleteShareLink_OtherUser_Returns404() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "sharelinkdel", "sharelinkdel@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var createResp = await client.PostAsync("/1/shares/links", TestHelper.JsonContent(new - { - name = "To Delete" - })); - var createJson = await createResp.Content.ReadAsStringAsync(); - using var createDoc = JsonDocument.Parse(createJson); - var shareId = createDoc.RootElement.GetProperty("data").GetString(); - - var response = await client.DeleteAsync($"/1/shares/links/{shareId}"); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - } + var user1 = await CreateUser("sharelinkown"); + var user2 = await CreateUser("sharelinkoth"); - [Test] - public async Task DeleteShareLink_NotFound() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "sharelinkdnf", "sharelinkdnf@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + using var client1 = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user1.SessionToken); + using var client2 = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user2.SessionToken); + var shareId = await CreateShare(client1, "User1's Share"); - var response = await client.DeleteAsync($"/1/shares/links/{Guid.CreateVersion7()}"); + var response = await client2.DeleteAsync($"/1/shares/links/{shareId}"); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); - } - - // --- Add shocker to share link --- - - [Test] - public async Task AddShockerToShareLink_Success() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "sharelinkshock", "sharelinkshock@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - // Create device and shocker via DB helpers - var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id, "ShareDevice"); - - var shockerResp = await client.PostAsync("/1/shockers", TestHelper.JsonContent(new - { - name = "ShareShocker", - rfId = 12345, - model = 0, - device = deviceId - })); - await Assert.That(shockerResp.StatusCode).IsEqualTo(HttpStatusCode.Created); - var shockerJson = await shockerResp.Content.ReadAsStringAsync(); - using var shockerDoc = JsonDocument.Parse(shockerJson); - var shockerId = shockerDoc.RootElement.GetProperty("data").GetString(); - - // Create public share - var createResp = await client.PostAsync("/1/shares/links", TestHelper.JsonContent(new - { - name = "Share With Shocker" - })); - await Assert.That(createResp.StatusCode).IsEqualTo(HttpStatusCode.OK); - var createJson = await createResp.Content.ReadAsStringAsync(); - using var createDoc = JsonDocument.Parse(createJson); - var shareId = createDoc.RootElement.GetProperty("data").GetString(); - - // Add shocker to share - var response = await client.PostAsync($"/1/shares/links/{shareId}/{shockerId}", null); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.PublicShares.AnyAsync(x => x.Id == shareId)).IsTrue(); } - // --- Unauthenticated access --- - [Test] - public async Task ListShareLinks_Unauthenticated_Returns401() + public async Task AddShocker_OtherUsersShocker_Returns404() { - using var client = WebApplicationFactory.CreateClient(); + var owner = await CreateUser("sharelinkaddown"); + var victim = await CreateUser("sharelinkaddvic"); + var victimShockerId = await CreateShocker(WebApplicationFactory, victim.Id, "Not yours"); - var response = await client.GetAsync("/1/shares/links"); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); - } + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); + var shareId = await CreateShare(client, "Grab"); - // --- Cross-user isolation --- - - [Test] - public async Task DeleteShareLink_OtherUser_Returns404() - { - var user1 = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "sharelinkown", "sharelinkown@test.org", "SecurePassword123#"); - var user2 = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "sharelinkoth", "sharelinkoth@test.org", "SecurePassword123#"); - - using var client1 = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user1.SessionToken); - using var client2 = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user2.SessionToken); - - var createResp = await client1.PostAsync("/1/shares/links", TestHelper.JsonContent(new - { - name = "User1's Share" - })); - var createJson = await createResp.Content.ReadAsStringAsync(); - using var createDoc = JsonDocument.Parse(createJson); - var shareId = createDoc.RootElement.GetProperty("data").GetString(); - - // User2 tries to delete user1's share - var response = await client2.DeleteAsync($"/1/shares/links/{shareId}"); + var response = await client.PostAsync($"/1/shares/links/{shareId}/{victimShockerId}", null); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.PublicShareShockerMappings.AnyAsync(x => x.PublicShareId == shareId)).IsFalse(); } [Test] public async Task CreateShareLink_AtLimit_Returns409_ExpiredSharesDoNotCount() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("sharelinkcap"), - TestHelper.UniqueEmail("sharelinkcap"), "SecurePassword123#"); + var user = await CreateUser("sharelinkcap"); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) @@ -196,4 +77,15 @@ public async Task CreateShareLink_AtLimit_Returns409_ExpiredSharesDoNotCount() var overLimit = await client.PostAsync("/1/shares/links", TestHelper.JsonContent(new { name = "Too many" })); await Assert.That(overLimit.StatusCode).IsEqualTo(HttpStatusCode.Conflict); } + + private Task CreateUser(string prefix) => + TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), Password); + + private static async Task CreateShare(HttpClient client, string name) + { + var response = await client.PostAsync("/1/shares/links", TestHelper.JsonContent(new { name })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + return doc.RootElement.GetProperty("data").GetGuid(); + } } diff --git a/API.IntegrationTests/Tests/ShockerPermissionsTests.cs b/API.IntegrationTests/Tests/ShockerPermissionsTests.cs index a70718f1..edcd72f3 100644 --- a/API.IntegrationTests/Tests/ShockerPermissionsTests.cs +++ b/API.IntegrationTests/Tests/ShockerPermissionsTests.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; @@ -16,17 +17,22 @@ public sealed class ShockerPermissionsTests public required WebApplicationFactory WebApplicationFactory { get; init; } [Test] - public async Task SetLimits_ShowsUpOnShocker() + public async Task SetPermissionsAndLimits_ShowUpOnShocker_AndLimitsCanBeCleared() { var user = await CreateUser("limset"); var shockerId = await CreateShocker(WebApplicationFactory, user.Id, "Limited"); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - var response = await SetLimits(client, shockerId, 40, 2000); + var response = await SetPermissions(client, shockerId, shock: false, live: false, intensity: 40, duration: 2000); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); using var doc = JsonDocument.Parse(await client.GetStringAsync($"/1/shockers/{shockerId}")); - var limits = doc.RootElement.GetProperty("data").GetProperty("limits"); + var data = doc.RootElement.GetProperty("data"); + var permissions = data.GetProperty("permissions"); + await Assert.That(permissions.GetProperty("shock").GetBoolean()).IsFalse(); + await Assert.That(permissions.GetProperty("vibrate").GetBoolean()).IsTrue(); + await Assert.That(permissions.GetProperty("live").GetBoolean()).IsFalse(); + var limits = data.GetProperty("limits"); await Assert.That(limits.GetProperty("intensity").GetInt32()).IsEqualTo(40); await Assert.That(limits.GetProperty("duration").GetInt32()).IsEqualTo(2000); @@ -34,22 +40,13 @@ public async Task SetLimits_ShowsUpOnShocker() await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); using var cleared = JsonDocument.Parse(await client.GetStringAsync($"/1/shockers/{shockerId}")); - var clearedLimits = cleared.RootElement.GetProperty("data").GetProperty("limits"); + var clearedData = cleared.RootElement.GetProperty("data"); + await Assert.That(clearedData.GetProperty("permissions").GetProperty("shock").GetBoolean()).IsTrue(); + var clearedLimits = clearedData.GetProperty("limits"); await Assert.That(clearedLimits.GetProperty("intensity").ValueKind).IsEqualTo(JsonValueKind.Null); await Assert.That(clearedLimits.GetProperty("duration").ValueKind).IsEqualTo(JsonValueKind.Null); } - [Test] - public async Task SetLimits_OutOfRange_Returns400() - { - var user = await CreateUser("limrange"); - var shockerId = await CreateShocker(WebApplicationFactory, user.Id, "Limited"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - await Assert.That((await SetLimits(client, shockerId, 101, null)).StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - await Assert.That((await SetLimits(client, shockerId, null, 100)).StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - } - [Test] public async Task SetLimits_NotOwner_Returns404() { @@ -120,39 +117,25 @@ public async Task SharedControl_UsesTighterOfShockerAndShareLimits() await Assert.That(limits.GetProperty("duration").GetInt32()).IsEqualTo(1000); } - [Test] - public async Task SetPermissions_ShowsUpOnShocker() - { - var user = await CreateUser("permset"); - var shockerId = await CreateShocker(WebApplicationFactory, user.Id, "Restricted"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await SetPermissions(client, shockerId, shock: false, live: false); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - - using var doc = JsonDocument.Parse(await client.GetStringAsync($"/1/shockers/{shockerId}")); - var permissions = doc.RootElement.GetProperty("data").GetProperty("permissions"); - await Assert.That(permissions.GetProperty("shock").GetBoolean()).IsFalse(); - await Assert.That(permissions.GetProperty("vibrate").GetBoolean()).IsTrue(); - await Assert.That(permissions.GetProperty("live").GetBoolean()).IsFalse(); - } - [Test] public async Task OwnerControl_DisallowedType_IsRejected() { var user = await CreateUser("permctl"); var shockerId = await CreateShocker(WebApplicationFactory, user.Id, "Restricted"); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - await SetPermissions(client, shockerId, shock: false, live: true); + var set = await SetPermissions(client, shockerId, shock: false, live: true); + await Assert.That(set.StatusCode).IsEqualTo(HttpStatusCode.OK); var response = await Control(client, shockerId, 50, 1000); - await Assert.That(response.StatusCode).IsNotEqualTo(HttpStatusCode.OK); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await LogCount(shockerId)).IsEqualTo(0); var vibrate = await client.PostAsync("/2/shockers/control", TestHelper.JsonContent(new { shocks = new[] { new { id = shockerId, type = "Vibrate", intensity = 50, duration = 1000 } } })); await Assert.That(vibrate.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await LogCount(shockerId)).IsEqualTo(1); } [Test] @@ -179,7 +162,8 @@ public async Task SharedShocker_ShowsPermissionsAllowedByBoth() } using var ownerClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); - await SetPermissions(ownerClient, shockerId, shock: false, live: true); + var set = await SetPermissions(ownerClient, shockerId, shock: false, live: true); + await Assert.That(set.StatusCode).IsEqualTo(HttpStatusCode.OK); using var recipientClient = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, recipient.SessionToken); using var doc = JsonDocument.Parse(await recipientClient.GetStringAsync("/1/shockers/shared")); @@ -190,11 +174,12 @@ public async Task SharedShocker_ShowsPermissionsAllowedByBoth() await Assert.That(permissions.GetProperty("live").GetBoolean()).IsTrue(); var response = await Control(recipientClient, shockerId, 50, 1000); - await Assert.That(response.StatusCode).IsNotEqualTo(HttpStatusCode.OK); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await LogCount(shockerId)).IsEqualTo(0); } private Task CreateUser(string prefix) => - TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername(prefix), TestHelper.UniqueEmail(prefix), Password); + TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), Password); private static Task SetLimits(HttpClient client, Guid shockerId, int? intensity, int? duration) => SetPermissions(client, shockerId, shock: true, live: true, intensity, duration); @@ -213,6 +198,13 @@ private static Task Control(HttpClient client, Guid shocker shocks = new[] { new { id = shockerId, type = "Shock", intensity, duration } } })); + private async Task LogCount(Guid shockerId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.ShockerControlLogs.CountAsync(x => x.ShockerId == shockerId); + } + private async Task LastLog(Guid shockerId) { await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); diff --git a/API.IntegrationTests/Tests/ShockersTests.cs b/API.IntegrationTests/Tests/ShockersTests.cs index c0385c05..54bf4ebb 100644 --- a/API.IntegrationTests/Tests/ShockersTests.cs +++ b/API.IntegrationTests/Tests/ShockersTests.cs @@ -1,22 +1,24 @@ 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 ShockersTests { + private const string Password = "SecurePassword123#"; + [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } - // --- Register Shocker --- - [Test] - public async Task RegisterShocker_Success_Returns201() + public async Task RegisterShocker_ThenGetById_ReturnsIt() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "shkreg", "shkreg@test.org", "SecurePassword123#"); + var user = await CreateUser("shkreg"); var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id, "ShkHub"); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); @@ -27,72 +29,23 @@ public async Task RegisterShocker_Success_Returns201() device = deviceId, model = "CaiXianlin" })); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Created); + using var created = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + var shockerId = created.RootElement.GetProperty("data").GetGuid(); - var json = await response.Content.ReadAsStringAsync(); - using var doc = JsonDocument.Parse(json); - var data = doc.RootElement.GetProperty("data"); - // Should return a GUID - await Assert.That(Guid.TryParse(data.GetString(), out _)).IsTrue(); - } - - [Test] - public async Task RegisterShocker_NonexistentDevice_Returns404() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "shkregbad", "shkregbad@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.PostAsync("/1/shockers", TestHelper.JsonContent(new - { - name = "Ghost", - rfId = 9999, - device = Guid.CreateVersion7(), - model = "CaiXianlin" - })); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); - } - - // --- Get Shocker by ID --- - - [Test] - public async Task GetShockerById_Success() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "shkget", "shkget@test.org", "SecurePassword123#"); - var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id); - var shockerId = await CreateShockerInDb(user.Id, deviceId, "MyShocker", 100); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.GetAsync($"/1/shockers/{shockerId}"); - - 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 client.GetStringAsync($"/1/shockers/{shockerId}")); var data = doc.RootElement.GetProperty("data"); - await Assert.That(data.GetProperty("name").GetString()).IsEqualTo("MyShocker"); - } - - [Test] - public async Task GetShockerById_Nonexistent_Returns404() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "shkget404", "shkget404@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.GetAsync($"/1/shockers/{Guid.CreateVersion7()}"); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); + await Assert.That(data.GetProperty("name").GetString()).IsEqualTo("TestShocker"); + await Assert.That(data.GetProperty("rfId").GetInt32()).IsEqualTo(1234); + await Assert.That(data.GetProperty("device").GetGuid()).IsEqualTo(deviceId); } - // --- Edit Shocker --- - [Test] public async Task EditShocker_Rename_Success() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "shkedit", "shkedit@test.org", "SecurePassword123#"); + var user = await CreateUser("shkedit"); var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id); - var shockerId = await CreateShockerInDb(user.Id, deviceId, "OldShockerName", 200); + var shockerId = await CreateShockerInDb(deviceId, "OldShockerName", 200); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); var response = await client.PatchAsync($"/1/shockers/{shockerId}", TestHelper.JsonContent(new @@ -102,132 +55,128 @@ public async Task EditShocker_Rename_Success() device = deviceId, model = "CaiXianlin" })); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - // Verify the name changed - var getResponse = await client.GetAsync($"/1/shockers/{shockerId}"); - 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("RenamedShocker"); + var shocker = await GetShockerFromDb(shockerId); + await Assert.That(shocker!.Name).IsEqualTo("RenamedShocker"); } [Test] - public async Task EditShocker_Nonexistent_Returns404() + public async Task PauseShocker_PausesAndUnpauses() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "shkedit404", "shkedit404@test.org", "SecurePassword123#"); + var user = await CreateUser("shkpause"); var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id); + var shockerId = await CreateShockerInDb(deviceId, "PauseShocker", 300); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - var response = await client.PatchAsync($"/1/shockers/{Guid.CreateVersion7()}", TestHelper.JsonContent(new - { - name = "Whatever", - rfId = 100, - device = deviceId, - model = "CaiXianlin" - })); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); - } - - // --- Pause / Unpause --- - - [Test] - public async Task PauseShocker_Success() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "shkpause", "shkpause@test.org", "SecurePassword123#"); - var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id); - var shockerId = await CreateShockerInDb(user.Id, deviceId, "PauseShocker", 300); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - // Pause - var pauseResponse = await client.PostAsync($"/1/shockers/{shockerId}/pause", TestHelper.JsonContent(new - { - pause = true - })); + var pauseResponse = await client.PostAsync($"/1/shockers/{shockerId}/pause", TestHelper.JsonContent(new { pause = true })); await Assert.That(pauseResponse.StatusCode).IsEqualTo(HttpStatusCode.OK); + using (var doc = JsonDocument.Parse(await client.GetStringAsync($"/1/shockers/{shockerId}"))) + await Assert.That(doc.RootElement.GetProperty("data").GetProperty("isPaused").GetBoolean()).IsTrue(); - // Verify paused - var getResponse = await client.GetAsync($"/1/shockers/{shockerId}"); - var json = await getResponse.Content.ReadAsStringAsync(); - using var doc = JsonDocument.Parse(json); - var isPaused = doc.RootElement.GetProperty("data").GetProperty("isPaused").GetBoolean(); - await Assert.That(isPaused).IsTrue(); - - // Unpause - var unpauseResponse = await client.PostAsync($"/1/shockers/{shockerId}/pause", TestHelper.JsonContent(new - { - pause = false - })); + var unpauseResponse = await client.PostAsync($"/1/shockers/{shockerId}/pause", TestHelper.JsonContent(new { pause = false })); await Assert.That(unpauseResponse.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That((await GetShockerFromDb(shockerId))!.IsPaused).IsFalse(); } - [Test] - public async Task PauseShocker_Nonexistent_Returns404() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "shkpause404", "shkpause404@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.PostAsync($"/1/shockers/{Guid.CreateVersion7()}/pause", TestHelper.JsonContent(new - { - pause = true - })); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); - } - - // --- Delete Shocker --- - [Test] public async Task DeleteShocker_Success() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "shkdel", "shkdel@test.org", "SecurePassword123#"); + var user = await CreateUser("shkdel"); var (deviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id); - var shockerId = await CreateShockerInDb(user.Id, deviceId, "ToDelete", 400); + var shockerId = await CreateShockerInDb(deviceId, "ToDelete", 400); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); var response = await client.DeleteAsync($"/1/shockers/{shockerId}"); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - // Verify it no longer exists var getResponse = await client.GetAsync($"/1/shockers/{shockerId}"); await Assert.That(getResponse.StatusCode).IsEqualTo(HttpStatusCode.NotFound); } + // --- Another user's shocker or hub --- + [Test] - public async Task DeleteShocker_Nonexistent_Returns404() + [Arguments("get")] + [Arguments("edit")] + [Arguments("pause")] + [Arguments("delete")] + public async Task OtherUsersShocker_Returns404_AndIsUnchanged(string operation) { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "shkdel404", "shkdel404@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var owner = await CreateUser("shkxown"); + var attacker = await CreateUser("shkxatk"); + var (ownerDeviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, owner.Id); + var (attackerDeviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, attacker.Id); + var shockerId = await CreateShockerInDb(ownerDeviceId, "Victim", 500); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, attacker.SessionToken); + + var response = operation switch + { + "get" => await client.GetAsync($"/1/shockers/{shockerId}"), + // The target hub is the attacker's own, so only the shocker ownership check can reject this + "edit" => await client.PatchAsync($"/1/shockers/{shockerId}", TestHelper.JsonContent(new + { + name = "Stolen", rfId = 500, device = attackerDeviceId, model = "CaiXianlin" + })), + "pause" => await client.PostAsync($"/1/shockers/{shockerId}/pause", TestHelper.JsonContent(new { pause = true })), + "delete" => await client.DeleteAsync($"/1/shockers/{shockerId}"), + _ => throw new ArgumentOutOfRangeException(nameof(operation)) + }; + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); + + var shocker = await GetShockerFromDb(shockerId); + await Assert.That(shocker).IsNotNull(); + await Assert.That(shocker!.Name).IsEqualTo("Victim"); + await Assert.That(shocker.DeviceId).IsEqualTo(ownerDeviceId); + await Assert.That(shocker.IsPaused).IsFalse(); + } - var response = await client.DeleteAsync($"/1/shockers/{Guid.CreateVersion7()}"); + [Test] + public async Task RegisterShocker_OnOtherUsersDevice_Returns404() + { + var owner = await CreateUser("shkregxown"); + var attacker = await CreateUser("shkregxatk"); + var (ownerDeviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, owner.Id); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, attacker.SessionToken); + var response = await client.PostAsync("/1/shockers", TestHelper.JsonContent(new + { + name = "Planted", rfId = 9999, device = ownerDeviceId, model = "CaiXianlin" + })); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); - } - // --- Unauthorized --- + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.Shockers.AnyAsync(x => x.DeviceId == ownerDeviceId)).IsFalse(); + } [Test] - public async Task RegisterShocker_Unauthenticated_Returns401() + public async Task EditShocker_MovingOwnShockerOntoOtherUsersDevice_Returns404() { - using var client = WebApplicationFactory.CreateClient(); + var owner = await CreateUser("shkmovown"); + var other = await CreateUser("shkmovoth"); + var (ownDeviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, owner.Id); + var (otherDeviceId, _) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, other.Id); + var shockerId = await CreateShockerInDb(ownDeviceId, "Mine", 600); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); - var response = await client.PostAsync("/1/shockers", TestHelper.JsonContent(new + var response = await client.PatchAsync($"/1/shockers/{shockerId}", TestHelper.JsonContent(new { - name = "Test", - rfId = 1, - device = Guid.CreateVersion7(), - model = "CaiXianlin" + name = "Moved", rfId = 600, device = otherDeviceId, model = "CaiXianlin" })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + var shocker = await GetShockerFromDb(shockerId); + await Assert.That(shocker!.DeviceId).IsEqualTo(ownDeviceId); + await Assert.That(shocker.Name).IsEqualTo("Mine"); } - // --- Helper --- + // --- Helpers --- + + private Task CreateUser(string prefix) => + TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), Password); - private async Task CreateShockerInDb(Guid userId, Guid deviceId, string name, ushort rfId) + private async Task CreateShockerInDb(Guid deviceId, string name, ushort rfId) { await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); @@ -244,4 +193,11 @@ private async Task CreateShockerInDb(Guid userId, Guid deviceId, string na await db.SaveChangesAsync(); return shockerId; } + + private async Task GetShockerFromDb(Guid shockerId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Shockers.AsNoTracking().FirstOrDefaultAsync(x => x.Id == shockerId); + } } diff --git a/API.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index c1dfabbe..5290f7a2 100644 --- a/API.IntegrationTests/Tests/SignalRUserHubTests.cs +++ b/API.IntegrationTests/Tests/SignalRUserHubTests.cs @@ -1,7 +1,6 @@ using System.Net; using System.Text.Json; using Microsoft.AspNetCore.Http.Connections; -using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.SignalR.Client; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; @@ -13,7 +12,7 @@ using OpenShock.Common.Models.WebSocket.User; using OpenShock.Common.OpenShockDb; using OpenShock.Common.Redis; -using OpenShock.Common.Services.Session; +using OpenShock.IntegrationTests.Shared; using StackExchange.Redis; namespace OpenShock.API.IntegrationTests.Tests; @@ -23,28 +22,7 @@ public sealed class SignalRUserHubTests [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } - // --- Negotiate endpoint tests (HTTP-based, works with TestServer) --- - - [Test] - public async Task Negotiate_WithValidSession_ReturnsOk() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "hubneg", "hubneg@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.PostAsync("/1/hubs/user/negotiate?negotiateVersion=1", null); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - } - - [Test] - public async Task Negotiate_WithApiToken_ReturnsOk() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "hubnegapi", "hubnegapi@test.org", "SecurePassword123#"); - var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-negotiate-token"); - using var client = TestHelper.CreateApiTokenClient(WebApplicationFactory, rawToken); - - var response = await client.PostAsync("/1/hubs/user/negotiate?negotiateVersion=1", null); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - } + // --- Negotiate: credentials the user hub does not accept --- [Test] public async Task Negotiate_WithoutAuth_Returns401() @@ -55,25 +33,11 @@ public async Task Negotiate_WithoutAuth_Returns401() await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); } - [Test] - public async Task Negotiate_WithInvalidSession_Returns401() - { - using var client = WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions - { - AllowAutoRedirect = false, - HandleCookies = false - }); - client.DefaultRequestHeaders.Add("Cookie", $"{AuthConstants.UserSessionCookieName}=invalid-session-token"); - - var response = await client.PostAsync("/1/hubs/user/negotiate?negotiateVersion=1", null); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); - } - [Test] public async Task Negotiate_WithHubToken_Returns401() { // Hub/device tokens should NOT work on user hub - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "hubneghub", "hubneghub@test.org", "SecurePassword123#"); + var user = await CreateUser("hubneghub"); var (_, hubToken) = await TestHelper.CreateDeviceInDb(WebApplicationFactory, user.Id, "NegTestDevice"); using var client = TestHelper.CreateHubTokenClient(WebApplicationFactory, hubToken); @@ -81,51 +45,19 @@ public async Task Negotiate_WithHubToken_Returns401() await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); } - // --- Negotiate response content --- - - [Test] - public async Task Negotiate_ReturnsTransportInfo() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "hubneginfo", "hubneginfo@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.PostAsync("/1/hubs/user/negotiate?negotiateVersion=1", null); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - - var json = await response.Content.ReadAsStringAsync(); - using var doc = JsonDocument.Parse(json); - // Negotiate response should contain connectionId and available transports - await Assert.That(doc.RootElement.TryGetProperty("connectionId", out _)).IsTrue(); - await Assert.That(doc.RootElement.TryGetProperty("availableTransports", out _)).IsTrue(); - } - - // --- Public share hub --- - - [Test] - public async Task PublicShareHub_Negotiate_WithoutAuth_ReturnsOk() - { - // PublicShareHub doesn't require auth at the negotiate level - using var client = WebApplicationFactory.CreateClient(); - - var response = await client.PostAsync($"/1/hubs/share/link/{Guid.CreateVersion7()}/negotiate?negotiateVersion=1", null); - // Should return OK (negotiate doesn't check auth or share existence) - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - } - // --- A revocation closes the open connections it concerns right away, without them calling anything --- [Test] public async Task Logout_ClosesTheSessionsOpenConnection() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkicklogout"), TestHelper.UniqueEmail("hubkicklogout"), "SecurePassword123#"); - var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkickother"), TestHelper.UniqueEmail("hubkickother"), "SecurePassword123#"); + var user = await CreateUser("hubkicklogout"); + var other = await CreateUser("hubkickother"); await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); await using var otherConnection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={other.SessionToken}"); - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - await scope.ServiceProvider.GetRequiredService().DeleteSessionByTokenAsync(user.SessionToken); - } + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var logout = await client.PostAsync("/1/account/logout", null); + await Assert.That(logout.StatusCode).IsEqualTo(HttpStatusCode.OK); await AssertConnectionClosesAsync(connection); @@ -137,7 +69,7 @@ public async Task Logout_ClosesTheSessionsOpenConnection() [Test] public async Task DeletingAnApiToken_ClosesItsOpenConnection() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkicktoken"), TestHelper.UniqueEmail("hubkicktoken"), "SecurePassword123#"); + var user = await CreateUser("hubkicktoken"); var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-kick-deleted"); var (_, otherRawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-kick-kept"); await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); @@ -156,7 +88,7 @@ public async Task DeletingAnApiToken_ClosesItsOpenConnection() [Test] public async Task DeactivatingAnAccount_ClosesItsSessionAndApiTokenConnections() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkickdeact"), TestHelper.UniqueEmail("hubkickdeact"), "SecurePassword123#"); + var user = await CreateUser("hubkickdeact"); var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-kick-deactivated"); await using var sessionConnection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); await using var tokenConnection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); @@ -174,13 +106,12 @@ public async Task DeactivatingAnAccount_ClosesItsSessionAndApiTokenConnections() [Test] public async Task SessionExpiring_ClosesItsOpenConnection() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkickexpire"), TestHelper.UniqueEmail("hubkickexpire"), "SecurePassword123#"); + var user = await CreateUser("hubkickexpire"); await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); // Let the session reach the end of its lifetime in Redis, as an unused one does. var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase(); - var key = $"{typeof(LoginSession).FullName}:{HubConnectionTracker.GetSessionId(user.SessionToken)}"; - await Assert.That(await redis.KeyExpireAsync(key, TimeSpan.FromMilliseconds(100))).IsTrue(); + await Assert.That(await redis.KeyExpireAsync(SessionKey(user.SessionToken), TimeSpan.FromMilliseconds(100))).IsTrue(); await AssertConnectionClosesAsync(connection); } @@ -188,8 +119,8 @@ public async Task SessionExpiring_ClosesItsOpenConnection() [Test] public async Task DeletingAnAccount_ClosesItsSessionAndApiTokenConnections() { - var admin = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkickadmin"), TestHelper.UniqueEmail("hubkickadmin"), "SecurePassword123#"); - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkickdelete"), TestHelper.UniqueEmail("hubkickdelete"), "SecurePassword123#"); + var admin = await CreateUser("hubkickadmin"); + var user = await CreateUser("hubkickdelete"); var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-kick-deleted-account"); await using var sessionConnection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); await using var tokenConnection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); @@ -212,7 +143,7 @@ public async Task DeletingAnAccount_ClosesItsSessionAndApiTokenConnections() [Test] public async Task PausingAnApiToken_ClosesItsConnection() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubtokenedit"), TestHelper.UniqueEmail("hubtokenedit"), "SecurePassword123#"); + var user = await CreateUser("hubtokenedit"); var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-token-edited"); await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); @@ -228,7 +159,7 @@ public async Task PausingAnApiToken_ClosesItsConnection() [Test] public async Task PublicShareHub_Guest_CanConnectAndKeepCalling() { - var owner = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubguestowner"), TestHelper.UniqueEmail("hubguestowner"), "SecurePassword123#"); + var owner = await CreateUser("hubguestowner"); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, owner.SessionToken); var created = await client.PostAsync("/1/shares/links", TestHelper.JsonContent(new { name = "guest hub" })); await Assert.That(created.IsSuccessStatusCode).IsTrue(); @@ -247,28 +178,14 @@ public async Task PublicShareHub_Guest_CanConnectAndKeepCalling() // --- The fallback: a connection whose revocation was never announced stops at its next periodic check --- [Test] - public async Task Invoke_WithValidSession_KeepsWorking() + public async Task Invoke_AfterSessionRemovedWithoutAnnouncement_FailsAndClosesConnection() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevalok"), TestHelper.UniqueEmail("hubrevalok"), "SecurePassword123#"); - await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); + var user = await CreateUser("hubrevalsess"); + await using var connection = await ConnectCheckedSessionAsync(user); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); - } - - [Test] - public async Task Invoke_AfterSessionDeleted_FailsAndClosesConnection() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevalsess"), TestHelper.UniqueEmail("hubrevalsess"), "SecurePassword123#"); - await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - await scope.ServiceProvider.GetRequiredService().DeleteSessionsByUserIdAsync(user.Id); - } + // Removed straight from Redis: no revocation message, and a deleted key raises no expiry event. + var redis = WebApplicationFactory.Services.GetRequiredService().GetDatabase(); + await Assert.That(await redis.KeyDeleteAsync(SessionKey(user.SessionToken))).IsTrue(); await AssertInvokeFailsAndConnectionClosesAsync(connection); } @@ -277,9 +194,8 @@ public async Task Invoke_AfterSessionDeleted_FailsAndClosesConnection() public async Task Invoke_AfterAccountDeactivated_WithTheSessionLeftBehind_FailsAndClosesConnection() { // Deactivation removes sessions after its database commit; if that step fails the session survives. - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaldeact"), TestHelper.UniqueEmail("hubrevaldeact"), "SecurePassword123#"); - await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + var user = await CreateUser("hubrevaldeact"); + await using var connection = await ConnectCheckedSessionAsync(user); await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) { @@ -296,93 +212,74 @@ public async Task Invoke_AfterAccountDeactivated_WithTheSessionLeftBehind_FailsA await AssertInvokeFailsAndConnectionClosesAsync(connection); } - [Test] - public async Task Invoke_WithValidApiToken_KeepsWorking() + public enum UnannouncedTokenChange { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokok"), TestHelper.UniqueEmail("hubrevaltokok"), "SecurePassword123#"); - var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-ok"); - await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); - - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + Deleted, + Paused, + Expired, + OwnerDeactivated } [Test] - public async Task Invoke_AfterApiTokenDeleted_FailsAndClosesConnection() + [Arguments(UnannouncedTokenChange.Deleted)] + [Arguments(UnannouncedTokenChange.Paused)] + [Arguments(UnannouncedTokenChange.Expired)] + [Arguments(UnannouncedTokenChange.OwnerDeactivated)] + public async Task Invoke_AfterApiTokenChangedWithoutAnnouncement_FailsAndClosesConnection(UnannouncedTokenChange change) { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokdel"), TestHelper.UniqueEmail("hubrevaltokdel"), "SecurePassword123#"); - var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-deleted"); + var user = await CreateUser("hubrevaltok"); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate"); await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + // Written straight to the database, so no revocation message is published. await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) { var db = scope.ServiceProvider.GetRequiredService(); - await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteDeleteAsync(); + var tokens = db.ApiTokens.Where(t => t.Id == tokenId); + switch (change) + { + case UnannouncedTokenChange.Deleted: + await tokens.ExecuteDeleteAsync(); + break; + case UnannouncedTokenChange.Paused: + await tokens.ExecuteUpdateAsync(s => s.SetProperty(t => t.ShockerControlPaused, true)); + break; + case UnannouncedTokenChange.Expired: + var expired = DateTime.UtcNow.AddMinutes(-1); + await tokens.ExecuteUpdateAsync(s => s.SetProperty(t => t.ValidUntil, expired)); + break; + case UnannouncedTokenChange.OwnerDeactivated: + db.UserDeactivations.Add(new UserDeactivation + { + DeactivatedUserId = user.Id, + DeactivatedByUserId = user.Id, + DeleteLater = false + }); + await db.SaveChangesAsync(); + break; + default: + throw new ArgumentOutOfRangeException(nameof(change), change, null); + } } await AssertInvokeFailsAndConnectionClosesAsync(connection); } - [Test] - public async Task Invoke_AfterApiTokenPausedWithoutAnnouncement_FailsAndClosesConnection() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokpause"), TestHelper.UniqueEmail("hubrevaltokpause"), "SecurePassword123#"); - var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-paused"); - await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - var db = scope.ServiceProvider.GetRequiredService(); - await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteUpdateAsync(s => s.SetProperty(t => t.ShockerControlPaused, true)); - } - - await AssertInvokeFailsAndConnectionClosesAsync(connection); - } + private Task CreateUser(string prefix) => + TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), "SecurePassword123#"); - [Test] - public async Task Invoke_AfterApiTokenExpired_FailsAndClosesConnection() + /// Opens a session connection and makes one call on it, so it has been checked once. + private async Task ConnectCheckedSessionAsync(AuthenticatedUser user) { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokexp"), TestHelper.UniqueEmail("hubrevaltokexp"), "SecurePassword123#"); - var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-expired"); - await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - var db = scope.ServiceProvider.GetRequiredService(); - var expired = DateTime.UtcNow.AddMinutes(-1); - await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteUpdateAsync(s => s.SetProperty(t => t.ValidUntil, expired)); - } - - await AssertInvokeFailsAndConnectionClosesAsync(connection); + return connection; } - [Test] - public async Task Invoke_AfterApiTokenOwnerDeactivated_FailsAndClosesConnection() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokdeact"), TestHelper.UniqueEmail("hubrevaltokdeact"), "SecurePassword123#"); - var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-deactivated"); - await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - var db = scope.ServiceProvider.GetRequiredService(); - db.UserDeactivations.Add(new UserDeactivation - { - DeactivatedUserId = user.Id, - DeactivatedByUserId = user.Id, - DeleteLater = false - }); - await db.SaveChangesAsync(); - } - - await AssertInvokeFailsAndConnectionClosesAsync(connection); - } + /// The Redis key a session is stored under. + private static string SessionKey(string sessionToken) => + $"{typeof(LoginSession).FullName}:{HubConnectionTracker.GetSessionId(sessionToken)}"; /// /// Opens a real hub connection against the in-process test server. The hub only allows WebSockets, which @@ -419,6 +316,9 @@ private static async Task AssertInvokeFailsAndConnectionClosesAsync(HubConnectio // revocation only reaches it on the first call after that. await Task.Delay(WebApplicationFactory.HubRevalidationInterval + TimeSpan.FromMilliseconds(500)); + // Still open here, so it is the periodic check below that ends it, not a revocation message. + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + // The server answers with an error and aborts; which of the two the client sees first is a race. Exception? failure = null; try diff --git a/API.IntegrationTests/Tests/SignupActivationTests.cs b/API.IntegrationTests/Tests/SignupActivationTests.cs index ab18d9c7..0f2f12d5 100644 --- a/API.IntegrationTests/Tests/SignupActivationTests.cs +++ b/API.IntegrationTests/Tests/SignupActivationTests.cs @@ -7,7 +7,7 @@ using OpenShock.API.Services.Signup; using OpenShock.Common.Constants; using OpenShock.Common.OpenShockDb; -using OpenShock.Common.Utils; +using OpenShock.IntegrationTests.Shared; using static OpenShock.API.IntegrationTests.Helpers.PendingSignupHelper; namespace OpenShock.API.IntegrationTests.Tests; @@ -31,13 +31,20 @@ public sealed class SignupActivationTests [Test] public async Task Signup_CreatesNoAccount_AndEnqueuesTheActivationCode() { - var email = TestHelper.UniqueEmail("signup-pending"); - var username = TestHelper.UniqueUsername("signuppending"); + var email = UniqueNames.Email("signup-pending"); + var username = UniqueNames.Username("signuppending"); using var client = CreateClient(); var response = await PostSignupAsync(client, email, username); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + // __Host- prefix, no Domain, HttpOnly: a sibling subdomain cannot plant one in someone else's browser. + var cookie = response.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith(AuthConstants.SignupBrowserSecureCookieName + "=")); + await Assert.That(cookie.Contains("httponly", StringComparison.OrdinalIgnoreCase)).IsTrue(); + await Assert.That(cookie.Contains("secure", StringComparison.OrdinalIgnoreCase)).IsTrue(); + await Assert.That(cookie.Contains("path=/", StringComparison.OrdinalIgnoreCase)).IsTrue(); + await Assert.That(cookie.Contains("domain=", StringComparison.OrdinalIgnoreCase)).IsFalse(); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); var pending = (await FindByEmailAsync(WebApplicationFactory, email)).Single(); @@ -56,43 +63,33 @@ public async Task Signup_CreatesNoAccount_AndEnqueuesTheActivationCode() } [Test] - public async Task Signup_SetsTheSignupBrowserCookie_BoundToTheApiHost() + public async Task Signup_InvalidTurnstile_Returns403_AndStartsNoSignup() { + var email = UniqueNames.Email("signup-turnstile"); using var client = CreateClient(); - var response = await PostSignupAsync(client, TestHelper.UniqueEmail("signup-browsercookie"), TestHelper.UniqueUsername("signupbrowsercookie")); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - // __Host- prefix, no Domain, HttpOnly: a sibling subdomain cannot plant one in someone else's browser. - var cookie = response.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith(AuthConstants.SignupBrowserSecureCookieName + "=")); - await Assert.That(cookie.Contains("httponly", StringComparison.OrdinalIgnoreCase)).IsTrue(); - await Assert.That(cookie.Contains("secure", StringComparison.OrdinalIgnoreCase)).IsTrue(); - await Assert.That(cookie.Contains("path=/", StringComparison.OrdinalIgnoreCase)).IsTrue(); - await Assert.That(cookie.Contains("domain=", StringComparison.OrdinalIgnoreCase)).IsFalse(); - } - - // A pending signup does not reserve its address: someone who signs up with an address that is not - // theirs does not keep its owner (or anyone else) from signing up with it. - [Test] - public async Task Signup_AddressOfAPendingSignup_IsAccepted() - { - var email = TestHelper.UniqueEmail("signup-twice"); - using var client = CreateClient(); - - await Assert.That((await PostSignupAsync(client, email, TestHelper.UniqueUsername("signuptwicea"))).StatusCode).IsEqualTo(HttpStatusCode.OK); - await Assert.That((await PostSignupAsync(client, email, TestHelper.UniqueUsername("signuptwiceb"), "AnotherPassword123#")).StatusCode).IsEqualTo(HttpStatusCode.OK); + var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new + { + username = UniqueNames.Username("signupturnstile"), + password = Password, + email, + turnstileResponse = "invalid-token" + })); - await Assert.That((await FindByEmailAsync(WebApplicationFactory, email)).Count).IsEqualTo(2); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Turnstile.Invalid"); + await Assert.That(await FindByEmailAsync(WebApplicationFactory, email)).IsEmpty(); } // The username is different: whoever is entering their code keeps the name while they do. [Test] public async Task Signup_UsernameOfAPendingSignupStartedWithinTheHour_Returns409() { - var username = TestHelper.UniqueUsername("signupreserved"); - var email = TestHelper.UniqueEmail("signup-reserved-second"); + var username = UniqueNames.Username("signupreserved"); + var email = UniqueNames.Email("signup-reserved-second"); using var client = CreateClient(); - await Assert.That((await PostSignupAsync(client, TestHelper.UniqueEmail("signup-reserved-first"), username)).StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That((await PostSignupAsync(client, UniqueNames.Email("signup-reserved-first"), username)).StatusCode).IsEqualTo(HttpStatusCode.OK); var response = await PostSignupAsync(client, email, username); @@ -101,17 +98,36 @@ public async Task Signup_UsernameOfAPendingSignupStartedWithinTheHour_Returns409 await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); } + // A name is taken by an account, and for an hour by a pending signup that was started with it. [Test] - public async Task CheckUsername_UsernameOfAPendingSignupStartedWithinTheHour_IsTaken() + [Arguments("nobody", "Available")] + [Arguments("account", "Taken")] + [Arguments("pending-signup", "Taken")] + [Arguments("pending-signup-older-than-the-hour", "Available")] + public async Task CheckUsername_ReportsWhetherTheNameIsTaken(string heldBy, string expected) { - var username = TestHelper.UniqueUsername("checkreserved"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("check-reserved"), username); + var username = UniqueNames.Username("checkname"); + switch (heldBy) + { + case "account": + await TestHelper.CreateUserInDb(WebApplicationFactory, username, UniqueNames.Email("check-account"), Password); + break; + case "pending-signup": + await CreateInDbAsync(WebApplicationFactory, UniqueNames.Email("check-pending"), username); + break; + case "pending-signup-older-than-the-hour": + var pendingId = await CreateInDbAsync(WebApplicationFactory, UniqueNames.Email("check-pending-old"), username); + await BackdateSignupAsync(pendingId, Duration.PendingSignupUsernameReservation + TimeSpan.FromMinutes(1)); + break; + } using var client = CreateClient(); - await Assert.That(await CheckUsernameAsync(client, username)).IsEqualTo("Taken"); + var response = await client.PostAsync("/1/account/username/check", TestHelper.JsonContent(new { username })); - await BackdateSignupAsync(pendingId, Duration.PendingSignupUsernameReservation + TimeSpan.FromMinutes(1)); - await Assert.That(await CheckUsernameAsync(client, username)).IsEqualTo("Available"); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + await Assert.That(body.RootElement.GetProperty("availability").GetString()).IsEqualTo(expected); + await Assert.That(body.RootElement.GetProperty("error").ValueKind).IsEqualTo(JsonValueKind.Null); } // After the hour the name is open again, though the older signup can still be completed: the first of @@ -119,9 +135,9 @@ public async Task CheckUsername_UsernameOfAPendingSignupStartedWithinTheHour_IsT [Test] public async Task Signup_UsernameOfAPendingSignupOlderThanTheHour_IsAccepted_AndTheFirstToActivateGetsIt() { - var username = TestHelper.UniqueUsername("signupreleased"); - var olderEmail = TestHelper.UniqueEmail("signup-released-older"); - var newerEmail = TestHelper.UniqueEmail("signup-released-newer"); + var username = UniqueNames.Username("signupreleased"); + var olderEmail = UniqueNames.Email("signup-released-older"); + var newerEmail = UniqueNames.Email("signup-released-newer"); var older = await CreateInDbAsync(WebApplicationFactory, olderEmail, username); await BackdateSignupAsync(older, Duration.PendingSignupUsernameReservation + TimeSpan.FromMinutes(1)); @@ -145,9 +161,9 @@ public async Task Signup_UsernameOfAPendingSignupOlderThanTheHour_IsAccepted_And [Test] public async Task ChangeUsername_ToTheUsernameOfAPendingSignupStartedWithinTheHour_Returns409() { - var username = TestHelper.UniqueUsername("renamereserved"); - await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("rename-reserved"), username); - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("renamereserveduser"), TestHelper.UniqueEmail("rename-reserved-user"), Password); + var username = UniqueNames.Username("renamereserved"); + await CreateInDbAsync(WebApplicationFactory, UniqueNames.Email("rename-reserved"), username); + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("renamereserveduser"), UniqueNames.Email("rename-reserved-user"), Password); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); var response = await client.PostAsync("/1/account/username", TestHelper.JsonContent(new { username })); @@ -158,11 +174,11 @@ public async Task ChangeUsername_ToTheUsernameOfAPendingSignupStartedWithinTheHo [Test] public async Task Signup_EmailOfAnAccount_Returns409() { - var email = TestHelper.UniqueEmail("signup-taken-email"); - await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("signuptakenemail"), email, Password); + var email = UniqueNames.Email("signup-taken-email"); + await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("signuptakenemail"), email, Password); using var client = CreateClient(); - var response = await PostSignupAsync(client, email, TestHelper.UniqueUsername("signuptakenemail")); + var response = await PostSignupAsync(client, email, UniqueNames.Username("signuptakenemail")); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); await Assert.That(await FindByEmailAsync(WebApplicationFactory, email)).IsEmpty(); @@ -172,9 +188,9 @@ public async Task Signup_EmailOfAnAccount_Returns409() [Test] public async Task Signup_UsernameOfAnAccount_Returns409() { - var username = TestHelper.UniqueUsername("signuptakenname"); - await TestHelper.CreateUserInDb(WebApplicationFactory, username, TestHelper.UniqueEmail("signup-taken-name"), Password); - var email = TestHelper.UniqueEmail("signup-taken-name-new"); + var username = UniqueNames.Username("signuptakenname"); + await TestHelper.CreateUserInDb(WebApplicationFactory, username, UniqueNames.Email("signup-taken-name"), Password); + var email = UniqueNames.Email("signup-taken-name-new"); using var client = CreateClient(); var response = await PostSignupAsync(client, email, username); @@ -189,20 +205,21 @@ public async Task Signup_UsernameOfAnAccount_Returns409() [Test] public async Task Signup_AddressAlreadySentTheDailyCapOfActivationEmails_Returns429_AndMailsNothing() { - var email = TestHelper.UniqueEmail("signup-address-cap"); + var email = UniqueNames.Email("signup-address-cap"); using var client = CreateClient(); - for (var i = 0; i < 5; i++) + for (var i = 0; i < SignupConstants.MaxActivationEmailsPerWindow; i++) { - var response = await PostSignupAsync(client, email, TestHelper.UniqueUsername("signupaddresscap")); + var response = await PostSignupAsync(client, email, UniqueNames.Username("signupaddresscap")); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); } - var sixth = await PostSignupAsync(client, email, TestHelper.UniqueUsername("signupaddresscap")); + var sixth = await PostSignupAsync(client, email, UniqueNames.Username("signupaddresscap")); await Assert.That(sixth.StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); await Assert.That(await sixth.Content.ReadAsStringAsync()).Contains("Account.Activation.ResendTooMany"); - await Assert.That(await CountOutboxAsync(email)).IsEqualTo(5); - await Assert.That((await FindByEmailAsync(WebApplicationFactory, email)).Count).IsEqualTo(5); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(SignupConstants.MaxActivationEmailsPerWindow); + // A pending signup does not reserve its address: every one of them was accepted. + await Assert.That((await FindByEmailAsync(WebApplicationFactory, email)).Count).IsEqualTo(SignupConstants.MaxActivationEmailsPerWindow); } // The count behind the cap is only good while nobody else queues mail for the address, so counting and @@ -211,7 +228,7 @@ public async Task Signup_AddressAlreadySentTheDailyCapOfActivationEmails_Returns [Test] public async Task Signup_WhileAnotherRequestQueuesActivationMailForTheAddress_Returns429_AndMailsNothing() { - var email = TestHelper.UniqueEmail("signup-address-lock"); + var email = UniqueNames.Email("signup-address-lock"); using var client = CreateClient(); @@ -222,12 +239,12 @@ public async Task Signup_WhileAnotherRequestQueuesActivationMailForTheAddress_Re await using var transaction = await db.Database.BeginTransactionAsync(); await Assert.That(await db.Database.TryLockForTransactionAsync(SignupService.ActivationEmailLockName(email))).IsTrue(); - var blocked = await PostSignupAsync(client, email, TestHelper.UniqueUsername("signupaddresslock")); + var blocked = await PostSignupAsync(client, email, UniqueNames.Username("signupaddresslock")); await Assert.That(blocked.StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); } - var afterwards = await PostSignupAsync(client, email, TestHelper.UniqueUsername("signupaddresslock")); + var afterwards = await PostSignupAsync(client, email, UniqueNames.Username("signupaddresslock")); await Assert.That(afterwards.StatusCode).IsEqualTo(HttpStatusCode.OK); await Assert.That(await CountOutboxAsync(email)).IsEqualTo(1); } @@ -237,8 +254,8 @@ public async Task Signup_WhileAnotherRequestQueuesActivationMailForTheAddress_Re [Test] public async Task Activate_CodeFromTheMail_InTheSignupBrowser_CreatesTheAccount() { - var email = TestHelper.UniqueEmail("activate-ok"); - var username = TestHelper.UniqueUsername("activateok"); + var email = UniqueNames.Email("activate-ok"); + var username = UniqueNames.Username("activateok"); using var client = CreateClient(); var signup = await PostSignupAsync(client, email, username); @@ -269,8 +286,8 @@ public async Task Activate_CodeFromTheMail_InTheSignupBrowser_CreatesTheAccount( [Test] public async Task Activate_CodeWithoutTheSignupCookie_Returns400_AndCreatesNoAccount() { - var email = TestHelper.UniqueEmail("activate-nocookie"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatenocookie")); + var email = UniqueNames.Email("activate-nocookie"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("activatenocookie")); var code = await MailCodeAsync(WebApplicationFactory, pendingId); using var client = CreateClient(); @@ -288,9 +305,9 @@ public async Task Activate_CodeWithoutTheSignupCookie_Returns400_AndCreatesNoAcc [Test] public async Task Activate_CodeOfAnotherSignupForTheSameAddress_Returns400() { - var email = TestHelper.UniqueEmail("activate-othersignup"); - var theirs = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateothers"), "TheirPassword123#"); - var mine = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatemine")); + var email = UniqueNames.Email("activate-othersignup"); + var theirs = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("activateothers"), "TheirPassword123#"); + var mine = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("activatemine")); await MailCodeAsync(WebApplicationFactory, theirs); var myCode = await MailCodeAsync(WebApplicationFactory, mine); @@ -306,8 +323,8 @@ public async Task Activate_CodeOfAnotherSignupForTheSameAddress_Returns400() public async Task Activate_SignupBrowserCookieWithoutHostPrefix_Returns400() { // The unprefixed name is the one a sibling subdomain could set. - var email = TestHelper.UniqueEmail("activate-noprefix"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatenoprefix")); + var email = UniqueNames.Email("activate-noprefix"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("activatenoprefix")); var code = await MailCodeAsync(WebApplicationFactory, pendingId); var value = MintSignupBrowserCookie(WebApplicationFactory, pendingId)[(AuthConstants.SignupBrowserSecureCookieName.Length + 1)..]; @@ -321,8 +338,8 @@ public async Task Activate_SignupBrowserCookieWithoutHostPrefix_Returns400() [Test] public async Task Activate_WrongCode_Returns400_WithTheAttemptsLeft() { - var email = TestHelper.UniqueEmail("activate-wrong"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatewrong")); + var email = UniqueNames.Email("activate-wrong"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("activatewrong")); var code = await MailCodeAsync(WebApplicationFactory, pendingId, "RGHT-0001"); var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); @@ -342,8 +359,8 @@ public async Task Activate_WrongCode_Returns400_WithTheAttemptsLeft() [Test] public async Task Activate_AfterTooManyWrongCodes_EvenTheRightOneIsRefused_UntilANewOneIsMailed() { - var email = TestHelper.UniqueEmail("activate-attempts"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateattempts")); + var email = UniqueNames.Email("activate-attempts"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("activateattempts")); var code = await MailCodeAsync(WebApplicationFactory, pendingId, "RGHT-0001"); var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); @@ -367,8 +384,8 @@ public async Task Activate_AfterTooManyWrongCodes_EvenTheRightOneIsRefused_Until [Test] public async Task Activate_CodeOlderThanItsLifetime_Returns400() { - var email = TestHelper.UniqueEmail("activate-oldcode"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateoldcode")); + var email = UniqueNames.Email("activate-oldcode"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("activateoldcode")); var code = await MailCodeAsync(WebApplicationFactory, pendingId); await BackdateCodeAsync(pendingId, Duration.ActivationCodeLifetime + TimeSpan.FromMinutes(1)); @@ -384,8 +401,8 @@ public async Task Activate_CodeOlderThanItsLifetime_Returns400() public async Task Activate_BeforeAnyCodeWasMailed_Returns400() { // The row is created with a throwaway hash; nothing may match it. - var email = TestHelper.UniqueEmail("activate-nocode"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatenocode")); + var email = UniqueNames.Email("activate-nocode"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("activatenocode")); using var client = CreateClient(); var response = await PostActivateAsync(client, "AAAA-0000", MintSignupBrowserCookie(WebApplicationFactory, pendingId)); @@ -397,8 +414,8 @@ public async Task Activate_BeforeAnyCodeWasMailed_Returns400() [Test] public async Task Activate_SignupOlderThanItsLifetime_Returns400_AndRemovesTheCookies() { - var email = TestHelper.UniqueEmail("activate-oldsignup"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateoldsignup")); + var email = UniqueNames.Email("activate-oldsignup"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("activateoldsignup")); var code = await MailCodeAsync(WebApplicationFactory, pendingId); await BackdateSignupAsync(pendingId, Duration.PendingSignupLifetime + TimeSpan.FromMinutes(1)); @@ -414,18 +431,13 @@ public async Task Activate_SignupOlderThanItsLifetime_Returns400_AndRemovesTheCo // The code is read off a mail and typed in, often on another device: neither the case it is typed in // nor a left out dash should make it wrong. [Test] - [Arguments(true, true)] - [Arguments(true, false)] - [Arguments(false, true)] - public async Task Activate_CodeTypedInLowercaseOrWithoutTheDash_IsAccepted(bool lowercase, bool withoutDash) + public async Task Activate_CodeTypedInLowercaseAndWithoutTheDash_IsAccepted() { - var email = TestHelper.UniqueEmail("activate-typed"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatetyped")); + var email = UniqueNames.Email("activate-typed"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("activatetyped")); var code = await MailCodeAsync(WebApplicationFactory, pendingId); - var typed = code; - if (lowercase) typed = typed.ToLowerInvariant(); - if (withoutDash) typed = typed.Replace("-", ""); + var typed = code.ToLowerInvariant().Replace("-", ""); using var client = CreateClient(); var response = await PostActivateAsync(client, typed, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); @@ -435,39 +447,25 @@ public async Task Activate_CodeTypedInLowercaseOrWithoutTheDash_IsAccepted(bool } [Test] - [Arguments("12")] - [Arguments("ABCD_1234")] - [Arguments("ABC-D1234")] - [Arguments("ABCD-12345")] - [Arguments("ABCD-12!4")] - public async Task Activate_NotACode_Returns400_WithoutCountingAsAGuess(string notACode) + public async Task Activate_NotACode_Returns400_WithoutCountingAsAGuess() { - var pendingId = await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("activate-notacode"), TestHelper.UniqueUsername("activatenotacode")); + var pendingId = await CreateInDbAsync(WebApplicationFactory, UniqueNames.Email("activate-notacode"), UniqueNames.Username("activatenotacode")); await MailCodeAsync(WebApplicationFactory, pendingId); using var client = CreateClient(); - var response = await PostActivateAsync(client, notACode, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + var response = await PostActivateAsync(client, "ABCD_1234", MintSignupBrowserCookie(WebApplicationFactory, pendingId)); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); await Assert.That((await FindAsync(WebApplicationFactory, pendingId))!.FailedAttempts).IsEqualTo(0); } - [Test] - public async Task MailedCode_IsTwoGroupsOfFourUppercaseLettersOrDigits() - { - for (var i = 0; i < 50; i++) - { - await Assert.That(SignupCode.Generate()).Matches("^[A-Z0-9]{4}-[A-Z0-9]{4}$"); - } - } - // Whoever enters their code first gets the address. The others can no longer be completed. [Test] public async Task Activate_TwoSignupsForOneAddress_TheFirstToEnterItsCodeGetsIt() { - var email = TestHelper.UniqueEmail("activate-race"); - var first = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateracea"), "FirstPassword123#"); - var second = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateraceb"), "SecondPassword123#"); + var email = UniqueNames.Email("activate-race"); + var first = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("activateracea"), "FirstPassword123#"); + var second = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("activateraceb"), "SecondPassword123#"); await MailCodeAsync(WebApplicationFactory, first); var secondCode = await MailCodeAsync(WebApplicationFactory, second); @@ -487,36 +485,25 @@ public async Task Activate_TwoSignupsForOneAddress_TheFirstToEnterItsCodeGetsIt( // Nothing about such a signup can be completed any more, so it does not linger: it is deleted and the // browser stops holding it, instead of being shown a code form that can only ever answer 409. [Test] - public async Task Activate_AddressTakenByAnAccountWhileTheSignupWasPending_Returns409_AndDeletesTheSignup() + [Arguments(true)] + [Arguments(false)] + public async Task Activate_AddressOrUsernameTakenByAnAccountWhileTheSignupWasPending_Returns409_AndDeletesTheSignup(bool addressTaken) { - var email = TestHelper.UniqueEmail("activate-taken"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatetaken")); - var code = await MailCodeAsync(WebApplicationFactory, pendingId); - var existingUserId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("activatetakenby"), email, "TheirPassword123#"); - - using var client = CreateClient(); - var response = await PostActivateAsync(client, code, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); - await Assert.That((await FindUserByEmailAsync(WebApplicationFactory, email))!.Id).IsEqualTo(existingUserId); - await Assert.That(await FindAsync(WebApplicationFactory, pendingId)).IsNull(); - await Assert.That(DeletesCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsTrue(); - } - - [Test] - public async Task Activate_UsernameTakenByAnAccountWhileTheSignupWasPending_Returns409_AndDeletesTheSignup() - { - var email = TestHelper.UniqueEmail("activate-nametaken"); - var username = TestHelper.UniqueUsername("activatenametaken"); + var email = UniqueNames.Email("activate-taken"); + var username = UniqueNames.Username("activatetaken"); var pendingId = await CreateInDbAsync(WebApplicationFactory, email, username); var code = await MailCodeAsync(WebApplicationFactory, pendingId); - await TestHelper.CreateUserInDb(WebApplicationFactory, username, TestHelper.UniqueEmail("activate-nametaken-by"), "TheirPassword123#"); + var existingUserId = addressTaken + ? await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("activatetakenby"), email, "TheirPassword123#") + : await TestHelper.CreateUserInDb(WebApplicationFactory, username, UniqueNames.Email("activate-taken-by"), "TheirPassword123#"); using var client = CreateClient(); var response = await PostActivateAsync(client, code, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); - await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + var holder = await FindUserByEmailAsync(WebApplicationFactory, email); + if (addressTaken) await Assert.That(holder!.Id).IsEqualTo(existingUserId); + else await Assert.That(holder).IsNull(); await Assert.That(await FindAsync(WebApplicationFactory, pendingId)).IsNull(); await Assert.That(DeletesCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsTrue(); } @@ -524,8 +511,8 @@ public async Task Activate_UsernameTakenByAnAccountWhileTheSignupWasPending_Retu [Test] public async Task Activate_Twice_SecondReturns400() { - var email = TestHelper.UniqueEmail("activate-twice"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatetwice")); + var email = UniqueNames.Email("activate-twice"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("activatetwice")); var code = await MailCodeAsync(WebApplicationFactory, pendingId); var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); @@ -543,8 +530,8 @@ public async Task Activate_Twice_SecondReturns400() [Test] public async Task GetPendingActivation_BrowserHoldingASignup_ReturnsWhereTheCodeWent_AndWhenItCanBeResent() { - var email = TestHelper.UniqueEmail("pending-status"); - var username = TestHelper.UniqueUsername("pendingstatus"); + var email = UniqueNames.Email("pending-status"); + var username = UniqueNames.Username("pendingstatus"); using var client = CreateClient(); var signup = await PostSignupAsync(client, email, username); var cookie = ReadSetCookie(signup, AuthConstants.SignupBrowserSecureCookieName); @@ -555,49 +542,69 @@ public async Task GetPendingActivation_BrowserHoldingASignup_ReturnsWhereTheCode using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); await Assert.That(body.RootElement.GetProperty("email").GetString()).IsEqualTo(email); await Assert.That(body.RootElement.GetProperty("username").GetString()).IsEqualTo(username); - // The signup mail was just queued: four left today, and the cooldown is running. - await Assert.That(body.RootElement.GetProperty("resendsRemaining").GetInt32()).IsEqualTo(4); + // The signup mail was just queued: one fewer left today, and the cooldown is running. + await Assert.That(body.RootElement.GetProperty("resendsRemaining").GetInt32()).IsEqualTo(SignupConstants.MaxActivationEmailsPerWindow - 1); await Assert.That(body.RootElement.GetProperty("resendAvailableAt").GetDateTime().ToUniversalTime()).IsGreaterThan(DateTime.UtcNow); - // What it says is what a resend does. - await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); await BackdateOutboxAsync(email, Duration.ActivationResendCooldown + TimeSpan.FromMinutes(1)); using var later = JsonDocument.Parse(await (await GetPendingActivationAsync(client, cookie)).Content.ReadAsStringAsync()); await Assert.That(later.RootElement.GetProperty("resendAvailableAt").GetDateTime().ToUniversalTime()).IsLessThanOrEqualTo(DateTime.UtcNow); - await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); } + // The cap of an address counts across signups, so a second signup can neither get it mailed past the cap + // nor be told it can. [Test] - public async Task GetPendingActivation_AddressAtItsDailyCapThroughOtherSignups_HasNoResendsLeft() + public async Task AddressAtItsDailyCapThroughOtherSignups_HasNoResendsLeft_AndResendReturns429() { - var email = TestHelper.UniqueEmail("pending-status-cap"); - using var client = CreateClient(); - for (var i = 0; i < 5; i++) + var email = UniqueNames.Email("address-cap"); + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) { - await PostSignupAsync(client, email, TestHelper.UniqueUsername("pendingstatuscap")); + var db = scope.ServiceProvider.GetRequiredService(); + for (var i = 0; i < SignupConstants.MaxActivationEmailsPerWindow; i++) + { + db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(Guid.CreateVersion7(), email, null)); + } + await db.SaveChangesAsync(); } - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("pendingstatuscap")); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("addresscap")); + var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); - var response = await GetPendingActivationAsync(client, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + using var client = CreateClient(); + var status = await GetPendingActivationAsync(client, cookie); + await Assert.That(status.StatusCode).IsEqualTo(HttpStatusCode.OK); + using (var body = JsonDocument.Parse(await status.Content.ReadAsStringAsync())) + { + await Assert.That(body.RootElement.GetProperty("resendsRemaining").GetInt32()).IsEqualTo(0); + } - using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); - await Assert.That(body.RootElement.GetProperty("resendsRemaining").GetInt32()).IsEqualTo(0); + var resend = await PostResendAsync(client, cookie); + await Assert.That(resend.StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(SignupConstants.MaxActivationEmailsPerWindow); } [Test] - public async Task GetPendingActivation_NoCookie_Returns400() + [Arguments("status", false)] + [Arguments("status", true)] + [Arguments("resend", false)] + [Arguments("resend", true)] + public async Task NoUsableSignupCookie_Returns400(string endpoint, bool tampered) { + var cookie = tampered ? $"{AuthConstants.SignupBrowserSecureCookieName}=not-a-valid-token" : null; + using var client = CreateClient(); - var response = await GetPendingActivationAsync(client, cookie: null); + var response = endpoint == "status" + ? await GetPendingActivationAsync(client, cookie) + : await PostResendAsync(client, cookie); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.Activation.NotFound"); + await Assert.That(await response.Content.ReadAsStringAsync()) + .Contains(endpoint == "status" ? "Account.Activation.NotFound" : "Account.Activation.ResendUnavailable"); } [Test] public async Task GetPendingActivation_SignupAlreadyCompleted_Returns400_AndRemovesCookie() { - var pendingId = await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("pending-status-done"), TestHelper.UniqueUsername("pendingstatusdone")); + var pendingId = await CreateInDbAsync(WebApplicationFactory, UniqueNames.Email("pending-status-done"), UniqueNames.Username("pendingstatusdone")); var code = await MailCodeAsync(WebApplicationFactory, pendingId); var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); @@ -614,15 +621,14 @@ public async Task GetPendingActivation_SignupAlreadyCompleted_Returns400_AndRemo [Test] public async Task ResendActivation_WithSignupCookie_EnqueuesAnotherActivationCode() { - var email = TestHelper.UniqueEmail("resend-ok"); + var email = UniqueNames.Email("resend-ok"); using var client = CreateClient(); - var signup = await PostSignupAsync(client, email, TestHelper.UniqueUsername("resendok")); + var signup = await PostSignupAsync(client, email, UniqueNames.Username("resendok")); var cookie = ReadSetCookie(signup, AuthConstants.SignupBrowserSecureCookieName); var pending = (await FindByEmailAsync(WebApplicationFactory, email)).Single(); - // Move the signup email out of the resend cooldown. - await BackdateOutboxAsync(email, TimeSpan.FromMinutes(11)); + await BackdateOutboxAsync(email, Duration.ActivationResendCooldown + TimeSpan.FromMinutes(1)); // The delivery job mints a new code for the newer row and supersedes the older one at send time // (coalesce key); that rotation is covered in Cron.IntegrationTests. @@ -640,8 +646,8 @@ public async Task ResendActivation_WithSignupCookie_EnqueuesAnotherActivationCod [Test] public async Task ResendActivation_WithinCooldown_Returns429_AndEnqueuesNothing() { - var email = TestHelper.UniqueEmail("resend-cooldown"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("resendcooldown")); + var email = UniqueNames.Email("resend-cooldown"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("resendcooldown")); var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); using var client = CreateClient(); @@ -654,45 +660,27 @@ public async Task ResendActivation_WithinCooldown_Returns429_AndEnqueuesNothing( [Test] public async Task ResendActivation_DailyCapReached_Returns429() { - var email = TestHelper.UniqueEmail("resend-cap"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("resendcap")); + var email = UniqueNames.Email("resend-cap"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("resendcap")); var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); using var client = CreateClient(); - for (var i = 0; i < 5; i++) + for (var i = 0; i < SignupConstants.MaxActivationEmailsPerWindow; i++) { await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); - // Step past the cooldown each time; only the 24h cap of 5 should stop the sixth. - await BackdateOutboxAsync(email, TimeSpan.FromMinutes(11)); + // Step past the cooldown each time; only the daily cap should stop the last one. + await BackdateOutboxAsync(email, Duration.ActivationResendCooldown + TimeSpan.FromMinutes(1)); } await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); - await Assert.That(await CountOutboxAsync(email)).IsEqualTo(5); - } - - // The cap of an address counts across signups, so a second signup cannot get it mailed past the cap. - [Test] - public async Task ResendActivation_AddressAtItsDailyCapThroughOtherSignups_Returns429() - { - var email = TestHelper.UniqueEmail("resend-address-cap"); - using var client = CreateClient(); - for (var i = 0; i < 5; i++) - { - await Assert.That((await PostSignupAsync(client, email, TestHelper.UniqueUsername("resendaddresscap"))).StatusCode).IsEqualTo(HttpStatusCode.OK); - } - - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("resendaddresscap")); - var response = await PostResendAsync(client, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); - await Assert.That(await CountOutboxAsync(email)).IsEqualTo(5); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(SignupConstants.MaxActivationEmailsPerWindow); } [Test] public async Task ResendActivation_SignupAlreadyCompleted_Returns400_AndRemovesCookie() { - var email = TestHelper.UniqueEmail("resend-completed"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("resendcompleted")); + var email = UniqueNames.Email("resend-completed"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("resendcompleted")); var code = await MailCodeAsync(WebApplicationFactory, pendingId); using var client = CreateClient(); @@ -705,22 +693,6 @@ public async Task ResendActivation_SignupAlreadyCompleted_Returns400_AndRemovesC await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); } - [Test] - public async Task ResendActivation_NoCookie_Returns400() - { - using var client = CreateClient(); - var response = await PostResendAsync(client, cookie: null); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - } - - [Test] - public async Task ResendActivation_TamperedCookie_Returns400() - { - using var client = CreateClient(); - var response = await PostResendAsync(client, $"{AuthConstants.SignupBrowserSecureCookieName}=not-a-valid-token"); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - } - // --- Signing in with what a pending signup was started with --- // Whoever knows the password a signup carries is whoever started it. Signing in with it does not sign @@ -729,8 +701,8 @@ public async Task ResendActivation_TamperedCookie_Returns400() [Test] public async Task Login_PendingSignup_CorrectPassword_ReturnsNotActivated_HoldsTheSignup_AndMailsACode() { - var email = TestHelper.UniqueEmail("login-pending"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("loginpending")); + var email = UniqueNames.Email("login-pending"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("loginpending")); using var client = CreateClient(); var response = await PostLoginAsync(client, email, Password); @@ -756,8 +728,8 @@ public async Task Login_PendingSignup_CorrectPassword_ReturnsNotActivated_HoldsT [Test] public async Task Login_PendingSignup_ByUsername_HoldsTheSignup() { - var username = TestHelper.UniqueUsername("loginpendingname"); - await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("login-pending-name"), username); + var username = UniqueNames.Username("loginpendingname"); + await CreateInDbAsync(WebApplicationFactory, UniqueNames.Email("login-pending-name"), username); using var client = CreateClient(); var response = await PostLoginAsync(client, username, Password); @@ -769,8 +741,8 @@ public async Task Login_PendingSignup_ByUsername_HoldsTheSignup() [Test] public async Task Login_PendingSignup_WrongPassword_IsAnOrdinaryFailedSignIn() { - var email = TestHelper.UniqueEmail("login-pending-wrong"); - await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("loginpendingwrong")); + var email = UniqueNames.Email("login-pending-wrong"); + await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("loginpendingwrong")); using var client = CreateClient(); var response = await PostLoginAsync(client, email, "WrongPassword123#"); @@ -786,9 +758,9 @@ public async Task Login_PendingSignup_WrongPassword_IsAnOrdinaryFailedSignIn() [Test] public async Task Login_SeveralPendingSignupsForOneAddress_HoldsTheOneWithThatPassword() { - var email = TestHelper.UniqueEmail("login-pending-several"); - var mine = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("loginseveralmine"), "MyPassword123#"); - await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("loginseveralother"), "TheirPassword123#"); + var email = UniqueNames.Email("login-pending-several"); + var mine = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("loginseveralmine"), "MyPassword123#"); + await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("loginseveralother"), "TheirPassword123#"); using var client = CreateClient(); var response = await PostLoginAsync(client, email, "MyPassword123#"); @@ -804,9 +776,9 @@ public async Task Login_SeveralPendingSignupsForOneAddress_HoldsTheOneWithThatPa [Test] public async Task Login_AccountExists_PendingSignupWithTheSameAddress_IsIgnored() { - var email = TestHelper.UniqueEmail("login-account-wins"); - await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("loginaccountwins"), email, "AccountPassword123#"); - await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("loginaccountpending"), "PendingPassword123#"); + var email = UniqueNames.Email("login-account-wins"); + await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("loginaccountwins"), email, "AccountPassword123#"); + await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("loginaccountpending"), "PendingPassword123#"); using var client = CreateClient(); var response = await PostLoginAsync(client, email, "PendingPassword123#"); @@ -821,9 +793,9 @@ public async Task Login_AccountExists_PendingSignupWithTheSameAddress_IsIgnored( [Test] public async Task Login_Success_KeepsTheSignupCookie() { - var email = TestHelper.UniqueEmail("login-keeps"); - await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("loginkeeps"), email, Password); - var pendingId = await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("login-keeps-pending"), TestHelper.UniqueUsername("loginkeepspending")); + var email = UniqueNames.Email("login-keeps"); + await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("loginkeeps"), email, Password); + var pendingId = await CreateInDbAsync(WebApplicationFactory, UniqueNames.Email("login-keeps-pending"), UniqueNames.Username("loginkeepspending")); using var client = CreateClient(); var response = await PostLoginAsync(client, email, Password, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); @@ -837,9 +809,9 @@ public async Task Login_Success_KeepsTheSignupCookie() [Test] public async Task GetPendingActivation_WhileSignedInToAnotherAccount_KeepsTheSignupCookie_AndTheCodeStillWorks() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("signedinholder"), TestHelper.UniqueEmail("signed-in-holder"), Password); - var email = TestHelper.UniqueEmail("signed-in-pending"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("signedinpending")); + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("signedinholder"), UniqueNames.Email("signed-in-holder"), Password); + var email = UniqueNames.Email("signed-in-pending"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("signedinpending")); var code = await MailCodeAsync(WebApplicationFactory, pendingId); var cookies = $"{AuthConstants.UserSessionCookieName}={user.SessionToken}; {MintSignupBrowserCookie(WebApplicationFactory, pendingId)}"; @@ -856,28 +828,58 @@ public async Task GetPendingActivation_WhileSignedInToAnotherAccount_KeepsTheSig // --- Where the request comes from --- // CORS lets any website call the API with cookies. A page that is not the frontend must not be able to - // sign a visitor's browser in to a signup of its own making: that browser would then hold the signup, - // and its owner entering the mailed code would create an account with a stranger's password. - [Test] - public async Task Login_PendingSignup_FromAPageThatIsNotTheFrontend_Returns403_AndDoesNotHoldTheSignup() - { - var email = TestHelper.UniqueEmail("origin-foreign"); - await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("originforeign")); + // start a signup in a visitor's browser, sign it in to a signup of its own making (its owner entering the + // mailed code would then create an account with a stranger's password), read which address and username + // a held signup is for, or act on it. + [Test] + [Arguments("signup")] + [Arguments("login")] + [Arguments("status")] + [Arguments("activate")] + [Arguments("resend")] + public async Task FromAPageThatIsNotTheFrontend_Returns403_AndDoesNothing(string endpoint) + { + var email = UniqueNames.Email("origin-" + endpoint); + var username = UniqueNames.Username("origin" + endpoint); + Guid? pendingId = endpoint == "signup" ? null : await CreateInDbAsync(WebApplicationFactory, email, username); + var code = pendingId is { } mailedTo ? await MailCodeAsync(WebApplicationFactory, mailedTo) : null; + + using var request = endpoint switch + { + "signup" => new HttpRequestMessage(HttpMethod.Post, "/2/account/signup") + { + Content = TestHelper.JsonContent(new { username, password = Password, email, turnstileResponse = "valid-token" }) + }, + "login" => new HttpRequestMessage(HttpMethod.Post, "/2/account/login") + { + Content = TestHelper.JsonContent(new { usernameOrEmail = email, password = Password, turnstileResponse = "valid-token" }) + }, + "status" => new HttpRequestMessage(HttpMethod.Get, "/1/account/activate"), + "activate" => new HttpRequestMessage(HttpMethod.Post, "/1/account/activate") { Content = TestHelper.JsonContent(new { code }) }, + "resend" => new HttpRequestMessage(HttpMethod.Post, "/1/account/activate/resend"), + _ => throw new ArgumentOutOfRangeException(nameof(endpoint)) + }; + if (endpoint is "status" or "activate" or "resend") request.Headers.Add("Cookie", MintSignupBrowserCookie(WebApplicationFactory, pendingId!.Value)); + request.Headers.Add("Origin", "https://evil.openshock.app"); using var client = CreateClient(); - var response = await PostLoginAsync(client, email, Password, origin: "https://evil.openshock.app"); + var response = await client.SendAsync(request); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); - await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Authorization.Origin.NotTrusted"); + var body = await response.Content.ReadAsStringAsync(); + await Assert.That(body).Contains("Authorization.Origin.NotTrusted"); + await Assert.That(body).DoesNotContain(email); await Assert.That(SetsCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsFalse(); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + await Assert.That((await FindByEmailAsync(WebApplicationFactory, email)).Count).IsEqualTo(endpoint == "signup" ? 0 : 1); await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); } [Test] public async Task Login_PendingSignup_FromTheFrontend_HoldsTheSignup() { - var email = TestHelper.UniqueEmail("origin-frontend"); - await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("originfrontend")); + var email = UniqueNames.Email("origin-frontend"); + await CreateInDbAsync(WebApplicationFactory, email, UniqueNames.Username("originfrontend")); using var client = CreateClient(); var response = await PostLoginAsync(client, email, Password, origin: "https://openshock.app"); @@ -886,87 +888,6 @@ public async Task Login_PendingSignup_FromTheFrontend_HoldsTheSignup() await Assert.That(SetsCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsTrue(); } - [Test] - [Arguments("https://evil.openshock.app")] - [Arguments("http://openshock.app")] - [Arguments("https://openshock.app.evil.example")] - [Arguments("null")] - public async Task Signup_FromAPageThatIsNotTheFrontend_Returns403_AndStartsNoSignup(string origin) - { - var email = TestHelper.UniqueEmail("origin-signup"); - - using var client = CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Post, "/2/account/signup") - { - Content = TestHelper.JsonContent(new { username = TestHelper.UniqueUsername("originsignup"), password = Password, email, turnstileResponse = "valid-token" }) - }; - request.Headers.TryAddWithoutValidation("Origin", origin); - var response = await client.SendAsync(request); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); - await Assert.That((await FindByEmailAsync(WebApplicationFactory, email)).Count).IsEqualTo(0); - } - - // Reading is refused as well: the answer says which address and username the signup is for. - [Test] - public async Task GetPendingActivation_FromAPageThatIsNotTheFrontend_Returns403() - { - var email = TestHelper.UniqueEmail("origin-status"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("originstatus")); - - using var client = CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Get, "/1/account/activate"); - request.Headers.Add("Cookie", MintSignupBrowserCookie(WebApplicationFactory, pendingId)); - request.Headers.Add("Origin", "https://evil.openshock.app"); - var response = await client.SendAsync(request); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); - await Assert.That(await response.Content.ReadAsStringAsync()).DoesNotContain(email); - } - - // The database treats a name in another case, or with an accented letter written another way, as the - // same username. They have to be the same lock too, or two requests could each take "the" name at the - // same moment. - [Test] - [Arguments("caf\u00e9", "cafe\u0301")] - [Arguments("caf\u00e9", "CAF\u00c9")] - public async Task UsernameLock_NameTheDatabaseTreatsAsTheSame_IsTheSameLock(string held, string asked) - { - var suffix = Guid.NewGuid().ToString("N")[..8]; - - await using var holderScope = WebApplicationFactory.Services.CreateAsyncScope(); - var holder = holderScope.ServiceProvider.GetRequiredService(); - await using var holderTransaction = await holder.Database.BeginTransactionAsync(); - await Assert.That(await holder.Database.TryLockForTransactionAsync("lock-test:" + held + suffix)).IsTrue(); - - await using var otherScope = WebApplicationFactory.Services.CreateAsyncScope(); - var other = otherScope.ServiceProvider.GetRequiredService(); - await using var otherTransaction = await other.Database.BeginTransactionAsync(); - - await Assert.That(await other.Database.TryLockForTransactionAsync("lock-test:" + asked + suffix)).IsFalse(); - await Assert.That(await other.Database.TryLockForTransactionAsync("lock-test:other" + suffix)).IsTrue(); - } - - [Test] - public async Task Activate_FromAPageThatIsNotTheFrontend_Returns403_AndCreatesNoAccount() - { - var email = TestHelper.UniqueEmail("origin-activate"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("originactivate")); - var code = await MailCodeAsync(WebApplicationFactory, pendingId); - - using var client = CreateClient(); - var request = new HttpRequestMessage(HttpMethod.Post, "/1/account/activate") - { - Content = TestHelper.JsonContent(new { code }) - }; - request.Headers.Add("Cookie", MintSignupBrowserCookie(WebApplicationFactory, pendingId)); - request.Headers.Add("Origin", "https://evil.openshock.app"); - var response = await client.SendAsync(request); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); - await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); - } - // --- helpers --- private HttpClient CreateClient() => WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions diff --git a/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs b/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs index a55f899f..caa42bb6 100644 --- a/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs +++ b/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs @@ -2,6 +2,7 @@ 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; @@ -10,59 +11,37 @@ namespace OpenShock.API.IntegrationTests.Tests; /// The signup browser cookie only lets a browser enter the code when it comes back from the country the /// signup was made in. /// -// One at a time: every test moves the single fake location all requests of this host resolve to. The key is -// the one the LCG assignment suites use, because they share this host and read the same fake location. -[NotInParallel("gateway_assignment")] public sealed class SignupBrowserCookieCountryTests { - [ClassDataSource(Shared = SharedType.PerTestSession)] - public required GeoLocatedWebApplicationFactory WebApplicationFactory { get; init; } - - [After(Test)] - public void ResetCountry() => WebApplicationFactory.ClientCountryCode = null; - - [Test] - public async Task Activate_FromTheCountryOfTheSignup_CreatesTheAccount() - { - WebApplicationFactory.ClientCountryCode = "NO"; - var (email, code, cookie) = await SignUpAndGetCodeAsync("countrysame"); - - var response = await PostActivateAsync(code, cookie); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNotNull(); - } + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required WebApplicationFactory WebApplicationFactory { get; init; } [Test] public async Task Activate_FromAnotherCountry_IgnoresTheCookie() { - WebApplicationFactory.ClientCountryCode = "NO"; - var (email, code, cookie) = await SignUpAndGetCodeAsync("countryother"); + var (email, code, cookie) = await SignUpAndGetCodeAsync("countryother", "NO"); - WebApplicationFactory.ClientCountryCode = "DE"; - var response = await PostActivateAsync(code, cookie); + var response = await PostActivateAsync(code, cookie, "DE"); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); // Only ignored, not removed: it works again from where the signup was made. await Assert.That(DeletesCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsFalse(); - // The signup itself is untouched, and signing in with its password holds it from here as well. - WebApplicationFactory.ClientCountryCode = "DE"; - using var client = CreateClient(); + // The signup itself is untouched, and signing in with its password holds it from here as well: a + // cookie handed out in this country works in this country. + using var client = CreateClient("DE"); var login = await PostLoginAsync(client, email, Password); - var abroad = await PostActivateAsync(code, ReadSetCookie(login, AuthConstants.SignupBrowserSecureCookieName)); + var abroad = await PostActivateAsync(code, ReadSetCookie(login, AuthConstants.SignupBrowserSecureCookieName), "DE"); await Assert.That(abroad.StatusCode).IsEqualTo(HttpStatusCode.OK); } [Test] public async Task Activate_WhenTheCountryCannotBeResolved_StillAcceptsTheCookie() { - WebApplicationFactory.ClientCountryCode = "NO"; - var (email, code, cookie) = await SignUpAndGetCodeAsync("countryunknown"); + var (email, code, cookie) = await SignUpAndGetCodeAsync("countryunknown", "NO"); - WebApplicationFactory.ClientCountryCode = null; - var response = await PostActivateAsync(code, cookie); + var response = await PostActivateAsync(code, cookie, countryCode: null); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNotNull(); @@ -71,28 +50,30 @@ public async Task Activate_WhenTheCountryCannotBeResolved_StillAcceptsTheCookie( [Test] public async Task Activate_CookieFromASignupOfUnknownCountry_IsAcceptedAnywhere() { - var pendingId = await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("country-none"), TestHelper.UniqueUsername("countrynone")); + var pendingId = await CreateInDbAsync(WebApplicationFactory, UniqueNames.Email("country-none"), UniqueNames.Username("countrynone")); var code = await MailCodeAsync(WebApplicationFactory, pendingId); - WebApplicationFactory.ClientCountryCode = "DE"; - var response = await PostActivateAsync(code, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + var response = await PostActivateAsync(code, MintSignupBrowserCookie(WebApplicationFactory, pendingId), "DE"); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); } - private HttpClient CreateClient() => WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions - { - AllowAutoRedirect = false, - HandleCookies = false - }); + /// A client whose requests resolve to , or to no country when null. + private HttpClient CreateClient(string? countryCode) => HeaderIpEnrichmentService.Place( + WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + HandleCookies = false + }), + countryCode); /// Signs up through the API, and stands in for the Cron job that mails the activation code. - private async Task<(string Email, string Code, string Cookie)> SignUpAndGetCodeAsync(string prefix) + private async Task<(string Email, string Code, string Cookie)> SignUpAndGetCodeAsync(string prefix, string countryCode) { - var email = TestHelper.UniqueEmail(prefix); + var email = UniqueNames.Email(prefix); - using var client = CreateClient(); - var response = await PostSignupAsync(client, email, TestHelper.UniqueUsername(prefix)); + using var client = CreateClient(countryCode); + var response = await PostSignupAsync(client, email, UniqueNames.Username(prefix)); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); var cookie = ReadSetCookie(response, AuthConstants.SignupBrowserSecureCookieName); @@ -101,9 +82,9 @@ private HttpClient CreateClient() => WebApplicationFactory.CreateClient(new WebA return (email, await MailCodeAsync(WebApplicationFactory, pending.Id), cookie); } - private async Task PostActivateAsync(string code, string cookie) + private async Task PostActivateAsync(string code, string cookie, string? countryCode) { - using var client = CreateClient(); + using var client = CreateClient(countryCode); return await PendingSignupHelper.PostActivateAsync(client, code, cookie); } } diff --git a/API.IntegrationTests/Tests/TimescaleDbRequirementTests.cs b/API.IntegrationTests/Tests/TimescaleDbRequirementTests.cs index 09b0c26d..fe5c678e 100644 --- a/API.IntegrationTests/Tests/TimescaleDbRequirementTests.cs +++ b/API.IntegrationTests/Tests/TimescaleDbRequirementTests.cs @@ -10,6 +10,7 @@ namespace OpenShock.API.IntegrationTests.Tests; public sealed class TimescaleDbRequirementTests { private const string Community = "timescale/timescaledb:latest-pg18"; + private const string Requirement = "The database requires the TimescaleDB Community edition"; private static PostgreSqlContainer CreateContainer(string image) => new PostgreSqlBuilder(image: image).Build(); @@ -30,18 +31,6 @@ private static async Task HasExtension(PostgreSqlContainer container, stri return (long)(await command.ExecuteScalarAsync())! == 1; } - private static async Task HasControlStatsPolicy(PostgreSqlContainer container, string database) - { - await using var connection = new NpgsqlConnection(WithDatabase(container, database)); - await connection.OpenAsync(); - await using var command = new NpgsqlCommand( - """ - SELECT count(*) FROM timescaledb_information.jobs - WHERE proc_name = 'policy_refresh_continuous_aggregate' AND hypertable_name = 'control_stats' - """, connection); - return (long)(await command.ExecuteScalarAsync())! == 1; - } - private static async Task HasMigrationHistory(PostgreSqlContainer container) { await using var connection = new NpgsqlConnection(container.GetConnectionString()); @@ -57,33 +46,9 @@ private static async Task ApplyMigrations(string connectionString) } [Test] - public async Task Community_ApplyingMigrationsOnNewDatabase_Works() - { - await using var container = CreateContainer(Community); - await container.StartAsync(); - - await ApplyMigrations(WithDatabase(container, "created_on_startup")); - - await Assert.That(await HasExtension(container, "created_on_startup")).IsTrue(); - await Assert.That(await HasControlStatsPolicy(container, "created_on_startup")).IsTrue(); - } - - [Test] - public async Task Community_Check_LeavesNothingBehind() - { - await using var container = CreateContainer(Community); - await container.StartAsync(); - await Psql(container, PostgreSqlBuilder.DefaultDatabase, "CREATE DATABASE fresh TEMPLATE template0"); - - await OpenShockMiddlewareHelper.EnsureTimescaleDbAsync(WithDatabase(container, "fresh")); - - await Assert.That(await HasExtension(container, "fresh")).IsFalse(); - } - - [Test] - [Arguments("postgres:18", "is not available")] - [Arguments("timescale/timescaledb:latest-pg18-oss", "apache")] - public async Task WrongEdition_RefusesToMigrate(string image, string reason) + [Arguments("postgres:18", null)] + [Arguments("timescale/timescaledb:latest-pg18-oss", "Found the apache edition")] + public async Task WrongEdition_RefusesToMigrate(string image, string? reason) { await using var container = CreateContainer(image); await container.StartAsync(); @@ -91,7 +56,8 @@ public async Task WrongEdition_RefusesToMigrate(string image, string reason) var exception = await Assert.That(() => ApplyMigrations(container.GetConnectionString())) .Throws(); - await Assert.That(exception!.Message).Contains(reason); + await Assert.That(exception!.Message).StartsWith(Requirement); + if (reason is not null) await Assert.That(exception.Message).Contains(reason); await Assert.That(await HasMigrationHistory(container)).IsFalse(); } @@ -103,16 +69,23 @@ public async Task NotPreloaded_RefusesToMigrate() await Psql(container, PostgreSqlBuilder.DefaultDatabase, "CREATE DATABASE fresh TEMPLATE template0"); await Psql(container, PostgreSqlBuilder.DefaultDatabase, "CREATE DATABASE has_extension TEMPLATE template0"); await Psql(container, "has_extension", "CREATE EXTENSION timescaledb"); + + // While still preloaded the check passes, and it creates the extension only to read its license + await OpenShockMiddlewareHelper.EnsureTimescaleDbAsync(WithDatabase(container, "fresh")); + await Assert.That(await HasExtension(container, "fresh")).IsFalse(); + await Psql(container, PostgreSqlBuilder.DefaultDatabase, "ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements'"); await container.StopAsync(); await container.StartAsync(); - foreach (var (database, reason) in new[] { ("fresh", "must be preloaded"), ("has_extension", "not preloaded") }) + // Without the extension, creating it fails; with it, it reports no license + foreach (var (database, reason) in new[] { ("fresh", "must be preloaded"), ("has_extension", "It is not preloaded.") }) { var exception = await Assert.That(() => ApplyMigrations(WithDatabase(container, database))) .Throws(); - await Assert.That(exception!.Message).Contains(reason); + await Assert.That(exception!.Message).StartsWith(Requirement); + await Assert.That(exception.Message).Contains(reason); } } } diff --git a/API.IntegrationTests/Tests/TokensTests.cs b/API.IntegrationTests/Tests/TokensTests.cs index b6dd3b8e..c7dc2770 100644 --- a/API.IntegrationTests/Tests/TokensTests.cs +++ b/API.IntegrationTests/Tests/TokensTests.cs @@ -1,37 +1,47 @@ 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 TokensTests { + private const string Password = "SecurePassword123#"; + [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } // --- Create Token --- [Test] - public async Task CreateToken_Success_ReturnsTokenString() + public async Task CreateToken_ReturnedSecretAuthenticatesWithTheRequestedPermissions() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "tokcreate", "tokcreate@test.org", "SecurePassword123#"); + var user = await CreateUser("tokcreate"); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); var response = await client.PostAsync("/1/tokens", TestHelper.JsonContent(new { name = "MyToken", - permissions = new[] { "shockers.use" } + permissions = new[] { "shockers.use", "devices.edit" } })); 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.GetProperty("token").GetString()).IsNotNullOrWhiteSpace(); - await Assert.That(root.GetProperty("name").GetString()).IsEqualTo("MyToken"); - await Assert.That(root.TryGetProperty("id", out _)).IsTrue(); + using var created = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + var tokenId = created.RootElement.GetProperty("id").GetGuid(); + var secret = created.RootElement.GetProperty("token").GetString()!; + + using var tokenClient = TestHelper.CreateApiTokenClient(WebApplicationFactory, secret); + var self = await tokenClient.GetAsync("/1/tokens/self"); + + await Assert.That(self.StatusCode).IsEqualTo(HttpStatusCode.OK); + using var doc = JsonDocument.Parse(await self.Content.ReadAsStringAsync()); + await Assert.That(doc.RootElement.GetProperty("id").GetGuid()).IsEqualTo(tokenId); + await Assert.That(doc.RootElement.GetProperty("name").GetString()).IsEqualTo("MyToken"); + await Assert.That(ReadPermissions(doc.RootElement)).IsEquivalentTo(new[] { "shockers.use", "devices.edit" }); } // --- Create Token V2 (shocker control) --- @@ -43,26 +53,10 @@ public async Task CreateToken_Success_ReturnsTokenString() duration = new { min = 300, max = 65535, mode = "Clamp" } }; - [Test] - public async Task CreateTokenV2_MissingShockerControl_Returns400() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "tokv2def", "tokv2def@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - // shockerControl is required on v2 create. - var response = await client.PostAsync("/2/tokens", TestHelper.JsonContent(new - { - name = "NoShockerControl", - permissions = new[] { "shockers.use" } - })); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - } - [Test] public async Task CreateTokenV2_CustomShockerControl_RoundTrips() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "tokv2custom", "tokv2custom@test.org", "SecurePassword123#"); + var user = await CreateUser("tokv2custom"); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); var createResponse = await client.PostAsync("/2/tokens", TestHelper.JsonContent(new @@ -95,10 +89,14 @@ public async Task CreateTokenV2_CustomShockerControl_RoundTrips() await Assert.That(sc.GetProperty("duration").GetProperty("max").GetInt32()).IsEqualTo(2000); } + // ShockerControlSettings lives in the API project, which no unit test project references, so its + // IValidatableObject check is covered here. [Test] - public async Task CreateTokenV2_MinGreaterThanMax_Returns400() + [Arguments(80, 20, 300, 65535)] + [Arguments(0, 100, 2000, 500)] + public async Task CreateTokenV2_MinGreaterThanMax_Returns400(int intensityMin, int intensityMax, int durationMin, int durationMax) { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "tokv2minmax", "tokv2minmax@test.org", "SecurePassword123#"); + var user = await CreateUser("tokv2minmax"); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); var response = await client.PostAsync("/2/tokens", TestHelper.JsonContent(new @@ -108,39 +106,21 @@ public async Task CreateTokenV2_MinGreaterThanMax_Returns400() shockerControl = new { paused = false, - intensity = new { min = 80, max = 20, mode = "Clamp" }, - duration = new { min = 300, max = 65535, mode = "Clamp" } - } - })); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - } - - [Test] - public async Task CreateTokenV2_IntensityOutOfRange_Returns400() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "tokv2range", "tokv2range@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.PostAsync("/2/tokens", TestHelper.JsonContent(new - { - name = "OutOfRange", - permissions = new[] { "shockers.use" }, - shockerControl = new - { - paused = false, - intensity = new { min = 0, max = 200, mode = "Clamp" }, - duration = new { min = 300, max = 65535, mode = "Clamp" } + intensity = new { min = intensityMin, max = intensityMax, mode = "Clamp" }, + duration = new { min = durationMin, max = durationMax, mode = "Clamp" } } })); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.ApiTokens.AnyAsync(t => t.UserId == user.Id)).IsFalse(); } [Test] public async Task SetTokenPaused_TogglesAndReturnsState() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "tokv2pause", "tokv2pause@test.org", "SecurePassword123#"); + var user = await CreateUser("tokv2pause"); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); var createResponse = await client.PostAsync("/2/tokens", TestHelper.JsonContent(new @@ -167,82 +147,33 @@ public async Task SetTokenPaused_TogglesAndReturnsState() await Assert.That(getDoc.RootElement.GetProperty("shockerControl").GetProperty("paused").GetBoolean()).IsTrue(); } - [Test] - public async Task SetTokenPaused_Nonexistent_Returns404() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "tokv2pause404", "tokv2pause404@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.PatchAsync($"/2/tokens/{Guid.CreateVersion7()}/paused", TestHelper.JsonContent(new { paused = true })); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); - } - // --- List Tokens --- [Test] - public async Task ListTokens_ReturnsCreatedTokens() + public async Task ListTokens_ReturnsExactlyTheCallersTokens() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "toklist", "toklist@test.org", "SecurePassword123#"); + var user = await CreateUser("toklist"); + var other = await CreateUser("toklistother"); + await TestHelper.CreateApiTokenInDb(WebApplicationFactory, other.Id, "OtherUsersToken"); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - // Create two tokens await client.PostAsync("/1/tokens", TestHelper.JsonContent(new { name = "Token1", permissions = new[] { "shockers.use" } })); await client.PostAsync("/1/tokens", TestHelper.JsonContent(new { name = "Token2", permissions = new[] { "shockers.use" } })); var response = await client.GetAsync("/1/tokens"); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - - var json = await response.Content.ReadAsStringAsync(); - using var doc = JsonDocument.Parse(json); - await Assert.That(doc.RootElement.GetArrayLength()).IsGreaterThanOrEqualTo(2); - } - - // --- Get Token by ID --- - - [Test] - public async Task GetTokenById_Success() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "tokgetid", "tokgetid@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - // Create a token - var createResponse = await client.PostAsync("/1/tokens", TestHelper.JsonContent(new - { - name = "GetMe", - permissions = new[] { "shockers.use" } - })); - var createJson = await createResponse.Content.ReadAsStringAsync(); - using var createDoc = JsonDocument.Parse(createJson); - var tokenId = createDoc.RootElement.GetProperty("id").GetString(); - - var response = await client.GetAsync($"/1/tokens/{tokenId}"); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - - var json = await response.Content.ReadAsStringAsync(); - using var doc = JsonDocument.Parse(json); - await Assert.That(doc.RootElement.GetProperty("name").GetString()).IsEqualTo("GetMe"); - } - - [Test] - public async Task GetTokenById_Nonexistent_Returns404() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "tokget404", "tokget404@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.GetAsync($"/1/tokens/{Guid.CreateVersion7()}"); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + var names = doc.RootElement.EnumerateArray().Select(t => t.GetProperty("name").GetString()!).ToList(); + await Assert.That(names).IsEquivalentTo(new[] { "Token1", "Token2" }); } // --- Edit Token --- [Test] - public async Task EditToken_ChangeName_Success() + public async Task EditToken_ChangesNameAndPermissions() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "tokedit", "tokedit@test.org", "SecurePassword123#"); + var user = await CreateUser("tokedit"); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); // Create @@ -264,26 +195,55 @@ public async Task EditToken_ChangeName_Success() await Assert.That(editResponse.StatusCode).IsEqualTo(HttpStatusCode.OK); - // Verify name changed var getResponse = await client.GetAsync($"/1/tokens/{tokenId}"); - var json = await getResponse.Content.ReadAsStringAsync(); - using var doc = JsonDocument.Parse(json); + await Assert.That(getResponse.StatusCode).IsEqualTo(HttpStatusCode.OK); + using var doc = JsonDocument.Parse(await getResponse.Content.ReadAsStringAsync()); await Assert.That(doc.RootElement.GetProperty("name").GetString()).IsEqualTo("NewName"); + await Assert.That(ReadPermissions(doc.RootElement)).IsEquivalentTo(new[] { "shockers.use", "shockers.edit" }); } + // --- Another user's token: not found, and left as it was --- + [Test] - public async Task EditToken_Nonexistent_Returns404() + public async Task EditToken_OfAnotherUser_Returns404AndLeavesItUnchanged() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "tokedit404", "tokedit404@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var (tokenId, client) = await CreateOtherUsersTokenAndCallerClient("tokeditx"); + using var _ = client; - var response = await client.PatchAsync($"/1/tokens/{Guid.CreateVersion7()}", TestHelper.JsonContent(new + var response = await client.PatchAsync($"/1/tokens/{tokenId}", TestHelper.JsonContent(new { - name = "Nope", - permissions = new[] { "shockers.use" } + name = "Hijacked", + permissions = new[] { "shockers.use", "devices.auth" } })); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); + var token = await GetTokenFromDb(tokenId); + await Assert.That(token!.Name).IsEqualTo("OwnersToken"); + await Assert.That(token.Permissions).IsEquivalentTo(new[] { PermissionType.Shockers_Use }); + } + + [Test] + public async Task SetTokenPaused_OfAnotherUser_Returns404AndLeavesItUnpaused() + { + var (tokenId, client) = await CreateOtherUsersTokenAndCallerClient("tokpausex"); + using var _ = client; + + var response = await client.PatchAsync($"/2/tokens/{tokenId}/paused", TestHelper.JsonContent(new { paused = true })); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); + await Assert.That((await GetTokenFromDb(tokenId))!.ShockerControlPaused).IsFalse(); + } + + [Test] + public async Task DeleteToken_OfAnotherUser_Returns404AndKeepsIt() + { + var (tokenId, client) = await CreateOtherUsersTokenAndCallerClient("tokdelx"); + using var _ = client; + + var response = await client.DeleteAsync($"/1/tokens/{tokenId}"); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); + await Assert.That(await GetTokenFromDb(tokenId)).IsNotNull(); } // --- Delete Token --- @@ -291,7 +251,7 @@ public async Task EditToken_Nonexistent_Returns404() [Test] public async Task DeleteToken_Success() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "tokdel", "tokdel@test.org", "SecurePassword123#"); + var user = await CreateUser("tokdel"); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); // Create @@ -313,59 +273,57 @@ public async Task DeleteToken_Success() await Assert.That(getResponse.StatusCode).IsEqualTo(HttpStatusCode.NotFound); } - [Test] - public async Task DeleteToken_Nonexistent_Returns404() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "tokdel404", "tokdel404@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.DeleteAsync($"/1/tokens/{Guid.CreateVersion7()}"); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); - } - - // --- Token Self (API Token Auth) --- + // --- Delete Token with API token auth --- [Test] - public async Task GetTokenSelf_WithApiToken_ReturnsInfo() + public async Task DeleteToken_ApiTokenDeletingItself_Succeeds() { - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, "tokself", "tokself@test.org", "SecurePassword123#"); - var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId, "SelfToken"); + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("tokdelself"), UniqueNames.Email("tokdelself"), Password); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId, "DeleteMyself"); using var client = TestHelper.CreateApiTokenClient(WebApplicationFactory, rawToken); - var response = await client.GetAsync("/1/tokens/self"); + var response = await client.DeleteAsync($"/1/tokens/{tokenId}"); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - - var json = await response.Content.ReadAsStringAsync(); - using var doc = JsonDocument.Parse(json); - await Assert.That(doc.RootElement.GetProperty("name").GetString()).IsEqualTo("SelfToken"); + await Assert.That(await GetTokenFromDb(tokenId)).IsNull(); } - // --- API Token Auth for other endpoints --- - [Test] - public async Task ApiTokenAuth_CanAccessDevices() + public async Task DeleteToken_ApiTokenDeletingAnotherTokenOfItsOwner_Returns403AndKeepsIt() { - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, "tokauth", "tokauth@test.org", "SecurePassword123#"); - var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId, "AuthToken", - [PermissionType.Shockers_Use, PermissionType.Devices_Edit]); + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username("tokdelsib"), UniqueNames.Email("tokdelsib"), Password); + var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId, "Caller"); + var (siblingId, _) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId, "Sibling"); using var client = TestHelper.CreateApiTokenClient(WebApplicationFactory, rawToken); - var response = await client.GetAsync("/1/devices"); + var response = await client.DeleteAsync($"/1/tokens/{siblingId}"); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("ApiToken.CanOnlyDeleteSelf"); + await Assert.That(await GetTokenFromDb(siblingId)).IsNotNull(); } - // --- Unauthorized --- + // --- Helpers --- - [Test] - public async Task ListTokens_Unauthenticated_Returns401() - { - using var client = WebApplicationFactory.CreateClient(); + private Task CreateUser(string prefix) => + TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username(prefix), UniqueNames.Email(prefix), Password); - var response = await client.GetAsync("/1/tokens"); + /// A token owned by one user, and a session client of another user. + private async Task<(Guid TokenId, HttpClient CallerClient)> CreateOtherUsersTokenAndCallerClient(string prefix) + { + var ownerId = await TestHelper.CreateUserInDb(WebApplicationFactory, UniqueNames.Username(prefix + "own"), UniqueNames.Email(prefix + "own"), Password); + var (tokenId, _) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, ownerId, "OwnersToken", [PermissionType.Shockers_Use]); + var caller = await CreateUser(prefix + "oth"); + return (tokenId, TestHelper.CreateAuthenticatedClient(WebApplicationFactory, caller.SessionToken)); + } - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + private async Task GetTokenFromDb(Guid tokenId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.ApiTokens.AsNoTracking().FirstOrDefaultAsync(t => t.Id == tokenId); } + + private static List ReadPermissions(JsonElement token) => + token.GetProperty("permissions").EnumerateArray().Select(p => p.GetString()!).ToList(); } diff --git a/API.IntegrationTests/Tests/TransactionLockTests.cs b/API.IntegrationTests/Tests/TransactionLockTests.cs new file mode 100644 index 00000000..3dc69d50 --- /dev/null +++ b/API.IntegrationTests/Tests/TransactionLockTests.cs @@ -0,0 +1,36 @@ +using Microsoft.Extensions.DependencyInjection; +using OpenShock.Common.OpenShockDb; + +namespace OpenShock.API.IntegrationTests.Tests; + +/// +/// against real Postgres. +/// +public sealed class TransactionLockTests +{ + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required WebApplicationFactory WebApplicationFactory { get; init; } + + // The database treats a name in another case, or with an accented letter written another way, as the + // same username. They have to be the same lock too, or two requests could each take "the" name at the + // same moment. + [Test] + [Arguments("café", "café")] + [Arguments("café", "CAFÉ")] + public async Task NameTheDatabaseTreatsAsTheSame_IsTheSameLock(string held, string asked) + { + var suffix = Guid.NewGuid().ToString("N")[..8]; + + await using var holderScope = WebApplicationFactory.Services.CreateAsyncScope(); + var holder = holderScope.ServiceProvider.GetRequiredService(); + await using var holderTransaction = await holder.Database.BeginTransactionAsync(); + await Assert.That(await holder.Database.TryLockForTransactionAsync("lock-test:" + held + suffix)).IsTrue(); + + await using var otherScope = WebApplicationFactory.Services.CreateAsyncScope(); + var other = otherScope.ServiceProvider.GetRequiredService(); + await using var otherTransaction = await other.Database.BeginTransactionAsync(); + + await Assert.That(await other.Database.TryLockForTransactionAsync("lock-test:" + asked + suffix)).IsFalse(); + await Assert.That(await other.Database.TryLockForTransactionAsync("lock-test:other" + suffix)).IsTrue(); + } +} diff --git a/API.IntegrationTests/Tests/UsersTests.cs b/API.IntegrationTests/Tests/UsersTests.cs index cecb2b40..62faa58d 100644 --- a/API.IntegrationTests/Tests/UsersTests.cs +++ b/API.IntegrationTests/Tests/UsersTests.cs @@ -1,11 +1,14 @@ using System.Net; using System.Text.Json; using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.IntegrationTests.Shared; namespace OpenShock.API.IntegrationTests.Tests; public sealed class UsersTests { + private const string Password = "SecurePassword123#"; + [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } @@ -14,7 +17,9 @@ public sealed class UsersTests [Test] public async Task GetSelf_ReturnsCurrentUserInfo() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "userself", "userself@test.org", "SecurePassword123#"); + var username = UniqueNames.Username("userself"); + var email = UniqueNames.Email("userself"); + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, username, email, Password); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); var response = await client.GetAsync("/1/users/self"); @@ -24,73 +29,32 @@ public async Task GetSelf_ReturnsCurrentUserInfo() 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("userself"); - await Assert.That(data.GetProperty("email").GetString()).IsEqualTo("userself@test.org"); - await Assert.That(data.TryGetProperty("id", out _)).IsTrue(); + await Assert.That(data.GetProperty("id").GetGuid()).IsEqualTo(user.Id); + await Assert.That(data.GetProperty("name").GetString()).IsEqualTo(username); + await Assert.That(data.GetProperty("email").GetString()).IsEqualTo(email); await Assert.That(data.TryGetProperty("image", out _)).IsTrue(); await Assert.That(data.TryGetProperty("roles", out _)).IsTrue(); } - [Test] - public async Task GetSelf_WithApiToken_ReturnsUserInfo() - { - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, "userselfapi", "userselfapi@test.org", "SecurePassword123#"); - var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId, "SelfApiToken"); - using var client = TestHelper.CreateApiTokenClient(WebApplicationFactory, rawToken); - - var response = await client.GetAsync("/1/users/self"); - - 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("userselfapi"); - } - // --- Lookup by Name --- [Test] - public async Task LookupByName_Found_ReturnsUserInfo() + public async Task LookupByName_ReturnsTheNamedUserWithoutTheirEmail_And404ForAnUnknownName() { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "lookupme", "lookupme@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var targetName = UniqueNames.Username("lookupme"); + var targetId = await TestHelper.CreateUserInDb(WebApplicationFactory, targetName, UniqueNames.Email("lookupme"), Password); + var caller = await TestHelper.CreateAndLoginUser(WebApplicationFactory, UniqueNames.Username("lookupcaller"), UniqueNames.Email("lookupcaller"), Password); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, caller.SessionToken); - var response = await client.GetAsync("/1/users/by-name/lookupme"); + var response = await client.GetAsync($"/1/users/by-name/{targetName}"); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - } - - [Test] - public async Task LookupByName_NotFound_Returns404() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, "lookupexist", "lookupexist@test.org", "SecurePassword123#"); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.GetAsync("/1/users/by-name/nonexistentuser12345"); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); - } - - // --- Unauthenticated --- - - [Test] - public async Task GetSelf_Unauthenticated_Returns401() - { - using var client = WebApplicationFactory.CreateClient(); - - var response = await client.GetAsync("/1/users/self"); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); - } - - [Test] - public async Task LookupByName_Unauthenticated_Returns401() - { - using var client = WebApplicationFactory.CreateClient(); - - var response = await client.GetAsync("/1/users/by-name/anyone"); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + await Assert.That(doc.RootElement.GetProperty("id").GetGuid()).IsEqualTo(targetId); + await Assert.That(doc.RootElement.GetProperty("name").GetString()).IsEqualTo(targetName); + await Assert.That(doc.RootElement.TryGetProperty("email", out _)).IsFalse(); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + var unknown = await client.GetAsync($"/1/users/by-name/{UniqueNames.Username("nobody")}"); + await Assert.That(unknown.StatusCode).IsEqualTo(HttpStatusCode.NotFound); } } diff --git a/API.IntegrationTests/WebApplicationFactory.cs b/API.IntegrationTests/WebApplicationFactory.cs index b10c5dc1..54f64e3a 100644 --- a/API.IntegrationTests/WebApplicationFactory.cs +++ b/API.IntegrationTests/WebApplicationFactory.cs @@ -1,15 +1,13 @@ -using System.Threading.RateLimiting; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; -using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Http; -using Microsoft.Extensions.Options; -using OpenShock.API.IntegrationTests.Docker; using OpenShock.API.IntegrationTests.HttpMessageHandlers; using OpenShock.Common.Hubs; +using OpenShock.Common.Services.Geo; +using OpenShock.IntegrationTests.Shared; using Serilog; using Serilog.Events; @@ -21,11 +19,12 @@ namespace OpenShock.API.IntegrationTests; // so this factory deliberately boots no Cron host, no SMTP server, and no delivery loop. public class WebApplicationFactory : WebApplicationFactory { - [ClassDataSource(Shared = SharedType.PerTestSession)] - public required InMemoryDatabase PostgreSql { get; init; } + // Injected so the database is started and migrated before the host boots; the host reads PostgresFixture.ConnectionString. + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required PostgresFixture PostgreSql { get; init; } - [ClassDataSource(Shared = SharedType.PerTestSession)] - public required InMemoryRedis Redis { get; init; } + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required RedisFixture Redis { get; init; } /// How long an open hub connection can go on after its session or API token was revoked, in tests. public static readonly TimeSpan HubRevalidationInterval = TimeSpan.FromSeconds(1); @@ -55,8 +54,8 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) { { "ASPNETCORE_UNDER_INTEGRATION_TEST", "1" }, - { "OPENSHOCK__DB__CONN", PostgreSql.Container.GetConnectionString() }, - // InMemoryDatabase migrates the shared database once per test session. Every factory + { "OPENSHOCK__DB__CONN", PostgresFixture.ConnectionString }, + // PostgresFixture migrates the shared database once per test session. Every factory // variant boots its own host against that same database, and concurrent EF migrators // corrupt each other, so no host migrates on boot here. { "OPENSHOCK__DB__SKIPMIGRATION", "true" }, @@ -74,7 +73,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) { "OPENSHOCK__MAIL__TYPE", "Smtp" }, { "OPENSHOCK__TURNSTILE__ENABLED", "true" }, - { "OPENSHOCK__TURNSTILE__SECRETKEY", "turnstile-secret-key" }, + { "OPENSHOCK__TURNSTILE__SECRETKEY", InterceptedHttpMessageHandler.TurnstileSecretKey }, { "OPENSHOCK__TURNSTILE__SITEKEY", "turnstile-site-key" }, // Never contacted: enough for the provider to be offered and for the authorize endpoint to @@ -107,36 +106,13 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) { services.AddTransient(); + // No GeoLite2 databases here: requests resolve to nothing unless a test places them with headers + services.RemoveAll(); + services.AddSingleton(); + // Hub connections re-check their session or API token at most once per interval. Kept short so // the tests that revoke one do not have to wait out the production interval. services.Configure(options => options.Interval = HubRevalidationInterval); - - // Disable rate limiting for integration tests so auth-endpoint tests - // don't interfere with each other (10 req/min is too restrictive for test suites). - // Rate limiter behavior is covered by dedicated unit tests. - var rateLimiterDescriptors = services - .Where(d => d.ServiceType.IsGenericType - && d.ServiceType.GetGenericTypeDefinition() == typeof(IConfigureOptions<>) - && d.ServiceType.GetGenericArguments()[0] == typeof(RateLimiterOptions)) - .ToList(); - foreach (var descriptor in rateLimiterDescriptors) - { - services.Remove(descriptor); - } - - services.Configure(options => - { - options.GlobalLimiter = PartitionedRateLimiter.Create( - _ => RateLimitPartition.GetNoLimiter("test-no-limit")); - options.AddPolicy("auth", _ => - RateLimitPartition.GetNoLimiter("test-auth-no-limit")); - options.AddPolicy("token-reporting", _ => - RateLimitPartition.GetNoLimiter("test-token-reporting-no-limit")); - options.AddPolicy("shocker-logs", _ => - RateLimitPartition.GetNoLimiter("test-shocker-logs-no-limit")); - options.AddPolicy("control-stats", _ => - RateLimitPartition.GetNoLimiter("test-control-stats-no-limit")); - }); }); } } diff --git a/API/Models/Requests/EditTokenRequestV2.cs b/API/Models/Requests/EditTokenRequestV2.cs index 71500406..13bd4879 100644 --- a/API/Models/Requests/EditTokenRequestV2.cs +++ b/API/Models/Requests/EditTokenRequestV2.cs @@ -13,7 +13,7 @@ public class EditTokenRequestV2 public required IReadOnlyList Permissions { get; init; } /// - /// Per-token shocker control configuration. When omitted, the permissive default is used. + /// Per-token shocker control configuration. Required: a request without it is rejected. /// public required ShockerControlSettings ShockerControl { get; init; } } diff --git a/Common.Tests/Authentication/TrustedOriginAttributeTests.cs b/Common.Tests/Authentication/TrustedOriginAttributeTests.cs new file mode 100644 index 00000000..d18642a4 --- /dev/null +++ b/Common.Tests/Authentication/TrustedOriginAttributeTests.cs @@ -0,0 +1,80 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using OpenShock.Common.Authentication.Attributes; +using OpenShock.Common.Options; + +namespace OpenShock.Common.Tests.Authentication; + +public sealed class TrustedOriginAttributeTests +{ + private static readonly FrontendOptions Frontend = new() + { + BaseUrl = new Uri("https://openshock.app"), + ShortUrl = new Uri("https://openshock.app"), + CookieDomains = ["openshock.app"] + }; + + private static AuthorizationFilterContext Authorize(string host, params string[] origins) + { + var httpContext = new DefaultHttpContext + { + RequestServices = new ServiceCollection().AddSingleton(Frontend).BuildServiceProvider() + }; + httpContext.Request.Host = new HostString(host); + if (origins.Length > 0) httpContext.Request.Headers.Origin = origins; + + var context = new AuthorizationFilterContext(new ActionContext(httpContext, new RouteData(), new ActionDescriptor()), []); + new TrustedOriginAttribute().OnAuthorization(context); + return context; + } + + [Test] + [Arguments("https://openshock.app")] + [Arguments("https://OpenShock.app")] + [Arguments("https://openshock.app:443")] + public async Task FrontendOrigin_IsLetThrough(string origin) + { + await Assert.That(Authorize("api.openshock.app", origin).Result).IsNull(); + } + + // A request without Origin does not come from a page, so it has no browser's cookies to abuse. + [Test] + public async Task NoOrigin_IsLetThrough() + { + await Assert.That(Authorize("api.openshock.app").Result).IsNull(); + } + + // A page the API serves itself, like its documentation. Behind a TLS-terminating proxy the scheme may differ. + [Test] + [Arguments("https://api.openshock.app")] + [Arguments("http://api.openshock.app")] + public async Task OwnOrigin_IsLetThrough(string origin) + { + await Assert.That(Authorize("api.openshock.app", origin).Result).IsNull(); + } + + [Test] + [Arguments("https://evil.openshock.app")] + [Arguments("http://openshock.app")] + [Arguments("https://openshock.app:8443")] + [Arguments("https://openshock.app.evil.example")] + [Arguments("null")] + [Arguments("not a uri")] + public async Task OtherOrigin_IsRefused(string origin) + { + var result = Authorize("api.openshock.app", origin).Result; + + await Assert.That(result).IsNotNull(); + await Assert.That(((ObjectResult)result!).StatusCode).IsEqualTo(StatusCodes.Status403Forbidden); + } + + [Test] + public async Task SeveralOrigins_AreRefused() + { + await Assert.That(Authorize("api.openshock.app", "https://openshock.app", "https://openshock.app").Result).IsNotNull(); + } +} diff --git a/Common.Tests/Common.Tests.csproj b/Common.Tests/Common.Tests.csproj index ed2ba0a5..c88ae700 100644 --- a/Common.Tests/Common.Tests.csproj +++ b/Common.Tests/Common.Tests.csproj @@ -5,19 +5,6 @@ - - - - - - - - Always - - - Always - - diff --git a/Common.Tests/HealthChecks/CachedHealthCheckServiceTests.cs b/Common.Tests/HealthChecks/CachedHealthCheckServiceTests.cs index c0026c7f..e9128fda 100644 --- a/Common.Tests/HealthChecks/CachedHealthCheckServiceTests.cs +++ b/Common.Tests/HealthChecks/CachedHealthCheckServiceTests.cs @@ -45,6 +45,7 @@ private sealed class CountingHealthCheckService : HealthCheckService private int _calls; public int Calls => Volatile.Read(ref _calls); + public bool ReceivedPredicate { get; private set; } public CountingHealthCheckService(HealthReport report, TimeSpan delay = default) { @@ -56,6 +57,7 @@ public override async Task CheckHealthAsync(Func TimeSpan.Zero) await Task.Delay(_delay, cancellationToken); return _report; @@ -138,7 +140,7 @@ public async Task CheckHealth_WithPredicate_RecomputesStatusFromSelectedEntries( } [Test] - public async Task CheckHealth_DifferentPredicates_ShareOneRun() + public async Task CheckHealth_DifferentPredicates_ShareOneFullRun() { var inner = new CountingHealthCheckService( Report(("database", HealthStatus.Healthy), ("scratch", HealthStatus.Healthy))); @@ -151,6 +153,8 @@ public async Task CheckHealth_DifferentPredicates_ShareOneRun() await cached.CheckHealthAsync(null); await Assert.That(inner.Calls).IsEqualTo(1); + // The cold call came with a predicate, but the cached run has to be the full one. + await Assert.That(inner.ReceivedPredicate).IsFalse(); } // --- wiring --- diff --git a/Common.Tests/Hubs/TrackedHubConnectionTests.cs b/Common.Tests/Hubs/TrackedHubConnectionTests.cs index 177f8cd7..a20c0b10 100644 --- a/Common.Tests/Hubs/TrackedHubConnectionTests.cs +++ b/Common.Tests/Hubs/TrackedHubConnectionTests.cs @@ -23,4 +23,13 @@ public async Task MarkValidated_RecordsTheCheck() await Assert.That(connection.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsTrue(); } + [Test] + public async Task ResetValidation_ForcesTheNextCheck() + { + var connection = Create(); + connection.MarkValidated(); + connection.ResetValidation(); + + await Assert.That(connection.WasValidatedWithin(TimeSpan.FromMinutes(1))).IsFalse(); + } } diff --git a/Common.Tests/JsonSerialization/IPAddressJsonConverterTests.cs b/Common.Tests/JsonSerialization/IPAddressJsonConverterTests.cs index 11e53379..9e30f8d3 100644 --- a/Common.Tests/JsonSerialization/IPAddressJsonConverterTests.cs +++ b/Common.Tests/JsonSerialization/IPAddressJsonConverterTests.cs @@ -10,9 +10,7 @@ public sealed class IPAddressJsonConverterTests [Test] [Arguments("127.0.0.1")] - [Arguments("8.8.4.4")] [Arguments("::1")] - [Arguments("2001:db8::ff00:42:8329")] public async Task Serialize_WritesTextualForm(string address) { var json = JsonSerializer.Serialize(IPAddress.Parse(address), Options); @@ -20,14 +18,6 @@ public async Task Serialize_WritesTextualForm(string address) await Assert.That(json).IsEqualTo($"\"{address}\""); } - [Test] - public async Task Serialize_Property_WritesString() - { - var json = JsonSerializer.Serialize(new Holder { Ip = IPAddress.Loopback }, Options); - - await Assert.That(json).IsEqualTo("""{"ip":"127.0.0.1"}"""); - } - [Test] [Arguments("127.0.0.1")] [Arguments("::1")] @@ -41,14 +31,8 @@ public async Task Deserialize_ParsesTextualForm(string address) [Test] [Arguments("\"not an ip\"")] [Arguments("{\"addressFamily\":\"InterNetwork\"}")] - [Arguments("1")] public async Task Deserialize_Throws_WhenNotAnAddressString(string json) { await Assert.That(() => JsonSerializer.Deserialize(json, Options)).Throws(); } - - private sealed class Holder - { - public required IPAddress Ip { get; init; } - } } diff --git a/Common.Tests/Models/ApiTokenControlLimitsTests.cs b/Common.Tests/Models/ApiTokenControlLimitsTests.cs index 95c8a6af..755c9840 100644 --- a/Common.Tests/Models/ApiTokenControlLimitsTests.cs +++ b/Common.Tests/Models/ApiTokenControlLimitsTests.cs @@ -68,20 +68,13 @@ public async Task ApplyDuration_Clamp(int min, int max, ushort input, ushort exp // --- Duration lerp (input range 300-65535 remapped onto [min,max]) --- [Test] - public async Task ApplyDuration_Lerp_Endpoints() + [Arguments((ushort)300, (ushort)1000)] // input min -> min + [Arguments((ushort)65535, (ushort)5000)] // input max -> max + [Arguments((ushort)32917, (ushort)3000)] // midpoint of the input range -> midpoint + public async Task ApplyDuration_Lerp(ushort input, ushort expected) { - var limits = DurationLimits(1000, 5000, ControlLimitMode.Lerp); - await Assert.That(limits.ApplyDuration(300)).IsEqualTo((ushort)1000); // input min -> min - await Assert.That(limits.ApplyDuration(65535)).IsEqualTo((ushort)5000); // input max -> max - } - - [Test] - public async Task ApplyDuration_Lerp_Midpoint() - { - var limits = DurationLimits(1000, 5000, ControlLimitMode.Lerp); - // midpoint of input range -> midpoint of [1000,5000] == 3000 - var midInput = (ushort)((300 + 65535) / 2); - await Assert.That(limits.ApplyDuration(midInput)).IsEqualTo((ushort)3000); + var result = DurationLimits(1000, 5000, ControlLimitMode.Lerp).ApplyDuration(input); + await Assert.That(result).IsEqualTo(expected); } // --- A minimum above its maximum (not storable, the database rejects it) narrows to the maximum --- diff --git a/Common.Tests/Models/AuditMetadataTests.cs b/Common.Tests/Models/AuditMetadataTests.cs index 9cc34d47..b4d9369d 100644 --- a/Common.Tests/Models/AuditMetadataTests.cs +++ b/Common.Tests/Models/AuditMetadataTests.cs @@ -28,12 +28,31 @@ public async Task EverySubtype_IsRegisteredForJson() await Assert.That(unregistered).IsEmpty(); } + // The discriminator is stored in the audit log's jsonb column, so renaming one orphans every existing row. [Test] - public async Task Discriminators_AreUnique() + public async Task Discriminators_AreUnchanged() { - var duplicates = Registrations.GroupBy(r => r.TypeDiscriminator).Where(g => g.Count() > 1).Select(g => g.Key).ToArray(); + var expected = new Dictionary + { + [typeof(LoginMetadata)] = "login", + [typeof(UsernameChangedMetadata)] = "usernameChanged", + [typeof(EmailChangeRequestedMetadata)] = "emailChangeRequested", + [typeof(EmailChangedMetadata)] = "emailChanged", + [typeof(ApiTokenCreatedMetadata)] = "apiTokenCreated", + [typeof(ApiTokenDeletedMetadata)] = "apiTokenDeleted", + [typeof(OAuthConnectedMetadata)] = "oauthConnected", + [typeof(OAuthDisconnectedMetadata)] = "oauthDisconnected", + [typeof(AccountDeactivatedMetadata)] = "accountDeactivated", + [typeof(AutomationTokenCreatedMetadata)] = "automationTokenCreated", + [typeof(AutomationTokenUpdatedMetadata)] = "automationTokenUpdated", + [typeof(AutomationTokenRotatedMetadata)] = "automationTokenRotated", + [typeof(AutomationTokenDeletedMetadata)] = "automationTokenDeleted", + [typeof(AutomationTokenUsedMetadata)] = "automationTokenUsed", + }; - await Assert.That(duplicates).IsEmpty(); + var actual = Registrations.Select(r => $"{r.DerivedType.Name}={r.TypeDiscriminator}").Order().ToArray(); + + await Assert.That(actual).IsEquivalentTo(expected.Select(kv => $"{kv.Key.Name}={kv.Value}").Order().ToArray()); } [Test] diff --git a/Common.Tests/Models/SemVersion.cs b/Common.Tests/Models/SemVersion.cs index 28be5988..e77212e6 100644 --- a/Common.Tests/Models/SemVersion.cs +++ b/Common.Tests/Models/SemVersion.cs @@ -1,144 +1,70 @@ -using System.Text; -using OpenShock.Common.Models; +using OpenShock.Common.Models; namespace OpenShock.Common.Tests.Models; public sealed class SemVersionTests { // --------------------------- - // Parse / TryParse - happy path + // Parse / TryParse // --------------------------- [Test] - public async Task TryParse_CoreOnly_OnePart_Succeeds() + [Arguments("1", 1, 0, 0, null, null)] + [Arguments("1.2", 1, 2, 0, null, null)] + [Arguments("1.2.3", 1, 2, 3, null, null)] + [Arguments("0.0.0", 0, 0, 0, null, null)] + [Arguments("65535.0.0", 65535, 0, 0, null, null)] + [Arguments("1.2.3-alpha.1", 1, 2, 3, "alpha.1", null)] + [Arguments("1.2.3+build.5", 1, 2, 3, null, "build.5")] + [Arguments("1.2.3-rc.2+exp.sha", 1, 2, 3, "rc.2", "exp.sha")] + public async Task TryParse_Accepts(string input, int major, int minor, int patch, string? prerelease, string? build) { - var ok = SemVersion.TryParse("1", out var v); - await Assert.That(ok).IsTrue(); - await Assert.That(v!.Major).IsEqualTo((ushort)1); - await Assert.That(v.Minor).IsEqualTo((ushort)0); - await Assert.That(v.Patch).IsEqualTo((ushort)0); - await Assert.That(v.Prerelease).IsNull(); - await Assert.That(v.Build).IsNull(); - } - - [Test] - public async Task TryParse_CoreOnly_TwoParts_Succeeds() - { - var ok = SemVersion.TryParse("1.2", out var v); - await Assert.That(ok).IsTrue(); - await Assert.That(v!.Major).IsEqualTo((ushort)1); - await Assert.That(v.Minor).IsEqualTo((ushort)2); - await Assert.That(v.Patch).IsEqualTo((ushort)0); - } - - [Test] - public async Task TryParse_CoreOnly_ThreeParts_Succeeds() - { - var ok = SemVersion.TryParse("1.2.3", out var v); - await Assert.That(ok).IsTrue(); - await Assert.That(v!.Major).IsEqualTo((ushort)1); - await Assert.That(v.Minor).IsEqualTo((ushort)2); - await Assert.That(v.Patch).IsEqualTo((ushort)3); - } - - [Test] - public async Task TryParse_WithPrerelease_Succeeds() - { - var ok = SemVersion.TryParse("1.2.3-alpha.1", out var v); - await Assert.That(ok).IsTrue(); - await Assert.That(v!.Prerelease).IsEqualTo("alpha.1"); - await Assert.That(v.Build).IsNull(); - } + var ok = SemVersion.TryParse(input, out var v); - [Test] - public async Task TryParse_WithBuild_Succeeds() - { - var ok = SemVersion.TryParse("1.2.3+build.5", out var v); await Assert.That(ok).IsTrue(); - await Assert.That(v!.Build).IsEqualTo("build.5"); - await Assert.That(v.Prerelease).IsNull(); - } - - [Test] - public async Task TryParse_WithPrereleaseAndBuild_Succeeds() - { - var ok = SemVersion.TryParse("1.2.3-rc.2+exp.sha", out var v); - await Assert.That(ok).IsTrue(); - await Assert.That(v!.Prerelease).IsEqualTo("rc.2"); - await Assert.That(v.Build).IsEqualTo("exp.sha"); - } - - [Test] - public async Task Parse_String_Valid_ReturnsInstance() - { - var v = SemVersion.Parse("2.0.1-beta"); - await Assert.That(v.Major).IsEqualTo((ushort)2); - await Assert.That(v.Minor).IsEqualTo((ushort)0); - await Assert.That(v.Patch).IsEqualTo((ushort)1); - await Assert.That(v.Prerelease).IsEqualTo("beta"); - } - - [Test] - public async Task Parse_Span_Valid_ReturnsInstance() - { - ReadOnlySpan s = "3.4.5+meta"; - var v = SemVersion.Parse(s); - await Assert.That(v.Major).IsEqualTo((ushort)3); - await Assert.That(v.Minor).IsEqualTo((ushort)4); - await Assert.That(v.Patch).IsEqualTo((ushort)5); - await Assert.That(v.Build).IsEqualTo("meta"); - } - - // --------------------------- - // Parse / TryParse - invalid inputs - // --------------------------- - - [Test] - public async Task TryParse_NullOrEmpty_False() - { - await Assert.That(SemVersion.TryParse(null, out _)).IsFalse(); - await Assert.That(SemVersion.TryParse("", out _)).IsFalse(); + await Assert.That(v!.Major).IsEqualTo((ushort)major); + await Assert.That(v.Minor).IsEqualTo((ushort)minor); + await Assert.That(v.Patch).IsEqualTo((ushort)patch); + await Assert.That(v.Prerelease).IsEqualTo(prerelease); + await Assert.That(v.Build).IsEqualTo(build); } [Test] - public async Task TryParse_OnlyDashOrPlus_False() + [Arguments(null)] + [Arguments("")] + [Arguments("1.2.3-")] // '-' with nothing after + [Arguments("1.2.3+")] // '+' with nothing after + [Arguments("1.2.3.4")] // too many dots + [Arguments("1..2")] // empty segments + [Arguments(".1.2")] + [Arguments("1.")] + [Arguments(".1")] + [Arguments("v1.2.3")] // non-numeric core + [Arguments("1.x.3")] + [Arguments(" 1.2.3")] // whitespace is not trimmed + [Arguments("1.2.3 ")] + [Arguments(" ")] + [Arguments("01.2.3")] // leading zero + [Arguments("1.02.3")] + [Arguments("65536.0.0")] // does not fit a ushort + public async Task TryParse_Rejects(string? input) { - await Assert.That(SemVersion.TryParse("-", out _)).IsFalse(); - await Assert.That(SemVersion.TryParse("+", out _)).IsFalse(); + await Assert.That(SemVersion.TryParse(input, out _)).IsFalse(); } [Test] - public async Task TryParse_DashWithNothingAfter_False() + public async Task TryParse_EnforcesMaxLength() { - await Assert.That(SemVersion.TryParse("1.2.3-", out _)).IsFalse(); - } + var atLimit = "1.2.3-" + new string('a', SemVersion.MaxLength - "1.2.3-".Length); - [Test] - public async Task TryParse_PlusWithNothingAfter_False() - { - await Assert.That(SemVersion.TryParse("1.2.3+", out _)).IsFalse(); + await Assert.That(SemVersion.TryParse(atLimit, out _)).IsTrue(); + await Assert.That(SemVersion.TryParse(atLimit + "a", out _)).IsFalse(); } [Test] - public async Task TryParse_TooManyDots_False() + public async Task Parse_Valid_ReturnsInstance() { - await Assert.That(SemVersion.TryParse("1.2.3.4", out _)).IsFalse(); - } - - [Test] - public async Task TryParse_EmptySegments_False() - { - await Assert.That(SemVersion.TryParse("1..2", out _)).IsFalse(); - await Assert.That(SemVersion.TryParse(".1.2", out _)).IsFalse(); - await Assert.That(SemVersion.TryParse("1.", out _)).IsFalse(); - await Assert.That(SemVersion.TryParse(".1", out _)).IsFalse(); - } - - [Test] - public async Task TryParse_NonNumericCore_False() - { - await Assert.That(SemVersion.TryParse("v1.2.3", out _)).IsFalse(); - await Assert.That(SemVersion.TryParse("1.x.3", out _)).IsFalse(); + await Assert.That(SemVersion.Parse("2.0.1-beta")).IsEqualTo(new SemVersion(2, 0, 1, "beta")); } [Test] @@ -149,70 +75,23 @@ await Assert .ThrowsExactly(); } - [Test] - public async Task TryParse_ExceedsMaxLength_False() - { - // Build a version that exceeds MaxLength after trim - var sb = new StringBuilder(); - sb.Append("1.2.3-"); - sb.Append(new string('a', SemVersion.MaxLength)); // force over limit - var longVersion = sb.ToString(); - - await Assert.That(SemVersion.TryParse(longVersion, out _)).IsFalse(); - } - - [Test] - public async Task TryParse_LeadingWhitespace_Fails() - { - await Assert.That(SemVersion.TryParse(" 1.2.3", out _)).IsFalse(); - } - - [Test] - public async Task TryParse_TrailingWhitespace_Fails() - { - await Assert.That(SemVersion.TryParse("1.2.3 ", out _)).IsFalse(); - } - - [Test] - public async Task TryParse_OnlyWhitespace_Fails() - { - await Assert.That(SemVersion.TryParse(" ", out _)).IsFalse(); - } - // --------------------------- // ToString // --------------------------- [Test] - public async Task ToString_CoreOnly_ThreeParts() + [Arguments(1, 2, 3, null, null, "1.2.3")] + [Arguments(1, 0, 0, "alpha", null, "1.0.0-alpha")] + [Arguments(1, 0, 0, null, "001", "1.0.0+001")] + [Arguments(1, 2, 3, "rc.1", "exp.sha", "1.2.3-rc.1+exp.sha")] + public async Task ToString_Formats(int major, int minor, int patch, string? prerelease, string? build, string expected) { - var v = new SemVersion(1, 2, 3); - await Assert.That(v.ToString()).IsEqualTo("1.2.3"); - } - - [Test] - public async Task ToString_WithPrerelease() - { - var v = new SemVersion(1, 0, 0, "alpha"); - await Assert.That(v.ToString()).IsEqualTo("1.0.0-alpha"); - } - - [Test] - public async Task ToString_WithBuild() - { - var v = new SemVersion(1, 0, 0, build: "001"); - await Assert.That(v.ToString()).IsEqualTo("1.0.0+001"); - } - - [Test] - public async Task ToString_WithPrereleaseAndBuild() - { - var v = new SemVersion(1, 2, 3, "rc.1", "exp.sha"); - await Assert.That(v.ToString()).IsEqualTo("1.2.3-rc.1+exp.sha"); + var v = new SemVersion((ushort)major, (ushort)minor, (ushort)patch, prerelease, build); + await Assert.That(v.ToString()).IsEqualTo(expected); } // --------------------------- - // Equality / GetHashCode + // Equality // --------------------------- [Test] @@ -226,64 +105,6 @@ public async Task Equals_Structural_IncludingBuild() await Assert.That(a.GetHashCode()).IsEqualTo(b.GetHashCode()); } - [Test] - public async Task Equals_DiffersInBuild_False() - { - var a = new SemVersion(1, 2, 3, "alpha", "b1"); - var b = new SemVersion(1, 2, 3, "alpha", "b2"); - - await Assert.That(a).IsNotEqualTo(b); - } - - [Test] - public async Task Equals_DiffersInPrerelease_False() - { - var a = new SemVersion(1, 2, 3, "alpha"); - var b = new SemVersion(1, 2, 3, "beta"); - - await Assert.That(a).IsNotEqualTo(b); - } - - // --------------------------- - // FBS roundtrip (requires your Serialization.Types.SemVer) - // --------------------------- - - [Test] - public async Task Fbs_Roundtrip_PreservesFields() - { - var original = new SemVersion(10, 20, 30, "alpha.1", "build.7"); - var fbs = original.ToFbs(); - var roundtrip = SemVersion.FromFbs(fbs); - - await Assert.That(roundtrip.Major).IsEqualTo(original.Major); - await Assert.That(roundtrip.Minor).IsEqualTo(original.Minor); - await Assert.That(roundtrip.Patch).IsEqualTo(original.Patch); - await Assert.That(roundtrip.Prerelease).IsEqualTo(original.Prerelease); - await Assert.That(roundtrip.Build).IsEqualTo(original.Build); - } - - // --------------------------- - // Span overloads (extra coverage) - // --------------------------- - - [Test] - public async Task TryParse_Span_Input_Succeeds() - { - ReadOnlySpan s = "7.8.9-beta+ci"; - var ok = SemVersion.TryParse(s, out var v); - - await Assert.That(ok).IsTrue(); - await Assert.That(v!.Major).IsEqualTo((ushort)7); - await Assert.That(v.Minor).IsEqualTo((ushort)8); - await Assert.That(v.Patch).IsEqualTo((ushort)9); - await Assert.That(v.Prerelease).IsEqualTo("beta"); - await Assert.That(v.Build).IsEqualTo("ci"); - } - - // --------------------------- - // Equality operators (== / !=) - // --------------------------- - [Test] public async Task OperatorEquality_Structural_IncludingBuild() { @@ -327,4 +148,22 @@ public async Task OperatorEquality_NullHandling() await Assert.That(n1 != v).IsTrue(); await Assert.That(v != n1).IsTrue(); } + + // --------------------------- + // FBS roundtrip + // --------------------------- + + [Test] + public async Task Fbs_Roundtrip_PreservesFields() + { + var original = new SemVersion(10, 20, 30, "alpha.1", "build.7"); + var fbs = original.ToFbs(); + var roundtrip = SemVersion.FromFbs(fbs); + + await Assert.That(roundtrip.Major).IsEqualTo(original.Major); + await Assert.That(roundtrip.Minor).IsEqualTo(original.Minor); + await Assert.That(roundtrip.Patch).IsEqualTo(original.Patch); + await Assert.That(roundtrip.Prerelease).IsEqualTo(original.Prerelease); + await Assert.That(roundtrip.Build).IsEqualTo(original.Build); + } } diff --git a/Common.Tests/OpenShockDb/EmailOutboxMessageTests.cs b/Common.Tests/OpenShockDb/EmailOutboxMessageTests.cs index 9e6d802c..ff68898a 100644 --- a/Common.Tests/OpenShockDb/EmailOutboxMessageTests.cs +++ b/Common.Tests/OpenShockDb/EmailOutboxMessageTests.cs @@ -2,36 +2,57 @@ namespace OpenShock.Common.Tests.OpenShockDb; +/// +/// Each factory owns the (type, payload key, coalesce key) triple of its email. The coalesce key decides which +/// rows supersede each other, so newest-wins types must key on the user (or signup), not on the request row. +/// public sealed class EmailOutboxMessageTests { + private static readonly Guid RequestId = Guid.Parse("11111111-1111-1111-1111-111111111111"); + private static readonly Guid UserId = Guid.Parse("22222222-2222-2222-2222-222222222222"); + [Test] - public async Task Create_InitializesAsPendingWithGivenFields() + public async Task ForAccountActivation_KeysOnTheSignup() { - var payload = new Dictionary - { - [EmailOutboxPayloadKeys.PasswordResetId] = "11111111-1111-1111-1111-111111111111" - }; - - var message = EmailOutboxMessage.Create(EmailType.PasswordReset, "user@example.com", "User", payload); + var message = EmailOutboxMessage.ForAccountActivation(RequestId, "user@example.com", "User"); + await Assert.That(message.Type).IsEqualTo(EmailType.AccountActivation); await Assert.That(message.Status).IsEqualTo(EmailStatus.Pending); - await Assert.That(message.Type).IsEqualTo(EmailType.PasswordReset); await Assert.That(message.Recipient).IsEqualTo("user@example.com"); await Assert.That(message.RecipientName).IsEqualTo("User"); - await Assert.That(message.SentAt).IsNull(); - await Assert.That(message.FailedAt).IsNull(); - await Assert.That(message.Payload[EmailOutboxPayloadKeys.PasswordResetId]) - .IsEqualTo("11111111-1111-1111-1111-111111111111"); + await Assert.That(message.Payload[EmailOutboxPayloadKeys.PendingSignupId]).IsEqualTo(RequestId.ToString()); + await Assert.That(message.CoalesceKey).IsEqualTo($"activation:{RequestId}"); } [Test] - public async Task Create_AllowsNullRecipientName() + public async Task ForPasswordReset_KeysOnTheUser() { - var message = EmailOutboxMessage.Create(EmailType.EmailChangeNotice, "old@example.com", null, - new Dictionary { [EmailOutboxPayloadKeys.NewEmail] = "new@example.com" }); + var message = EmailOutboxMessage.ForPasswordReset(RequestId, UserId, "user@example.com", null); + + await Assert.That(message.Type).IsEqualTo(EmailType.PasswordReset); + await Assert.That(message.Payload[EmailOutboxPayloadKeys.PasswordResetId]).IsEqualTo(RequestId.ToString()); + await Assert.That(message.CoalesceKey).IsEqualTo($"pwreset:{UserId}"); + } - await Assert.That(message.RecipientName).IsNull(); + [Test] + public async Task ForEmailVerification_KeysOnTheUser() + { + var message = EmailOutboxMessage.ForEmailVerification(RequestId, UserId, "new@example.com", null); + + await Assert.That(message.Type).IsEqualTo(EmailType.EmailVerification); + await Assert.That(message.Payload[EmailOutboxPayloadKeys.EmailChangeId]).IsEqualTo(RequestId.ToString()); + await Assert.That(message.CoalesceKey).IsEqualTo($"emailchange:{UserId}"); + } + + [Test] + public async Task ForEmailChangeNotice_IsNeverCoalesced() + { + var message = EmailOutboxMessage.ForEmailChangeNotice("new@example.com", "old@example.com", null); + + await Assert.That(message.Type).IsEqualTo(EmailType.EmailChangeNotice); + await Assert.That(message.Recipient).IsEqualTo("old@example.com"); await Assert.That(message.Payload[EmailOutboxPayloadKeys.NewEmail]).IsEqualTo("new@example.com"); + await Assert.That(message.CoalesceKey).IsNull(); } [Test] diff --git a/Common.Tests/OpenShockDb/SaturatingConverterTests.cs b/Common.Tests/OpenShockDb/SaturatingConverterTests.cs index 575475be..f5a9df8d 100644 --- a/Common.Tests/OpenShockDb/SaturatingConverterTests.cs +++ b/Common.Tests/OpenShockDb/SaturatingConverterTests.cs @@ -8,7 +8,6 @@ public sealed class SaturatingConverterTests [Arguments(0, (ushort)0)] [Arguments(65535, (ushort)65535)] [Arguments(65536, (ushort)65535)] // an unchecked cast would read 0 - [Arguments(100000, (ushort)65535)] // an unchecked cast would read 34464 [Arguments(-1, (ushort)0)] // an unchecked cast would read 65535 public async Task UInt16_ClampsOnRead(int stored, ushort expected) { @@ -24,11 +23,4 @@ public async Task UInt32_ClampsOnRead(long stored, uint expected) { await Assert.That(new SaturatingUInt32Converter().ConvertFromProvider(stored)).IsEqualTo(expected); } - - [Test] - public async Task ValuesInRange_RoundTrip() - { - await Assert.That(new SaturatingUInt16Converter().ConvertToProvider(ushort.MaxValue)).IsEqualTo(65535); - await Assert.That(new SaturatingUInt32Converter().ConvertToProvider(uint.MaxValue)).IsEqualTo(4294967295L); - } } diff --git a/Common.Tests/Options/SecurityTxtOptionsTests.cs b/Common.Tests/Options/SecurityTxtOptionsTests.cs index 30c062f3..eb54a7e0 100644 --- a/Common.Tests/Options/SecurityTxtOptionsTests.cs +++ b/Common.Tests/Options/SecurityTxtOptionsTests.cs @@ -87,6 +87,19 @@ public async Task Render_CannotBeInjectedWithExtraLines() await Assert.That(options.Render().Split('\n', StringSplitOptions.RemoveEmptyEntries).Length).IsEqualTo(2); } + // Unlike the URI fields, PreferredLanguages is written verbatim, so a newline would add a line to the file. + [Test] + [Arguments("en\nContact: mailto:evil@example.org")] + [Arguments("en\rContact: mailto:evil@example.org")] + public async Task FromConfiguration_MultiLinePreferredLanguages_Throws(string languages) + { + await Assert.That(() => SecurityTxtOptions.FromConfiguration(Config( + ("Contact", "mailto:security@example.org"), + ("Expires", "2027-10-31"), + ("PreferredLanguages", languages)))) + .Throws(); + } + [Test] public async Task IsExpired_ComparesAgainstExpires() { diff --git a/Common.Tests/Redis/PubSubSerializationTests.cs b/Common.Tests/Redis/PubSubSerializationTests.cs index 9736512d..70eb0ab4 100644 --- a/Common.Tests/Redis/PubSubSerializationTests.cs +++ b/Common.Tests/Redis/PubSubSerializationTests.cs @@ -8,7 +8,7 @@ namespace OpenShock.Common.Tests.Redis; /// /// The API publishes these messages and the gateway consumes them, so during a rolling deploy old and new builds -/// talk to each other. The pinned bytes guard the wire format, the round trips guard the union dispatch. +/// talk to each other. The pinned bytes guard the wire format, decoding them back guards the union dispatch. /// public sealed class PubSubSerializationTests { @@ -16,43 +16,35 @@ public sealed class PubSubSerializationTests private static readonly MessagePackSerializerOptions Options = MessagePackSerializerOptions.Standard.WithResolver( CompositeResolver.Create(NativeGuidResolver.Instance, StandardResolver.Instance)); - private static T RoundTrip(T value) => - MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(value, Options), Options); + private static T FromHex(string hex) => MessagePackSerializer.Deserialize(Convert.FromHexString(hex), Options); - [Test] - public async Task DeviceMessage_WireFormat_IsUnchanged() - { - var bytes = MessagePackSerializer.Serialize(DeviceMessage.Create(DeviceTriggerType.DeviceReboot), Options); + private static string ToHex(T value) => Convert.ToHexString(MessagePackSerializer.Serialize(value, Options)); - // [ [unionKey 0, [Type 2]] ] - await Assert.That(Convert.ToHexString(bytes)).IsEqualTo("9192009102"); - } + private static readonly Guid FixedId = Guid.Parse("01234567-89ab-cdef-0123-456789abcdef"); + private static readonly string FixedIdHex = Convert.ToHexString(FixedId.ToByteArray()); [Test] - public async Task DeviceStatus_WireFormat_IsUnchanged() + public async Task DeviceMessage_Trigger_WireFormat_IsUnchanged() { - var deviceId = Guid.Parse("01234567-89ab-cdef-0123-456789abcdef"); - var bytes = MessagePackSerializer.Serialize(DeviceStatus.Create(deviceId, DeviceBoolStateType.Online, true), Options); - var guidHex = Convert.ToHexString(deviceId.ToByteArray()); - - // [ bin8(16) deviceId, [unionKey 0, [Type 0, State true]] ] - await Assert.That(Convert.ToHexString(bytes)).IsEqualTo($"92C410{guidHex}92009200C3"); - } + // [ [unionKey 0, [Type 2]] ] + const string hex = "9192009102"; - [Test] - public async Task DeviceMessage_Trigger_RoundTrips() - { - var payload = RoundTrip(DeviceMessage.Create(DeviceTriggerType.DeviceEmergencyStop)).Payload; + await Assert.That(ToHex(DeviceMessage.Create(DeviceTriggerType.DeviceReboot))).IsEqualTo(hex); + var payload = FromHex(hex).Payload; await Assert.That(payload).IsTypeOf(); - await Assert.That(((DeviceTriggerPayload)payload).Type).IsEqualTo(DeviceTriggerType.DeviceEmergencyStop); + await Assert.That(((DeviceTriggerPayload)payload).Type).IsEqualTo(DeviceTriggerType.DeviceReboot); } [Test] - public async Task DeviceMessage_Toggle_RoundTrips() + public async Task DeviceMessage_Toggle_WireFormat_IsUnchanged() { - var payload = RoundTrip(DeviceMessage.Create(DeviceToggleTarget.CaptivePortal, true)).Payload; + // [ [unionKey 1, [Target 0, State true]] ] + const string hex = "9192019200C3"; + + await Assert.That(ToHex(DeviceMessage.Create(DeviceToggleTarget.CaptivePortal, true))).IsEqualTo(hex); + var payload = FromHex(hex).Payload; await Assert.That(payload).IsTypeOf(); var toggle = (DeviceTogglePayload)payload; await Assert.That(toggle.Target).IsEqualTo(DeviceToggleTarget.CaptivePortal); @@ -60,21 +52,24 @@ public async Task DeviceMessage_Toggle_RoundTrips() } [Test] - public async Task DeviceMessage_Control_RoundTrips() + public async Task DeviceMessage_Control_WireFormat_IsUnchanged() { var command = new ShockerControlCommand { - ShockerId = Guid.CreateVersion7(), + ShockerId = FixedId, RfId = 1234, Intensity = 50, Duration = 1000, Type = ControlType.Vibrate, - Model = ShockerModelType.CaiXianlin, + Model = ShockerModelType.Petrainer998DR, Exclusive = true }; + // [ [unionKey 2, [ [ [bin8(16) ShockerId, RfId 1234, Intensity 50, Duration 1000, Type 2, Model 2, Exclusive true] ] ]] ] + var hex = $"919202919197C410{FixedIdHex}CD04D232CD03E80202C3"; - var payload = RoundTrip(DeviceMessage.Create(new DeviceControlPayload { Controls = [command] })).Payload; + await Assert.That(ToHex(DeviceMessage.Create(new DeviceControlPayload { Controls = [command] }))).IsEqualTo(hex); + var payload = FromHex(hex).Payload; await Assert.That(payload).IsTypeOf(); var controls = ((DeviceControlPayload)payload).Controls; await Assert.That(controls).Count().IsEqualTo(1); @@ -88,24 +83,29 @@ public async Task DeviceMessage_Control_RoundTrips() } [Test] - public async Task DeviceMessage_OtaInstall_RoundTrips() + public async Task DeviceMessage_OtaInstall_WireFormat_IsUnchanged() { var version = SemVersion.Parse("1.4.2-beta.1"); + // [ [unionKey 3, [ [Major 1, Minor 4, Patch 2, Prerelease "beta.1", Build nil] ]] ] + const string hex = "9192039195010402A6626574612E31C0"; - var payload = RoundTrip(DeviceMessage.Create(new DeviceOtaInstallPayload { Version = version })).Payload; + await Assert.That(ToHex(DeviceMessage.Create(new DeviceOtaInstallPayload { Version = version }))).IsEqualTo(hex); + var payload = FromHex(hex).Payload; await Assert.That(payload).IsTypeOf(); await Assert.That(((DeviceOtaInstallPayload)payload).Version).IsEqualTo(version); } [Test] - public async Task DeviceStatus_BoolState_RoundTrips() + public async Task DeviceStatus_WireFormat_IsUnchanged() { - var deviceId = Guid.CreateVersion7(); + // [ bin8(16) deviceId, [unionKey 0, [Type 1, State true]] ] + var hex = $"92C410{FixedIdHex}92009201C3"; - var status = RoundTrip(DeviceStatus.Create(deviceId, DeviceBoolStateType.EStopped, true)); + await Assert.That(ToHex(DeviceStatus.Create(FixedId, DeviceBoolStateType.EStopped, true))).IsEqualTo(hex); - await Assert.That(status.DeviceId).IsEqualTo(deviceId); + var status = FromHex(hex); + await Assert.That(status.DeviceId).IsEqualTo(FixedId); await Assert.That(status.Payload).IsTypeOf(); var state = (DeviceBoolStatePayload)status.Payload; await Assert.That(state.Type).IsEqualTo(DeviceBoolStateType.EStopped); diff --git a/Common.Tests/Services/GeoPointTests.cs b/Common.Tests/Services/GeoPointTests.cs index de8b9552..69965b68 100644 --- a/Common.Tests/Services/GeoPointTests.cs +++ b/Common.Tests/Services/GeoPointTests.cs @@ -13,25 +13,6 @@ public async Task DistanceToKm_BerlinToParis_MatchesKnownDistance() await Assert.That(berlin.DistanceToKm(paris)).IsBetween(870, 885); } - [Test] - public async Task DistanceToKm_IsSymmetricAndZeroForSamePoint() - { - var a = new GeoPoint(47.61, -122.33); - var b = new GeoPoint(-33.87, 151.21); - - await Assert.That(a.DistanceToKm(a)).IsEqualTo(0); - await Assert.That(Math.Abs(a.DistanceToKm(b) - b.DistanceToKm(a))).IsLessThan(0.01); - } - - [Test] - public async Task DistanceToKm_AcrossAntimeridian_TakesShortWay() - { - var west = new GeoPoint(0, 179.5); - var east = new GeoPoint(0, -179.5); - - await Assert.That(west.DistanceToKm(east)).IsLessThan(120); - } - [Test] [Arguments(null, 10d)] [Arguments(10d, null)] diff --git a/Common.Tests/Services/IpEnrichmentServiceTests.cs b/Common.Tests/Services/IpEnrichmentServiceTests.cs index c864933d..8b82dd2c 100644 --- a/Common.Tests/Services/IpEnrichmentServiceTests.cs +++ b/Common.Tests/Services/IpEnrichmentServiceTests.cs @@ -32,19 +32,10 @@ public async Task MatchesVpnProvider_HostingOrgs_ReturnsFalse(string asnOrg) } // "pia" is a real vendor abbreviation and also a substring of ordinary words. Whole-token - // matching is what keeps the second case from being reported as a VPN. + // matching is what keeps this from being reported as a VPN. [Test] - [Arguments("Olympia Networks")] - [Arguments("Compia Telecom")] - [Arguments("Utopia Broadband")] - public async Task MatchesVpnProvider_SubstringLookalikes_ReturnsFalse(string asnOrg) + public async Task MatchesVpnProvider_SubstringLookalike_ReturnsFalse() { - await Assert.That(IpEnrichmentService.MatchesVpnProvider(asnOrg)).IsFalse(); - } - - [Test] - public async Task MatchesVpnProvider_EmptyOrg_ReturnsFalse() - { - await Assert.That(IpEnrichmentService.MatchesVpnProvider(string.Empty)).IsFalse(); + await Assert.That(IpEnrichmentService.MatchesVpnProvider("Olympia Networks")).IsFalse(); } } diff --git a/Common.Tests/Utils/ControlLimitUtilsTests.cs b/Common.Tests/Utils/ControlLimitUtilsTests.cs index c5849d1f..8174e6cf 100644 --- a/Common.Tests/Utils/ControlLimitUtilsTests.cs +++ b/Common.Tests/Utils/ControlLimitUtilsTests.cs @@ -10,8 +10,7 @@ public sealed class ControlLimitUtilsTests [Arguments((ushort)100, null, (ushort)300)] // below the hard minimum is raised [Arguments((ushort)5000, 2000, (ushort)2000)] // above the cap is lowered [Arguments((ushort)1000, 2000, (ushort)1000)] // within the cap passes through - [Arguments((ushort)5000, 0, (ushort)300)] // a cap below the hard minimum acts as the minimum - [Arguments((ushort)5000, 299, (ushort)300)] + [Arguments((ushort)5000, 299, (ushort)300)] // a cap below the hard minimum acts as the minimum public async Task ClampDuration(ushort duration, int? cap, ushort expected) { await Assert.That(ControlLimitUtils.ClampDuration(duration, (ushort?)cap)).IsEqualTo(expected); diff --git a/Common.Tests/Utils/DomainUtilsTests.cs b/Common.Tests/Utils/DomainUtilsTests.cs index 75d47e79..208895ee 100644 --- a/Common.Tests/Utils/DomainUtilsTests.cs +++ b/Common.Tests/Utils/DomainUtilsTests.cs @@ -5,307 +5,62 @@ namespace OpenShock.Common.Tests.Utils; public sealed class DomainUtilsTests { [Test] - public async Task NullString_ReturnsFalse() + [Arguments("")] + [Arguments("example")] // no dot, and not localhost + [Arguments(".example.com")] // empty label + [Arguments("example.com.")] + [Arguments("a..b.com")] + [Arguments("-abc.com")] // hyphen placement + [Arguments("abc-.com")] + [Arguments("exa_mple.com")] // characters outside LDH + [Arguments("examp le.com")] + [Arguments("exam!ple.com")] + public async Task IsValidDomain_Rejects(string domain) { - // Act - var result = DomainUtils.IsValidDomain(null); - - // Assert - await Assert.That(result).IsFalse(); - } - - [Test] - public async Task EmptyString_ReturnsFalse() - { - // Act - var result = DomainUtils.IsValidDomain(""); - - // Assert - await Assert.That(result).IsFalse(); - } - - [Test] - public async Task NoDot_ReturnsFalse() - { - // Act - var result = DomainUtils.IsValidDomain("example"); - - // Assert - await Assert.That(result).IsFalse(); - } - - [Test] - public async Task LeadingDot_ReturnsFalse() - { - // Act - var result = DomainUtils.IsValidDomain(".example.com"); - - // Assert - await Assert.That(result).IsFalse(); - } - - [Test] - public async Task TrailingDot_ReturnsFalse() - { - // Act - var result = DomainUtils.IsValidDomain("example.com."); - - // Assert - await Assert.That(result).IsFalse(); - } - - [Test] - public async Task ConsecutiveDots_ReturnsFalse() - { - // Act - var result = DomainUtils.IsValidDomain("a..b.com"); - - // Assert - await Assert.That(result).IsFalse(); - } - - [Test] - public async Task LabelTooLong_ReturnsFalse() - { - // Arrange: label with 64 chars (invalid), then ".com" - var tooLong = new string('a', 64) + ".com"; - - // Act - var result = DomainUtils.IsValidDomain(tooLong); - - // Assert - await Assert.That(result).IsFalse(); - } - - [Test] - public async Task LabelStartingHyphen_ReturnsFalse() - { - // Act - var result = DomainUtils.IsValidDomain("-abc.com"); - - // Assert - await Assert.That(result).IsFalse(); - } - - [Test] - public async Task LabelEndingHyphen_ReturnsFalse() - { - // Act - var result = DomainUtils.IsValidDomain("abc-.com"); - - // Assert - await Assert.That(result).IsFalse(); + await Assert.That(DomainUtils.IsValidDomain(domain)).IsFalse(); } [Test] - public async Task InvalidCharacters_ReturnsFalse() + [Arguments("example.com")] + [Arguments("a.b")] + [Arguments("foo-bar.baz0")] + [Arguments("xn--d1acufc.xn--p1ai")] // punycode + [Arguments("localhost")] + public async Task IsValidDomain_Accepts(string domain) { - // Act - var r1 = DomainUtils.IsValidDomain("exa_mple.com"); - var r2 = DomainUtils.IsValidDomain("examp le.com"); - var r3 = DomainUtils.IsValidDomain("exam!ple.com"); - - // Assert - await Assert.That(r1).IsFalse(); - await Assert.That(r2).IsFalse(); - await Assert.That(r3).IsFalse(); + await Assert.That(DomainUtils.IsValidDomain(domain)).IsTrue(); } [Test] - public async Task TotalLengthOver253_ReturnsFalse() + public async Task IsValidDomain_EnforcesLabelAndTotalLength() { - // Arrange: construct >253 chars with dots - // "a." repeated 200 times yields 400 chars; ensure clearly >253. - var longHost = string.Join('.', Enumerable.Repeat("a", 130)); // 129 dots + 130 a's ~ 259 chars + var host253 = string.Join('.', Enumerable.Repeat("a", 127)); - // Act - var result = DomainUtils.IsValidDomain(longHost); - - // Assert - await Assert.That(result).IsFalse(); + await Assert.That(DomainUtils.IsValidDomain(new string('a', 63) + ".com")).IsTrue(); + await Assert.That(DomainUtils.IsValidDomain(new string('a', 64) + ".com")).IsFalse(); + await Assert.That(DomainUtils.IsValidDomain(host253)).IsTrue(); + await Assert.That(DomainUtils.IsValidDomain("b" + host253)).IsFalse(); } + // The list is passed '|'-separated because attribute arguments can't be arrays of strings here. [Test] - public async Task ValidAsciiLDH_ReturnsTrue() - { - // Act - var r1 = DomainUtils.IsValidDomain("example.com"); - var r2 = DomainUtils.IsValidDomain("a.b"); - var r3 = DomainUtils.IsValidDomain("foo-bar.baz0"); - var r4 = DomainUtils.IsValidDomain("xn--d1acufc.xn--p1ai"); // Punycode - - // Assert - await Assert.That(r1).IsTrue(); - await Assert.That(r2).IsTrue(); - await Assert.That(r3).IsTrue(); - await Assert.That(r4).IsTrue(); - } - - [Test] - public async Task HostMatchesCookieDomain_ExactMatch_ReturnsTrue() - { - // Act - var result = DomainUtils.HostMatchesCookieDomain("example.com", "example.com"); - - // Assert - await Assert.That(result).IsTrue(); - } - - [Test] - public async Task HostMatchesCookieDomain_SuffixLabelMatch_ReturnsTrue() - { - // Act - var result = DomainUtils.HostMatchesCookieDomain("shop.foo.example.com".AsSpan(), "example.com".AsSpan()); - - // Assert - await Assert.That(result).IsTrue(); - } - - [Test] - public async Task HostMatchesCookieDomain_PartialSuffixNoBoundary_ReturnsFalse() - { - // Act - var result = DomainUtils.HostMatchesCookieDomain("badexample.com", "example.com"); - - // Assert - await Assert.That(result).IsFalse(); - } - - [Test] - public async Task HostMatchesCookieDomain_CookieLongerThanHost_ReturnsFalse() - { - // Act - var result = DomainUtils.HostMatchesCookieDomain("example.com", "foo.example.com"); - - // Assert - await Assert.That(result).IsFalse(); - } - - [Test] - public async Task HostMatchesCookieDomain_InvalidHost_ReturnsFalse() - { - // Act - var result = DomainUtils.HostMatchesCookieDomain("example", "example.com"); // host without dot is invalid - - // Assert - await Assert.That(result).IsFalse(); - } - - [Test] - public async Task HostMatchesCookieDomain_CaseInsensitive_ReturnsTrue() - { - // Act - var result = DomainUtils.HostMatchesCookieDomain("SHOP.Foo.Example.COM", "example.com"); - - // Assert - await Assert.That(result).IsTrue(); - } - - // ---- GetBestMatchingCookieDomain ---- - - [Test] - public async Task GetBestMatchingCookieDomain_PicksMostSpecific() - { - // Arrange - string[] list = ["example.com","foo.example.com","bar.com"]; - - // Act - var best = DomainUtils.GetBestMatchingCookieDomain("shop.foo.example.com", list); - - // Assert - await Assert.That(best).IsEqualTo("foo.example.com"); - } - - [Test] - public async Task GetBestMatchingCookieDomain_ExactMatchBeatsShorterSuffix() - { - // Arrange - string[] list = ["example.com","shop.foo.example.com"]; - - // Act - var best = DomainUtils.GetBestMatchingCookieDomain("shop.foo.example.com", list); - - // Assert - await Assert.That(best).IsEqualTo("shop.foo.example.com"); - } - - [Test] - public async Task GetBestMatchingCookieDomain_EmptySegmentsIgnored() - { - // Arrange - string[] list = ["","","example.com","","foo.example.com",""]; - - // Act - var best = DomainUtils.GetBestMatchingCookieDomain("shop.foo.example.com", list); - - // Assert - await Assert.That(best).IsEqualTo("foo.example.com"); - } - - [Test] - public async Task GetBestMatchingCookieDomain_InvalidDomainsIgnored() - { - // Arrange: includes invalid ".example.com" and "exa_mple.com" - string[] list = [".example.com","exa_mple.com","example.com"]; - - // Act - var best = DomainUtils.GetBestMatchingCookieDomain("shop.example.com", list); - - // Assert - await Assert.That(best).IsEqualTo("example.com"); - } - - [Test] - public async Task GetBestMatchingCookieDomain_NoMatch_ReturnsNull() - { - // Arrange - string[] list = ["foo.com","bar.net"]; - - // Act - var best = DomainUtils.GetBestMatchingCookieDomain("example.com", list); - - // Assert - await Assert.That(best).IsNull(); - } - - [Test] - public async Task GetBestMatchingCookieDomain_HostInvalid_ReturnsNull() - { - // Arrange - string[] list = ["example.com","foo.example.com"]; - - // Act - var best = DomainUtils.GetBestMatchingCookieDomain("example", list); - - // Assert - await Assert.That(best).IsNull(); - } - - [Test] - public async Task GetBestMatchingCookieDomain_WhitespaceNotTrimmedInCurrentImplementation_SkipsEntry() - { - // Arrange: first entry has spaces (invalid for current impl), second is valid and more specific. - string[] list = [" example.com ","foo.example.com"]; - - // Use a host that matches *both* example.com and foo.example.com - var best = DomainUtils.GetBestMatchingCookieDomain("shop.foo.example.com", list); - - // Assert: because the first is invalid (whitespace not trimmed), the best is foo.example.com - await Assert.That(best).IsEqualTo("foo.example.com"); - } - - // ---- Additional boundary checks via HostMatchesCookieDomain ---- - - [Test] - public async Task HostBoundary_ChecksLabelBoundary() + [Arguments("shop.foo.example.com", "example.com|foo.example.com|bar.com", "foo.example.com")] // most labels wins + [Arguments("shop.foo.example.com", "example.com|shop.foo.example.com", "shop.foo.example.com")] // exact match + [Arguments("SHOP.Foo.Example.COM", "example.com", "example.com")] // case-insensitive + [Arguments("shop.example.com", ".example.com", "example.com")] // leading dot is ignored + [Arguments("shop.example.com", " example.com ", "example.com")] // surrounding whitespace is trimmed + [Arguments("shop.foo.example.com", "||example.com||foo.example.com|", "foo.example.com")] // empty entries skipped + [Arguments("shop.foo.example.com", "example.com|x..example.com", "example.com")] // invalid entry skipped, though its labels would match + [Arguments("localhost", "localhost", "localhost")] + [Arguments("badexample.com", "example.com", null)] // suffix not on a label boundary + [Arguments("example.com", "ample.com", null)] + [Arguments("example.com", "foo.example.com", null)] // cookie domain longer than host + [Arguments("example.com", "foo.com|bar.net", null)] + [Arguments("example", "example.com|foo.example.com", null)] // invalid host + public async Task GetBestMatchingCookieDomain(string host, string list, string? expected) { - // "ample.com" is substring but not a label-suffix of "example.com" - var r1 = DomainUtils.HostMatchesCookieDomain("example.com", "ample.com"); - var r2 = DomainUtils.HostMatchesCookieDomain("xample.com", "ample.com"); - var r3 = DomainUtils.HostMatchesCookieDomain("fooample.com", "ample.com"); + var best = DomainUtils.GetBestMatchingCookieDomain(host, list.Split('|')); - await Assert.That(r1).IsFalse(); - await Assert.That(r2).IsFalse(); - await Assert.That(r3).IsFalse(); + await Assert.That(best).IsEqualTo(expected); } } diff --git a/Common.Tests/Utils/GravatarUtilsTests.cs b/Common.Tests/Utils/GravatarUtilsTests.cs index bb736ffc..a1375b2f 100644 --- a/Common.Tests/Utils/GravatarUtilsTests.cs +++ b/Common.Tests/Utils/GravatarUtilsTests.cs @@ -4,46 +4,20 @@ namespace OpenShock.Common.Tests.Utils; public sealed class GravatarUtilsTests { - [Test] - public async Task GuestImageUrl_IsGravatarUrl() - { - await Assert.That(GravatarUtils.GuestImageUrl.Host).IsEqualTo("www.gravatar.com"); - } - - [Test] - public async Task GuestImageUrl_UsesZeroHash() - { - await Assert.That(GravatarUtils.GuestImageUrl.AbsolutePath).IsEqualTo("/avatar/0"); - } - - [Test] - public async Task GetUserImageUrl_IsGravatarUrl() - { - var url = GravatarUtils.GetUserImageUrl("test@example.com"); - await Assert.That(url.Host).IsEqualTo("www.gravatar.com"); - } - - [Test] - public async Task GetUserImageUrl_ContainsEmailHash() - { - var email = "test@example.com"; - var expectedHash = HashingUtils.HashSha256(email); - var url = GravatarUtils.GetUserImageUrl(email); - await Assert.That(url.AbsolutePath).IsEqualTo($"/avatar/{expectedHash}"); - } + private const string DefaultImageQuery = "?d=https%3a%2f%2fopenshock.app%2fstatic%2fimages%2fIcon512.png"; [Test] - public async Task GetUserImageUrl_ContainsDefaultImageParam() + public async Task GuestImageUrl_IsZeroHashWithDefaultImage() { - var url = GravatarUtils.GetUserImageUrl("test@example.com"); - await Assert.That(url.Query).Contains("d="); + await Assert.That(GravatarUtils.GuestImageUrl.AbsoluteUri) + .IsEqualTo("https://www.gravatar.com/avatar/0" + DefaultImageQuery); } [Test] - public async Task GetUserImageUrl_DifferentEmails_ProduceDifferentUrls() + public async Task GetUserImageUrl_IsSha256OfEmailWithDefaultImage() { - var url1 = GravatarUtils.GetUserImageUrl("a@example.com"); - var url2 = GravatarUtils.GetUserImageUrl("b@example.com"); - await Assert.That(url1).IsNotEqualTo(url2); + // SHA-256 of "test@example.com" + await Assert.That(GravatarUtils.GetUserImageUrl("test@example.com").AbsoluteUri) + .IsEqualTo("https://www.gravatar.com/avatar/973dfe463ec85785f5f95af5ba3906eedb2d931c24e69824a89ea65dba4e813b" + DefaultImageQuery); } } diff --git a/Common.Tests/Utils/HashingUtilsTests.cs b/Common.Tests/Utils/HashingUtilsTests.cs index 44f24f6e..f1ffa849 100644 --- a/Common.Tests/Utils/HashingUtilsTests.cs +++ b/Common.Tests/Utils/HashingUtilsTests.cs @@ -8,6 +8,7 @@ public sealed class HashingUtilsTests // --- HashSha256 --- [Test] + [Arguments("", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")] [Arguments("test", "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08")] [Arguments("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in", "2fac5f5f1d048a84fbb75c389f4596e05023ac17da4fcf45a5954d2d9a394301")] public async Task HashSha256(string str, string expectedHash) @@ -16,28 +17,6 @@ public async Task HashSha256(string str, string expectedHash) await Assert.That(result).IsEqualTo(expectedHash); } - [Test] - public async Task HashSha256_EmptyString_ReturnsKnownHash() - { - // SHA-256 of empty string - var result = HashingUtils.HashSha256(""); - await Assert.That(result).IsEqualTo("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); - } - - [Test] - public async Task HashSha256_ReturnsLowercaseHex() - { - var result = HashingUtils.HashSha256("test"); - await Assert.That(result).IsEqualTo(result.ToLowerInvariant()); - } - - [Test] - public async Task HashSha256_Returns64CharHex() - { - var result = HashingUtils.HashSha256("anything"); - await Assert.That(result.Length).IsEqualTo(64); - } - // --- HashPassword / VerifyPassword --- [Test] @@ -73,64 +52,36 @@ public async Task VerifyPassword_InvalidHashFormat_ReturnsFalse() await Assert.That(result.Verified).IsFalse(); } - [Test] - public async Task VerifyPassword_EmptyHash_ReturnsFalse() - { - var result = HashingUtils.VerifyPassword("test", ""); - await Assert.That(result.Verified).IsFalse(); - } + // Accounts from before bcrypt still carry a PBKDF2 hash: it must verify, and ask to be rehashed. + // PBKDF2-SHA512, 1000 iterations, salt 00..0F, password "LegacyP@ssw0rd". + private const string LegacyPbkdf2Hash = "pbkdf2:$1$1000$AAECAwQFBgcICQoLDA0ODwbD1jMBBv8AhWB2BeiziTfpSS8lIWAMl5FTqGJX64O9"; [Test] - public async Task HashPassword_DifferentPasswords_DifferentHashes() + public async Task VerifyPassword_LegacyPbkdf2_VerifiesAndNeedsRehash() { - var hash1 = HashingUtils.HashPassword("password1"); - var hash2 = HashingUtils.HashPassword("password2"); - await Assert.That(hash1).IsNotEqualTo(hash2); + var result = HashingUtils.VerifyPassword("LegacyP@ssw0rd", LegacyPbkdf2Hash); + await Assert.That(result.Verified).IsTrue(); + await Assert.That(result.NeedsRehash).IsTrue(); } [Test] - public async Task HashPassword_SamePassword_DifferentSalts() + public async Task VerifyPassword_LegacyPbkdf2_WrongPassword_ReturnsFalse() { - var hash1 = HashingUtils.HashPassword("same"); - var hash2 = HashingUtils.HashPassword("same"); - await Assert.That(hash1).IsNotEqualTo(hash2); + var result = HashingUtils.VerifyPassword("WrongP@ssw0rd", LegacyPbkdf2Hash); + await Assert.That(result.Verified).IsFalse(); } // --- GetPasswordHashingAlgorithm --- [Test] - public async Task GetPasswordHashingAlgorithm_BCryptPrefix_ReturnsBCrypt() + [Arguments("bcrypt:$2a$11$...", PasswordHashingAlgorithm.BCrypt)] + [Arguments("pbkdf2:somehash", PasswordHashingAlgorithm.PBKDF2)] + [Arguments("argon2:hash", PasswordHashingAlgorithm.Unknown)] + [Arguments("nocolonhere", PasswordHashingAlgorithm.Unknown)] + [Arguments(":hash", PasswordHashingAlgorithm.Unknown)] // empty prefix + public async Task GetPasswordHashingAlgorithm(string combinedHash, PasswordHashingAlgorithm expected) { - var result = HashingUtils.GetPasswordHashingAlgorithm("bcrypt:$2a$11$..."); - await Assert.That(result).IsEqualTo(PasswordHashingAlgorithm.BCrypt); - } - - [Test] - public async Task GetPasswordHashingAlgorithm_Pbkdf2Prefix_ReturnsPBKDF2() - { - var result = HashingUtils.GetPasswordHashingAlgorithm("pbkdf2:somehash"); - await Assert.That(result).IsEqualTo(PasswordHashingAlgorithm.PBKDF2); - } - - [Test] - public async Task GetPasswordHashingAlgorithm_UnknownPrefix_ReturnsUnknown() - { - var result = HashingUtils.GetPasswordHashingAlgorithm("argon2:hash"); - await Assert.That(result).IsEqualTo(PasswordHashingAlgorithm.Unknown); - } - - [Test] - public async Task GetPasswordHashingAlgorithm_NoColon_ReturnsUnknown() - { - var result = HashingUtils.GetPasswordHashingAlgorithm("nocolonhere"); - await Assert.That(result).IsEqualTo(PasswordHashingAlgorithm.Unknown); - } - - [Test] - public async Task GetPasswordHashingAlgorithm_Empty_ReturnsUnknown() - { - var result = HashingUtils.GetPasswordHashingAlgorithm(""); - await Assert.That(result).IsEqualTo(PasswordHashingAlgorithm.Unknown); + await Assert.That(HashingUtils.GetPasswordHashingAlgorithm(combinedHash)).IsEqualTo(expected); } // --- HashToken / VerifyToken --- @@ -170,15 +121,17 @@ public async Task VerifyToken_EmptyToken_NotVerified() await Assert.That(result.Verified).IsFalse(); } + // Tokens issued before the switch to SHA-256 are stored as bcrypt hashes (they contain '$'). [Test] - public async Task VerifyToken_LegacyBcryptHash_NeedsRehash() + public async Task VerifyToken_LegacyBcryptHash_VerifiesAndNeedsRehash() { - // Legacy tokens stored with bcrypt (contains '$' in hash) - var token = "legacy-token"; - var bcryptHash = HashingUtils.HashPassword(token); - var result = HashingUtils.VerifyToken(token, bcryptHash); - // Whether verified depends on bcrypt, but NeedsRehash should be true + var bcryptHash = HashingUtils.HashPassword("legacy-token"); + + var result = HashingUtils.VerifyToken("legacy-token", bcryptHash); + await Assert.That(result.Verified).IsTrue(); await Assert.That(result.NeedsRehash).IsTrue(); + + await Assert.That(HashingUtils.VerifyToken("other-token", bcryptHash).Verified).IsFalse(); } // --- VerifyPasswordFake --- @@ -190,14 +143,14 @@ public async Task VerifyToken_LegacyBcryptHash_NeedsRehash() public async Task VerifyPasswordFake_TakesAboutAsLongAsARealCheck_NotAHundredTimesLonger() { var hash = HashingUtils.HashPassword("SomePassword123#"); - var realCheck = System.Diagnostics.Stopwatch.StartNew(); + var realChecks = System.Diagnostics.Stopwatch.StartNew(); for (var i = 0; i < 5; i++) HashingUtils.VerifyPassword("SomePassword123#", hash); - var slowestRealCheck = realCheck.Elapsed; + var fiveRealChecks = realChecks.Elapsed; var fake = System.Diagnostics.Stopwatch.StartNew(); await HashingUtils.VerifyPasswordFake(); // Five real checks together are far more than one faked one should ever take, with room for noise. - await Assert.That(fake.Elapsed).IsLessThan(slowestRealCheck * 3 + TimeSpan.FromSeconds(1)); + await Assert.That(fake.Elapsed).IsLessThan(fiveRealChecks * 3 + TimeSpan.FromSeconds(1)); } } diff --git a/Common.Tests/Utils/IpAddressUtilsTests.cs b/Common.Tests/Utils/IpAddressUtilsTests.cs index 172ce26f..673f0628 100644 --- a/Common.Tests/Utils/IpAddressUtilsTests.cs +++ b/Common.Tests/Utils/IpAddressUtilsTests.cs @@ -13,19 +13,15 @@ public async Task ParseStoredOrThrow_Null_ReturnsNull() } [Test] - [Arguments("127.0.0.1")] - [Arguments("::1")] - public async Task ParseStoredOrThrow_Valid_ReturnsAddress(string stored) + public async Task ParseStoredOrThrow_Valid_ReturnsAddress() { - await Assert.That(IpAddressUtils.ParseStoredOrThrow(stored, NullLogger.Instance)).IsEqualTo(IPAddress.Parse(stored)); + await Assert.That(IpAddressUtils.ParseStoredOrThrow("::1", NullLogger.Instance)).IsEqualTo(IPAddress.IPv6Loopback); } [Test] - [Arguments("")] - [Arguments("not an ip")] - public async Task ParseStoredOrThrow_Malformed_Throws(string stored) + public async Task ParseStoredOrThrow_Malformed_Throws() { - await Assert.That(() => IpAddressUtils.ParseStoredOrThrow(stored, NullLogger.Instance)).Throws(); + await Assert.That(() => IpAddressUtils.ParseStoredOrThrow("not an ip", NullLogger.Instance)).Throws(); } [Test] @@ -35,18 +31,14 @@ public async Task ParseStoredOrNull_Null_ReturnsNull() } [Test] - [Arguments("127.0.0.1")] - [Arguments("::1")] - public async Task ParseStoredOrNull_Valid_ReturnsAddress(string stored) + public async Task ParseStoredOrNull_Valid_ReturnsAddress() { - await Assert.That(IpAddressUtils.ParseStoredOrNull(stored, NullLogger.Instance)).IsEqualTo(IPAddress.Parse(stored)); + await Assert.That(IpAddressUtils.ParseStoredOrNull("127.0.0.1", NullLogger.Instance)).IsEqualTo(IPAddress.Loopback); } [Test] - [Arguments("")] - [Arguments("not an ip")] - public async Task ParseStoredOrNull_Malformed_ReturnsNull(string stored) + public async Task ParseStoredOrNull_Malformed_ReturnsNull() { - await Assert.That(IpAddressUtils.ParseStoredOrNull(stored, NullLogger.Instance)).IsNull(); + await Assert.That(IpAddressUtils.ParseStoredOrNull("not an ip", NullLogger.Instance)).IsNull(); } } diff --git a/Common.Tests/Utils/PermissionUtilsTests.cs b/Common.Tests/Utils/PermissionUtilsTests.cs index 0d87c08f..49e61c5e 100644 --- a/Common.Tests/Utils/PermissionUtilsTests.cs +++ b/Common.Tests/Utils/PermissionUtilsTests.cs @@ -6,6 +6,12 @@ namespace OpenShock.Common.Tests.Utils; public sealed class PermissionUtilsTests { + private static SharePermsAndLimits Perms(bool shock, bool vibrate, bool sound, bool live) => new() + { + Shock = shock, Vibrate = vibrate, Sound = sound, Live = live, + Duration = null, Intensity = null + }; + [Test] public async Task NullPerms_AlwaysAllowed() { @@ -16,116 +22,27 @@ public async Task NullPerms_AlwaysAllowed() await Assert.That(PermissionUtils.IsAllowed(ControlType.Shock, true, null)).IsTrue(); } + // A denied case grants every other permission, so reading the wrong flag would let it through. [Test] - public async Task Shock_Allowed_WhenShockPermTrue() - { - var perms = new SharePermsAndLimits - { - Shock = true, Vibrate = false, Sound = false, Live = false, - Duration = null, Intensity = null - }; - await Assert.That(PermissionUtils.IsAllowed(ControlType.Shock, false, perms)).IsTrue(); - } - - [Test] - public async Task Shock_Denied_WhenShockPermFalse() - { - var perms = new SharePermsAndLimits - { - Shock = false, Vibrate = true, Sound = true, Live = true, - Duration = null, Intensity = null - }; - await Assert.That(PermissionUtils.IsAllowed(ControlType.Shock, false, perms)).IsFalse(); - } - - [Test] - public async Task Vibrate_Allowed_WhenVibratePermTrue() - { - var perms = new SharePermsAndLimits - { - Shock = false, Vibrate = true, Sound = false, Live = false, - Duration = null, Intensity = null - }; - await Assert.That(PermissionUtils.IsAllowed(ControlType.Vibrate, false, perms)).IsTrue(); - } - - [Test] - public async Task Vibrate_Denied_WhenVibratePermFalse() - { - var perms = new SharePermsAndLimits - { - Shock = true, Vibrate = false, Sound = true, Live = true, - Duration = null, Intensity = null - }; - await Assert.That(PermissionUtils.IsAllowed(ControlType.Vibrate, false, perms)).IsFalse(); - } - - [Test] - public async Task Sound_Allowed_WhenSoundPermTrue() - { - var perms = new SharePermsAndLimits - { - Shock = false, Vibrate = false, Sound = true, Live = false, - Duration = null, Intensity = null - }; - await Assert.That(PermissionUtils.IsAllowed(ControlType.Sound, false, perms)).IsTrue(); - } - - [Test] - public async Task Sound_Denied_WhenSoundPermFalse() - { - var perms = new SharePermsAndLimits - { - Shock = true, Vibrate = true, Sound = false, Live = true, - Duration = null, Intensity = null - }; - await Assert.That(PermissionUtils.IsAllowed(ControlType.Sound, false, perms)).IsFalse(); - } - - [Test] - public async Task Stop_Allowed_WhenAnyPermTrue() - { - var shockOnly = new SharePermsAndLimits - { - Shock = true, Vibrate = false, Sound = false, Live = false, - Duration = null, Intensity = null - }; - await Assert.That(PermissionUtils.IsAllowed(ControlType.Stop, false, shockOnly)).IsTrue(); - - var vibrateOnly = new SharePermsAndLimits - { - Shock = false, Vibrate = true, Sound = false, Live = false, - Duration = null, Intensity = null - }; - await Assert.That(PermissionUtils.IsAllowed(ControlType.Stop, false, vibrateOnly)).IsTrue(); - - var soundOnly = new SharePermsAndLimits - { - Shock = false, Vibrate = false, Sound = true, Live = false, - Duration = null, Intensity = null - }; - await Assert.That(PermissionUtils.IsAllowed(ControlType.Stop, false, soundOnly)).IsTrue(); - } - - [Test] - public async Task Stop_Denied_WhenAllPermsFalse() + [Arguments(ControlType.Shock, true, false, false, true)] + [Arguments(ControlType.Shock, false, true, true, false)] + [Arguments(ControlType.Vibrate, false, true, false, true)] + [Arguments(ControlType.Vibrate, true, false, true, false)] + [Arguments(ControlType.Sound, false, false, true, true)] + [Arguments(ControlType.Sound, true, true, false, false)] + [Arguments(ControlType.Stop, true, false, false, true)] // stop needs any one of the three + [Arguments(ControlType.Stop, false, true, false, true)] + [Arguments(ControlType.Stop, false, false, true, true)] + [Arguments(ControlType.Stop, false, false, false, false)] + public async Task IsAllowed_ChecksTheMatchingPermission(ControlType type, bool shock, bool vibrate, bool sound, bool expected) { - var perms = new SharePermsAndLimits - { - Shock = false, Vibrate = false, Sound = false, Live = true, - Duration = null, Intensity = null - }; - await Assert.That(PermissionUtils.IsAllowed(ControlType.Stop, false, perms)).IsFalse(); + await Assert.That(PermissionUtils.IsAllowed(type, false, Perms(shock, vibrate, sound, live: true))).IsEqualTo(expected); } [Test] public async Task Live_Denied_WhenLivePermFalse() { - var perms = new SharePermsAndLimits - { - Shock = true, Vibrate = true, Sound = true, Live = false, - Duration = null, Intensity = null - }; + var perms = Perms(true, true, true, live: false); await Assert.That(PermissionUtils.IsAllowed(ControlType.Shock, true, perms)).IsFalse(); await Assert.That(PermissionUtils.IsAllowed(ControlType.Vibrate, true, perms)).IsFalse(); await Assert.That(PermissionUtils.IsAllowed(ControlType.Sound, true, perms)).IsFalse(); @@ -134,11 +51,7 @@ public async Task Live_Denied_WhenLivePermFalse() [Test] public async Task Live_Allowed_WhenLivePermTrue() { - var perms = new SharePermsAndLimits - { - Shock = true, Vibrate = true, Sound = true, Live = true, - Duration = null, Intensity = null - }; + var perms = Perms(true, true, true, live: true); await Assert.That(PermissionUtils.IsAllowed(ControlType.Shock, true, perms)).IsTrue(); await Assert.That(PermissionUtils.IsAllowed(ControlType.Vibrate, true, perms)).IsTrue(); await Assert.That(PermissionUtils.IsAllowed(ControlType.Sound, true, perms)).IsTrue(); @@ -147,11 +60,6 @@ public async Task Live_Allowed_WhenLivePermTrue() [Test] public async Task UnknownControlType_ReturnsFalse() { - var perms = new SharePermsAndLimits - { - Shock = true, Vibrate = true, Sound = true, Live = true, - Duration = null, Intensity = null - }; - await Assert.That(PermissionUtils.IsAllowed((ControlType)999, false, perms)).IsFalse(); + await Assert.That(PermissionUtils.IsAllowed((ControlType)999, false, Perms(true, true, true, live: true))).IsFalse(); } } diff --git a/Common.Tests/Utils/RateLimitPartitionsTests.cs b/Common.Tests/Utils/RateLimitPartitionsTests.cs new file mode 100644 index 00000000..e531d115 --- /dev/null +++ b/Common.Tests/Utils/RateLimitPartitionsTests.cs @@ -0,0 +1,159 @@ +using System.Net; +using System.Security.Claims; +using System.Threading.RateLimiting; +using Microsoft.AspNetCore.Http; +using OpenShock.Common.Extensions; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.AutomationTokens; +using OpenShock.Common.Utils; + +namespace OpenShock.Common.Tests.Utils; + +public sealed class RateLimitPartitionsTests +{ + private static readonly IPAddress RemoteIp = IPAddress.Parse("203.0.113.5"); + + private static DefaultHttpContext CreateContext(IPAddress? ip = null, Guid? userId = null, params string[] roles) + { + var context = new DefaultHttpContext(); + context.Connection.RemoteIpAddress = ip; + if (userId is not null) + { + List claims = [new(ClaimTypes.NameIdentifier, userId.Value.ToString())]; + claims.AddRange(roles.Select(r => new Claim(ClaimTypes.Role, r))); + context.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "Test")); + } + return context; + } + + private static ResolvedAutomationToken SetAutomationToken(HttpContext context, params AutomationTokenType[] types) + { + var token = new ResolvedAutomationToken(Guid.NewGuid(), "test", types, "hash"); + context.SetResolvedAutomationToken(token); + return token; + } + + /// How many permits the partition's limiter hands out in a row before refusing, up to . + private static int CountPermits(RateLimitPartition partition, int max) + { + using var limiter = partition.Factory(partition.PartitionKey); + var leases = new List(); + try + { + for (var i = 0; i < max; i++) + { + var lease = limiter.AttemptAcquire(); + leases.Add(lease); + if (!lease.IsAcquired) return i; + } + return max; + } + finally + { + foreach (var lease in leases) lease.Dispose(); + } + } + + [Test] + public async Task TryBypass_WithoutAutomationToken_ReturnsNull() + { + await Assert.That(RateLimitPartitions.TryBypass(CreateContext(RemoteIp))).IsNull(); + } + + [Test] + public async Task TryBypass_TurnstileOnlyToken_ReturnsNull() + { + var context = CreateContext(RemoteIp); + SetAutomationToken(context, AutomationTokenType.Turnstile); + + await Assert.That(RateLimitPartitions.TryBypass(context)).IsNull(); + } + + [Test] + public async Task TryBypass_RateLimitToken_IsUnlimitedPartitionOfThatToken() + { + var context = CreateContext(RemoteIp); + var token = SetAutomationToken(context, AutomationTokenType.Turnstile, AutomationTokenType.RateLimit); + + var partition = RateLimitPartitions.TryBypass(context); + + await Assert.That(partition).IsNotNull(); + await Assert.That(partition!.Value.PartitionKey).IsEqualTo($"automation-token-{token.Id}"); + await Assert.That(CountPermits(partition.Value, 5000)).IsEqualTo(5000); + } + + [Test] + public async Task Global_RateLimitToken_BypassesTheUserLimit() + { + var context = CreateContext(RemoteIp, Guid.NewGuid()); + var token = SetAutomationToken(context, AutomationTokenType.RateLimit); + + await Assert.That(RateLimitPartitions.Global(context).PartitionKey).IsEqualTo($"automation-token-{token.Id}"); + } + + [Test] + public async Task Global_AnonymousLoopback_IsUnlimited() + { + var partition = RateLimitPartitions.Global(CreateContext(IPAddress.Loopback)); + + await Assert.That(partition.PartitionKey).IsEqualTo("ip-loopback-nolimit"); + await Assert.That(CountPermits(partition, 5000)).IsEqualTo(5000); + } + + [Test] + public async Task Global_AnonymousRemote_IsLimitedPerIp() + { + var partition = RateLimitPartitions.Global(CreateContext(RemoteIp)); + + await Assert.That(partition.PartitionKey).IsEqualTo($"ip-{RemoteIp}"); + await Assert.That(CountPermits(partition, 5000)).IsEqualTo(1000); + } + + [Test] + public async Task Global_User_IsLimitedPerUser() + { + var userId = Guid.NewGuid(); + var partition = RateLimitPartitions.Global(CreateContext(RemoteIp, userId)); + + await Assert.That(partition.PartitionKey).IsEqualTo($"user-{userId}"); + await Assert.That(CountPermits(partition, 5000)).IsEqualTo(120); + } + + [Test] + public async Task Global_Staff_IsLimitedLikeAnyUser() + { + var userId = Guid.NewGuid(); + var partition = RateLimitPartitions.Global(CreateContext(RemoteIp, userId, "Staff")); + + await Assert.That(partition.PartitionKey).IsEqualTo($"user-{userId}"); + } + + [Test] + [Arguments("Admin")] + [Arguments("System")] + public async Task Global_Privileged_IsUnlimited(string role) + { + var partition = RateLimitPartitions.Global(CreateContext(RemoteIp, Guid.NewGuid(), role)); + + await Assert.That(partition.PartitionKey).IsEqualTo("privileged-nolimit"); + await Assert.That(CountPermits(partition, 5000)).IsEqualTo(5000); + } + + [Test] + public async Task Auth_IsLimitedPerIp_EvenForPrivilegedUsers() + { + var partition = RateLimitPartitions.Auth(CreateContext(RemoteIp, Guid.NewGuid(), "Admin")); + + await Assert.That(partition.PartitionKey).IsEqualTo(RemoteIp.ToString()); + await Assert.That(CountPermits(partition, 100)).IsEqualTo(10); + } + + [Test] + public async Task Auth_RateLimitToken_Bypasses() + { + var context = CreateContext(RemoteIp); + var token = SetAutomationToken(context, AutomationTokenType.RateLimit); + + await Assert.That(RateLimitPartitions.Auth(context).PartitionKey).IsEqualTo($"automation-token-{token.Id}"); + } +} diff --git a/Common.Tests/Utils/SignupCodeTests.cs b/Common.Tests/Utils/SignupCodeTests.cs new file mode 100644 index 00000000..b3f714fb --- /dev/null +++ b/Common.Tests/Utils/SignupCodeTests.cs @@ -0,0 +1,53 @@ +using OpenShock.Common.Utils; + +namespace OpenShock.Common.Tests.Utils; + +public sealed class SignupCodeTests +{ + [Test] + public async Task Generate_IsTwoGroupsOfFourUppercaseLettersOrDigits() + { + for (var i = 0; i < 50; i++) + { + await Assert.That(SignupCode.Generate()).Matches("^[A-Z0-9]{4}-[A-Z0-9]{4}$"); + } + } + + // The code is read off a mail and typed in, often on another device: neither the case it is typed in + // nor a left out dash should make it wrong. + [Test] + [Arguments("ABCD-1234", "ABCD-1234")] + [Arguments("abcd-1234", "ABCD-1234")] + [Arguments("ABCD1234", "ABCD-1234")] + [Arguments("abcd1234", "ABCD-1234")] + [Arguments(" aBcD-12x4 ", "ABCD-12X4")] + public async Task TryNormalize_AcceptsCodeAsTyped(string typed, string expected) + { + await Assert.That(SignupCode.TryNormalize(typed, out var code)).IsTrue(); + await Assert.That(code).IsEqualTo(expected); + } + + [Test] + [Arguments(null)] + [Arguments("")] + [Arguments("12")] + [Arguments("ABCD_1234")] + [Arguments("ABC-D1234")] + [Arguments("ABCD-12345")] + [Arguments("ABCD-12!4")] + [Arguments("ABCD--234")] + [Arguments("ÄBCD-1234")] + public async Task TryNormalize_RejectsWhatIsNotACode(string? typed) + { + await Assert.That(SignupCode.TryNormalize(typed, out var code)).IsFalse(); + await Assert.That(code).IsNull(); + } + + [Test] + public async Task Hash_IsBoundToTheSignup() + { + var code = SignupCode.Generate(); + + await Assert.That(SignupCode.Hash(Guid.NewGuid(), code)).IsNotEqualTo(SignupCode.Hash(Guid.NewGuid(), code)); + } +} diff --git a/Common.Tests/Utils/StringUtilsTests.cs b/Common.Tests/Utils/StringUtilsTests.cs index 42220f03..a7a17657 100644 --- a/Common.Tests/Utils/StringUtilsTests.cs +++ b/Common.Tests/Utils/StringUtilsTests.cs @@ -5,67 +5,21 @@ namespace OpenShock.Common.Tests.Utils; public sealed class StringUtilsTests { [Test] - public async Task Truncate_ShorterThanMax_ReturnsOriginal() + [Arguments("hello", 10, "hello")] // shorter than max + [Arguments("hello", 5, "hello")] // exactly max + [Arguments("hello world", 5, "hello")] + [Arguments("hello", 0, "")] + [Arguments("abc\U0001F600", 4, "abc")] // cut inside a surrogate pair drops the whole pair + [Arguments("abc\U0001F600def", 5, "abc\U0001F600")] // cut right after a pair keeps it + public async Task Truncate(string input, int maxLength, string expected) { - var result = "hello".Truncate(10); - await Assert.That(result).IsEqualTo("hello"); - } - - [Test] - public async Task Truncate_ExactLength_ReturnsOriginal() - { - var result = "hello".Truncate(5); - await Assert.That(result).IsEqualTo("hello"); - } - - [Test] - public async Task Truncate_LongerThanMax_Truncates() - { - var result = "hello world".Truncate(5); - await Assert.That(result).IsEqualTo("hello"); - } - - [Test] - public async Task Truncate_EmptyString_ReturnsEmpty() - { - var result = "".Truncate(5); - await Assert.That(result).IsEqualTo(""); - } - - [Test] - public async Task Truncate_MaxZero_ReturnsEmpty() - { - var result = "hello".Truncate(0); - await Assert.That(result).IsEqualTo(""); - } - - [Test] - public async Task Truncate_MaxOne_ReturnsSingleChar() - { - var result = "hello".Truncate(1); - await Assert.That(result).IsEqualTo("h"); - } - - [Test] - public async Task Truncate_CutInsideSurrogatePair_DropsWholePair() - { - var result = "abc😀".Truncate(4); - await Assert.That(result).IsEqualTo("abc"); - } - - [Test] - public async Task Truncate_CutAfterSurrogatePair_KeepsPair() - { - var result = "abc😀def".Truncate(5); - await Assert.That(result).IsEqualTo("abc😀"); + await Assert.That(input.Truncate(maxLength)).IsEqualTo(expected); } [Test] [Arguments("1")] [Arguments("true")] - [Arguments("True")] [Arguments("TRUE")] - [Arguments("yes")] [Arguments("Yes")] [Arguments(" true \t")] public async Task IsTruthy_TruthyValues_ReturnsTrue(string value) @@ -77,11 +31,9 @@ public async Task IsTruthy_TruthyValues_ReturnsTrue(string value) [Arguments(null)] [Arguments("")] [Arguments(" ")] - [Arguments("0")] [Arguments("false")] [Arguments("no")] [Arguments("on")] - [Arguments("2")] [Arguments("11")] [Arguments("truthy")] public async Task IsTruthy_AnythingElse_ReturnsFalse(string? value) diff --git a/Common.Tests/Validation/DataSets/BlackList.txt b/Common.Tests/Validation/DataSets/BlackList.txt deleted file mode 100644 index 399e1e2a..00000000 --- a/Common.Tests/Validation/DataSets/BlackList.txt +++ /dev/null @@ -1,1882 +0,0 @@ -📌 This file contains all characters that should not pass testing. -📌 All lines are tested individually and need to fail the character check for all the tests to pass. -📌 <-- Comments need to be prefixed with an invalid character to make sure the line fails. -📌 Empty lines will be ignored - - -📌 ZeroWidthSpace: -Z​e​r​o​W​i​d​t​h - - -📌 ZalgoText: -T̷̛͎̹͙̞͍̮̭̙̗̫̯͖̜̖̫̝́̿̉̈́̓̀̒̂̈͛̇͂̅́́̂̓̈́͛͜ḩ̵͔̺̲̬̮̤͍̰̣̩̠͑̊͑̆̔̂͗̈͊̀͗͘͘ͅḭ̵̢̡̨̡̺̤̜͈̣͙̟̣̝̣̰̤̥̪̘̮̝̓̈́͗͋̈́͛̂͌̈͐́̏̽̍̽̋̓͐͐͘͝s̴̡̨̡̢̡̛̠͖̲͇̥̳̝͎͍̺̠̜̥̼̞̗̳̜͈̘̬̰̖͕̩̳̘̤̖͓̥͕̬̓̌̐͛̓̍͗̍͛̓̃́̀̊̄̀̈́̿͑̈̎̇͒̔͂̚͜͠͝ ̷̧̧̢̨̭͉͔̘̲̤̣̜̻͉̙̩̦̳̼̺͖̺̳͔̯͉͙͙̞͇̦̥̫̋̇̿͆̓́͛̋̚͜͝ͅͅi̷̢̡̞̘̙̠͔̬̥̫̤͕̙͓͈̼̻͈̟̯̩̫͓͉̣̙̣̺̝̤̳̤͓̭̙̥̜̪̣̝͈̳̤̞̭̳̓́̔̉̈́̄̉̌́͜s̸̡̛̹̰̳̰̘̥̠̳͕̜͖̭͎̹͇͌̽̊͋̎͆̆͆̿̀̂̑̉̄̌̌̾̊̎͋̌̀̉͋̏͘̕͜͝͝͝͝ ̵̨̢̛̬͉̩͓̩̲̖̙͍̙̤͖̏̿̄̿̄̏͋͊̇̍͆̉ͅŗ̸̧̢̛̛̛͓͚͕̳͓͎̝͓͍͎̫̫̙̗̺̰̟͎͈͔̬͍͎̠̝̣̎̐̐́̊̔̊̅̀͂́̅͋͒̉̿̐̀͋͗̌̍́̂̒̐͑͌͛͂́̆̃̍̆͗̓̚͘͜͠͝͝͝ḙ̶̢̧̢̫̟̞̯̰̯̻͇̳͙̼̼̟̙̮̭̜̭̮͙͈̥̤̲̜͈̞̰̭͍͎̝̖̯̖̜͇̪̙̜͍̪͈͇̲͋͆̃̾͑ͅą̴̨̢̢̛̬̘̬̯͍͎͎͓͉̞̬̣͓̟̲̱̞̟͉̞̘̟̙͕͔̋̿̂͛̉̔̀̎̾̊͋̅͑̊͋͋̑̽̈́̽́̉̇͆̓͒̽̅͜͝͝͠͠l̷̨̢̧̹̯̱͚̩͓̗̫̱̩̩̯̬̬̲̖͉̮̠̰͈̫̬̝͖̈̈́̍̅̍̀̈̅̀̏̚͜ͅḽ̶̢͇̙͇̹̯̱̞̭̗̄͋̄͑̄̍͌̊͛̋͌̑̎̎͊̍̿̀̔̓̓̀̾̋̀̄̍̀́́͘͝ÿ̶̡̛̛̜̞̲͈̳̦̪̪̟̤̖̘͖̭̪̱̠̫́́̋͋̑̔͗̎̅͑́͘̚͘͜͝͝ͅ ̴͕̀͒̈̈́͂̽̎͗͐̂̾̕̚͝͝͝b̶̨̢̢̢̛̳̠̮̹̟̥̦̗̫̲͚̼̮͍̞̹̻̩̪̥̣͉̱̖͔̯͉̻̤̦̫͙̻̥̥͎̣̀͋͒̎̈̏̓̈́̈́̎̍̀̑͂́̅͌̓̓̐̓͋͐̈́͐̀̃͛̋̈́̐͋͒̏͆͘͘̚̚͜͠͝a̵̡̡̧̤̺̮̠̹̰͔̦̥͎̳̯͑̅̑̀͑̒̍͆̌͒̈́͆̌̀̃̌͆̄̆̉̓̂̍͂̽̒̽̽̉̎̐́̌̈̊̒́̀̒̐͋͑͠d̶̢̡̨̘͇̹̳̰̦͈̺͈͉̝͔͈͖͈̟̙͕̯̞̰̣̟͈̙̭̬̝͙̭̘͈̻̪̈́̈́͜ ̶̡͕̥̪̱̗̟̲͍̪͍̲̖͉͉̱̻̤͇̩̹̬̱̺̪̓͋̈̈́̑̓͆̈́̎̔̈͊́͌̾̆́̕̚̕͝͝t̷̡͖͓̻̘̟͕̑̒̈́͂̽̽͛̄̾̈̍̾̈́͒̐͊́̇̄͋̏̅̋́͊̔̔̒̅͂̚͝ͅe̴̡̛͚̳̠̰͂̇̏̓̌͛̾̉͑̓͑̐̑͋͛͂͊̅̾̽̀̚̕͘̕͠͝x̸͖͙̥̱̬̣̭͓̺͇̹͈̜̦͎̱̟͎̤̞̘̭̩̦̤̻̫̤͓̳̲̗̼̓̎͂̀͛̍̓́̆̍͑̕͝ţ̵̨̡̡̢̡̡̧̭̥̺̞̞̗̗̮̼̺̖̱̬̳̫̤̦͕͎̩̣̱͈̦̼͙͎̜̳͕̳̣̫̺͚̘̋̀̿̾̒̑̈́́̈̌̔̂͊͂́̔̚̚̚͜͜͝͝ͅͅ ̵̧̨̛̙͖̘͉̻̺͇͈̗̲̙͉̠͕̹͚͓̣̱̩̪̺͖̬̪̬͉̮̪͚̟̪̳̰̫͓̼͍̤͚̤͍̫̅͐̔̈́͂͊̄̄̏͊̾̆͂̽̒̉̎͒́̅̔̏̊̇̓͗͑́͂͌̊̀̓̍̈́̅͐̂̄͌̅̚̕̚̕̚͜͠͠͝t̶̢̢̢̡̺̱̗̼̱̬̙̼͚̭̰͓̰͚̬̱̗̫̻͈̗̝͇͚̬͉̘̮̣̰͙̱̥͎͈̻̻͍̹̮́͒̅̒̈̈̍̀̆̽̑̆̔̾̇̽͋͐͊̒͋̿͒̈́̈̓́͑̆̌͑̚̚͜͜͝͝ͅh̴̡̡̧͕͕̖͈͈̜̞͖̬̝̩͍͍͇͎̖͚̣̠̘̲͓͖͆̔̽̄͂̆̈́̈́̀̏̀͗̈́͌̈́̿̐͆̊̐̈́͊̒̾̃̌̎͐̀͌̀̎̃̃̀̓̅̒̀̓̕̕̕͘̚̚͜͜͜͠͝͠͝ͅą̵̨̧̧̤̗̭̠̝͉̫͈̜͇̣̪͖̼̯̠̺̞̠̫͉͙̮̣̥̼̤̬̗̱̼̪̥̘̩̥̱̬̝̀̋̅̉̂̀͊̆͗̈̽̽̈́̆̓̈́̏̌̇̃̎͗̅̑̿͛̕̚̕͝͝͝ͅͅẗ̷̨̡̛̠̂̾͌͛̓͌̿̃̌̈́̿͑̓̄͐͗́́̒̄̒̾́͆͛͆̚͘͝ ̵̧̡̱͈̙̞̦̱̳̣̆̏̿̆̂͜Ȋ̵̡̢̢̛̮̙̳̱͙̬̻̼͚̺̪͇͖̦̖̯̿̊̔̍̈́͛̉̓̐̈́͗̀͛̔͌̊̀͗́̀͘̚̕̕̚͠͠ ̵̡̡̡̠͖͕̱̼̠͖̝̘̻͓̭̫̮͕̭̪̱̖̣͙̺̭̟̮̬͎͇̖̱̗̪̹͚̖͓͛̂̀̋̔̋͛͒͒̚͠ͅd̶̖͔̲̦̠͈̻̰̤̺̰͉̠̱̯̀̐̏̊́̀̾̾̿̿̈͐͂͊͋͜͝ơ̶̡̫͕͚͙͇̹͖̼̹͍͈͍̣͔̣͍̩̻͖͓͚̞̮̬̫͕̞̹͍͔̞͚̞̻̳̲̼͍̫̮̫͕̲̪̒̓̀̓̓̄͌̓̐̑̏̑̒͐͊̈́̃͋͊̈́̀̆̈́̕͘͘̕͝ͅ ̶̢̙̼̳̩͉̠̮͊͐͛͂̽̔̈͆̀͋̓̂̉̈̀̆̈̿̀̑̽͐̈́͐̇̀͛̏̈̃́͂͑͗̈́͊̋̌̊̂̅̚̕̚͜͝͠n̵̨̡̡̨͓̻̲̹̯͓̞̺͚̭͉̪̼͍̮̙̭̱̭̼̗̹͓̠͉̥͕̦̘̠̼̲̏̈́̓̃̊̐̒͛͂͐̏̈͒̋͗̃͌̌̌̑́̈́̔̎̇̀̓̈̎̈͑̒̀̅͂̊̐͐́̋̚̚͘͜͜͜͝͠͠͠͠ǫ̸̧͍͎̘͇͈̙̗̹͖̯͍̺͕͍̣̭̪̙̠̻̼̹͓̣̤̺̪̺̌̾̓̈́͗̈́̌͗̽̿́͋̌͋̄̃̓͛̊́̾̃̑͌̊̎̊̐̊̓̔̈͛͑̕̚͘͘͘͝͠͠͝͝͝͝ͅt̵̞̦͓͎̦̮̼͈̭͒̓̃̃̂͐̒̉͗̊̽̈̒͐͌̊̒̾͆͒͂̓̃̕ͅ ̸̧̧̧̨̨͉͖̭̰̗͚̪͖͖͇̱̞̜͙̻̠̖̞̫͔͓͉̩̺̞̘̤͔̭̗̰̬̩͇̖̬͓̥͕̗̟̦͗͂̆̽̑̇̀̀͂̒͊̑͘̚͜ͅw̶̧̢̛̰̹̩͚̹͎̹͉̖̻̣͖͎͛̉̇̇̎͛̑́̍́̊̿̋̾͂̿ͅa̴̛̦͇̐̏̎̈́͂̆͐̑̇̃͗̊̎̈́̆̾̈́̈́͆͂̀̆͗͘̕ṅ̷̢̡̧̢̛͎̝̬͇̗̫̙̼̙̰͇͕̪͙̣̤͉̣̺̣̹͔̖̥͙͖̻̈́̐̆̓̆͑̎̒̇̄͘͜͝ͅt̶̢͇͍͉̬̝̠̰̮̟̖͉̠̪̘͖͇͉̘̤̤͚̼̳̥̹͑̎̂̄͋̃̄̌̊̂̓͝ ̴̨̨̧̢̛̛̛̤̩͍̳͎̮̘͙̙̻̻̳͈̦̞̬̯̘͖͙̻̮̟͉̼̜͓̬̝̗͕͈̳̦͓̯̽̌̑̅̈́̒͒̈́̑̂̊̍́͛̈̔͋͑̍̏̏͒̅̂̌̐̇̾̅̏́͂̈͌̚̕̕͠͝͠͝͠͝í̶̧̧̨̡̢͖͎̪̣̺̦͎̦̲̱̗̮͈̭̘͇͚͓̪̤̠͕̺̮̹̬̪̝̲̠̝̠͔̠̟͕͍̫̼̺͖ͅͅͅņ̷̨̨̢̨̺͚̤̟̠̠̦͕̹̦͚͙̬̪̘̱̳͈̹̩̜̪̫̘͚͕̠͔͕̋̌̔̆̇̕͜͜͜ş̷̨̢̢̨̛̛̼̜̯̖̙̞̪̞̰̩̼͖̫̳͈̗̟̃́̄̈́̀͛̀̌̇̀̈̈́̑̒̉̓͒́̀̇̇̕̕͝͝͝͝į̵̢̥̝̞̗̬͚̲̪̤̝̘͓̞͙̗͓͍̼͕̖̗̙͇͔̹̼̜̳̞̫̥̭̞̺͖̩̝̰̙̘̩͙̹̈̋́͒͂͜d̵̡̧̨̧̛̲͙̣̳̯̮̣̟̪̫̭̹̬̜̥̘̱͖̪͖͔̻͕̲̰̩̭̗̒̅͐̾͛̉̾͋̍̄̑̆̑̎̀̌́̿̅̓͆͊̽̄̽̈́̆̑̏̆͛̅̏̓̋̕̚̕̚̚̕̕͠ͅė̴̡̨̠͇͎͔͔̠̯͔̖̱̹͐̋̔͐̍̀̾̀̿̄́̀̄̅̋̂ ̵̢̢̧̛̛͙͚̘͓͓̝̻̞͙̮̯̭̲̝̥̬̪̹̦̞̠̣̭̣͈̈́͌̍͗̑̀̒͒̽̇͐̀͗̐̋̽͐̏̅̎̏̃͒͂͒̑͂̔̑͌͆͘̕̕̕͜͜ͅơ̷̧̧̨̼͓̥͎͔̫͖͇̜̰͓̘̱͙̥̭͕̹̗͇͇̤̼̥̣̖̳̤̝̘̈́̓̂̇͋̎̀͂̒͂̓̎̎̌̅̀̃̐̓̓̈́̆͋̓̽͒͆̊̔̒̇͑̚̚̕̕͠f̴̡̨̛̫̱̜̭̦̯͚̖͍͇͈̪̤̲̟̺͔̤̺͍̫̲̬͎̹̲̻̝͍̥͙͚͖̱͉̦̤̤̈̔͊́͐́̅̀̍̓͊͂́́̉̀̈́̽̎̔̃̓͐͘͜͠͝ ̴̡̧̢̢̜̳̣͎͔͉͔̰̟̬̖̲͔̘͕̙͙͈̺͇̪̝̞̫̼̲̣͇̈́̽̓͗͌͆͂̍̈́̊̏̍̄̓͆́̂̽͑͌̑́͜͠ͅZ̷̨̢̛̠͈̦̳͔̟̟̼͔͕̹̝̠͎͎̺̞̝̀̽́̇̂̃̑́͒͑͋̏̾̿͂̋̀̀̍͆̕̕̕͝͠͝͠ȁ̶̛̛̦̤̭̙̬̌̈́́̉͌͂̅͋͂́̽̀͆͝p̶̨̨͉̞̦̾̎͒̅̉͑̅͂̊͗͛̎̓͂͐̚͝M̷̨̢̨̡̛͕̗̙̻͔͎̱͇̠͎̬̲͚͓͈͕̼̹̘͔̝̩͇͚̗̼̱̯̟̰̓͑̃̂̅̍̅̐́̐̈́̀̈́̓̀̾̀̈́͗͒͗͆͛͂̎̚̕͝͝͝ͅę̸̢̨̣̰̮̝͖̰̲̰̥̲͙͕̼̝͕̙̖̥̦̮̝̹̜̬͈̺̤̤̮̭͓̞͖̗͍͓̗̜͖̯̲̥̟̒̈́̈́̽̆͛͋̓̀̈́̄̉͑̅̈́͒̏̐͊̏͒̃̔̏̉͛̍̊́̇̋̂͛̎͗͑̆̾͘̚͝͝͝͠͝ͅͅͅ - - -📌 Emojis: -😀 -😃 -😄 -😁 -😆 -😅 -🤣 -😂 -🙂 -🙃 -🫠 -😉 -😊 -😇 -🥰 -😍 -🤩 -😘 -😗 -☺ -😚 -😙 -🥲 -😋 -😛 -😜 -🤪 -😝 -🤑 -🤗 -🤭 -🫢 -🫣 -🤫 -🤔 -🫡 -🤐 -🤨 -😐 -😑 -😶 -🫥 -😶‍🌫️ -😏 -😒 -🙄 -😬 -😮‍💨 -🤥 -🫨 -😌 -😔 -😪 -🤤 -😴 -😷 -🤒 -🤕 -🤢 -🤮 -🤧 -🥵 -🥶 -🥴 -😵 -😵‍💫 -🤯 -🤠 -🥳 -🥸 -😎 -🤓 -🧐 -😕 -🫤 -😟 -🙁 -☹ -😮 -😯 -😲 -😳 -🥺 -🥹 -😦 -😧 -😨 -😰 -😥 -😢 -😭 -😱 -😖 -😣 -😞 -😓 -😩 -😫 -🥱 -😤 -😡 -😠 -🤬 -😈 -👿 -💀 -☠ -💩 -🤡 -👹 -👺 -👻 -👽 -👾 -🤖 -😺 -😸 -😹 -😻 -😼 -😽 -🙀 -😿 -😾 -🙈 -🙉 -🙊 -💌 -💘 -💝 -💖 -💗 -💓 -💞 -💕 -💟 -❣ -💔 -❤️‍🔥 -❤️‍🩹 -❤ -🩷 -🧡 -💛 -💚 -💙 -🩵 -💜 -🤎 -🖤 -🩶 -🤍 -💋 -💯 -💢 -💥 -💫 -💦 -💨 -🕳 -💬 -👁️‍🗨️ -🗨 -🗯 -💭 -💤 -👋 -🤚 -🖐 -✋ -🖖 -🫱 -🫲 -🫳 -🫴 -🫷 -🫸 -👌 -🤌 -🤏 -✌ -🤞 -🫰 -🤟 -🤘 -🤙 -👈 -👉 -👆 -🖕 -👇 -☝ -🫵 -👍 -👎 -✊ -👊 -🤛 -🤜 -👏 -🙌 -🫶 -👐 -🤲 -🤝 -🙏 -✍ -💅 -🤳 -💪 -🦾 -🦿 -🦵 -🦶 -👂 -🦻 -👃 -🧠 -🫀 -🫁 -🦷 -🦴 -👀 -👁 -👅 -👄 -🫦 -👶 -🧒 -👦 -👧 -🧑 -👱 -👨 -🧔 -🧔‍♂️ -🧔‍♀️ -👨‍🦰 -👨‍🦱 -👨‍🦳 -👨‍🦲 -👩 -👩‍🦰 -🧑‍🦰 -👩‍🦱 -🧑‍🦱 -👩‍🦳 -🧑‍🦳 -👩‍🦲 -🧑‍🦲 -👱‍♀️ -👱‍♂️ -🧓 -👴 -👵 -🙍 -🙍‍♂️ -🙍‍♀️ -🙎 -🙎‍♂️ -🙎‍♀️ -🙅 -🙅‍♂️ -🙅‍♀️ -🙆 -🙆‍♂️ -🙆‍♀️ -💁 -💁‍♂️ -💁‍♀️ -🙋 -🙋‍♂️ -🙋‍♀️ -🧏 -🧏‍♂️ -🧏‍♀️ -🙇 -🙇‍♂️ -🙇‍♀️ -🤦 -🤦‍♂️ -🤦‍♀️ -🤷 -🤷‍♂️ -🤷‍♀️ -🧑‍⚕️ -👨‍⚕️ -👩‍⚕️ -🧑‍🎓 -👨‍🎓 -👩‍🎓 -🧑‍🏫 -👨‍🏫 -👩‍🏫 -🧑‍⚖️ -👨‍⚖️ -👩‍⚖️ -🧑‍🌾 -👨‍🌾 -👩‍🌾 -🧑‍🍳 -👨‍🍳 -👩‍🍳 -🧑‍🔧 -👨‍🔧 -👩‍🔧 -🧑‍🏭 -👨‍🏭 -👩‍🏭 -🧑‍💼 -👨‍💼 -👩‍💼 -🧑‍🔬 -👨‍🔬 -👩‍🔬 -🧑‍💻 -👨‍💻 -👩‍💻 -🧑‍🎤 -👨‍🎤 -👩‍🎤 -🧑‍🎨 -👨‍🎨 -👩‍🎨 -🧑‍✈️ -👨‍✈️ -👩‍✈️ -🧑‍🚀 -👨‍🚀 -👩‍🚀 -🧑‍🚒 -👨‍🚒 -👩‍🚒 -👮 -👮‍♂️ -👮‍♀️ -🕵 -🕵️‍♂️ -🕵️‍♀️ -💂 -💂‍♂️ -💂‍♀️ -🥷 -👷 -👷‍♂️ -👷‍♀️ -🫅 -🤴 -👸 -👳 -👳‍♂️ -👳‍♀️ -👲 -🧕 -🤵 -🤵‍♂️ -🤵‍♀️ -👰 -👰‍♂️ -👰‍♀️ -🤰 -🫃 -🫄 -🤱 -👩‍🍼 -👨‍🍼 -🧑‍🍼 -👼 -🎅 -🤶 -🧑‍🎄 -🦸 -🦸‍♂️ -🦸‍♀️ -🦹 -🦹‍♂️ -🦹‍♀️ -🧙 -🧙‍♂️ -🧙‍♀️ -🧚 -🧚‍♂️ -🧚‍♀️ -🧛 -🧛‍♂️ -🧛‍♀️ -🧜 -🧜‍♂️ -🧜‍♀️ -🧝 -🧝‍♂️ -🧝‍♀️ -🧞 -🧞‍♂️ -🧞‍♀️ -🧟 -🧟‍♂️ -🧟‍♀️ -🧌 -💆 -💆‍♂️ -💆‍♀️ -💇 -💇‍♂️ -💇‍♀️ -🚶 -🚶‍♂️ -🚶‍♀️ -🧍 -🧍‍♂️ -🧍‍♀️ -🧎 -🧎‍♂️ -🧎‍♀️ -🧑‍🦯 -👨‍🦯 -👩‍🦯 -🧑‍🦼 -👨‍🦼 -👩‍🦼 -🧑‍🦽 -👨‍🦽 -👩‍🦽 -🏃 -🏃‍♂️ -🏃‍♀️ -💃 -🕺 -🕴 -👯 -👯‍♂️ -👯‍♀️ -🧖 -🧖‍♂️ -🧖‍♀️ -🧗 -🧗‍♂️ -🧗‍♀️ -🤺 -🏇 -⛷ -🏂 -🏌 -🏌️‍♂️ -🏌️‍♀️ -🏄 -🏄‍♂️ -🏄‍♀️ -🚣 -🚣‍♂️ -🚣‍♀️ -🏊 -🏊‍♂️ -🏊‍♀️ -⛹ -⛹️‍♂️ -⛹️‍♀️ -🏋 -🏋️‍♂️ -🏋️‍♀️ -🚴 -🚴‍♂️ -🚴‍♀️ -🚵 -🚵‍♂️ -🚵‍♀️ -🤸 -🤸‍♂️ -🤸‍♀️ -🤼 -🤼‍♂️ -🤼‍♀️ -🤽 -🤽‍♂️ -🤽‍♀️ -🤾 -🤾‍♂️ -🤾‍♀️ -🤹 -🤹‍♂️ -🤹‍♀️ -🧘 -🧘‍♂️ -🧘‍♀️ -🛀 -🛌 -🧑‍🤝‍🧑 -👭 -👫 -👬 -💏 -👩‍❤️‍💋‍👨 -👨‍❤️‍💋‍👨 -👩‍❤️‍💋‍👩 -💑 -👩‍❤️‍👨 -👨‍❤️‍👨 -👩‍❤️‍👩 -👪 -👨‍👩‍👦 -👨‍👩‍👧 -👨‍👩‍👧‍👦 -👨‍👩‍👦‍👦 -👨‍👩‍👧‍👧 -👨‍👨‍👦 -👨‍👨‍👧 -👨‍👨‍👧‍👦 -👨‍👨‍👦‍👦 -👨‍👨‍👧‍👧 -👩‍👩‍👦 -👩‍👩‍👧 -👩‍👩‍👧‍👦 -👩‍👩‍👦‍👦 -👩‍👩‍👧‍👧 -👨‍👦 -👨‍👦‍👦 -👨‍👧 -👨‍👧‍👦 -👨‍👧‍👧 -👩‍👦 -👩‍👦‍👦 -👩‍👧 -👩‍👧‍👦 -👩‍👧‍👧 -🗣 -👤 -👥 -🫂 -👣 -🦰 -🦱 -🦳 -🦲 -🐵 -🐒 -🦍 -🦧 -🐶 -🐕 -🦮 -🐕‍🦺 -🐩 -🐺 -🦊 -🦝 -🐱 -🐈 -🐈‍⬛ -🦁 -🐯 -🐅 -🐆 -🐴 -🫎 -🫏 -🐎 -🦄 -🦓 -🦌 -🦬 -🐮 -🐂 -🐃 -🐄 -🐷 -🐖 -🐗 -🐽 -🐏 -🐑 -🐐 -🐪 -🐫 -🦙 -🦒 -🐘 -🦣 -🦏 -🦛 -🐭 -🐁 -🐀 -🐹 -🐰 -🐇 -🐿 -🦫 -🦔 -🦇 -🐻 -🐻‍❄️ -🐨 -🐼 -🦥 -🦦 -🦨 -🦘 -🦡 -🐾 -🦃 -🐔 -🐓 -🐣 -🐤 -🐥 -🐦 -🐧 -🕊 -🦅 -🦆 -🦢 -🦉 -🦤 -🪶 -🦩 -🦚 -🦜 -🪽 -🐦‍⬛ -🪿 -🐸 -🐊 -🐢 -🦎 -🐍 -🐲 -🐉 -🦕 -🦖 -🐳 -🐋 -🐬 -🦭 -🐟 -🐠 -🐡 -🦈 -🐙 -🐚 -🪸 -🪼 -🐌 -🦋 -🐛 -🐜 -🐝 -🪲 -🐞 -🦗 -🪳 -🕷 -🕸 -🦂 -🦟 -🪰 -🪱 -🦠 -💐 -🌸 -💮 -🪷 -🏵 -🌹 -🥀 -🌺 -🌻 -🌼 -🌷 -🪻 -🌱 -🪴 -🌲 -🌳 -🌴 -🌵 -🌾 -🌿 -☘ -🍀 -🍁 -🍂 -🍃 -🪹 -🪺 -🍄 -🍇 -🍈 -🍉 -🍊 -🍋 -🍌 -🍍 -🥭 -🍎 -🍏 -🍐 -🍑 -🍒 -🍓 -🫐 -🥝 -🍅 -🫒 -🥥 -🥑 -🍆 -🥔 -🥕 -🌽 -🌶 -🫑 -🥒 -🥬 -🥦 -🧄 -🧅 -🥜 -🫘 -🌰 -🫚 -🫛 -🍞 -🥐 -🥖 -🫓 -🥨 -🥯 -🥞 -🧇 -🧀 -🍖 -🍗 -🥩 -🥓 -🍔 -🍟 -🍕 -🌭 -🥪 -🌮 -🌯 -🫔 -🥙 -🧆 -🥚 -🍳 -🥘 -🍲 -🫕 -🥣 -🥗 -🍿 -🧈 -🧂 -🥫 -🍱 -🍘 -🍙 -🍚 -🍛 -🍜 -🍝 -🍠 -🍢 -🍣 -🍤 -🍥 -🥮 -🍡 -🥟 -🥠 -🥡 -🦀 -🦞 -🦐 -🦑 -🦪 -🍦 -🍧 -🍨 -🍩 -🍪 -🎂 -🍰 -🧁 -🥧 -🍫 -🍬 -🍭 -🍮 -🍯 -🍼 -🥛 -☕ -🫖 -🍵 -🍶 -🍾 -🍷 -🍸 -🍹 -🍺 -🍻 -🥂 -🥃 -🫗 -🥤 -🧋 -🧃 -🧉 -🧊 -🥢 -🍽 -🍴 -🥄 -🔪 -🫙 -🏺 -🌍 -🌎 -🌏 -🌐 -🗺 -🗾 -🧭 -🏔 -⛰ -🌋 -🗻 -🏕 -🏖 -🏜 -🏝 -🏞 -🏟 -🏛 -🏗 -🧱 -🪨 -🪵 -🛖 -🏘 -🏚 -🏠 -🏡 -🏢 -🏣 -🏤 -🏥 -🏦 -🏨 -🏩 -🏪 -🏫 -🏬 -🏭 -🏯 -🏰 -💒 -🗼 -🗽 -⛪ -🕌 -🛕 -🕍 -⛩ -🕋 -⛲ -⛺ -🌁 -🌃 -🏙 -🌄 -🌅 -🌆 -🌇 -🌉 -♨ -🎠 -🛝 -🎡 -🎢 -💈 -🎪 -🚂 -🚃 -🚄 -🚅 -🚆 -🚇 -🚈 -🚉 -🚊 -🚝 -🚞 -🚋 -🚌 -🚍 -🚎 -🚐 -🚑 -🚒 -🚓 -🚔 -🚕 -🚖 -🚗 -🚘 -🚙 -🛻 -🚚 -🚛 -🚜 -🏎 -🏍 -🛵 -🦽 -🦼 -🛺 -🚲 -🛴 -🛹 -🛼 -🚏 -🛣 -🛤 -🛢 -⛽ -🛞 -🚨 -🚥 -🚦 -🛑 -🚧 -⚓ -🛟 -⛵ -🛶 -🚤 -🛳 -⛴ -🛥 -🚢 -✈ -🛩 -🛫 -🛬 -🪂 -💺 -🚁 -🚟 -🚠 -🚡 -🛰 -🚀 -🛸 -🛎 -🧳 -⌛ -⏳ -⌚ -⏰ -⏱ -⏲ -🕰 -🕛 -🕧 -🕐 -🕜 -🕑 -🕝 -🕒 -🕞 -🕓 -🕟 -🕔 -🕠 -🕕 -🕡 -🕖 -🕢 -🕗 -🕣 -🕘 -🕤 -🕙 -🕥 -🕚 -🕦 -🌑 -🌒 -🌓 -🌔 -🌕 -🌖 -🌗 -🌘 -🌙 -🌚 -🌛 -🌜 -🌡 -☀ -🌝 -🌞 -🪐 -⭐ -🌟 -🌠 -🌌 -☁ -⛅ -⛈ -🌤 -🌥 -🌦 -🌧 -🌨 -🌩 -🌪 -🌫 -🌬 -🌀 -🌈 -🌂 -☂ -☔ -⛱ -⚡ -❄ -☃ -⛄ -☄ -🔥 -💧 -🌊 -🎃 -🎄 -🎆 -🎇 -🧨 -✨ -🎈 -🎉 -🎊 -🎋 -🎍 -🎎 -🎏 -🎐 -🎑 -🧧 -🎀 -🎁 -🎗 -🎟 -🎫 -🎖 -🏆 -🏅 -🥇 -🥈 -🥉 -⚽ -⚾ -🥎 -🏀 -🏐 -🏈 -🏉 -🎾 -🥏 -🎳 -🏏 -🏑 -🏒 -🥍 -🏓 -🏸 -🥊 -🥋 -🥅 -⛳ -⛸ -🎣 -🤿 -🎽 -🎿 -🛷 -🥌 -🎯 -🪀 -🪁 -🔫 -🎱 -🔮 -🪄 -🎮 -🕹 -🎰 -🎲 -🧩 -🧸 -🪅 -🪩 -🪆 -♠ -♥ -♦ -♣ -♟ -🃏 -🀄 -🎴 -🎭 -🖼 -🎨 -🧵 -🪡 -🧶 -🪢 -👓 -🕶 -🥽 -🥼 -🦺 -👔 -👕 -👖 -🧣 -🧤 -🧥 -🧦 -👗 -👘 -🥻 -🩱 -🩲 -🩳 -👙 -👚 -🪭 -👛 -👜 -👝 -🛍 -🎒 -🩴 -👞 -👟 -🥾 -🥿 -👠 -👡 -🩰 -👢 -🪮 -👑 -👒 -🎩 -🎓 -🧢 -🪖 -⛑ -📿 -💄 -💍 -💎 -🔇 -🔈 -🔉 -🔊 -📢 -📣 -📯 -🔔 -🔕 -🎼 -🎵 -🎶 -🎙 -🎚 -🎛 -🎤 -🎧 -📻 -🎷 -🪗 -🎸 -🎹 -🎺 -🎻 -🪕 -🥁 -🪘 -🪇 -🪈 -📱 -📲 -☎ -📞 -📟 -📠 -🔋 -🪫 -🔌 -💻 -🖥 -🖨 -⌨ -🖱 -🖲 -💽 -💾 -💿 -📀 -🧮 -🎥 -🎞 -📽 -🎬 -📺 -📷 -📸 -📹 -📼 -🔍 -🔎 -🕯 -💡 -🔦 -🏮 -🪔 -📔 -📕 -📖 -📗 -📘 -📙 -📚 -📓 -📒 -📃 -📜 -📄 -📰 -🗞 -📑 -🔖 -🏷 -💰 -🪙 -💴 -💵 -💶 -💷 -💸 -💳 -🧾 -💹 -✉ -📧 -📨 -📩 -📤 -📥 -📦 -📫 -📪 -📬 -📭 -📮 -🗳 -✏ -✒ -🖋 -🖊 -🖌 -🖍 -📝 -💼 -📁 -📂 -🗂 -📅 -📆 -🗒 -🗓 -📇 -📈 -📉 -📊 -📋 -📌 -📍 -📎 -🖇 -📏 -📐 -✂ -🗃 -🗄 -🗑 -🔒 -🔓 -🔏 -🔐 -🔑 -🗝 -🔨 -🪓 -⛏ -⚒ -🛠 -🗡 -⚔ -💣 -🪃 -🏹 -🛡 -🪚 -🔧 -🪛 -🔩 -⚙ -🗜 -⚖ -🦯 -🔗 -⛓ -🪝 -🧰 -🧲 -🪜 -⚗ -🧪 -🧫 -🧬 -🔬 -🔭 -📡 -💉 -🩸 -💊 -🩹 -🩼 -🩺 -🩻 -🚪 -🛗 -🪞 -🪟 -🛏 -🛋 -🪑 -🚽 -🪠 -🚿 -🛁 -🪤 -🪒 -🧴 -🧷 -🧹 -🧺 -🧻 -🪣 -🧼 -🫧 -🪥 -🧽 -🧯 -🛒 -🚬 -⚰ -🪦 -⚱ -🧿 -🪬 -🗿 -🪧 -🪪 -🏧 -🚮 -🚰 -♿ -🚹 -🚺 -🚻 -🚼 -🚾 -🛂 -🛃 -🛄 -🛅 -⚠ -🚸 -⛔ -🚫 -🚳 -🚭 -🚯 -🚱 -🚷 -📵 -🔞 -☢ -☣ -⬆ -↗ -➡ -↘ -⬇ -↙ -⬅ -↖ -↕ -↔ -↩ -↪ -⤴ -⤵ -🔃 -🔄 -🔙 -🔚 -🔛 -🔜 -🔝 -🛐 -⚛ -🕉 -✡ -☸ -☯ -✝ -☦ -☪ -☮ -🕎 -🔯 -🪯 -♈ -♉ -♊ -♋ -♌ -♍ -♎ -♏ -♐ -♑ -♒ -♓ -⛎ -🔀 -🔁 -🔂 -▶ -⏩ -⏭ -⏯ -◀ -⏪ -⏮ -🔼 -⏫ -🔽 -⏬ -⏸ -⏹ -⏺ -⏏ -🎦 -🔅 -🔆 -📶 -🛜 -📳 -📴 -♀ -♂ -⚧ -✖ -➕ -➖ -➗ -🟰 -♾ -‼ -⁉ -❓ -❔ -❕ -❗ -💱 -💲 -⚕ -♻ -⚜ -🔱 -📛 -🔰 -⭕ -✅ -☑ -✔ -❌ -❎ -➰ -➿ -✳ -✴ -❇ -#️⃣ -*️⃣ -0️⃣ -1️⃣ -2️⃣ -3️⃣ -4️⃣ -5️⃣ -6️⃣ -7️⃣ -8️⃣ -9️⃣ -🔟 -🔠 -🔡 -🔢 -🔣 -🔤 -🅰 -🆎 -🅱 -🆑 -🆒 -🆓 -ℹ -🆔 -Ⓜ -🆕 -🆖 -🅾 -🆗 -🅿 -🆘 -🆙 -🆚 -🈁 -🈂 -🈷 -🈶 -🈯 -🉐 -🈹 -🈚 -🈲 -🉑 -🈸 -🈴 -🈳 -🈺 -🈵 -🔴 -🟠 -🟡 -🟢 -🔵 -🟣 -🟤 -⚫ -⚪ -🟥 -🟧 -🟨 -🟩 -🟦 -🟪 -🟫 -⬛ -⬜ -◼ -◻ -◾ -◽ -▪ -▫ -🔶 -🔷 -🔸 -🔹 -🔺 -🔻 -💠 -🔘 -🔳 -🔲 -🏁 -🚩 -🎌 -🏴 -🏳 -🏳️‍🌈 -🏳️‍⚧️ -🏴‍☠️ -🇦🇨 -🇦🇩 -🇦🇪 -🇦🇫 -🇦🇬 -🇦🇮 -🇦🇱 -🇦🇲 -🇦🇴 -🇦🇶 -🇦🇷 -🇦🇸 -🇦🇹 -🇦🇺 -🇦🇼 -🇦🇽 -🇦🇿 -🇧🇦 -🇧🇧 -🇧🇩 -🇧🇪 -🇧🇫 -🇧🇬 -🇧🇭 -🇧🇮 -🇧🇯 -🇧🇱 -🇧🇲 -🇧🇳 -🇧🇴 -🇧🇶 -🇧🇷 -🇧🇸 -🇧🇹 -🇧🇻 -🇧🇼 -🇧🇾 -🇧🇿 -🇨🇦 -🇨🇨 -🇨🇩 -🇨🇫 -🇨🇬 -🇨🇭 -🇨🇮 -🇨🇰 -🇨🇱 -🇨🇲 -🇨🇳 -🇨🇴 -🇨🇵 -🇨🇷 -🇨🇺 -🇨🇻 -🇨🇼 -🇨🇽 -🇨🇾 -🇨🇿 -🇩🇪 -🇩🇬 -🇩🇯 -🇩🇰 -🇩🇲 -🇩🇴 -🇩🇿 -🇪🇦 -🇪🇨 -🇪🇪 -🇪🇬 -🇪🇭 -🇪🇷 -🇪🇸 -🇪🇹 -🇪🇺 -🇫🇮 -🇫🇯 -🇫🇰 -🇫🇲 -🇫🇴 -🇫🇷 -🇬🇦 -🇬🇧 -🇬🇩 -🇬🇪 -🇬🇫 -🇬🇬 -🇬🇭 -🇬🇮 -🇬🇱 -🇬🇲 -🇬🇳 -🇬🇵 -🇬🇶 -🇬🇷 -🇬🇸 -🇬🇹 -🇬🇺 -🇬🇼 -🇬🇾 -🇭🇰 -🇭🇲 -🇭🇳 -🇭🇷 -🇭🇹 -🇭🇺 -🇮🇨 -🇮🇩 -🇮🇪 -🇮🇱 -🇮🇲 -🇮🇳 -🇮🇴 -🇮🇶 -🇮🇷 -🇮🇸 -🇮🇹 -🇯🇪 -🇯🇲 -🇯🇴 -🇯🇵 -🇰🇪 -🇰🇬 -🇰🇭 -🇰🇮 -🇰🇲 -🇰🇳 -🇰🇵 -🇰🇷 -🇰🇼 -🇰🇾 -🇰🇿 -🇱🇦 -🇱🇧 -🇱🇨 -🇱🇮 -🇱🇰 -🇱🇷 -🇱🇸 -🇱🇹 -🇱🇺 -🇱🇻 -🇱🇾 -🇲🇦 -🇲🇨 -🇲🇩 -🇲🇪 -🇲🇫 -🇲🇬 -🇲🇭 -🇲🇰 -🇲🇱 -🇲🇲 -🇲🇳 -🇲🇴 -🇲🇵 -🇲🇶 -🇲🇷 -🇲🇸 -🇲🇹 -🇲🇺 -🇲🇻 -🇲🇼 -🇲🇽 -🇲🇾 -🇲🇿 -🇳🇦 -🇳🇨 -🇳🇪 -🇳🇫 -🇳🇬 -🇳🇮 -🇳🇱 -🇳🇴 -🇳🇵 -🇳🇷 -🇳🇺 -🇳🇿 -🇴🇲 -🇵🇦 -🇵🇪 -🇵🇫 -🇵🇬 -🇵🇭 -🇵🇰 -🇵🇱 -🇵🇲 -🇵🇳 -🇵🇷 -🇵🇸 -🇵🇹 -🇵🇼 -🇵🇾 -🇶🇦 -🇷🇪 -🇷🇴 -🇷🇸 -🇷🇺 -🇷🇼 -🇸🇦 -🇸🇧 -🇸🇨 -🇸🇩 -🇸🇪 -🇸🇬 -🇸🇭 -🇸🇮 -🇸🇯 -🇸🇰 -🇸🇱 -🇸🇲 -🇸🇳 -🇸🇴 -🇸🇷 -🇸🇸 -🇸🇹 -🇸🇻 -🇸🇽 -🇸🇾 -🇸🇿 -🇹🇦 -🇹🇨 -🇹🇩 -🇹🇫 -🇹🇬 -🇹🇭 -🇹🇯 -🇹🇰 -🇹🇱 -🇹🇲 -🇹🇳 -🇹🇴 -🇹🇷 -🇹🇹 -🇹🇻 -🇹🇼 -🇹🇿 -🇺🇦 -🇺🇬 -🇺🇲 -🇺🇳 -🇺🇸 -🇺🇾 -🇺🇿 -🇻🇦 -🇻🇨 -🇻🇪 -🇻🇬 -🇻🇮 -🇻🇳 -🇻🇺 -🇼🇫 -🇼🇸 -🇽🇰 -🇾🇪 -🇾🇹 -🇿🇦 -🇿🇲 -🇿🇼 -🏴󠁧󠁢󠁥󠁮󠁧󠁿 -🏴󠁧󠁢󠁳󠁣󠁴󠁿 -🏴󠁧󠁢󠁷󠁬󠁳󠁿 \ No newline at end of file diff --git a/Common.Tests/Validation/DataSets/WhiteList.txt b/Common.Tests/Validation/DataSets/WhiteList.txt deleted file mode 100644 index 0c130e14..00000000 --- a/Common.Tests/Validation/DataSets/WhiteList.txt +++ /dev/null @@ -1,482 +0,0 @@ -This file contains a collection of text used for testing, - -Some of this text has been generated using ChatGPT, a language model developed by OpenAI. - -If you have any concern or would like to change the example text, please create an issue on the GitHub repository. - -################# -## Lorem Ipsum ## -################# - -Lorem ipsum dolor sit amet, ex vis stet rationibus, probo minimum et nam, nec suas posse ea. Ex temporibus conclusionemque mea, cu movet dolorum voluptaria est. Te nam clita oratio dissentiet. Eos legere vulputate dissentiunt te. Id feugait ponderum voluptaria vix, eu tempor ceteros ius, no mel eirmod detracto postulant. - -Ne error deterruisset duo, enim munere eirmod te usu, mei ad esse definitionem. Ius cibo augue consulatu ad. Nam et vituperata scriptorem, propriae erroribus ex vim. Sea et vide deleniti, latine nostrum pri ex, hinc magna definiebas an pro. - -Atqui soleat postulant an cum. Nec ne justo consequat complectitur, ad nec illud mollis ancillae. Meis nonumy mel ea. Cu utamur vituperatoribus eam, mazim dictas ornatus in eum. Vis at quodsi bonorum, id sit mucius scriptorem. - -Nam ignota iisque te. Usu adhuc iuvaret iracundia ex, impedit denique voluptaria mei at, posse labore scripta in sea. Populo molestiae abhorreant ad eos, eu vocibus albucius mel. Facer suscipit oportere sea et. - -Cu duo purto labore scripta. Per civibus elaboraret ex, nec aliquid volumus philosophia no, ne mei choro numquam. Vim eu liberavisse delicatissimi. Has ut option accusam aliquando, ad cum diam tincidunt. - -Ut qui etiam volumus laboramus, mea te solet labitur scripserit. Ut vim malis iusto putant, duo et congue nostrum inimicus, eu his dicat noluisse appellantur. Et quo solum mentitum omittantur, et has wisi mediocritatem, clita euripidis mel ne. Solum solet semper sit ex, summo timeam expetendis sed no. Mollis honestatis ne usu, purto accusamus philosophia duo ut. - -Et his assum graeci volutpat, detracto epicurei referrentur id duo, dico mucius ius ea. Eu mei tractatos repudiare, est nonumy ornatus interesset eu. Te quot accusam senserit his, recusabo qualisque percipitur mei te, utinam utamur pericula mei ne. Quo et debet fastidii, dico qualisque an eos. - -Eos ea movet tollit, quodsi omittam instructior nec te, iisque partiendo disputationi eam ea. Bonorum propriae platonem ea mea. Quod causae voluptaria his te, mutat noluisse appetere eu eum. Quo ex deleniti complectitur. Ea paulo probatus petentium vix. - -Cum lorem appetere erroribus eu. Ut aperiri voluptaria delicatissimi duo. Pri no nullam explicari, ex vel facilisi assentior gloriatur. Pro tollit commune cu, vix ei dissentias dissentiunt. - -Usu postea ornatus suscipiantur id, et vis decore aliquid, veri inermis ponderum id duo. Blandit antiopam recteque his te, eos ea senserit iracundia definiebas, at pro iusto expetendis. Vis ex accusata atomorum theophrastus, ea omnium maiorum appareat eum. Invenire hendrerit ne vis, vel te duis nusquam indoctum, nam in quod ornatus epicuri. - -############ -## Arabic ## -############ - -يذكر وسوء مليون كل قام. الحدود المواد الأثنان لان كل, مع للأراضي وبالتحديد، حدى. أم الأعمال للأراضي تحت. كما دارت السادس أم, يبق كل تحرّك الأولى. مدن إذ والنرويج الدولارات. إذ خلاف اقتصادية لها, لمّ إذ الجو والتي الجنوبي, أن خطّة هنا؟ الإكتفاء وقد. و نفس بشرية غرّة،, إذ إيطاليا الساحلية دنو. - -كان مع لهيمنة التبرعات, يرتبط التخطيط لم انه. ثم ضرب بتطويق الاندونيسية, مع دأبوا السيء المارق وفي. الثالث الشتاء، عن ضرب, يبق كل إنطلاق وحرمان. إذ إيو تمهيد مشارف وانتهاءً, يبق أم وفنلندا ويكيبيديا. - -الأمم لأداء الهادي تم جهة. في ذات الجو الخاسرة. أوزار استرجاع الأوروبيّون تحت ان, انه تم بوابة المحيط. في حين أجزاء الخطّة الأوروبية, مع وقد أراضي تكاليف, تُصب ليبين عدد أي. - -ثم انه دخول بالرّد ابتدعها, أن بعض وبدون التكاليف. في فعل أوسع الشهير والكساد. بين المشترك الثانية تم, بلا في ٢٠٠٤ الثقيل, ودول أثره، بلديهما هو غير. تم فصل مايو تكبّد الإتفاقية. - -تم الأخذ الشّعبين الأمريكية هذا, و والعتاد الأوروبية، عدم. للأراضي استراليا، واندونيسيا، يبق مع, أما مع تحرّك للجزر, المنتصر الموسوعة اليابانية مع إيو. لكل حاملات الساحل اقتصادية من, تحت كل وحرمان الخاسرة, أدنى بقسوة في إيو. عجّل المزيفة في عرض. ولم فسقط تطوير وإيطالي تم, عل كلّ الحدود الأرضية, ماشاء بالجانب الأوروبيّون حول إذ. - -وفي إذ جنوب مرجع ومحاولة. قد يكن استدعى الضغوط التكاليف, أي جيما مكّن التي حدى. جديدة كانتا وقامت ذلك تم, مايو أفاق الأوروبية، و وفي. عل كما اعلان والمعدات الإقتصادية. أما و حلّت اسبوعين وايرلندا, أن بعض ودول دأبوا استمرار, عدد مقاطعة للحكومة هو. لان ويتّفق السادس هو. - -لمّ يتمكن الحدود الإقتصادية عن, حيث بـ للجزر المدن. عجّل التنازلي عل مكن. من الأمم ويتّفق التنازلي على. وبعد الشمل وبالتحديد، لها تم. ٣٠ تلك فمرّ وتنصيب. - -لمّ دخول ساعة فرنسا و. إبّان الصفحات هو إيو, عل أطراف الشهيرة لمّ. يكن قادة الإكتفاء تم, زهاء ثمّة إنطلاق بلا تم. لها وإعلان بمعارضة لم, بال إذ جيما واتّجه, أم بحث ومضى الثانية وهولندا،. غريمه البولندي حدى مع, تم بحث فرنسية وتنامت, موالية الجنرال أم فصل. تم حاول طوكيو يونيو جعل, من تحت القادة ولاتّساع, ما قامت عليها بولندا، فصل. - -زهاء بتحدّي وباستثناء حدى ان, حادثة أجزاء ان دار. عن المدن بالإنزال باستخدام بحق, كل الشطر الاندونيسية جهة, لم بين التي هاربر. اعلان وصافرات الاندونيسية ما لان, تُصب اوروبا نفس مع, ذات إعمار وصافرات بـ. يتم نتيجة كانتا أم, معزّزة الأوروبي هو أخر. الله لغات بالسيطرة بحق إذ. و وإعلان والعتاد الدولارات نفس, استدعى ارتكبها والمانيا جعل عل, و تحرّك الموسوعة بحق. - -حين لم اتفاق العسكري, عل دارت يعادل دنو. لفرنسا الأهداف حتى أي, وفي بقصف إجلاء القوى من. نتيجة بمحاولة مع حتى. حيث بـ بحشد وسوء. - -############## -## Armenian ## -############## - -լոռեմ իպսում դոլոռ սիթ ամեթ, եի ապպեթեռե պհաեդռում թհեոպհռասթուս ծում, եռաթ ալիքուանդո քուո նե. աթ քուո դիծեռեթ իմպեռդիեթ ծոնծլուսիոնեմքուե, ծու նեծ եխպեթենդա պռինծիպես պեռծիպիթուռ. ութ մունդի իմպեդիթ ապեիռիան նամ, իդ սեդ եխպլիծառի գլոռիաթուռ. վիմ դեբեթ մելիոռե ծու, եու հաբեմուս մենանդռի աբհոռռեանթ հիս, սծռիպսեռիթ պհիլոսոպհիա եխ սիթ. ին հաս ուլլում եխպեթենդիս. - -մեի դիծո ալիքուիդ ռեֆեռռենթուռ ան. պռո նո մինիմ թամքուամ, մունդի մենանդռի ին եում. հաս ութ թալե պոռռո թիմեամ, իուս իուդիծաբիթ ռեպուդիառե նո. պեռֆեծթո եուռիպիդիս պեռթինածիա եու վել, մեա եա ինանի վիռիս վենիամ. աթ ծոռպոռա ելիգենդի հիս. - -իդքուե ծեթեռոս ծոնվենիռե վիխ ադ. ուսու սոլում վելիթ ծոմպլեծթիթուռ եխ. ծու դուո ինսոլենս գուբեռգռեն, նամ եի թռիթանի իմպեռդիեթ, մել ադոլեսծենս ծոնսեքուունթուռ ան. ան նեծ գռաեծո լաթինե մենանդռի, մեա քուաեքուե նումքուամ ան, նե նոնումը լաբոռամուս հենդռեռիթ մեի. - -իուս ռեծթեքուե սալութաթուս սենթենթիաե թե, ան իուս ոմիթթամ ինդոծթում. նո թիբիքուե պռոբաթուս իուս. ան ֆեռռի ադիպիսծի դուո, ութ սիթ մուծիուս դելենիթի լաբոռամուս. վիմ ալիի ծոռռումպիթ ծու. ութ ինթելլեգաթ առգումենթում դիսսենթիեթ պեռ. - -եա եում դոլոռե դեֆինիթիոնես, ոմիթթամ ասսենթիոռ աթ եսթ, ծում եու սոլեաթ պութանթ. եոս եա եռանթ եպիծուռի, եու պռո դոծենդի թռածթաթոս, ալիա նումքուամ իմպեդիթ եամ ին. ին դուո ունում անծիլլաե, ութամուռ թածիմաթես պհիլոսոպհիա իդ ուսու. ադ սեդ դոլոռ սոլութա ասսուեվեռիթ, պութանթ մենթիթում ֆածիլիսի եի ծում, ֆածեթե աուդիռե ինդոծթում ադ վիխ. եու ալիքուիպ դոծենդի պռինծիպես եամ, թամքուամ հենդռեռիթ ծոնսեծթեթուեռ վել նո. պեռ ապեռիամ պոսթուլանթ գլոռիաթուռ ին. ծում իդ սուաս նեմոռե վոլումուս. - -եոս ին ապպեթեռե ոպոռթեռե, վեռո ծոնգուե ադոլեսծենս իուս եա. մոդեռաթիուս պհիլոսոպհիա եսթ եու, սոլում հաբեմուս հաս ադ, մունեռե թռիթանի թիբիքուե մեա ին. քուո մութաթ մինիմում նո. նո մուծիուս անթիոպամ ծոմպլեծթիթուռ վել. եամ եու նոնումը վիռթութե պաթռիոքուե. - -պեռ աթ թամքուամ դելենիթ. ուսու նե բռութե լաբիթուռ դոլոռում, եսթ վեռեառ ածծումսան ութ. եթ նեմոռե մոլեսթիե ֆածիլիսի վել, գռաեծե ինթեգռե դեբիթիս ութ քուի. վիս եու ոպթիոն սուավիթաթե, մինիմ հոմեռո ռիդենս ծու ծում. սոլեթ ոֆֆիծիիս լաբոռամուս ադ մեի, դիսծեռե մաիոռում թածիմաթես նո հաս, ջուսթո դոլոռես դիսպութանդո եամ եա. - -ուսու աթ պեռիծուլիս ծոմպլեծթիթուռ վոլուպթաթիբուս. նիհիլ ութինամ լեգիմուս թե սեդ. քուի եի դիծթա նեգլեգենթուռ, նո վիս ագամ պուռթո, եսթ ելիթ գռաեծե եիռմոդ եխ. վել եխ եռուդիթի ծոթիդիեքուե, քուո ծու ծիբո եուռիպիդիս, պլաթոնեմ ածծուսամուս եում ութ. եթ սեա մունեռե բլանդիթ վիթուպեռաթա, թե հաս ռեքուե գռաեծե. - -հիս եխ ֆածիլիսի սալութանդի, եխ մեի ամեթ պութենթ դելիծաթա. սեդ ունում պութանթ պռաեսենթ ան. ոդիո հոմեռո ոմնեսքուե եա եում. ադ վիվենդում գլոռիաթուռ պռի. մինիմ եռռոռիբուս դիսպութաթիոնի ին պռո, թե վիդիթ նոսթռուդ լաոռեեթ վել, եիուս պեռպեթուա մել ութ. - -վիմ ան ելիթ սոլում վեռեառ, ան ունում դիծիթ ֆոռենսիբուս մել. ինթեգռե նոնումես ծու մեի, հիս դելենիթ ադիպիսծինգ ինսթռուծթիոռ իդ. պռաեսենթ ելոքուենթիամ սեա ծու, եոս նե նիսլ ոպթիոն նեծեսսիթաթիբուս, քուի ադ ֆուգիթ իռածունդիա. թե սեա պեռսիուս դելենիթի, աթ ծլիթա թաթիոն սեդ. եխ եոս սոլեթ աֆֆեռթ ապպառեաթ, նամ եթ ոպոռթեռե ծոթիդիեքուե ինթեռպռեթառիս. - -############# -## Bengali ## -############# - -একটি সুন্দর সকালে, শহরের কোণে একটি ছোট্ট বইয়ের দোকান ছিল। দোকানটির নাম ছিল "সপ্নের পাতা।" সেখানে প্রতিদিন অনেক পাঠক আসতেন নতুন বইয়ের খোঁজে। দোকানের মালিক, একজন বৃদ্ধ ব্যক্তি, বইয়ের প্রতি গভীর ভালোবাসা ছিল। তিনি সব সময় নতুন বইয়ের কথা জানাতেন এবং পাঠকদের সাথে গল্প শেয়ার করতেন। - -একদিন, একটি যুবক সেখানে এল। তার হাতে একটি পুরনো বই ছিল, যা তার দাদার কাছ থেকে পাওয়া। বইটি পড়ে যুবক খুব বিমুগ্ধ হয়। বৃদ্ধ ব্যক্তিটি বইটি দেখে বললেন, "এটি একটি বিরল গ্রন্থ, এর মধ্যে জাদুর মতো গল্প রয়েছে।" যুবকটি বইটি কিনে নিয়ে গেল এবং প্রতিজ্ঞা করল প্রতিবার পড়ার সময় সেই দোকানটি ভিজিট করবে। - -তথ্য আর কল্পনার মিশেলে, বইয়ের জগতে মানুষ নতুন অভিজ্ঞতা অর্জন করে। এইভাবেই, "সপ্নের পাতা" বইপ্রেমীদের একটি বিশেষ স্থান হয়ে উঠেছিল। - -############# -## Chinese ## -############# - -家当権複発算出術敬条智門写護笑。事撤予監和被江般国変様末映薦質部逮八報政。向父渡座提煙手芸営読話図本催政楽無保。数売図体出挑世下経考勢去愉条。組簡向際違転似司座坊件惑大案僚選初全師宇。護円未生思木女演掲湾要思者演残辞。知響真楽許改贅輪禁一多転軽載売京。辺開葉給見延勝式銃拉研忘界金。判済明語男覚新士回報鮮何第位関付表。 - -次必四終粘通京前内秋業可園馬療月岸春加査。更給横同写業街数塗求属韓療供違別仕問。集診身和白外一社案報架変水負。問武前金花美故芸診振越進隆献軽。種撃版験遅望主初掲応界聞。宮止銅専予致長新央著演徳見型児風犯氷。際語移載支文都覇挙経移災見会間駆題留。記島確意京坦相欲展示気役所果。最都愛教信方議分担参禁合自新日解甲川誕。 - -事推社投住近言金医真尊供望聞炭一顔。有毎増上情率景青郎務仏芸約就国活社。験賞警般教生改乱落京歩上暮連演線印市島月。案館議争担化共展有稿両型欲組使線草学。分県鳴並報天事権評追新万計事制高約策対岡。林徹禁面前出千回携掲帯格揮昨献軽連部康。術断維益書気基東全応芸感落禁危世杏画引。合辺超物吉元末込位座周亜治容需報実田名変。 - -額後企息発相暴均二更戦査裁買下。載映引居警軽室枠保聞暖険木。懸見報熊試不始採細題確迎演帯市奪技。身傷区構旅約犯怪文戸論落於話情計編呼書。深顔見走変会島男工写属送年公口庭務幅端。積内観著続楽万得山売権金誌車事験。走了募総報室会就掲間本科株身情教。禁教確覧愛気植農使脊解猛明削更言表囲行値。域設国川係組結果販隠午報愛視処。 - -碁増機功佐立保下捜天用学格。惑読了旅接正摘回渡俳神通足低旅尚平。新佐現門最大早払査書奏際測気穂。作満新民成理節化倉旅待著推。人夜玉際約聞制魚季見大売然競福催。書旅活昨持府未記実協究変務転陥画自額。版拡視関筆掲囲軽記運投見。元焼発名載動応個社毎称域川佳題安。介地次年新格験田解島府持。馬理関稿旅信五売来一圧論鉢線申聞注。 - -全来育幸増覧織世邦異非伸思人。社察区回税国離東悩十約神処参夜容小。理場玲発中無野最富橋策稿感。圧掲引味索社測取語際掲意一男等。挙師負盛改飛保世車情掲決紀宅要城軽。門生索古斉薬京加騎京映発上団過男転算製。上永年別本面談居完語録岐格限会除。政雪台岐建文記魅完古天近写杯市化社岡居。客花居速沢板阜初場東企民体。 - -権竹原機住仮速関張民準所伴戦口軍監際検巨。緑判懸道死安予図伝午来際同錯展縮図任指。全応報了州話容造出近無新山真子帰射豊択。放派位鈴則力覧権品所法国財強応子景疲害。訪席話熱載気庫残故求否事際無具応目奈謝。給時末重微法山国枚友堀合量芸問刊必工。世氷降毎子姿打正作調予品語食変。会間相童作先高園覧送王枠高。 - -良同提織際碁球登屋鹿芸為台駅支城。来由表術一障間日読大熱法度将政堂。泉語組受授質少重家聞銀鮮問後連世事島手提。属成態亡幸一親残道個父転国催。締任職協園東提代洋著大例大都村酉右。代明真作圭転済遺治座子図。対賞話新撃葬肥怪典品分趣混前層。第済民育近記潟主安革部給備宅風装開函予。動国定生真名受表員周際困鈴逆広京。 - -枢夫確通南歴季金企完産整染以堤断物台。産提国広保今致佐井聞世世価円砂題建来戸。者身載講設引逮北爆展際適名芸者著園。林個動月示氏来員野記明徳。出治総者況新練発内手道北壊規。淳教撮武実用全師付四科集。散衛効川図署中数室年表請開無覧経都界烈眠。聞戦真子情明購載碁要外越題逮稲米建全。禁表研図済千重観率時川本億要患鉄。 - -正年外語港備町暮宇貌同分属属周怪玉約砂目。第再全写在催異情般気決合。動報静離習井更券俳投募宿皇医畿義暮山夫掲。聴来玲月功学津必東問画務楽機著減。政刀悟口手案明棋負目降稿走筑作事死択。老振務企聴読政毎体情光形文判値毎報報頃。芸練人型以年交区中済階元警。題供百呂運率写差東勝備文球新素外前事。実宅日生行京西介家迫田困京顔。 - -############## -## Cyrillic ## -############## - -Лорем ипсум долор сит амет, аеяуе репудиандае еум ат, нец ут витае тациматес, яуандо граецис ат про. Иус ид дуис воцибус сцрибентур, сит ид алиа хинц виси. Ан пер аетерно ехплицари дигниссим, легере фацете вулпутате ид вих. Вел цлита цоммодо цомпрехенсам цу, ех хис риденс постеа. Еррем саепе детерруиссет те иус, при алии ерипуит ид, ех нец форенсибус ратионибус. Еум видиссе регионе еа, нам те апериам аццумсан алияуандо. - -Адверсариум цонцлудатуряуе еу усу. Примис виртуте дефинитионем ин при, детрацто яуаестио темпорибус не цум. Иуварет инимицус яуи ан, мел урбанитас цомпрехенсам ид. Цу нец яуем прима медиоцрем, сед модус дебет елигенди цу. Ут сонет персецути яуи, ест но яуандо тритани, иллум мовет сусципит меа еу. - -Еи нец перципит неглегентур, яуо ут хинц пауло цонсецтетуер. Ид хис виси аццусата инцоррупте, вих татион нуллам принципес ан. Не еум яуот омнесяуе. Облияуе малорум сеа те, магна нонумы нусяуам ад про, популо дицерет яуи еа. Алиа яуот аццумсан ин хис, еи нец миним витае аццоммодаре, ин пер нихил фуиссет перфецто. Еу лаборе цивибус тибияуе ест, атяуи орнатус урбанитас еи еум, тота импетус тациматес еа еос. - -Толлит иисяуе анциллае вих ех, поссит инструцтиор хис не. Те поссим сцрипта еам, ан хис модус ехпетендис. Татион реферрентур те нам, еи еос делецтус пондерум модератиус. Вих не латине модератиус инцоррупте, мел еу юсто утамур омиттам. Доцтус ехпетенда усу но, ет сед цонсул алияуид. Ад долорес сенсерит хас, про виде иудицо виртуте еа. - -Ан цум модо дебитис аппеллантур, новум молестиае цу усу, ат солет цонсететур интерессет усу. Регионе фиерент но хис. Муциус тамяуам еи меи, мазим регионе еу хас. Цу еам ириуре сингулис диспутандо, не диам алтера диссентиас вим, цум вери постеа яуаестио но. - -Вим уллум дицтас глориатур еа. Еиус лаборе делицатиссими цу цум, стет яуодси ехпетендис вим ех, яуо цетеро садипсцинг ан. Еам еи дицант дицерет елеифенд. Дуо антиопам сплендиде но. Ан еум етиам перицулис, сит еи лаборес бландит. Мунди опортере ад иус. Дицант нонумы ет яуи. - -Яуодси ириуре денияуе ех еос, аццусам пробатус вел ид. Вих вивендо пертинациа ет. Деленит перпетуа ут при, меа идяуе хабемус ин. Ин еум идяуе тибияуе лобортис, дицант утрояуе глориатур ан иус. Виртуте адиписци инцидеринт цу мел, ин еос цасе епицуреи. Сит ид суммо фацилиси. - -Еирмод саперет орнатус ин еам, солум нихил инермис сеа ет. Яуо ад ириуре адолесценс улламцорпер, нец не аутем яуалисяуе. Цум те темпор оффендит, ерат вирис дисцере еу ест, не оратио вениам сеа. Ид утинам тхеопхрастус вис, долорем десеруиссе еа пер. Пер но виде фабулас, еиус ехплицари ирацундиа ат хас. - -Дебитис минимум еа пер, тамяуам форенсибус пер не. Усу реяуе алияуид те, татион пондерум яуалисяуе не хас. Волуптуа глориатур цонституам дуо ин. Еа фабулас цоммуне иус, ад одио фацилис салутанди сит. - -Поссит ноструд ан яуо, нец ех доцтус фацилисис цоррумпит. Виде апериам аццусам ат вих. Нулла иисяуе цоррумпит при ут, афферт алияуам сусципиантур ид меа, еум ин волумус вулпутате. Пурто яуас харум ут сеа, ет сед цонсулату персецути. Ат алии солет легере вел, сит ад лаборес аццоммодаре. - -########### -## Czech ## -########### - -V dávných dobách, na úpatí velkých hor, žil malý chlapec jménem Jakub. Každé ráno se probouzel se zvuky ptáků, kteří zpívali svou radostnou píseň. Jakub měl velké sny o tom, že se stane hrdinou, který zachrání svou vesnici před zlými silami. - -Jednoho dne se vydal na dobrodružství do tajemného lesa, kde se setkal s moudrým starcem, který mu vyprávěl příběhy o odvaze a přátelství. Jakub se rozhodl, že se postaví svým strachům a vydá se na cestu, která ho naučí o síle lásky a víry. - -Tak začalo jeho dobrodružství, které ho dovedlo k nečekaným přátelstvím a mnoha zkouškám. Vždy, když se dostal do potíží, vzpomněl si na slova starce a pokračoval dál, s odhodláním a nadějí v srdci. - -############ -## Danish ## -############ - -En solrig morgen vågnede Mette tidligt og besluttede sig for at gå en tur langs stranden. Vejret var mildt, og bølgerne skyllede roligt ind over sandet. Hun elskede at starte dagen med at lytte til havets brusen og se mågerne flyve hen over vandet. Mens hun gik, mødte hun sin ven Lars, der også nød morgenturen. De besluttede sig for at sætte sig på en bænk og nyde udsigten sammen. - -############ -## French ## -############ - -Il était une fois, dans un petit village entouré de collines verdoyantes, un jeune garçon nommé Luc. Chaque matin, Luc se réveillait avec le chant des oiseaux et le doux parfum des fleurs. Il passait ses journées à explorer les forêts enchantées et à rêver d'aventures extraordinaires. - -Un jour, alors qu'il errait près d'un ruisseau scintillant, Luc découvrit un vieux livre poussiéreux caché sous une pierre. Curieux, il l'ouvrit et découvrit des histoires de héros, de dragons et de trésors perdus. Fasciné, il décida de partir à la recherche de ces trésors, armé de son courage et de son imagination. - -Au fil de ses voyages, Luc rencontra des amis fidèles, affronta des défis incroyables et apprit que l'aventure était bien plus qu'une quête de trésors matériels. C'était un voyage de découverte de soi et de création de souvenirs inoubliables. - -Ainsi, Luc grandit, non seulement en taille mais aussi en sagesse, portant toujours avec lui les leçons apprises au cours de ses incroyables aventures. - -############## -## Georgian ## -############## - -ლორემ იფსუმ დოლორ სით ამეთ, ნიჰილ სოლუთა ნოლუისსე ჰას იდ, ერუდითი ალბუციუს ფრობათუს ვის ან. ეხ ცუმ ალიი ეხერცი, ეუ ჰის ფოსსიმ დესერუნთ. სეა ეთ დიცთა ფაულო სიმილიყუე, თე ფოსსით აცცუმსან იუს. ადჰუც ნოვუმ ოფთიონ ცუ მეი, ვის ეთ ფრინციფეს თორყუათოს დესერუისსე. ნო ვიმ ფოსსიმ სალუთანდი, სალუთათუს ცონთენთიონეს ეთ ყუო. - -ეი ფრო ეიუს მაიორუმ ცორფორა, ოფფენდით გლორიათურ ათ ეოს. ეა მელ თინციდუნთ ცონცლუსიონემყუე, ან იუს ნოსთრუდ ინთერესსეთ. ეხ ლორემ ფალლი ურბანითას ესთ. ალიი ცლითა ეთ ესთ. ნამ ეხ ვოციბუს ინსოლენს, ინ იუს ვისი იფსუმ ინერმის. ყუო უთ ლიბერ თიმეამ ფლაცერათ. - -ათ ცუმ ვივენდუმ თორყუათოს. ენიმ აფერირი ფაცილის სით ინ, მალის ცონცლუსიონემყუე ეამ თე, თოთა იისყუე ნამ ცუ. ეთიამ ცოფიოსაე სიმილიყუე ნამ ნე, ან ფართემ მანდამუს ვიმ. ეა აუთემ მოვეთ მალუისსეთ ეუმ. ნამ ომნეს ცონგუე თიმეამ ეუ, ეოს ორნათუს რეფრიმიყუე დისსენთიეთ ეი. - -ეა ცორფორა ვივენდუმ ნეგლეგენთურ ველ. ნოსთრუდ ფერფეთუა ფერ ად, სეა ეა ვერთერემ ყუაერენდუმ მედიოცრითათემ, ცუ ყუოთ დოცენდი ასსენთიორ ჰას. ფერრი დიცთა ვოლუფთათიბუს ნო მეა, ეოს ნო იმფეთუს აცცუსამუს ცონსეყუუნთურ. ინ დიცო ერრორ სონეთ ველ. ვითაე ანიმალ ფეუგაით ვიმ უთ, ყუოთ საფერეთ დეთრახით ან სეა. - -ვერი ფეუგაით რეფერრენთურ ეი ფრი, ვიხ ესსენთ თიმეამ იუდიცაბით ეა. ფრი ოდიო ელეცთრამ სცრიფთორემ ეხ, მეა ეთ ცასე იგნოთა. უთ აუდიამ ეფფიციანთურ ვიმ. ყუიდამ ადიფისცი ფათრიოყუე ნეც თე, ცუ ყუო მაზიმ დიცუნთ. - -ად ყუოდ ფრინციფეს ცონსთითუთო ვის, ად ეფიცური მოლესთიაე ცონცლუდათურყუე ვიმ, სეა დიცათ ალიყუიფ ეთ. ეა სეა ყუიდამ ინთერფრეთარის. სედ ნულლამ დისსენთიუნთ ეა, ჰის ფუგით იგნოთა სემფერ ეა, იდ ფრო ცონგუე ეხფეთენდის. ად უსუ ბრუთე აუგუე ლეგენდოს, თე ყუის ვოცენთ ჰას, უთ ვის სუმო დიამ ვერთერემ. - -ალიენუმ ოფფენდით იდ ვიხ, მეი ვერეარ ვულფუთათე ეხ, ეუმ ათ ლუდუს გუბერგრენ. ცუმ უთ მოდუს ომნესყუე ადიფისცინგ, ეა ნიჰილ ვითაე ინთელლეგებათ ვიხ. მუნერე იმფედით ფუისსეთ ეუმ თე, ვიდერერ აფფარეათ მეი ინ. ეუისმოდ მენთითუმ ინთელლეგათ ეამ ეთ, ომნეს სენსერით ფოსიდონიუმ ჰის ად, ველ ცუ დებეთ ოფფიციის სცრიფსერით. დიამ ირიურე ევერთითურ ეუ სით. - -ეა ნეც სოლეათ დელენით ლეგენდოს, ნიჰილ იუდიცაბით ცუმ თე. ად უსუ მეის ფლაცერათ დისფუთათიონი, ინანი მინიმუმ ცორრუმფით ნო ჰას, ნო ველ ფრობო ვენიამ დოლორემ. ცუ სანცთუს მანდამუს ვიხ, ვის ნონუმy ინვიდუნთ ეუ, ოდიო მენანდრი სინგულის ჰას ეთ. ფრო ცომმუნე ცონცეფთამ რეფორმიდანს ათ. - -ნიჰილ დელიცათისსიმი ინ იუს, ნო სედ სუმო ფერფეცთო. იდ მეა ფერრი ნომინათი, თე ვიმ ფრობათუს დეფინითიონეს, ათ ანთიოფამ დელიცათისსიმი ჰის. ესთ ეთ დოლორემ ელეცთრამ ფოსთულანთ. ერუდითი ომითთანთურ ნამ ეუ, ველ ეთ ასსუმ ინერმის. ყუას ლათინე დისსენთიუნთ ფერ ეუ, ეხ ფუგით ფაცილისი ნეცესსითათიბუს ნეც, ათ ვიხ ნულლამ ვივენდუმ. - -ნამ ვიდით გრაეცე უთ, ფუგით აფფეთერე ეა ეოს. უსუ ნიჰილ ანცილლაე ეთ. ველ ინანი სოლუთა ეი. ეთ ესთ ელიგენდი სცაევოლა ინცორრუფთე, თე გრაეცი ალიყუიდ იუს, ვერო იგნოთა ვირთუთე ეთ ფერ. ველ ფუგით ყუალისყუე ეი, რიდენს გრაეცო დეფინითიონეს ჰის ეუ. იდ ველით ათომორუმ ეოს, ფრი ფრიმა ეირმოდ დეთრახით ან. - -############ -## German ## -############ - -Es war einmal in einem kleinen Dorf, wo die Blumen in allen Farben blühten. Die Sonne schien hell am Himmel, und die Vögel sangen fröhliche Melodien. Jeden Morgen trafen sich die Dorfbewohner am Marktplatz, um frisches Gemüse und leckere Früchte zu kaufen. Eines Tages kam ein Fremder in das Dorf und brachte Geschichten von fernen Ländern mit. Die Kinder hörten gebannt zu, während die Erwachsenen sich fragten, ob sie jemals die Welt außerhalb ihres kleinen Paradieses sehen würden. Doch in ihren Herzen wussten sie, dass das wahre Glück in den einfachen Momenten des Lebens lag. - -########### -## Greek ## -########### - -Λορεμ ιπσθμ δολορ σιτ αμετ, μει νοστρθμ δελιcατισσιμι cθ, νεc νο μθcιθσ μινιμθμ θρβανιτασ. Εαμ σανcτθσ cιvιβθσ αccθμσαν εξ, αδ θλλθμ αφφερτ σινγθλισ vελ, σεα σιντ ποστθλαντ cοντεντιονεσ αδ. Vιμ ανcιλλαε ρεcτεqθε τε, αλιqθαμ σcριβεντθρ vισ θτ, ναμ εξ vερο σθμμο σαλθτατθσ. Εστ τε ιλλθμ ηονεστατισ, νοvθμ αεqθε λεγερε εα πρι. Τε μελ qθαεστιο σαλθτατθσ εφφιcιενδι, λαβορεσ δισσεντιθντ νε προ. - -Τε ρεπθδιαρε μολεστιαε vθλπθτατε εθμ, αν εοσ μολεστιε τινcιδθντ τηεοπηραστθσ, ετ vελ vερι ινcιδεριντ. Cομμοδο cονστιτθαμ θτ vισ. Δετραξιτ qθαλισqθε μελ ιν, τραcτατοσ πατριοqθε vθλπθτατε ιθσ τε. Νιβη ιισqθε vολθμθσ σιτ ει, θσθ αδ σαλε αβηορρεαντ. Ιν νεc σθμο θβιqθε, ετ φαcιλισι λεγενδοσ προδεσσετ vισ, ιδ οδιο ελιτ ταcιματεσ δθο. - -Cαθσαε vιδερερ περcιπιτθρ νο σεδ, αν αλτερα εvερτι προ. Vιξ ει δθισ νεμορε cομπρεηενσαμ. Ιν ιπσθμ μοδερατιθσ ηισ, πθτεντ σιγνιφερθμqθε ιν vιξ, αγαμ δεβετ ιν vιμ. Cιβο σολθμ μολλισ σεδ θτ, ατ δθο δομινγ απειριαν περτιναξ. Νιβη σολθτα ιν μελ, ιθσ σιντ θβιqθε ιμπετθσ αδ. - -Θσθ αν οπτιον δελενιτι πλαcερατ, σολθτα εξπετενδισ λιβεραvισσε περ νε. Ατ ηισ μελιθσ φαβθλασ εξπετενδα, θβιqθε ταcιματεσ νο qθι, εα ηισ λεγερε vοcεντ μολεστιαε. Νε vερεαρ vοcιβθσ δεφινιτιονεσ ιθσ. Αδ αθγθε δεβιτισ σιτ. - -Νοστρο δελιcατισσιμι μελ ιδ. Σεα τατιον δοcενδι σενσεριτ αδ, γραεcο αλιqθανδο μεα εθ, εvερτιτθρ αccομμοδαρε cθ vισ. Ιδ vισ σθμμο vολθπτατθμ, δθο ιν σονετ σαδιπσcινγ, ατ δθο ινcορρθπτε λιβεραvισσε. Τε πριμισ μεντιτθμ οπορτερε σεδ. - -Νε σιτ θλλθμ εφφιcιενδι, σεα ατ νοστερ νθσqθαμ περφεcτο. Απεριρι φαβελλασ αν μει, νονθμυ πετεντιθμ cομπρεηενσαμ ετ δθο. Ηασ ομνεσ vθλπθτατε ιντελλεγαμ θτ. Μει νιηιλ φαcιλισι αν, θταμθρ ιισqθε cονσεqθατ ει ηισ. Ιλλθδ σενσεριτ εθ δθο, ηασ εα βρθτε cλιτα vολθπταρια. Vελ νεμορε δοcτθσ αν. - -Θσθ βονορθμ λεγιμθσ ελιγενδι αν, εοσ θτ ιπσθμ αccθσατα δισπθτατιονι. Ει θσθ σιμθλ σολετ ρεφερρεντθρ, ει σιτ ρεqθε εθισμοδ αδιπισcινγ, εοσ ατ ιγνοτα φεθγαιτ ελιγενδι. Εστ ρεqθε φορενσιβθσ qθαερενδθμ εθ, εστ αν πλαcερατ ινδοcτθμ qθαλισqθε, μελ αδηθc νονθμυ αν. Σολθμ cοπιοσαε δεφινιτιονεμ vισ ιν. Μεα vελιτ προβατθσ ιδ. Ετ ποσσιμ απεριρι οcθρρερετ qθι. - -Θσθ σθασ μεντιτθμ vιτθπερατα ετ. Εθ ιθδιcο ιθδιcαβιτ ρεπθδιανδαε μει, γραεcε φαcετε νεcεσσιτατιβθσ ιθσ τε, νε πρι vολθτπατ ηονεστατισ ρεφερρεντθρ. Σεδ νε jθστο ιραcθνδια cονστιτθτο, απεριρι απειριαν ινσολενσ αδ περ. Vοcεντ τιβιqθε ηονεστατισ ναμ ετ. Γραεcο vολθμθσ περφεcτο εθμ νο, μει εα ιθvαρετ σθσcιπιαντθρ. - -Νεc αν ερρορ νοστρο, αν νονθμυ προπριαε μνεσαρcηθμ εοσ. Cθμ ατ ριδενσ διcθντ, ερρορ δισσεντιθντ αccομμοδαρε ηασ νε. Μεα φαλλι σενσεριτ εθ, vισ ατ επιcθρι αντιοπαμ. Περ ενιμ qθοτ ηαβεμθσ νε. Λθcιλιθσ ιντελλεγατ cονσεqθθντθρ νο εαμ, ηισ επιcθρει φαβελλασ ρεφορμιδανσ εα. Ιδ περ cλιτα ποσσιμ αλιqθαμ, αλτερθμ qθαερενδθμ μει θτ. - -Εστ ει vολθμθσ εξπλιcαρι, vισ ρεqθε vεριτθσ vολθμθσ αν, cθ δετραξιτ vολθτπατ ιθσ. Εθ μελ cονσθλ νθμqθαμ, cθμ αδ λθcιλιθσ δισπθτανδο. Θσθ φαcερ cαθσαε εθ, δελεcτθσ cονσετετθρ ινcιδεριντ ατ qθι. Αccθμσαν μεντιτθμ πρι ιν, τε παρτεμ ιγνοτα αλβθcιθσ εαμ, cασε σεμπερ ρεφερρεντθρ ει vιξ. - -############ -## Hebrew ## -############ - -אם מיזם וקשקש זכר, מלא בחירות לעברית והגולשים בה, מה עזה המדינה ממונרכיה אנתרופולוגיה. חבריכם מדריכים כדי מה. תרבות בארגז גם עזה, ישראל לתרום מה רבה. אם ארץ כלכלה טבלאות ומהימנה, אל צ'ט רומנית העריכהגירסאות. אחר אל הראשי לעברית, ויש מאמר בשפות קישורים של. - -בהשחתה היסטוריה האטמוספירה או סדר, ב פולנית ליצירתה חפש. אחד אל שדרות המחשב ארכיאולוגיה. זאת לשון קבלו ביולי את. לציין בכפוף לערכים מדע או, קצרמרים גיאוגרפיה אל מתן, שמו המשפט ומהימנה גם. היום מוסיקה כלליים דת שכל, רקטות בהשחתה אגרונומיה מתן אם, בקר או מאמר האטמוספירה. של שתי לימודים מיתולוגיה ביוטכנולוגיה, היא עיצוב משחקים על. - -לראות הבקשה מרצועת אל קרן, צ'ט הקנאים הנאמנים היסטוריה את. מלא אקראי המדינה התפתחות גם. מלא קבלו ספרדית אנגלית של, בה אחר הרוח פנאי. חפש על להפוך לעתים. שמו ישראל יוצרים גם, אם אחר הרוח שימושיים ויקיפדיה. מה שער המשפט ארכיאולוגיה, מה מיזם נבחרים כתב. - -של כלים ספרות ארכיאולוגיה לוח, דת מיזמים לויקיפדים ארץ. אל קודמות וכמקובל אחד, ב אחד תקשורת למחיקה וספציפיים. רבה על רקטות נבחרים, אל ריקוד רומנית למתחילים קרן. המלחמה ייִדיש אדריכלות שתי בה, כדור נוסחאות שתי של, עמוד המלצת קודמות אם ארץ. או רשימות הקנאים אדריכלות שתי, עזה את מתוך כלשהו הבהרה. - -בה שער בהבנה זכויות, ב אספרנטו נוסחאות סוציולוגיה שכל. חפש טיפול שיתופית למאמרים אל, אל בישול בחירות חרטומים סדר. את כדי זקוק העמוד אנציקלופדיה, שער מושגי שימושי שינויים את, בכפוף החופשית בדף את. שאלות נבחרים ביוטכנולוגיה בה צ'ט, צעד על ובמתן ביולוגיה לויקיפדים. - -והוא פיסול של היא, הרוח לכאן סרבול חפש בה, ב תנך תבניות קלאסיים. מתוך מיזמי תקשורת אחד דת, אתה אל לערך תורת, יידיש ארכיאולוגיה בה מתן. מה בדף אודות שימושיים, אחד אם יסוד בכפוף מאמרשיחהצפה. של חפש גרמנית הגרפים קלאסיים, ויקי קולנוע אספרנטו רבה מה. - -אחר העמוד משפטים היסטוריה גם, אתה מה גרמנית למחיקה אירועים. על צילום אחרים התפתחות צ'ט, צעד דת משפטית עקרונות. כלל לתרום והגולשים של. אם ויש שפות הסביבה, מלא אם ברית מחליטה. - -אחרונים מועמדים גיאוגרפיה בה צעד. מה לימודים אקטואליה היא. תיבת המלצת מוסיקה על מלא. של טיפול חינוך מבוקשים קרן, על חינוך רשימות שמו, מה מתן החול לשון יוני. - -כלים רפואה ליצירתה ב תנך, עוד החלה אחרים למחיקה מה. דרכה איטליה פסיכולוגיה אל מלא, דת הבקשה לחיבור לערכים מדע. מה היא כדור התוכן תיאטרון. כלים בשפה ספרדית אם שמו, אודות אינטרנט הגולשות צ'ט גם. או זאת שדרות שיתופית, גם בדף המדינה לויקיפדים. - -תוכל עקרונות ב מדע, מדע ב ומדעים שינויים משופרות. לחבר ציור המקובל אנא או. אל לשון לערכים רבה, שכל דרכה פולנית של. גם כלשהו המקושרים היא. - -########### -## Hindi ## -########### - -लिये परस्पर अंतर्गत समस्याओ पहोच। जिसे हमारि कुशलता ऎसाजीस विभाग होभर सभिसमज लाभान्वित आंतरकार्यक्षमता ज्यादा एकत्रित केन्द्रिय सकती नवंबर अपनि हमेहो। गोपनीयता बिन्दुओमे बाजार दारी दौरान कार्यकर्ता माहितीवानीज्य भाषा आवश्यक उपयोगकर्ता अन्तरराष्ट्रीयकरन होसके करने जागरुक सुचनाचलचित्र विवरन अथवा शीघ्र सहायता दोषसके सोफ़तवेर किया तकरीबन ज्यादा एसेएवं पहेला सेऔर चिदंश संस्था और्४५० परिभाषित - -जाने सक्षम कुशलता पहोचने विकासक्षमता करता। कीसे किएलोग सोफ़तवेर ७०है सहयोग मेंभटृ पुर्णता आंतरकार्यक्षमता प्रति निर्माता विश्वव्यापि बहतर कलइस विशेष है।अभी निरपेक्ष भेदनक्षमता होने विश्व संपादक वैश्विक हिंदी नाकर हमेहो। प्रसारन चिदंश बहतर आवश्यकत विस्तरणक्षमता - -दारी ध्येय माध्यम सुविधा कार्यसिधान्तो लेने एसलिये संस्थान डाले। लेने उद्योग सभीकुछ विकेन्द्रित वर्णन जिवन सुचना संपुर्ण स्वतंत्र गुजरना एसेएवं कार्यकर्ता कीसे बलवान पहेला संस्थान निरपेक्ष समाज जिसकी ७०है सम्पर्क लाभान्वित सादगि जाएन दोषसके असक्षम लेने समजते कार्यसिधान्तो ढांचामात्रुभाषा - -७०है कार्य अमितकुमार पुष्टिकर्ता प्रतिबध्दता खरिदे पढाए कार्यकर्ता संस्क्रुति मेंभटृ कार्यलय समजते भाति भाषा ढांचा पहोचने रहारुप है।अभी प्रति अधिकार लक्ष्य अनुवाद कारन करता होसके कुशलता विकेन्द्रित प्रौध्योगिकी देते हमारी आवश्यक वास्तव सभीकुछ वर्णन तकरीबन शारिरिक प्रौध्योगिकी जिवन सुनत तकनिकल स्वतंत्र ढांचामात्रुभाषा कराना कार्य एवम् दुनिया दोषसके कीसे प्राण लक्ष्य अविरोधता अत्यंत पासपाई हार्डवेर नवंबर जाता सभीकुछ जानकारी देकर सक्षम जिम्मे व्यवहार कम्प्युटर नवंबर विषय - -रखते सदस्य लचकनहि मार्गदर्शन समाज डाले। ब्रौशर कार्यलय प्रोत्साहित समस्याए अविरोधता ढांचामात्रुभाषा समजते लेने चिदंश एसलिये अत्यंत बिन्दुओ पहोच रखते पासपाई विज्ञान सिद्धांत तरीके प्राण नीचे मुश्किले सार्वजनिक करने विवरन लक्ष्य है।अभी प्राथमिक बनाना संपादक प्रदान मानसिक कीसे खण्ड उपेक्ष मानसिक दोषसके हिंदी - -सदस्य संस्था अनुकूल जाएन दुनिया मार्गदर्शन हमारि एवम् परिवहन सुविधा विश्लेषण सकती खरिदे करता। एछित गुजरना वास्तव नवंबर बेंगलूर विभाजनक्षमता करती प्रति खरिदने उपेक्ष ७०है कराना यधपि स्थिति किएलोग मार्गदर्शन ध्येय मानसिक केन्द्रिय विश्वव्यापि करती शीघ्र वर्णित सार्वजनिक संस्क्रुति वर्ष मुख्य कीने गुजरना जानकारी सदस्य आवश्यक भेदनक्षमता विकेन्द्रित आपको है।अभी दोषसके सार्वजनिक होसके थातक कैसे सक्षम है।अभी वैश्विक उपयोगकर्ता - -उद्योग विभाजनक्षमता लिए। देखने व्याख्यान कार्यकर्ता विकेन्द्रित जिवन लेकिन क्षमता आधुनिक कराना भाषा जोवे औषधिक मुश्किल कम्प्युटर उशकी बाजार शुरुआत नयेलिए हमारि भाति ज्यादा विश्वास उपयोगकर्ता हमारी वैश्विक संपुर्ण सहित हैं। केन्द्रित व्याख्यान मुख्य कारन प्रमान नयेलिए करके(विशेष औषधिक गटको सक्षम हुएआदि यन्त्रालय - -लिए। पुर्व उपलब्ध परिवहन सम्पर्क अमितकुमार विभाग बदले समाजो संपादक अविरोधता व्याख्या पडता जिम्मे है।अभी विकेन्द्रित समजते सकती संभव दिनांक सिद्धांत लक्षण व्यवहार मुख्यतह विचरविमर्श ७०है नवंबर माध्यम प्रव्रुति विचरविमर्श देकर नवंबर ढांचा असरकारक व्याख्या होगा - -आशाआपस वातावरण एकएस डाले। स्थिति मर्यादित सिद्धांत बाटते उनके सादगि समूह पुस्तक जानकारी कारन तकनिकल व्यवहार असरकारक मुक्त विवरण कुशलता अंग्रेजी सुना अविरोधता ढांचामात्रुभाषा बहुत विश्व सकती पहोचने नयेलिए लचकनहि कराना तरीके तरहथा। सुस्पश्ट उनको प्रति सके। आवश्यक प्रमान प्रतिबध हमारी आपके वास्तव पत्रिका बिन्दुओमे - -विवरन प्रदान बेंगलूर जैसी रहारुप आंतरकार्यक्षमता उदेश ध्येय जिम्मे उदेशीत एकत्रित अपनि करता। पुर्व दारी सहायता तकरीबन क्षमता। औषधिक लचकनहि सभिसमज ७हल एकत्रित लाभान्वित स्वतंत्रता जैसे बनाकर सभीकुछ परिभाषित स्वतंत्रता रखते विवरण परस्पर असरकारक संस्क्रुति बलवान भाषा तरहथा। प्राप्त ढांचामात्रुभाषा बढाता अन्य जागरुक व्रुद्धि हमारी ७०है खरिदे एवम् लक्ष्य वास्तविक प्रव्रुति - -##################### -## Japanese Jugemu ## -##################### - -海砂利水魚の。やぶら小路の藪柑子、寿限無、寿限無。シューリンガンのグーリンダイ、水行末 雲来末 風来末。長久命の長助。五劫の擦り切れ。海砂利水魚の。五劫の擦り切れ、シューリンガンのグーリンダイ。長久命の長助。食う寝る処に住む処、食う寝る処に住む処、グーリンダイのポンポコピーのポンポコナーの。グーリンダイのポンポコピーのポンポコナーの。 - -水行末 雲来末 風来末。パイポパイポ パイポのシューリンガン。やぶら小路の藪柑子、水行末 雲来末 風来末、五劫の擦り切れ、やぶら小路の藪柑子、食う寝る処に住む処。長久命の長助。寿限無、寿限無。シューリンガンのグーリンダイ、グーリンダイのポンポコピーのポンポコナーの、海砂利水魚の。シューリンガンのグーリンダイ、パイポパイポ パイポのシューリンガン、グーリンダイのポンポコピーのポンポコナーの、海砂利水魚の。 - -寿限無、寿限無、食う寝る処に住む処。シューリンガンのグーリンダイ、食う寝る処に住む処。水行末 雲来末 風来末、水行末 雲来末 風来末、やぶら小路の藪柑子、長久命の長助、グーリンダイのポンポコピーのポンポコナーの、パイポパイポ パイポのシューリンガン、グーリンダイのポンポコピーのポンポコナーの。 - -パイポパイポ パイポのシューリンガン、やぶら小路の藪柑子。シューリンガンのグーリンダイ、長久命の長助、水行末 雲来末 風来末。食う寝る処に住む処。グーリンダイのポンポコピーのポンポコナーの。五劫の擦り切れ、海砂利水魚の。海砂利水魚の、食う寝る処に住む処。やぶら小路の藪柑子。五劫の擦り切れ、寿限無、寿限無。グーリンダイのポンポコピーのポンポコナーの。長久命の長助、寿限無、寿限無。 - -パイポパイポ パイポのシューリンガン、寿限無、寿限無、グーリンダイのポンポコピーのポンポコナーの。やぶら小路の藪柑子。シューリンガンのグーリンダイ、海砂利水魚の、水行末 雲来末 風来末。海砂利水魚の、五劫の擦り切れ、グーリンダイのポンポコピーのポンポコナーの。食う寝る処に住む処。 - -グーリンダイのポンポコピーのポンポコナーの。五劫の擦り切れ。シューリンガンのグーリンダイ。水行末 雲来末 風来末、パイポパイポ パイポのシューリンガン、やぶら小路の藪柑子。長久命の長助。食う寝る処に住む処、グーリンダイのポンポコピーのポンポコナーの。長久命の長助、海砂利水魚の。寿限無、寿限無。食う寝る処に住む処、水行末 雲来末 風来末。やぶら小路の藪柑子、五劫の擦り切れ、パイポパイポ パイポのシューリンガン。 - -長久命の長助。海砂利水魚の、水行末 雲来末 風来末、シューリンガンのグーリンダイ。シューリンガンのグーリンダイ。長久命の長助、寿限無、寿限無。五劫の擦り切れ。水行末 雲来末 風来末、食う寝る処に住む処、食う寝る処に住む処、五劫の擦り切れ、パイポパイポ パイポのシューリンガン、グーリンダイのポンポコピーのポンポコナーの、グーリンダイのポンポコピーのポンポコナーの、やぶら小路の藪柑子。海砂利水魚の、やぶら小路の藪柑子、寿限無、寿限無、パイポパイポ パイポのシューリンガン。 - -グーリンダイのポンポコピーのポンポコナーの。海砂利水魚の、五劫の擦り切れ。食う寝る処に住む処。五劫の擦り切れ。水行末 雲来末 風来末、パイポパイポ パイポのシューリンガン。やぶら小路の藪柑子、長久命の長助。 - -長久命の長助。グーリンダイのポンポコピーのポンポコナーの、寿限無、寿限無。やぶら小路の藪柑子、パイポパイポ パイポのシューリンガン、海砂利水魚の、水行末 雲来末 風来末。やぶら小路の藪柑子。水行末 雲来末 風来末。寿限無、寿限無、パイポパイポ パイポのシューリンガン、グーリンダイのポンポコピーのポンポコナーの、食う寝る処に住む処。長久命の長助。食う寝る処に住む処、五劫の擦り切れ、海砂利水魚の。 - -海砂利水魚の。寿限無、寿限無。長久命の長助、食う寝る処に住む処、グーリンダイのポンポコピーのポンポコナーの、シューリンガンのグーリンダイ、水行末 雲来末 風来末、やぶら小路の藪柑子。グーリンダイのポンポコピーのポンポコナーの、五劫の擦り切れ。パイポパイポ パイポのシューリンガン、食う寝る処に住む処、長久命の長助、五劫の擦り切れ、寿限無、寿限無、やぶら小路の藪柑子。海砂利水魚の。シューリンガンのグーリンダイ。パイポパイポ パイポのシューリンガン。水行末 雲来末 風来末。 - -################# -## Japanese v1 ## -################# - -共こわト車辺げちす時併要建ヒメクミ共欺イレヘ原就ヒカコ意名ざでいぴ因始ぜざいゅ史要トイニ成1度ラム見塩メ人板面うむル訃警わなだや際値知ホ係9幕可伸換とさー。泉ざゃべど京9車ヤソ派像らがふ意客つに帳整ナヒタロ超局ム回案べー選今じ問座エマ雪供やで進富ねふ最経8傷エトキ事掲フ域丈励寝ぶべ。 - -因ん対雑牟む耕王ぱえさ済棋ムラモ高権ウカイリ損報リニウ尾4散応っ真衝サオヘ充阪ラキト次中オ子副触ー。安レス郵車ミムヲ前療講もぼ運応生ど監第え症止ねど市那マヲ抜意ン庫紆就スニメ優年さぶぜ数換改エ馬真マワ著集ゃ予答僧兜函ぜにべ。民ツエヱ若思ね導囲地手ぶ旅画ーッ国4意ひをと也読し護済イうー査22接強論挑8政ノシト経訴3子オ組多ほるぽ祭拓泰至たてなこ。 - -部よごか種価ヤヱテ暖朝負量メヨ水提マ形入び待東ラしドか作年やぞかが覧高そ最質イス村32表カリ局今タヤ子囲フび本努っへほク成憂げてぐび歳匹つ基町トふは。更ヨユミ形公ホユソ閣独マセハテ鼻遅イ康推潤んち込重じんま投見キヱサ択自照ナア塚化ルト航問ラざゆ法重正おーゃね質5津装勘壇ばへ。迫フり小求号フ人川レひぽラ事百報ラぽ紹5競ノワ権正カコテヲ番要ンぶス米情名28懐蓄博及やうぎ。 - -裕にけゃぶ堂営ムリ町知しづゃ家浴広ロモ禁務友退ウリカタ統本どば演8程集か沸生げ両供ゃみざ載臨ニ依就ヱミノ手暮ゃぱ騒生しづ悩置か。南ト王期セヤヘ覧天塚うせくび面人おレめど新村ロ生弱リメマミ横増ざ的部ぶ提7本支きゆ学治た便事タヲ餅京サメヌ学案ぐ貴稿へでい心出圏看ひと。 - -競ごへろそ際特ひげめ応恐テ純最38化りぐよ議業ばすが交能じれ罪変モホ謙2感ケ保注ぎ研熊マ認応くとぱ。客ふ院純ヨ塗王提スぽぱ面知シ組往すう外夏ナフ主時ぞ変護べ芳記そ査旧オト京態リヘ彰料興もぽの。三議ム情義れ代調リろり断点ケヨ衛余売つこ思議困会だンお防者マテ厚態ヌテ点多碁ホ便新普わ飯府庭ナエ張30脱ょゅけざ止映哲控ぐでふ。 - -連テオ堀転ヱエス状案はぱ支政2熙だ真優ツヤ出30行ツ数軽ゆ大芸ずねかフ未明夢ツキエヒ民売こぎざば続医ミ便46右ー案65布まぼう。究く智身ニセライ無風写ラ草社出っ地結じ載王ばじごで進評オ点安マラ境覧界ハミテ瞬選雪傑摯ゆ。告オラヲネ記暮んンわ違出一オリニ愛宮チエ全個ぐくぼむ氏将ロサク統注ンだれ育秘ぽるゆへ意41壊トゆいぱ見上すッめ欺備会のに。 - -紀疲サ人際ウ属75南図クざず況本つづぜか会83月ユ市暮ぽ氏毎ねあすぜ上供てそろ顔格職に健略噴リへ。3安ぞイ存域ドゃず次図イづ皇北ヲ闘料を負年ラ自霊きふ湘知モクヌア中佐むく特数浦ワウ企申セミ象乞ーびも。過づうよ致技ソ転栄そン者期描をだす義連がよらり軍諸職ロ子約キリク報土ふま条参ケラネト海1同ツシ座校ヤ成者カセル申象世じ若悩織敢ゃ。 - -的13相ナロ球制ユレ輩務前みぐざず確権会へど回旬サスア間兆ハソウ終賠うもン仕認け日月霊他由喚かきゃ。無踏せぐじ視葉円くべう位81幅タ空格ヱラ組者ネヌム文払ろい糧36読象ナユミ面写めくぜぼ型創ーぐ関告トエスア最君恵熊リゅ。29冊ゃど地住クちむ葉前りわぴぱ藻天ホヲワク上点子カクロセ批個みょはど木川シチ図非らふ供氷サリヌ増軍ふゅイき済古了ヌコモ冬宿ま上83贈ねトあ増帯ウ贈販せ裏元フまうぶ。 - -供ル駆害ぶげゆじ伝福ヒチオテ区見レナウ読也性白都トぴり話責クイ他科どっク郎賀ムニミ歳仕男ゆこはだ年政ドぱ二援ヘヲルヒ典庁課拳比トぞー。住セス車点やたーン以歯造クサトネ安37整岩園26回リはしゃ声3毎クぐて輝毎県イてひ物載ぞくうお半周セマスシ勝被あ都1意こじの雪業13最むてしわ楽集アネ直思巡教ぴかわ。集ホケトヌ賞排フウメソ立選ゃ俳験ナト万意オ出銃ヒモ三新ぽ図向ゃち興聞ぞのン社緩望早みフね金報弁仁借おげラゃ。 - -拓ね物録2汁ト反61天蹴いろゆ奈支しだ宮性イセサ去写ば堀戦教偶レ売治ヘヒロ著非択しつ楽自フざ向球頼徳在みげにね。歌フハツヘ種概んば売知ばせ入43指9城縁はしさ挙皇ぼつッ社7市す信桜ウミメ福命具議れリイば。村ヤ真同スそ歌無づ前出エ択界かぜ産医ロトヨ体写処侵ヒク示況カツレ抜例ム後定ホチ問崩ヘロネ宮芸しだイ録未イ姿添づべ便聞ユソ深会スやへて毎男点がゅ。 - -################# -## Japanese v2 ## -################# - -尾きま舳列樹樹ソロオソ列雲ゆメタモモツオムラ知遊巣二他やねには「遊名ヌ」メケソテろへさ課知露野御譜巣ょすた。こ留目鵜よぬもし。列擢模かめ都ゃにあもや素屋素鵜サクュソニカ目巣。けて課屋他課区以譜野根派根御スウオタア名無絵列ひほせす列素めぬこ遊差以露無津都うっりこ絵野雲二目無いなぬてす。他差。 - -ねいそややとゆひいろゆ雲毛へたクテコきゃるりくちしかはふね雲瀬御手舳擢以たにあ阿阿っしつ雲名しまみ手阿。差津けのゆまおれ等鵜模れ阿舳知等派擢みけ目巣巣もまよこ日、以尾二他模、目舳尾目もゆまっハネネイセテヘふへっんょ遊以留知、ょっん都はにぬ以目差目絵瀬、みんこねふかなこょふきね。巣留区はえもちくひぬさ無露に模擢ョマホタヤセ絵等区ゆひ、氏名つゆれめ鵜野えゆろ保他夜ュカロミエ保ぬ。 - -せねんえ。ろやぬけぬめ津露御都根り氏阿鵜離。うしつ「お以御」雲他区ユロキカレナ列屋等派樹、名屋尾鵜ふあほき差尾やみウヘハくひはほ個にる瀬以名派め阿二ゅ。そのへりちへ他瀬せ尾差阿瀬模魔舳譜屋ひちにね夜他区津エノルミ差う課野の素瀬。御魔等あたちちいにゆ絵擢阿らまけちまゃ。てな、擢夜さかひすむ屋ち樹派模ふ舳ーハオュ二派名オツヌトヤ、瀬区阿根絵きにめ派魔毛りね。 - -都手ヘニュア。鵜都個素個個名模かとせひあて津以なかそくゅおしけか樹野ゆあそうせ野譜等派二派毛にちすろなっロケカョクまにむ瀬日すちョルニナきれもゃ尾氏鵜露鵜列毛たも。譜氏す差模以に野瀬譜擢阿素知等へねサヘふのほち。 - -つれつょつの鵜鵜屋列知手区むそ素他巣とりえぬふ区手名う素ふ等尾らろたっりさへはゆっんコヒヤウムユスヤ譜雲保留離鵜樹根夜。せつみほやウサマまろソアルメ舳課巣樹い日無毛舳屋ゆね。へえくつ雲鵜露ぬけろほ擢目魔絵阿レスヘニホ舳野日ゃんう絵いられょ尾課知二他夜御樹夜課としょゆ模二、きまほ離等個手み、素差課離氏無露もたしやぬね尾魔目夜毛ゃっ。るにいひちてしおやみみこけひに。 - -屋知保列たらュラアかそまひまなあ都鵜雲遊津日知個雲他名そ模擢せるち屋雲差以。離、のろき手魔れひ離屋ヤルほょれけはムュオツ露舳。課他巣。く、つゅすさうへぬや模手魔列離列っゅゃツロ舳と擢舳ムウリトフカ遊尾個差樹と野知巣模雲知、ナョエッロレ絵手差露差て目絵に絵他露せ等巣個離鵜根目樹。 - -無つとけ課もふらチノアヨ露名以もれきいきるケオハソ派以屋さこより。保樹へえもり絵瀬絵。派雲無てくるひそ露瀬瀬たへい課鵜たもろあむっまつしけ都ヌフリヌむめせょう毛屋瀬鵜やねれ。てね巣ゆり津留シネオ。ももりけはゅ御御御擢手津模ケトナ以いつ列列他ぬ御舳譜擢譜都すつまら屋らのそゃ名ろっるし根根遊課スケムラコむる派擢離名氏根巣っつみむみゃ。 - -そまクオハフソヤにきち根舳はやえ名雲んきヒオルウミコミシフフらみらたそほみねムアュモエコケえ、も素鵜れれゅこ、模樹ナシフウレれう、差瀬さ、手派ひおと「りうふ」ほされしゃよ露個ょはるかま毛無列れかえっぬに巣むたてと知樹遊ーーャュアウるとゆすあコモタニ、ょいろ。 - -うさりとは樹都素等模目うつふいま遊夜日知おあ氏譜差課目魔名巣名サヌコスモヌト等鵜区巣シー素遊舳区毛えま巣名雲露とハコ。いかな魔御しけひ課目りへ列区絵日露留離ふいゅらとさしんふ御遊擢離阿ハモャ屋他舳阿めひねうにつ尾差かヤヤハチヒャリるら。 - -派ゅひょ巣遊ケハンクニ差列っ二巣、差鵜ネロチフロオママさ、名つない露擢巣毛課等ぬょつのむミミュヘまりふのる魔遊よ鵜屋ユルリヒユ鵜ュエラめく毛留津譜譜御都等列舳差のそ。 - -############### -## Korean v1 ## -############### - -모든 국민은 법 앞에 평등하다. 모든 국민은 인간다운 생활을 할 권리를 가진다. 모든 국민은 능력에 따라 균등하게 교육을 받을 권리를 가진다. 국민의 자유와 권리는 헌법에 열거되지 아니한 이유로 경시되지 아니한다. - -국정의 중요한 사항에 관한 대통령의 자문에 응하기 위하여 국가원로로 구성되는 국가원로자문회의를 둘 수 있다. 국무총리는 부의장이 된다. 사영기업을 국유 또는 공유로 이전하거나 그 경영을 통제 또는 관리할 수 없다, 국회에서 의결된 법률안은 정부에 이송되어 15일 이내에 대통령이 공포한다. - -대통령은 조약을 체결·비준하고. 경제주체간의 조화를 통한 경제의 민주화를 위하여 경제에 관한 규제와 조정을 할 수 있다, 1차에 한하여 중임할 수 있다. 국방상 또는 국민경제상 긴절한 필요로 인하여 법률이 정하는 경우를 제외하고는. - -강화조약. 국회는 정부의 동의없이 정부가 제출한 지출예산 각항의 금액을 증가하거나 새 비목을 설치할 수 없다. 모든 국민의 재산권은 보장된다. 혼인과 가족생활은 개인의 존엄과 양성의 평등을 기초로 성립되고 유지되어야 하며. - -대통령은 내란 또는 외환의 죄를 범한 경우를 제외하고는 재직중 형사상의 소추를 받지 아니한다. 이 문서에는 국무총리와 관계 국무위원이 부서한다. 종교와 정치는 분리된다. 대법원장의 임기는 6년으로 하며. - -국가는 전통문화의 계승·발전과 민족문화의 창달에 노력하여야 한다. 국가안전보장회의의 조직·직무범위 기타 필요한 사항은 법률로 정한다. 신체장애자 및 질병·노령 기타의 사유로 생활능력이 없는 국민은 법률이 정하는 바에 의하여 국가의 보호를 받는다. 국가는 노인과 청소년의 복지향상을 위한 정책을 실시할 의무를 진다. - -국무총리·국무위원 또는 정부위원은 국회나 그 위원회에 출석하여 국정처리상황을 보고하거나 의견을 진술하고 질문에 응답할 수 있다. 대통령·국무총리·국무위원·행정각부의 장·헌법재판소 재판관·법관·중앙선거관리위원회 위원·감사원장·감사위원 기타 법률이 정한 공무원이 그 직무집행에 있어서 헌법이나 법률을 위배한 때에는 국회는 탄핵의 소추를 의결할 수 있다, 법률이 정하는 바에 의하여 최저임금제를 시행하여야 한다. 다만. - -국회는 법률에 저촉되지 아니하는 범위안에서 의사와 내부규율에 관한 규칙을 제정할 수 있다. 법률이 정하는 바에 의하여 연임할 수 있다. 국토와 자원은 국가의 보호를 받으며. 환경권의 내용과 행사에 관하여는 법률로 정한다. - -국회는 국민의 보통·평등·직접·비밀선거에 의하여 선출된 국회의원으로 구성한다, 언론·출판이 타인의 명예나 권리를 침해한 때에는 피해자는 이에 대한 피해의 배상을 청구할 수 있다, 대통령은 제3항과 제4항의 사유를 지체없이 공포하여야 한다, 교육의 자주성·전문성·정치적 중립성 및 대학의 자율성은 법률이 정하는 바에 의하여 보장된다. - -그 정치적 중립성은 준수된다, 다만, 대통령은 제4항과 제5항의 규정에 의하여 확정된 법률을 지체없이 공포하여야 한다. 모든 국민은 법률이 정하는 바에 의하여 선거권을 가진다. - -############### -## Korean v2 ## -############### - -새 이것이야말로 위하여서. 능히 그들은 것은 보배를 이상의 것이다. 같은 피는 불어 구하지 이상을 피에 피가 힘있다. 쓸쓸하랴? 못할 노래하며 일월과 갑 아름다우냐? 구하지 보내는 원대하고. 있는 인간에 보는 품으며, 위하여. 일월과 때에. 인간은 우리 피가 그러므로 이는 때까지 굳세게 낙원을 사막이다. - -풀이 있으며. 거친 원질이 소리다, 들어 목숨을 그들은 희망의 있으랴? 끓는 바로 광야에서 것이다. 있는 용기가 위하여 것이다. 소리다, 그러므로 풀이 밝은 튼튼하며, 같이 않는 동산에는 봄바람이다. 투명하되 못하다 그림자는 공자는 있을 이것이다. - -무한한 사랑의 약동하다, 오직 남는 불어 곳으로 싶이 피가 내는 인류의 보라. 고동을 끓는 거친 스며들어 그들을 보라, 봄바람이다. 그러므로 없으면. 전인 노년에게서 풀이 원대하고. 과실이 것은 이것을 무엇을 생생하며. 말이다. - -듣기만 부패뿐이다. 얼마나 가진 석가는 소금이라 그들은 사랑의 할지니. 방황하였으며. 곳이 피가 풀이 안고. 우리 가는 용기가 대고. 못할 우리의 가치를 무엇이 가지에 듣는다. 굳세게 그들에게 남는 간에 그와 인간은 소금이라 듣는다, 같으며. - -청춘이 있음으로써 가치를 피고 품으며. 수 그리하였는가? 아름답고 지혜는 얼음이 보라. 설산에서 열매를 원질이 남는 있으며. 이상의 두손을 사는가 무엇을 산야에 청춘은 그리하였는가? 철환하였는가 전인 곳이 피어나기 말이다. 보내는 부패를 그들은 끓는다. 뜨거운지라, 사람은 청춘이 황금시대를 같이, 산야에 품으며. - -그리하였는가? 날카로우나 천하를 이 품고 아름다우냐? 고동을 없는 대한 풀이 그들을 가슴에 피어나는 것이다. 위하여 과실이 예가 온갖 피다. 청춘은 현저하게 품고 동력은 있는 인간의 능히 천하를 보라. 아니다. 보내는 찬미를 피는 자신과 그들은 가슴에 운다. 만천하의 청춘의 얼음에 희망의 들어 보라, 끝에 인생의 풍부하게 가슴이 있을 있는 봄바람이다. 청춘 어디 아니더면. - -봄날의 피고. 작고 끓는 살 쓸쓸하랴? 때까지 품에 그들은 인간에 교향악이다. 길을 과실이 굳세게 설레는 그들의 것이다. 이상이 있을 따뜻한 얼음에 인생에 크고 쓸쓸하랴? 얼마나 청춘 없으면. 봄바람이다. 얼음과 듣기만 일월과 천지는 ? 대중을 청춘이 우리의 인생에 풀이 얼음이 아니다. 구할 이상은 일월과 돋고. 설산에서 때문이다. - -아름다우냐? 불러 구하지 그들은 아름다우냐? 속잎나고. 그들의 뛰노는 많이 희망의 우리의 일월과 그리하였는가? 구하지 반짝이는 이성은 봄바람이다. 장식하는 가는 그들에게 하여도 것이다, 앞이 작고 천지는 말이다. 우리 이것이다. 청춘에서만 청춘의 수 얼음이 하는 힘차게 위하여. 이상의 것은 산야에 이는 말이다. 것이다. - -심장은 타오르고 속에 얼마나 대한 있다, 이상의 따뜻한 길을 열락의 굳세게 것이다, 꽃 황금시대의 품으며, 위하여서 군영과 인간이 희망의 너의 부패뿐이다, 불어 대중을 놀이 하는 때에, 미묘한 아니한 바이며. 하는 수 장식하는 위하여. 원질이 인생을 전인 뿐이다. - -반짝이는 설산에서 들어 인도하겠다는 수 튼튼하며. 인생의 심장은 피고 무엇이 보배를 풀이 위하여서. 소담스러운 피고 청춘의 돋고. 들어 있는 놀이 끓는 설산에서 피는 봄바람이다. 귀는 있다, 보라. 밥을 굳세게 만천하의 이 것은 이것이다, 설산에서 이상이 심장의 곳이 사막이다. - -#################### -## Letzebuergesch ## -#################### - -Rem mä soubal rëscht. Si d'Sonn heemlech sin, sou spilt gréng erwaacht hu. D'Welt schnéiwäiss zum jo, ons hu erem gewëss. As Gart ruffen nei. Ronn wellen löschteg si ons. Wäit brét virun et sin. - -Heck heemlech um dat. Gëtt d'Kamäiner hu hun, Stret gebotzt wat un, frou hinnen hu dir. Do voll main méi. Rëm as gebotzt d'Stroos, sin ugedon weisen jo, iweral klinzecht de aus. Sou wa Hunn jeitzt, as oft Eisen gesiess. Päift Blieder gewalteg nei de, jéngt kréien löschteg dén hu, eise Stieren der as. - -Noper gebotzt mä ons, ech as iwer Mecht d'Mier, Mecht botze Biereg ze gin. Nei deser Kënnt wielen hu, op rout Himmel dén, un Biereg Minutt all. Ze der stét zwëschen, wa lait beschte prächteg fir. Wa éiweg duurch Völkerbond nët, mä d'Pan Stieren ass. Ech en Wisen derfir Dauschen, da Hunn eise goung dem, mir wa schéinen d'Hiezer. - -An Wand Freiesch sou, Dach zielen Riesen dén jo. Jo iwer aremt ons. Da rei vill d'Mier Säiten, da Mamm klinzecht gin. Well Freiesch dir wa. Get an d'Pied Milliounen, no rem deser derbei. Frot drun engem do dat, Mier Feld Minutt hu ons. - -Drun bléit d'Bëscher fir dé. Ke Land d'Loft hir, si sech jeitzt gewëss dan. Stad Säiten der un, aus Bänk Kënnt et, sech gehéiert schaddreg op oft. Kille Fletschen mir ze, ze och sinn rëschten schaddreg. - -Botze lossen sin wa, wou dé Fläiß Stréi d'Welt. Méngem Hémecht rëschten aus de. Do Fielse prächteg nei, dee Fläiß Schuebersonndeg am, gutt fond geplot jo fir. Hir geet sech do. - -Am hir d'Pan grousse, dat séngt iwerall dé. Do dan wait d'Kanner beschéngt, wee iwer d'Blumme fu. Mä Mier erem gin, fu méi Kléder Nuechtegall. Engel d'Hierz uechter wat un. As iech d'Sonn jeitzt wee. - -Wär un Bass dénen Dohannen, op Dall denkt Blieder rëm, eise Himmel fu déi. Haut d'Mier zwëschen en hun. Rëschten Klarinett am rem, prächteg Kolrettchen am wou. Vu Dall Scholl Feierwon nun, jéngt gréng kommen as rou, gin sech d'Welt d'Blumme um. En Minutt blëtzen méi, da dén gutt Frot. Um Wand uechter Blieder och, sin goung duerch si, sinn kommen rëschten hin ke. - -Haut fond räich oft mä. Och bléit Hierz d'Margréitchen am, oft vu Eisen eraus. Ruffen frësch wou de. Dénen iw'rem do déi. Gei wa geet muerges Hämmelsbrot. - -Bei wielen méngem genuch hu, ze d'Wéën Milliounen rëm. Blo eraus hirem no, Hunn Haus wa wéi, Frot muerges ons as. Wa räich d'Beem Dohannen der. Gei da keng Schiet d'Lëtzebuerger, hu den gutt gehéiert, wa dan bessert klinzecht. Ugedon bleiwe zwëschen fu dem, méi si Ierd Mier. - -############### -## Norwegian ## -############### - -I et land langt borte, mellom dype fjorder og høye fjell, bodde en stille landsby med vennlige mennesker. Landsbyen var kjent for sine vakre naturperler og klare innsjøer. Fjellene som omringet landsbyen, sto majestetisk og beskyttende, og de frodige skogene var fulle av liv. - -Selv om landsbyen var liten, hadde den en stor hjerte. Folk samlet seg på torget hver lørdag for å handle, prate og dele historier. De eldre satt ofte på benkene under trærne og fortalte eventyr om gamle dager. Det var alltid en følelse av fellesskap og tilhørighet. - -Hver vinter kom den iskalde vinden fra nord, og snøen dekket landsbyen som et tykt teppe. Barna lekte i snøen, bygde snømenn og skled på kjelker nedover bakkene. Når mørket falt på, lyste lyset fra peisene i hvert hjem, og landsbyen føltes som et trygt og varmt sted. - -Om sommeren blomstret engene med fargerike blomster, og fjellene var fulle av turister som ønsket å oppleve den storslåtte naturen. Elvene rant krystallklart, og lyden av rennende vann ga en rolig melodi til omgivelsene. Folket i landsbyen visste at de bodde i et spesielt sted, der naturen og menneskene levde i harmoni. - -############ -## Polish ## -############ - -W małym miasteczku, gdzie słońce zawsze świeci, żył sobie stary rzemieślnik. Jego umiejętności były legendarne, a jego wyroby przyciągały klientów z daleka. Każdego ranka, kiedy wstawał, jego pracownia wypełniała się dźwiękami młota uderzającego w metal i zapachem świeżo obrobionego drewna. Ludzie przychodzili nie tylko po przedmioty, ale także po opowieści o dawnych czasach, które rzemieślnik z chęcią opowiadał. - -Pewnego dnia, do jego pracowni zawitała młoda dziewczyna z ciekawym zleceniem. Chciała, aby stworzył dla niej niezwykłą skrzynię, w której mogłaby przechowywać swoje najcenniejsze skarby. Rzemieślnik z entuzjazmem przyjął wyzwanie i zaczął pracować, wykorzystując swoje najlepsze materiały i techniki. Po wielu dniach wytężonej pracy skrzynia była gotowa, a jej blask przyciągał wzrok każdego, kto przeszedł obok. - -Dziewczyna była zachwycona i od tej pory odwiedzała rzemieślnika, aby opowiadać mu o swoich przygodach, a on z radością dzielił się swoją wiedzą i doświadczeniem, tworząc nie tylko piękne przedmioty, ale także niezapomniane wspomnienia. - -################ -## Portuguese ## -################ - -Era uma vez, em uma pequena aldeia cercada por montanhas verdejantes, um jovem sonhador chamado Lucas. Ele passava seus dias explorando as florestas densas e os campos floridos. Um dia, enquanto caminhava à beira de um lago cristalino, Lucas encontrou um misterioso objeto brilhante enterrado na areia. Curioso, ele desenterrou o objeto e percebeu que era um antigo medallhão. - -Ao tocar o medallhão, Lucas sentiu uma onda de energia percorrer seu corpo. De repente, ele se viu transportado para um mundo mágico, repleto de criaturas fantásticas e paisagens deslumbrantes. Com coragem e determinação, Lucas embarcou em uma jornada épica para descobrir os segredos desse novo reino e, talvez, encontrar seu verdadeiro destino. - -############# -## Spanish ## -############# - -Era un cálido día de verano, y Sofía decidió pasar la tarde en la playa. Al llegar, extendió su toalla sobre la arena suave y se tumbó para disfrutar del sol. A su alrededor, el sonido de las olas rompiendo en la orilla y las risas de los niños jugando en el agua creaban una atmósfera relajante. - -Después de un rato, Sofía decidió dar un paseo por la orilla. Sentía la brisa marina en su rostro y el agua fresca acariciando sus pies. A lo lejos, observó a unos surfistas deslizándose sobre las olas, mientras un grupo de personas jugaba al voleibol en la arena. - -Al final del día, Sofía se sintió completamente renovada. Recolectó algunas conchas que encontró en la orilla y se despidió del mar, prometiendo volver pronto. - -############# -## Swedish ## -############# - -Skogens djupa grönska omsluter vandraren, och vinden susar genom trädkronorna. Ljuset filtreras genom lövverket och skapar ett magiskt sken på marken. I fjärran hörs ljudet av en fors som porlar, och en känsla av lugn sprider sig genom kroppen. - -Naturen är rik på skatter. Blåbär täcker marken och lingon lyser röda bland det gröna mossan. Vandra genom dalar och fjäll, och känn kraften av den svenska naturens orörda skönhet. Fåglar sjunger och ekorrar hoppar mellan grenarna, som om de vore naturens egna akrobater. - -Solen glittrar över den spegelblanka sjön, och ett par segelbåtar glider sakta fram. Lukten av nygrillat sprider sig från en grillplats, och skratt hörs från stranden. Alla njuter av sommaren, av gemenskapen och av de ljusa kvällarna som aldrig verkar ta slut. - -Höstens första kalla vindar sveper över landskapet, och löven skiftar till gult och rött. En promenad genom skogen blir som en färgsprakande föreställning. Svenska folkets kärlek till naturen är tydlig i alla årstider, från sommarens varma dagar till vinterns gnistrande snö. - -########## -## Thai ## -########## - -ในป่าลึก มีหมู่บ้านเล็กๆ ที่ผู้คนใช้ชีวิตอย่างสงบสุข ทุกวันพวกเขาตื่นขึ้นมาในยามเช้า และเดินไปหาน้ำใสๆ จากลำธาร เสียงน้ำไหลเรียกให้คนในหมู่บ้านมารวมตัวกันที่ใต้ต้นไม้ใหญ่ ที่นั่นพวกเขาเล่าเรื่องราวความรักและความฝันของพวกเขา - -วันหนึ่ง มีเด็กชายชื่อว่า "น้อย" ได้พบกับกบสีเขียวตัวหนึ่ง เขาตั้งชื่อให้มันว่า "กระโดด" ทั้งสองกลายเป็นเพื่อนที่ดีที่สุด น้อยและกระโดดผจญภัยไปในป่าทุกวัน พวกเขาได้ค้นพบโลกใหม่และเรียนรู้ว่าชีวิตนั้นมีความสวยงามเพียงใด - -เมื่อพระอาทิตย์ตกดิน พวกเขาจะกลับบ้านด้วยความสุขใจ บางครั้งน้อยนั่งลงใต้ต้นไม้และมองดาว twinkling ในท้องฟ้า เขาฝันถึงการผจญภัยใหม่ในวันพรุ่งนี้ - -############# -## Turkish ## -############# - -Bir zamanlar, uzak bir köyde yaşayan insanlar, her sabah güneşin doğuşunu kutlardı. Güneş, dağların arkasından yükseldiğinde, gökyüzü turuncu ve pembe renklere bürünürdü. Köylüler, taze ekmek ve süt ile kahvaltı yapar, ardından tarlalarda çalışmaya başlarlardı. - -Bir gün, köyün en cesur genci, ormanın derinliklerine gitmeye karar verdi. Yolda, büyüleyici çiçekler ve çeşitli kuş sesleri ile karşılaştı. Ormanın derinliklerinde, eski bir mağara buldu. Merakla içeri girdiğinde, karşısına muazzam bir hazine çıktı. Parlak altın ve değerli taşlarla dolu bu hazine, köyün kaderini değiştirecekti. - -Genç, hazineyi köyüne götürdü ve tüm köylülerle paylaştı. Böylece, köy daha önce hiç olmadığı kadar zenginleşti ve insanlar mutluluk içinde yaşamaya devam etti. - diff --git a/Common.Tests/Validation/EmailValidatorTests.cs b/Common.Tests/Validation/EmailValidatorTests.cs index 7c8d8b03..1c8f5929 100644 --- a/Common.Tests/Validation/EmailValidatorTests.cs +++ b/Common.Tests/Validation/EmailValidatorTests.cs @@ -10,7 +10,6 @@ internal sealed class EmailValidatorTests [Arguments("a!#$%&'*+-/=?^_`{|}~b@example.com")] [Arguments("x@a-b.c0")] [Arguments("taro..yamada@docomo.ne.jp")] // dot placement strict dot-atom forbids, but carriers issued - [Arguments("taro.@docomo.ne.jp")] [Arguments(".taro@ezweb.ne.jp")] public async Task IsValidAddress_Accepts(string address) { @@ -28,7 +27,6 @@ public async Task IsValidAddress_Accepts(string address) [Arguments("user@example.com ")] [Arguments("John ")] // display name, which MailAddress accepts [Arguments("\"quoted\"@example.com")] // quoted local part - [Arguments("us er@example.com")] [Arguments("user@localhost")] // single label [Arguments("user@1.2.3.4")] // IPv4 literal [Arguments("user@[1.2.3.4]")] @@ -95,8 +93,25 @@ public async Task TryNormalizeDomain_Accepts(string input, string expected) [Arguments("example.com..")] [Arguments("exa mple.com")] [Arguments("münchen.de")] + [Arguments("@")] + [Arguments("under_score.example")] + [Arguments("-leading.example")] + [Arguments("trailing-.example")] + [Arguments("double..dot.example")] public async Task TryNormalizeDomain_Rejects(string input) { await Assert.That(EmailValidator.TryNormalizeDomain(input, out _)).IsFalse(); } + + [Test] + public async Task TryNormalizeDomain_EnforcesLabelAndTotalLength() + { + var label63 = new string('a', 63); + var domain255 = string.Join('.', label63, label63, label63, label63); + + await Assert.That(EmailValidator.TryNormalizeDomain(label63 + ".example", out _)).IsTrue(); + await Assert.That(EmailValidator.TryNormalizeDomain(new string('a', 64) + ".example", out _)).IsFalse(); + await Assert.That(EmailValidator.TryNormalizeDomain(domain255, out _)).IsTrue(); + await Assert.That(EmailValidator.TryNormalizeDomain("a." + domain255, out _)).IsFalse(); + } } diff --git a/Common.Tests/Validation/SlugValidatorTests.cs b/Common.Tests/Validation/SlugValidatorTests.cs new file mode 100644 index 00000000..6cea87ae --- /dev/null +++ b/Common.Tests/Validation/SlugValidatorTests.cs @@ -0,0 +1,40 @@ +using OpenShock.Common.Constants; +using OpenShock.Common.Validation; + +namespace OpenShock.Common.Tests.Validation; + +internal sealed class SlugValidatorTests +{ + [Test] + [Arguments("ab")] + [Arguments("fun-times")] + [Arguments("a1-b2-c3")] + [Arguments("123")] + public async Task IsValid_LowercaseAlphanumericWithSingleHyphens_ReturnsTrue(string slug) + { + await Assert.That(SlugValidator.IsValid(slug)).IsTrue(); + } + + [Test] + [Arguments("a")] + [Arguments("-abc")] + [Arguments("abc-")] + [Arguments("a--b")] + [Arguments("with space")] + [Arguments("emojié")] + [Arguments("Upper")] + [Arguments("a_b")] + [Arguments("a/b")] + public async Task IsValid_Invalid_ReturnsFalse(string slug) + { + await Assert.That(SlugValidator.IsValid(slug)).IsFalse(); + } + + [Test] + public async Task IsValid_LengthBounds() + { + await Assert.That(SlugValidator.IsValid(new string('a', ApiHardLimits.PublicShareSlugMaxLength))).IsTrue(); + await Assert.That(SlugValidator.IsValid(new string('a', ApiHardLimits.PublicShareSlugMaxLength + 1))).IsFalse(); + await Assert.That(SlugValidator.IsValid("")).IsFalse(); + } +} diff --git a/Common.Tests/Validation/SocialValidatorTests.cs b/Common.Tests/Validation/SocialValidatorTests.cs new file mode 100644 index 00000000..34bec795 --- /dev/null +++ b/Common.Tests/Validation/SocialValidatorTests.cs @@ -0,0 +1,50 @@ +using OpenShock.Common.Constants; +using OpenShock.Common.Models; +using OpenShock.Common.Validation; + +namespace OpenShock.Common.Tests.Validation; + +internal sealed class SocialValidatorTests +{ + private static bool IsValid(SocialPlatform platform, string value) + => SocialValidator.IsValid(new UserProfileSocial { Platform = platform, Value = value }); + + [Test] + [Arguments(SocialPlatform.Website, "https://example.org")] + [Arguments(SocialPlatform.Website, "http://example.org/page")] + [Arguments(SocialPlatform.Bluesky, "someone.bsky.social")] + [Arguments(SocialPlatform.Discord, "someone")] + public async Task IsValid_Valid_ReturnsTrue(SocialPlatform platform, string value) + { + await Assert.That(IsValid(platform, value)).IsTrue(); + } + + [Test] + [Arguments(SocialPlatform.Website, "javascript:alert(1)")] + [Arguments(SocialPlatform.Website, "ftp://example.org")] + [Arguments(SocialPlatform.Website, "not a url")] + [Arguments(SocialPlatform.Website, "example.org")] + [Arguments(SocialPlatform.Discord, "has space")] + [Arguments(SocialPlatform.X, "https://x.com/someone")] + [Arguments(SocialPlatform.GitHub, "someone/repo")] + [Arguments(SocialPlatform.Reddit, "some\\one")] + [Arguments(SocialPlatform.Twitch, "tab\tname")] + [Arguments(SocialPlatform.Twitch, "")] + public async Task IsValid_Invalid_ReturnsFalse(SocialPlatform platform, string value) + { + await Assert.That(IsValid(platform, value)).IsFalse(); + } + + [Test] + public async Task IsValid_UndefinedPlatform_ReturnsFalse() + { + await Assert.That(IsValid((SocialPlatform)999, "someone")).IsFalse(); + } + + [Test] + public async Task IsValid_ValueLength() + { + await Assert.That(IsValid(SocialPlatform.Discord, new string('a', ApiHardLimits.UserProfileSocialValueMaxLength))).IsTrue(); + await Assert.That(IsValid(SocialPlatform.Discord, new string('a', ApiHardLimits.UserProfileSocialValueMaxLength + 1))).IsFalse(); + } +} diff --git a/Common.Tests/Validation/UsernameValidatorTests.cs b/Common.Tests/Validation/UsernameValidatorTests.cs index f03f4430..ed436535 100644 --- a/Common.Tests/Validation/UsernameValidatorTests.cs +++ b/Common.Tests/Validation/UsernameValidatorTests.cs @@ -1,4 +1,4 @@ -using OpenShock.Common.Results; +using OpenShock.Common.Results; using OpenShock.Common.Validation; namespace OpenShock.Common.Tests.Validation; @@ -6,191 +6,32 @@ namespace OpenShock.Common.Tests.Validation; internal sealed class UsernameValidatorTests { [Test] - public async Task Validate_ValidUsername_ReturnsSuccess() + [Arguments("TestUser123")] + [Arguments("abc")] // HardLimits.UsernameMinLength = 3 + [Arguments("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")] // HardLimits.UsernameMaxLength = 32 + [Arguments("test-user_123")] + [Arguments("test.user")] + [Arguments("test user")] // only leading/trailing whitespace is rejected + public async Task Validate_Accepts(string username) { - // Arrange - string username = "TestUser123"; - - // Act - var result = UsernameValidator.Validate(username); - - // Assert - await Assert.That(result is Success).IsTrue(); - } - - [Test] - public async Task Validate_TooShort_ReturnsError() - { - // Arrange - string username = "aa"; - - // Act - var result = UsernameValidator.Validate(username); - - // Assert - await Assert.That(result is UsernameError).IsTrue(); - await Assert.That(((UsernameError)result.Value!).Type).IsEqualTo(UsernameErrorType.TooShort); - } - - [Test] - public async Task Validate_TooLong_ReturnsError() - { - // Arrange - string username = new('a', 33); - - // Act - var result = UsernameValidator.Validate(username); - - // Assert - await Assert.That(result is UsernameError).IsTrue(); - await Assert.That(((UsernameError)result.Value!).Type).IsEqualTo(UsernameErrorType.TooLong); - } - - [Test] - public async Task Validate_StartWithWhitespace_ReturnsError() - { - // Arrange - string username = " TestUser123"; - - // Act - var result = UsernameValidator.Validate(username); - - // Assert - await Assert.That(result is UsernameError).IsTrue(); - await Assert.That(((UsernameError)result.Value!).Type).IsEqualTo(UsernameErrorType.StartOrEndWithWhitespace); - } - - [Test] - public async Task Validate_EndWithWhitespace_ReturnsError() - { - // Arrange - string username = "TestUser123 "; - - // Act - var result = UsernameValidator.Validate(username); - - // Assert - await Assert.That(result is UsernameError).IsTrue(); - await Assert.That(((UsernameError)result.Value!).Type).IsEqualTo(UsernameErrorType.StartOrEndWithWhitespace); - } - - [Test] - public async Task Validate_ResembleEmail_ReturnsError() - { - // Arrange - string username = "test@domain.com"; - - // Act - var result = UsernameValidator.Validate(username); - - // Assert - await Assert.That(result is UsernameError).IsTrue(); - await Assert.That(((UsernameError)result.Value!).Type).IsEqualTo(UsernameErrorType.ResembleEmail); + await Assert.That(UsernameValidator.Validate(username) is Success).IsTrue(); } [Test] - public async Task Validate_ContainsObnoxiousCharacters_ReturnsError() + [Arguments("ab", UsernameErrorType.TooShort)] + [Arguments("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", UsernameErrorType.TooLong)] + [Arguments(" TestUser123", UsernameErrorType.StartOrEndWithWhitespace)] + [Arguments("TestUser123 ", UsernameErrorType.StartOrEndWithWhitespace)] + [Arguments("\tTestUser", UsernameErrorType.StartOrEndWithWhitespace)] + [Arguments("test@domain.com", UsernameErrorType.ResembleEmail)] + [Arguments("TestUser\U0001F600", UsernameErrorType.ObnoxiousCharacters)] // emoji + [Arguments("test\u200Duser", UsernameErrorType.ObnoxiousCharacters)] // zero-width joiner + [Arguments("test\u202Euser", UsernameErrorType.ObnoxiousCharacters)] // right-to-left override + public async Task Validate_Rejects(string username, UsernameErrorType expected) { - // Arrange - string username = "TestUser😀"; - - // Act var result = UsernameValidator.Validate(username); - // Assert - await Assert.That(result is UsernameError).IsTrue(); - await Assert.That(((UsernameError)result.Value!).Type).IsEqualTo(UsernameErrorType.ObnoxiousCharacters); - } - - // --- Boundary value tests --- - - [Test] - public async Task Validate_ExactMinLength_ReturnsSuccess() - { - // HardLimits.UsernameMinLength = 3 - var result = UsernameValidator.Validate("abc"); - await Assert.That(result is Success).IsTrue(); - } - - [Test] - public async Task Validate_OneBelowMinLength_ReturnsTooShort() - { - // 2 chars = below min of 3 - var result = UsernameValidator.Validate("ab"); - await Assert.That(result is UsernameError).IsTrue(); - await Assert.That(((UsernameError)result.Value!).Type).IsEqualTo(UsernameErrorType.TooShort); - } - - [Test] - public async Task Validate_ExactMaxLength_ReturnsSuccess() - { - // HardLimits.UsernameMaxLength = 32 - var result = UsernameValidator.Validate(new string('a', 32)); - await Assert.That(result is Success).IsTrue(); - } - - [Test] - public async Task Validate_OneAboveMaxLength_ReturnsTooLong() - { - // 33 chars = above max of 32 - var result = UsernameValidator.Validate(new string('a', 33)); - await Assert.That(result is UsernameError).IsTrue(); - await Assert.That(((UsernameError)result.Value!).Type).IsEqualTo(UsernameErrorType.TooLong); - } - - [Test] - public async Task Validate_WithHyphensAndUnderscores_ReturnsSuccess() - { - var result = UsernameValidator.Validate("test-user_123"); - await Assert.That(result is Success).IsTrue(); - } - - [Test] - public async Task Validate_WithDots_ReturnsSuccess() - { - var result = UsernameValidator.Validate("test.user"); - await Assert.That(result is Success).IsTrue(); - } - - [Test] - public async Task Validate_WithMiddleSpaces_ReturnsSuccess() - { - // Middle spaces are allowed, only leading/trailing are rejected - var result = UsernameValidator.Validate("test user"); - await Assert.That(result is Success).IsTrue(); - } - - [Test] - public async Task Validate_TabAtStart_ReturnsWhitespaceError() - { - var result = UsernameValidator.Validate("\tTestUser"); - await Assert.That(result is UsernameError).IsTrue(); - await Assert.That(((UsernameError)result.Value!).Type).IsEqualTo(UsernameErrorType.StartOrEndWithWhitespace); - } - - [Test] - public async Task Validate_AtSignInMiddle_ReturnsResembleEmail() - { - var result = UsernameValidator.Validate("user@name"); - await Assert.That(result is UsernameError).IsTrue(); - await Assert.That(((UsernameError)result.Value!).Type).IsEqualTo(UsernameErrorType.ResembleEmail); - } - - [Test] - public async Task Validate_ZeroWidthJoiner_ReturnsObnoxious() - { - // Zero-width joiner U+200D - var result = UsernameValidator.Validate("test\u200Duser"); - await Assert.That(result is UsernameError).IsTrue(); - await Assert.That(((UsernameError)result.Value!).Type).IsEqualTo(UsernameErrorType.ObnoxiousCharacters); - } - - [Test] - public async Task Validate_RightToLeftOverride_ReturnsObnoxious() - { - // U+202E Right-to-left override - var result = UsernameValidator.Validate("test\u202Euser"); await Assert.That(result is UsernameError).IsTrue(); - await Assert.That(((UsernameError)result.Value!).Type).IsEqualTo(UsernameErrorType.ObnoxiousCharacters); + await Assert.That(((UsernameError)result.Value!).Type).IsEqualTo(expected); } } diff --git a/Common/Models/SemVersion.cs b/Common/Models/SemVersion.cs index 35e45d15..c59bb099 100644 --- a/Common/Models/SemVersion.cs +++ b/Common/Models/SemVersion.cs @@ -11,7 +11,7 @@ namespace OpenShock.Common.Models; /// /// - Accepts versions in the form MAJOR[.MINOR[.PATCH]][-PRERELEASE][+BUILD]. /// - Numeric parts are parsed into . -/// - Leading/trailing whitespace is trimmed. +/// - Whitespace is not trimmed: a version with leading or trailing whitespace is rejected. /// - Total input length is capped by . /// - This is intentionally permissive and not a full SemVer 2.0 validator. /// diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index df29666a..c7d5cd1b 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -356,17 +356,6 @@ public static IServiceCollection AddOpenShockServices(this IServiceCollection se return; } - // If the request resolved an automation token granting RateLimit, skip every limiter on it. - // Selectors are sync and the AutomationTokenMiddleware (which runs before UseRateLimiter) - // has already populated HttpContext.Items, so this is just a dictionary lookup. - static RateLimitPartition? TryBypass(HttpContext ctx) - { - var bypass = ctx.GetResolvedAutomationToken(); - return bypass is not null && bypass.Types.Contains(AutomationTokenType.RateLimit) - ? RateLimitPartition.GetNoLimiter($"automation-token-{bypass.Id}") - : null; - } - options.OnRejected = async (context, cancellationToken) => { var logger = context.HttpContext.RequestServices.GetRequiredService() @@ -393,60 +382,14 @@ await context.HttpContext.Response.WriteAsync("Too Many Requests. Please try aga // Global fallback limiter // Fixed window at 10k requests allows 20k bursts if burst occurs at window boundary - options.GlobalLimiter = PartitionedRateLimiter.Create(context => - { - if (TryBypass(context) is { } bypassPartition) return bypassPartition; - - var user = context.User; - var userId = user.FindFirstValue(ClaimTypes.NameIdentifier); - if (string.IsNullOrEmpty(userId)) - { - var ip = context.GetRemoteIP(); - if (IPAddress.IsLoopback(ip)) return RateLimitPartition.GetNoLimiter("ip-loopback-nolimit"); - - return RateLimitPartition.GetSlidingWindowLimiter($"ip-{ip}", _ => - new SlidingWindowRateLimiterOptions - { - PermitLimit = 1000, - Window = TimeSpan.FromMinutes(1), - SegmentsPerWindow = 6, - QueueProcessingOrder = QueueProcessingOrder.OldestFirst, - QueueLimit = 100 - }); - } - - if (user.HasClaim(claim => claim is { Type: ClaimTypes.Role, Value: "Admin" or "System" })) - return RateLimitPartition.GetNoLimiter("privileged-nolimit"); - - return RateLimitPartition.GetSlidingWindowLimiter($"user-{userId}", _ => - new SlidingWindowRateLimiterOptions - { - PermitLimit = 120, - Window = TimeSpan.FromMinutes(1), - SegmentsPerWindow = 6, - // No queue: this limiter runs after authentication, so a queued request would - // still execute, seconds later, with a session or API token that may have been - // revoked while it waited. Over the limit means 429, now. - QueueLimit = 0 - }); - }); + options.GlobalLimiter = PartitionedRateLimiter.Create(RateLimitPartitions.Global); // Authentication endpoints limiter - options.AddPolicy("auth", context => - { - if (TryBypass(context) is { } bypassPartition) return bypassPartition; - - var ip = context.GetRemoteIP().ToString(); - return RateLimitPartition.GetFixedWindowLimiter(ip, _ => new FixedWindowRateLimiterOptions - { - PermitLimit = 10, - Window = TimeSpan.FromMinutes(1) - }); - }); + options.AddPolicy("auth", RateLimitPartitions.Auth); // Token reporting endpoint concurrency limiter options.AddPolicy("token-reporting", context => - TryBypass(context) ?? + RateLimitPartitions.TryBypass(context) ?? RateLimitPartition.GetConcurrencyLimiter("token-reporting", _ => new ConcurrencyLimiterOptions { PermitLimit = 5, @@ -456,7 +399,7 @@ await context.HttpContext.Response.WriteAsync("Too Many Requests. Please try aga // Log fetching endpoint concurrency limiter options.AddPolicy("shocker-logs", context => - TryBypass(context) ?? + RateLimitPartitions.TryBypass(context) ?? RateLimitPartition.GetConcurrencyLimiter("shocker-logs", _ => new ConcurrencyLimiterOptions { PermitLimit = 10, @@ -468,7 +411,7 @@ await context.HttpContext.Response.WriteAsync("Too Many Requests. Please try aga // Control stats aggregate a user's whole history, so cap how many run at once options.AddPolicy("control-stats", context => - TryBypass(context) ?? + RateLimitPartitions.TryBypass(context) ?? RateLimitPartition.GetConcurrencyLimiter("control-stats", _ => new ConcurrencyLimiterOptions { PermitLimit = 10, diff --git a/Common/Services/Session/ISessionService.cs b/Common/Services/Session/ISessionService.cs index 43e23551..87d41128 100644 --- a/Common/Services/Session/ISessionService.cs +++ b/Common/Services/Session/ISessionService.cs @@ -16,8 +16,6 @@ public interface ISessionService public Task UpdateSessionAsync(LoginSession loginSession, TimeSpan ttl); - public Task DeleteSessionByTokenAsync(string sessionToken); - public Task DeleteSessionByIdAsync(Guid sessionId); public Task DeleteSessionsByUserIdAsync(Guid userId); diff --git a/Common/Services/Session/SessionService.cs b/Common/Services/Session/SessionService.cs index ce614cf8..fef78c2b 100644 --- a/Common/Services/Session/SessionService.cs +++ b/Common/Services/Session/SessionService.cs @@ -92,22 +92,6 @@ public async Task UpdateSessionAsync(LoginSession session, TimeSpan ttl) await _loginSessions.UpdateAsync(session, ttl); } - public async Task DeleteSessionByTokenAsync(string sessionToken) - { - // Only hash new tokens, old ones are 64 chars long - if (sessionToken.Length == AuthConstants.GeneratedTokenLength) - { - sessionToken = HashingUtils.HashToken(sessionToken); - } - - var session = await _loginSessions.FindByIdAsync(sessionToken); - if (session is null) return false; - - await _loginSessions.DeleteAsync(session); - await _redisPubService.SendSessionRevoked(session.Id); - return true; - } - public async Task DeleteSessionByIdAsync(Guid sessionId) { var session = await _loginSessions.FirstOrDefaultAsync(x => x.PublicId == sessionId); diff --git a/Common/Utils/DomainUtils.cs b/Common/Utils/DomainUtils.cs index cef65843..c89cfd8d 100644 --- a/Common/Utils/DomainUtils.cs +++ b/Common/Utils/DomainUtils.cs @@ -51,20 +51,6 @@ private static bool HostMatchesCookieDomainCore(ReadOnlySpan host, ReadOnl return true; // Even if host has more labels, the cookiedomain will match it } - /// - /// Returns true if ends with on a label boundary. - /// Accepts cookie domains with an optional leading '.' (ignored). - /// Both must be valid domains (after normalizing the cookie domain). - /// - public static bool HostMatchesCookieDomain(ReadOnlySpan host, ReadOnlySpan cookieDomain) - { - cookieDomain = RemoveLeadingDot(cookieDomain); - - if (!IsValidDomain(host) || !IsValidDomain(cookieDomain)) return false; - - return HostMatchesCookieDomainCore(host, cookieDomain); - } - /// /// Picks the most specific matching cookie domain (most labels) from a comma-separated list. /// Accepts items with an optional leading '.' and optional ASCII whitespace around them. diff --git a/Common/Utils/RateLimitPartitions.cs b/Common/Utils/RateLimitPartitions.cs new file mode 100644 index 00000000..a192918c --- /dev/null +++ b/Common/Utils/RateLimitPartitions.cs @@ -0,0 +1,81 @@ +using System.Net; +using System.Security.Claims; +using System.Threading.RateLimiting; +using OpenShock.Common.Extensions; +using OpenShock.Common.OpenShockDb; + +namespace OpenShock.Common.Utils; + +/// +/// The partition selectors of the rate limiter policies registered in . +/// +public static class RateLimitPartitions +{ + /// + /// If the request resolved an automation token granting RateLimit, skip every limiter on it. + /// Selectors are sync and the AutomationTokenMiddleware (which runs before UseRateLimiter) + /// has already populated HttpContext.Items, so this is just a dictionary lookup. + /// + public static RateLimitPartition? TryBypass(HttpContext ctx) + { + var bypass = ctx.GetResolvedAutomationToken(); + return bypass is not null && bypass.Types.Contains(AutomationTokenType.RateLimit) + ? RateLimitPartition.GetNoLimiter($"automation-token-{bypass.Id}") + : null; + } + + /// + /// Global fallback limiter: per IP for anonymous callers (loopback unlimited), per user otherwise, + /// with admins and the system unlimited. + /// + public static RateLimitPartition Global(HttpContext context) + { + if (TryBypass(context) is { } bypassPartition) return bypassPartition; + + var user = context.User; + var userId = user.FindFirstValue(ClaimTypes.NameIdentifier); + if (string.IsNullOrEmpty(userId)) + { + var ip = context.GetRemoteIP(); + if (IPAddress.IsLoopback(ip)) return RateLimitPartition.GetNoLimiter("ip-loopback-nolimit"); + + return RateLimitPartition.GetSlidingWindowLimiter($"ip-{ip}", _ => + new SlidingWindowRateLimiterOptions + { + PermitLimit = 1000, + Window = TimeSpan.FromMinutes(1), + SegmentsPerWindow = 6, + QueueProcessingOrder = QueueProcessingOrder.OldestFirst, + QueueLimit = 100 + }); + } + + if (user.HasClaim(claim => claim is { Type: ClaimTypes.Role, Value: "Admin" or "System" })) + return RateLimitPartition.GetNoLimiter("privileged-nolimit"); + + return RateLimitPartition.GetSlidingWindowLimiter($"user-{userId}", _ => + new SlidingWindowRateLimiterOptions + { + PermitLimit = 120, + Window = TimeSpan.FromMinutes(1), + SegmentsPerWindow = 6, + // No queue: this limiter runs after authentication, so a queued request would + // still execute, seconds later, with a session or API token that may have been + // revoked while it waited. Over the limit means 429, now. + QueueLimit = 0 + }); + } + + /// Authentication endpoints limiter: a small fixed window per IP. + public static RateLimitPartition Auth(HttpContext context) + { + if (TryBypass(context) is { } bypassPartition) return bypassPartition; + + var ip = context.GetRemoteIP().ToString(); + return RateLimitPartition.GetFixedWindowLimiter(ip, _ => new FixedWindowRateLimiterOptions + { + PermitLimit = 10, + Window = TimeSpan.FromMinutes(1) + }); + } +} diff --git a/Cron.IntegrationTests/AssemblyAttributes.cs b/Cron.IntegrationTests/AssemblyAttributes.cs new file mode 100644 index 00000000..6481fde7 --- /dev/null +++ b/Cron.IntegrationTests/AssemblyAttributes.cs @@ -0,0 +1,17 @@ +using OpenShock.Cron.IntegrationTests.Docker; +using OpenShock.IntegrationTests.Shared; + +// 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 the Cron host. +[assembly: Timeout(120_000)] + +namespace OpenShock.Cron.IntegrationTests; + +public static class TestSessionSetup +{ + // 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(), TestMailServer.WarmUpAsync()).WaitAsync(cancellationToken); +} diff --git a/Cron.IntegrationTests/Cron.IntegrationTests.csproj b/Cron.IntegrationTests/Cron.IntegrationTests.csproj index d3af8f27..ec5c6f2a 100644 --- a/Cron.IntegrationTests/Cron.IntegrationTests.csproj +++ b/Cron.IntegrationTests/Cron.IntegrationTests.csproj @@ -1,7 +1,7 @@ - + @@ -12,8 +12,6 @@ - - @@ -24,13 +22,4 @@ PreserveNewest - - - - - - <_Parameter1>$(SourceRevisionId) - - - diff --git a/Cron.IntegrationTests/CronApplicationFactory.cs b/Cron.IntegrationTests/CronApplicationFactory.cs index a88dfdd2..0c819e57 100644 --- a/Cron.IntegrationTests/CronApplicationFactory.cs +++ b/Cron.IntegrationTests/CronApplicationFactory.cs @@ -1,12 +1,16 @@ +using Hangfire; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Hosting; using OpenShock.Common.OpenShockDb; using OpenShock.Cron.IntegrationTests.Docker; using OpenShock.Cron.IntegrationTests.Helpers; using OpenShock.Cron.Jobs; +using OpenShock.Cron.Services.Email.Outbox; +using OpenShock.IntegrationTests.Shared; using Serilog; using Serilog.Events; using TUnit.Core.Interfaces; @@ -14,19 +18,19 @@ namespace OpenShock.Cron.IntegrationTests; /// -/// Boots the real Cron host (its Program) against throwaway Postgres / Redis / Mailpit -/// containers. Delivery is driven deterministically: tests seed outbox rows and then call -/// to run one pass of the real - -/// there is no background loop, so nothing races the assertions. The Cron host doesn't migrate on -/// boot, so the factory applies migrations to the fresh database first. +/// Boots the real Cron host (its Program) against throwaway Postgres / Redis / Mailpit containers, with +/// its background job processing taken out: no Hangfire server (so none of the recurring jobs ever fires) and no +/// listener enqueuing deliveries. Tests seed rows and then run a job themselves, e.g. one pass of the real +/// through , so nothing races the assertions. /// public sealed class CronApplicationFactory : WebApplicationFactory, IAsyncInitializer { - [ClassDataSource(Shared = SharedType.PerTestSession)] - public required InMemoryDatabase PostgreSql { get; init; } + // Injected so the database is started and migrated before the host boots; the host reads PostgresFixture.ConnectionString. + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required PostgresFixture PostgreSql { get; init; } - [ClassDataSource(Shared = SharedType.PerTestSession)] - public required InMemoryRedis Redis { get; init; } + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required RedisFixture Redis { get; init; } [ClassDataSource(Shared = SharedType.PerTestSession)] public required TestMailServer Mailpit { get; init; } @@ -36,17 +40,10 @@ public sealed class CronApplicationFactory : WebApplicationFactory, IAs public IDbContextFactory DbContextFactory => Services.GetRequiredService>(); - public async Task InitializeAsync() + public Task InitializeAsync() { - // The Cron host doesn't run migrations on boot, so apply them to the fresh database before - // anything touches it. Uses the same connection string the host will read from the env var. - await using (var migrationContext = new MigrationOpenShockContext( - PostgreSql.Container.GetConnectionString(), false, NullLoggerFactory.Instance)) - { - await migrationContext.Database.MigrateAsync(); - } - _ = Services; // Boot the Cron host (email dispatcher, templates, db factory, etc.). + return Task.CompletedTask; } /// @@ -66,7 +63,8 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) { { "ASPNETCORE_UNDER_INTEGRATION_TEST", "1" }, - { "OPENSHOCK__DB__CONN", PostgreSql.Container.GetConnectionString() }, + // The shared fixture has already migrated the database + { "OPENSHOCK__DB__CONN", PostgresFixture.ConnectionString }, { "OPENSHOCK__DB__SKIPMIGRATION", "true" }, { "OPENSHOCK__DB__DEBUG", "false" }, @@ -94,5 +92,36 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) { services.AddSerilog(configuration => configuration.WriteTo.Console(LogEventLevel.Warning)); }); + + builder.ConfigureTestServices(RemoveBackgroundProcessing); + } + + /// + /// Removes the Hangfire server and the Redis listener that enqueues deliveries. Without the server the + /// recurring jobs Program registers stay rows in Hangfire's storage and never run. Fails if either is not + /// found, so a Hangfire upgrade that registers its server differently cannot silently bring it back. + /// + private static void RemoveBackgroundProcessing(IServiceCollection services) + { + // AddHangfireServer registers AddTransient(factory), so + // the descriptor has no ImplementationType, only a Func. + static bool IsHangfireServer(ServiceDescriptor d) => + d.ImplementationFactory?.GetType().GenericTypeArguments is [_, var produced] && + produced == typeof(BackgroundJobServerHostedService); + + static bool IsOutboxListener(ServiceDescriptor d) => d.ImplementationType == typeof(EmailOutboxNotificationListener); + + var hostedServices = services.Where(d => d.ServiceType == typeof(IHostedService) && !d.IsKeyedService).ToList(); + var hangfireServers = hostedServices.Where(IsHangfireServer).ToList(); + var listeners = hostedServices.Where(IsOutboxListener).ToList(); + + if (hangfireServers.Count != 1 || listeners.Count != 1) + throw new InvalidOperationException( + $"Expected one Hangfire server and one outbox listener to remove, found {hangfireServers.Count} and {listeners.Count}"); + + foreach (var descriptor in hangfireServers.Concat(listeners)) + { + services.Remove(descriptor); + } } } diff --git a/Cron.IntegrationTests/Docker/DockerNetwork.cs b/Cron.IntegrationTests/Docker/DockerNetwork.cs deleted file mode 100644 index 7b4e9bb2..00000000 --- a/Cron.IntegrationTests/Docker/DockerNetwork.cs +++ /dev/null @@ -1,15 +0,0 @@ -using DotNet.Testcontainers.Builders; -using DotNet.Testcontainers.Networks; -using TUnit.Core.Interfaces; - -namespace OpenShock.Cron.IntegrationTests.Docker; - -public sealed class DockerNetwork : IAsyncInitializer, IAsyncDisposable -{ - public INetwork Instance { get; } = new NetworkBuilder() - .WithName($"tunit-cron-{Guid.CreateVersion7():N}") - .Build(); - - public Task InitializeAsync() => Instance.CreateAsync(); - public ValueTask DisposeAsync() => Instance.DisposeAsync(); -} diff --git a/Cron.IntegrationTests/Docker/InMemoryDatabase.cs b/Cron.IntegrationTests/Docker/InMemoryDatabase.cs deleted file mode 100644 index 68832b27..00000000 --- a/Cron.IntegrationTests/Docker/InMemoryDatabase.cs +++ /dev/null @@ -1,31 +0,0 @@ -using OpenShock.Internal.Common.Utils; -using Testcontainers.PostgreSql; -using TUnit.Core.Interfaces; - -namespace OpenShock.Cron.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-cron-postgresql-{Guid.CreateVersion7()}") - .WithDatabase("openshock") - .WithUsername("openshock") - .WithPassword(CryptoUtils.RandomString(32)) - .Build(); - - return _container; - } - } - - public Task InitializeAsync() => Container.StartAsync(); - public ValueTask DisposeAsync() => Container.DisposeAsync(); -} diff --git a/Cron.IntegrationTests/Docker/InMemoryRedis.cs b/Cron.IntegrationTests/Docker/InMemoryRedis.cs deleted file mode 100644 index 7d1a1c72..00000000 --- a/Cron.IntegrationTests/Docker/InMemoryRedis.cs +++ /dev/null @@ -1,28 +0,0 @@ -using Testcontainers.Redis; -using TUnit.Core.Interfaces; - -namespace OpenShock.Cron.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-cron-redis-{Guid.CreateVersion7()}") - .Build(); - - return _container; - } - } - - public Task InitializeAsync() => Container.StartAsync(); - public ValueTask DisposeAsync() => Container.DisposeAsync(); -} diff --git a/Cron.IntegrationTests/Docker/TestMailServer.cs b/Cron.IntegrationTests/Docker/TestMailServer.cs index d122cd5e..85d74863 100644 --- a/Cron.IntegrationTests/Docker/TestMailServer.cs +++ b/Cron.IntegrationTests/Docker/TestMailServer.cs @@ -4,33 +4,29 @@ namespace OpenShock.Cron.IntegrationTests.Docker; +/// +/// Mailpit, which the Cron host delivers to over SMTP and the tests read back over its HTTP API. Static for the +/// same reason as the shared Postgres and Redis fixtures: a session hook starts it ahead of the first test. +/// public sealed class TestMailServer : IAsyncInitializer, IAsyncDisposable { - [ClassDataSource(Shared = SharedType.PerTestSession)] - public required DockerNetwork DockerNetwork { get; init; } + private static readonly IContainer SharedContainer = new ContainerBuilder("axllent/mailpit:latest") // Same as Dev/docker-compose.yml, which does not pin it either + .WithPortBinding(1025, true) + .WithPortBinding(8025, true) + .WithWaitStrategy(Wait.ForUnixContainer() + .UntilHttpRequestIsSucceeded(r => r.ForPort(8025).ForPath("/api/v1/info"))) + .Build(); - private IContainer? _container; - public IContainer Container - { - get - { - _container ??= new ContainerBuilder("axllent/mailpit:latest") - .WithNetwork(DockerNetwork.Instance) - .WithName($"tunit-cron-mailpit-{Guid.CreateVersion7()}") - .WithPortBinding(1025, true) - .WithPortBinding(8025, true) - .WithWaitStrategy(Wait.ForUnixContainer() - .UntilHttpRequestIsSucceeded(r => r.ForPort(8025).ForPath("/api/v1/info"))) - .Build(); + private static readonly Lazy Started = new(() => SharedContainer.StartAsync()); - return _container; - } - } + public IContainer Container => SharedContainer; - public string SmtpHost => Container.Hostname; - public int SmtpPort => Container.GetMappedPublicPort(1025); - public string ApiBaseUrl => $"http://{Container.Hostname}:{Container.GetMappedPublicPort(8025)}"; + public string SmtpHost => SharedContainer.Hostname; + public int SmtpPort => SharedContainer.GetMappedPublicPort(1025); + public string ApiBaseUrl => $"http://{SharedContainer.Hostname}:{SharedContainer.GetMappedPublicPort(8025)}"; - public Task InitializeAsync() => Container.StartAsync(); - public ValueTask DisposeAsync() => Container.DisposeAsync(); + public static Task WarmUpAsync() => Started.Value; + + public Task InitializeAsync() => WarmUpAsync(); + public ValueTask DisposeAsync() => SharedContainer.DisposeAsync(); } diff --git a/Cron.IntegrationTests/Helpers/MailpitHelper.cs b/Cron.IntegrationTests/Helpers/MailpitHelper.cs index 55e39ebe..b65c19d7 100644 --- a/Cron.IntegrationTests/Helpers/MailpitHelper.cs +++ b/Cron.IntegrationTests/Helpers/MailpitHelper.cs @@ -72,15 +72,6 @@ public sealed class MailpitMessage { [JsonPropertyName("ID")] public string Id { get; init; } = string.Empty; - - [JsonPropertyName("Subject")] - public string Subject { get; init; } = string.Empty; - - [JsonPropertyName("To")] - public List? To { get; init; } - - [JsonPropertyName("Snippet")] - public string Snippet { get; init; } = string.Empty; } public sealed class MailpitFullMessage @@ -90,20 +81,5 @@ public sealed class MailpitFullMessage [JsonPropertyName("HTML")] public string Html { get; init; } = string.Empty; - - [JsonPropertyName("Text")] - public string Text { get; init; } = string.Empty; - - [JsonPropertyName("To")] - public List? To { get; init; } - } - - public sealed class MailpitContact - { - [JsonPropertyName("Name")] - public string Name { get; init; } = string.Empty; - - [JsonPropertyName("Address")] - public string Address { get; init; } = string.Empty; } } diff --git a/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs b/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs index e37e1818..3f620e25 100644 --- a/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs +++ b/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs @@ -3,6 +3,7 @@ using OpenShock.Common.Constants; using OpenShock.Common.OpenShockDb; using OpenShock.Common.Utils; +using OpenShock.IntegrationTests.Shared; using OpenShock.Internal.Common.Utils; namespace OpenShock.Cron.IntegrationTests.Tests; @@ -12,8 +13,9 @@ namespace OpenShock.Cron.IntegrationTests.Tests; /// mints the token lazily and renders the template, and the SMTP provider hands it to Mailpit. These are /// the behaviours that used to live (wrongly) in the API integration tests. /// -// Serialized with EmailOutboxQueryTests: this class's delivery job claims due rows under FOR UPDATE, -// whose held locks would otherwise make the query test's FOR UPDATE SKIP LOCKED read skip its row. +// Serialized with the other classes that touch the outbox: a delivery run claims every due row in the shared +// database under FOR UPDATE, which would make EmailOutboxQueryTests' FOR UPDATE SKIP LOCKED read skip its rows +// or deliver them first. [NotInParallel("email-outbox")] public sealed partial class EmailOutboxDeliveryTests { @@ -23,11 +25,11 @@ public sealed partial class EmailOutboxDeliveryTests [Test] public async Task PasswordReset_IsDelivered_AndEmailedTokenMatchesStoredHash() { - var email = UniqueEmail("cron-pwreset"); + var email = UniqueNames.Email("cron-pwreset"); using var mailpit = Factory.CreateMailpitHelper(); var (userId, stamp) = await AddUserAsync(email, "Reset User"); - var resetId = await AddPendingResetAsync(userId, stamp, email, "Reset User"); + var (resetId, _) = await AddPendingResetAsync(userId, stamp, email, "Reset User"); await Factory.RunDeliveryAsync(); @@ -55,8 +57,8 @@ public async Task PasswordReset_IsDelivered_AndEmailedTokenMatchesStoredHash() [Test] public async Task EmailChangeNotice_IsDelivered_ToOldAddress_WithoutAToken() { - var oldEmail = UniqueEmail("cron-notice-old"); - var newEmail = UniqueEmail("cron-notice-new"); + var oldEmail = UniqueNames.Email("cron-notice-old"); + var newEmail = UniqueNames.Email("cron-notice-new"); using var mailpit = Factory.CreateMailpitHelper(); // The change notice is self-contained (no token, no row to load): just enqueue and deliver. @@ -76,10 +78,55 @@ public async Task EmailChangeNotice_IsDelivered_ToOldAddress_WithoutAToken() await Assert.That(full.Html).DoesNotContain("token="); } + [Test] + public async Task EmailVerification_IsDelivered_ToNewAddress_AndEmailedTokenMatchesStoredHash() + { + var oldEmail = UniqueNames.Email("cron-verify-old"); + var newEmail = UniqueNames.Email("cron-verify-new"); + using var mailpit = Factory.CreateMailpitHelper(); + + var (userId, stamp) = await AddUserAsync(oldEmail, "Verify User"); + var change = new UserEmailChange + { + Id = Guid.CreateVersion7(), + UserId = userId, + OldEmail = oldEmail, + NewEmail = newEmail, + TokenHash = HashingUtils.HashToken(CryptoUtils.RandomString(AuthConstants.GeneratedTokenLength)), + SecurityStampAtCreate = stamp, + CreatedAt = DateTime.UtcNow + }; + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + db.UserEmailChanges.Add(change); + db.EmailOutbox.Add(EmailOutboxMessage.ForEmailVerification(change.Id, userId, newEmail, "Verify User")); + await db.SaveChangesAsync(); + } + + await Factory.RunDeliveryAsync(); + + var message = await mailpit.WaitForMessageAsync(newEmail); + await Assert.That(message).IsNotNull(); + + // The token is minted at send time: the link in the mail must hash to the value now stored on the change + var full = await mailpit.GetMessageAsync(message!.Id); + var token = VerifyLinkRegex().Match(full!.Html).Groups[1].Value; + await Assert.That(token).IsNotEmpty(); + + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + var stored = await db.UserEmailChanges.AsNoTracking().SingleAsync(c => c.Id == change.Id); + await Assert.That(HashingUtils.VerifyToken(token, stored.TokenHash).Verified).IsTrue(); + + var row = await db.EmailOutbox.AsNoTracking().SingleAsync(m => m.Recipient == newEmail); + await Assert.That(row.Status).IsEqualTo(EmailStatus.Sent); + } + } + [Test] public async Task PasswordReset_NewerRequest_SupersedesOlder_OnlyNewestDelivered() { - var email = UniqueEmail("cron-pwreset-coalesce"); + var email = UniqueNames.Email("cron-pwreset-coalesce"); using var mailpit = Factory.CreateMailpitHelper(); var (userId, stamp) = await AddUserAsync(email, "Coalesce User"); @@ -87,12 +134,13 @@ public async Task PasswordReset_NewerRequest_SupersedesOlder_OnlyNewestDelivered // Two pending resets for the same user sharing one coalesce key, each committed in its own // transaction so they get distinct created_at timestamps - exactly as two separate API requests // would. Both are pending before delivery runs; the newest must win, the older is superseded. - var olderOutboxId = await AddPendingResetOutboxAsync(userId, stamp, email, "Coalesce User"); - var newerOutboxId = await AddPendingResetOutboxAsync(userId, stamp, email, "Coalesce User"); + var (_, olderOutboxId) = await AddPendingResetAsync(userId, stamp, email, "Coalesce User"); + var (_, newerOutboxId) = await AddPendingResetAsync(userId, stamp, email, "Coalesce User"); await Factory.RunDeliveryAsync(); - // Exactly one email is delivered. + // Exactly one email is delivered: wait for the first to be stored, then count. + await Assert.That(await mailpit.WaitForMessageAsync(email)).IsNotNull(); var delivered = await mailpit.SearchByRecipientAsync(email); await Assert.That(delivered.Count).IsEqualTo(1); @@ -106,39 +154,20 @@ public async Task PasswordReset_NewerRequest_SupersedesOlder_OnlyNewestDelivered } [Test] - public async Task AccountActivation_ForASignupThatNoLongerExists_IsSkipped() + [Arguments(false)] // Completed, replaced or deleted since this message was queued + [Arguments(true)] // Still there, but past its lifetime + public async Task AccountActivation_ForASignupThatCannotBeCompleted_IsSkipped_AndMintsNoCode(bool signupStillExists) { - // Completed, replaced or expired since this message was queued: there is nothing to mail a code for. - var email = UniqueEmail("cron-activation-gone"); + var email = UniqueNames.Email("cron-activation-dead"); using var mailpit = Factory.CreateMailpitHelper(); - Guid outboxId; - await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + var pendingSignupId = Guid.CreateVersion7(); + string? seededHash = null; + if (signupStillExists) { - var outbox = EmailOutboxMessage.ForAccountActivation(Guid.CreateVersion7(), email, "Activation User"); - db.EmailOutbox.Add(outbox); - await db.SaveChangesAsync(); - outboxId = outbox.Id; + (pendingSignupId, seededHash) = await AddPendingSignupAsync(email, createdAt: DateTime.UtcNow - Duration.PendingSignupLifetime - TimeSpan.FromMinutes(1)); } - await Factory.RunDeliveryAsync(); - - await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) - { - var row = await db.EmailOutbox.AsNoTracking().SingleAsync(m => m.Id == outboxId); - await Assert.That(row.Status).IsEqualTo(EmailStatus.Skipped); - } - - await Assert.That((await mailpit.SearchByRecipientAsync(email)).Count).IsEqualTo(0); - } - - [Test] - public async Task AccountActivation_ForASignupPastItsLifetime_IsSkipped_AndMintsNoCode() - { - var email = UniqueEmail("cron-activation-expired"); - using var mailpit = Factory.CreateMailpitHelper(); - - var (pendingSignupId, seededHash) = await AddPendingSignupAsync(email, createdAt: DateTime.UtcNow - Duration.PendingSignupLifetime - TimeSpan.FromMinutes(1)); Guid outboxId; await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) { @@ -155,9 +184,12 @@ public async Task AccountActivation_ForASignupPastItsLifetime_IsSkipped_AndMints var row = await db.EmailOutbox.AsNoTracking().SingleAsync(m => m.Id == outboxId); await Assert.That(row.Status).IsEqualTo(EmailStatus.Skipped); - var pending = await db.PendingSignups.AsNoTracking().SingleAsync(p => p.Id == pendingSignupId); - await Assert.That(pending.CodeHash).IsEqualTo(seededHash); - await Assert.That(pending.CodeSentAt).IsNull(); + if (signupStillExists) + { + var pending = await db.PendingSignups.AsNoTracking().SingleAsync(p => p.Id == pendingSignupId); + await Assert.That(pending.CodeHash).IsEqualTo(seededHash); + await Assert.That(pending.CodeSentAt).IsNull(); + } } await Assert.That((await mailpit.SearchByRecipientAsync(email)).Count).IsEqualTo(0); @@ -166,7 +198,7 @@ public async Task AccountActivation_ForASignupPastItsLifetime_IsSkipped_AndMints [Test] public async Task AccountActivation_IsDelivered_AndEmailedCodeMatchesStoredHash() { - var email = UniqueEmail("cron-activation"); + var email = UniqueNames.Email("cron-activation"); using var mailpit = Factory.CreateMailpitHelper(); var (pendingSignupId, seededHash) = await AddPendingSignupAsync(email, failedAttempts: 3); @@ -219,8 +251,6 @@ public async Task AccountActivation_IsDelivered_AndEmailedCodeMatchesStoredHash( return (pending.Id, pending.CodeHash); } - // --- Helpers --- - private async Task<(Guid UserId, Guid Stamp)> AddUserAsync(string email, string name) { await using var db = await Factory.DbContextFactory.CreateDbContextAsync(); @@ -236,45 +266,28 @@ public async Task AccountActivation_IsDelivered_AndEmailedCodeMatchesStoredHash( }; db.Users.Add(user); await db.SaveChangesAsync(); - - // Read back the stamp in case the store generated it, so seeded SecurityStampAtCreate matches. - var stamp = await db.Users.AsNoTracking().Where(u => u.Id == user.Id).Select(u => u.SecurityStamp).FirstAsync(); - return (user.Id, stamp); + return (user.Id, user.SecurityStamp); } - private static UserPasswordReset NewResetRow(Guid userId, Guid stamp) => new() - { - Id = Guid.CreateVersion7(), - UserId = userId, - TokenHash = HashingUtils.HashToken(CryptoUtils.RandomString(AuthConstants.GeneratedTokenLength)), - SecurityStampAtCreate = stamp, - CreatedAt = DateTime.UtcNow - }; - - private async Task AddPendingResetAsync(Guid userId, Guid stamp, string email, string name) + /// Seeds a reset and its outbox row in their own transaction. + private async Task<(Guid ResetId, Guid OutboxId)> AddPendingResetAsync(Guid userId, Guid stamp, string email, string name) { await using var db = await Factory.DbContextFactory.CreateDbContextAsync(); - var reset = NewResetRow(userId, stamp); - db.UserPasswordResets.Add(reset); - db.EmailOutbox.Add(EmailOutboxMessage.ForPasswordReset(reset.Id, userId, email, name)); - await db.SaveChangesAsync(); - return reset.Id; - } - - /// Seeds a reset + its outbox row in their own transaction and returns the outbox row id. - private async Task AddPendingResetOutboxAsync(Guid userId, Guid stamp, string email, string name) - { - await using var db = await Factory.DbContextFactory.CreateDbContextAsync(); - var reset = NewResetRow(userId, stamp); + var reset = new UserPasswordReset + { + Id = Guid.CreateVersion7(), + UserId = userId, + TokenHash = HashingUtils.HashToken(CryptoUtils.RandomString(AuthConstants.GeneratedTokenLength)), + SecurityStampAtCreate = stamp, + CreatedAt = DateTime.UtcNow + }; var outbox = EmailOutboxMessage.ForPasswordReset(reset.Id, userId, email, name); db.UserPasswordResets.Add(reset); db.EmailOutbox.Add(outbox); await db.SaveChangesAsync(); - return outbox.Id; + return (reset.Id, outbox.Id); } - private static string UniqueEmail(string prefix) => $"{prefix}-{Guid.NewGuid().ToString("N")[..8]}@test.org"; - private static string? ExtractResetToken(string html) { var match = ResetLinkRegex().Match(html); @@ -283,4 +296,8 @@ private async Task AddPendingResetOutboxAsync(Guid userId, Guid stamp, str [GeneratedRegex(@"/account/password/recover/[0-9a-fA-F\-]+/([A-Za-z0-9]+)", RegexOptions.IgnoreCase)] private static partial Regex ResetLinkRegex(); + + // HtmlEncoder may write the = as a character reference + [GeneratedRegex(@"/verify-email\?token(?:=|=|=)([A-Za-z0-9]+)", RegexOptions.IgnoreCase)] + private static partial Regex VerifyLinkRegex(); } diff --git a/Cron.IntegrationTests/Tests/EmailOutboxQueryTests.cs b/Cron.IntegrationTests/Tests/EmailOutboxQueryTests.cs index 97613eb7..142fcf7b 100644 --- a/Cron.IntegrationTests/Tests/EmailOutboxQueryTests.cs +++ b/Cron.IntegrationTests/Tests/EmailOutboxQueryTests.cs @@ -1,19 +1,15 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenShock.Common.OpenShockDb; +using OpenShock.IntegrationTests.Shared; namespace OpenShock.Cron.IntegrationTests.Tests; /// -/// Runs the delivery job's actual claim query (, the single -/// source of truth the job uses) against real Postgres via the Cron host's own pooled context - the same -/// registration + enum-mapping path that runs in production. Guards the raw SQL (table/column names, the -/// email_status enum, LIMIT, FOR UPDATE SKIP LOCKED, SELECT * materialization) so a schema rename breaks -/// this test rather than only surfacing in the Cron host at runtime. +/// Which rows the delivery job's claim query () picks up, run as +/// the job runs it: through the Cron host's pooled context, inside a transaction. /// -// Serialized with EmailOutboxDeliveryTests: both share the session Postgres, and the delivery job -// claims due rows under FOR UPDATE (oldest-first). Running concurrently, that lock makes this test's -// FOR UPDATE SKIP LOCKED read skip its own (oldest) row. The shared key removes that window. +// A delivery run in another class would claim or lock these rows first [NotInParallel("email-outbox")] public sealed class EmailOutboxQueryTests { @@ -21,30 +17,49 @@ public sealed class EmailOutboxQueryTests public required CronApplicationFactory Factory { get; init; } [Test] - public async Task DueForDelivery_RunsTheJobsRawSql_AgainstTheRealSchema() + public async Task DueForDelivery_ClaimsDuePendingAndLapsedSending_OldestFirst_NotFutureOrTerminal() { - var recipient = $"outbox-claim-sql-{Guid.CreateVersion7():N}@test.org"; + var recipient = UniqueNames.Email("outbox-claim"); + var now = DateTime.UtcNow; - Guid id; - await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + var duePending = await SeedAsync(recipient, EmailStatus.Pending, now - TimeSpan.FromMinutes(10)); + var lapsedSending = await SeedAsync(recipient, EmailStatus.Sending, now - TimeSpan.FromMinutes(5)); + await SeedAsync(recipient, EmailStatus.Pending, now + TimeSpan.FromHours(1)); // scheduled retry, not yet due + await SeedAsync(recipient, EmailStatus.Sending, now + TimeSpan.FromHours(1)); // lease still held + await SeedAsync(recipient, EmailStatus.Sent, now - TimeSpan.FromMinutes(5)); + await SeedAsync(recipient, EmailStatus.Failed, now - TimeSpan.FromMinutes(5)); + await SeedAsync(recipient, EmailStatus.Skipped, now - TimeSpan.FromMinutes(5)); + + try { - var message = EmailOutboxMessage.Create( - EmailType.PasswordReset, recipient, "Claim", - new Dictionary { ["k"] = "v" }); - // Dated well into the past so it sorts first and the global LIMIT can never exclude it. - message.NextAttemptAt = DateTime.UtcNow - TimeSpan.FromDays(1); - db.EmailOutbox.Add(message); - await db.SaveChangesAsync(); - id = message.Id; - } + await using var scope = Factory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(); - // Resolve the pooled OpenShockContext exactly as the Cron delivery job does (DI-injected) so this - // covers the same registration + enum-mapping path that runs in production. - using var scope = Factory.Services.CreateScope(); - var db2 = scope.ServiceProvider.GetRequiredService(); + var claimed = await db.EmailOutbox.DueForDelivery(1000).ToListAsync(); - var claimed = await db2.EmailOutbox.DueForDelivery(1).ToListAsync(); + var ours = claimed.Where(m => m.Recipient == recipient).Select(m => m.Id).ToArray(); + await Assert.That(ours.Length).IsEqualTo(2); + await Assert.That(ours[0]).IsEqualTo(duePending); + await Assert.That(ours[1]).IsEqualTo(lapsedSending); + } + finally + { + await using var db = await Factory.DbContextFactory.CreateDbContextAsync(); + await db.EmailOutbox.Where(m => m.Recipient == recipient).ExecuteDeleteAsync(); + } + } - await Assert.That(claimed.Any(m => m.Id == id)).IsTrue(); + private async Task SeedAsync(string recipient, EmailStatus status, DateTime nextAttemptAt) + { + await using var db = await Factory.DbContextFactory.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/Cron.Tests/Services/Email/Outbox/EmailOutboxStateMachineTests.cs b/Cron.Tests/Services/Email/Outbox/EmailOutboxStateMachineTests.cs index ca48b4b2..7109c269 100644 --- a/Cron.Tests/Services/Email/Outbox/EmailOutboxStateMachineTests.cs +++ b/Cron.Tests/Services/Email/Outbox/EmailOutboxStateMachineTests.cs @@ -107,8 +107,20 @@ public async Task ApplyResult_Transient_WithAttemptsLeft_RequeuesWithBackoff() await Assert.That(message.SentAt).IsNull(); await Assert.That(message.FailedAt).IsNull(); await Assert.That(message.LastError).IsEqualTo("smtp timeout"); - // Rescheduled into the future on our own back-off curve. - await Assert.That(message.NextAttemptAt).IsEqualTo(Now + EmailOutboxRetryPolicy.BackoffFor(1)); + // Rescheduled on the back-off for one failed attempt. + await Assert.That(message.NextAttemptAt).IsEqualTo(Now + TimeSpan.FromSeconds(30)); + } + + [Test] + public async Task ApplyResult_Transient_OnSecondToLastAttempt_StillRequeues() + { + var message = NewMessage(); + message.AttemptCount = EmailOutboxRetryPolicy.MaxAttempts - 1; + + EmailOutboxStateMachine.ApplyResult(message, EmailDispatchResult.Transient("smtp timeout"), Now); + + await Assert.That(message.Status).IsEqualTo(EmailStatus.Pending); + await Assert.That(message.FailedAt).IsNull(); await Assert.That(message.NextAttemptAt).IsGreaterThan(Now); } @@ -128,15 +140,15 @@ public async Task ApplyResult_Transient_OnFinalAttempt_MarksFailed() // --- Back-off curve --- [Test] - public async Task BackoffFor_IsMonotonic_AndCapped() + [Arguments(0, 30)] // out of range is treated as the first attempt + [Arguments(1, 30)] + [Arguments(2, 60)] + [Arguments(3, 120)] + [Arguments(7, 1920)] + [Arguments(8, 3600)] // 3840s, capped at an hour + [Arguments(100, 3600)] + public async Task BackoffFor_DoublesFromThirtySeconds_CappedAtAnHour(int attempt, int expectedSeconds) { - var previous = TimeSpan.Zero; - for (var attempt = 1; attempt <= EmailOutboxRetryPolicy.MaxAttempts; attempt++) - { - var delay = EmailOutboxRetryPolicy.BackoffFor(attempt); - await Assert.That(delay).IsGreaterThanOrEqualTo(previous); // never decreases - await Assert.That(delay).IsLessThanOrEqualTo(TimeSpan.FromHours(1)); // capped - previous = delay; - } + await Assert.That(EmailOutboxRetryPolicy.BackoffFor(attempt)).IsEqualTo(TimeSpan.FromSeconds(expectedSeconds)); } } diff --git a/Cron/Program.cs b/Cron/Program.cs index f8f5cf6a..6469953f 100644 --- a/Cron/Program.cs +++ b/Cron/Program.cs @@ -21,8 +21,8 @@ builder.Services.AddOpenApi(OpenShockServiceHelper.OpenApiDocumentName, OpenShockServiceHelper.ConfigureOpenApi); // Hangfire workers fetch enqueued jobs by polling the queue table. The default interval (15s) is -// left as-is in production - email delivery within that window is fine and it adds no DB load. Only -// the integration test overrides it (via OpenShock:Hangfire:QueuePollInterval) to run fast. +// left as-is in production - email delivery within that window is fine and it adds no DB load. It can +// be overridden through OpenShock:Hangfire:QueuePollInterval. var hangfireStorageOptions = new PostgreSqlStorageOptions(); if (builder.Configuration.GetValue("OpenShock:Hangfire:QueuePollInterval") is { } queuePollInterval) hangfireStorageOptions.QueuePollInterval = queuePollInterval; diff --git a/Directory.Packages.props b/Directory.Packages.props index 4616e1eb..bcc63574 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -54,6 +54,7 @@ + \ No newline at end of file diff --git a/IntegrationTests.Shared/ContainerImages.cs b/IntegrationTests.Shared/ContainerImages.cs new file mode 100644 index 00000000..c63df0dd --- /dev/null +++ b/IntegrationTests.Shared/ContainerImages.cs @@ -0,0 +1,20 @@ +namespace OpenShock.IntegrationTests.Shared; + +/// +/// Images the integration tests run against, kept in one place so they move together with the compose stacks. +/// +public static class ContainerImages +{ + /// postgres:18 with TimescaleDB Community, the same image the compose stacks run. + public const string TimescaleDb = "ghcr.io/openshock/postgres-timescaledb:2.32.1-18.7-trixie"; + + /// + /// The image preloads TimescaleDB through its default command, which Testcontainers replaces with its own flags, + /// so every container started from has to pass these again. + /// + public static readonly string[] TimescaleDbCommand = + ["-c", "shared_preload_libraries=timescaledb", "-c", "timescaledb.telemetry_level=off"]; + + /// Same store as the compose stacks, which do not pin a version either. + public const string Dragonfly = "ghcr.io/dragonflydb/dragonfly:latest"; +} diff --git a/IntegrationTests.Shared/IntegrationTests.Shared.csproj b/IntegrationTests.Shared/IntegrationTests.Shared.csproj new file mode 100644 index 00000000..f13fae86 --- /dev/null +++ b/IntegrationTests.Shared/IntegrationTests.Shared.csproj @@ -0,0 +1,22 @@ + + + + + + + + + false + + + + + + + + + + + + + diff --git a/IntegrationTests.Shared/PostgresFixture.cs b/IntegrationTests.Shared/PostgresFixture.cs new file mode 100644 index 00000000..6587c890 --- /dev/null +++ b/IntegrationTests.Shared/PostgresFixture.cs @@ -0,0 +1,51 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using OpenShock.Common; +using OpenShock.Common.Options; +using OpenShock.Internal.Common.Utils; +using Testcontainers.PostgreSql; +using TUnit.Core.Interfaces; + +namespace OpenShock.IntegrationTests.Shared; + +/// +/// The one Postgres database of a test session. It is brought up the way the API brings up a database on boot, +/// through : the database does not exist +/// yet, so it is created, checked for TimescaleDB and migrated. That happens once, here, rather than in every host, +/// because every factory boots its own host against this database and EF's migrator is not safe to run +/// concurrently. The hosts set OPENSHOCK__DB__SKIPMIGRATION. +/// +/// +/// The container is static so a [Before(TestSession)] hook can start it through +/// ahead of the first test, instead of the first test's timeout paying for an image pull. +/// +public sealed class PostgresFixture : IAsyncInitializer, IAsyncDisposable +{ + private static readonly PostgreSqlContainer SharedContainer = new PostgreSqlBuilder(image: ContainerImages.TimescaleDb) + .WithCommand(ContainerImages.TimescaleDbCommand) + .WithUsername("openshock") + .WithPassword(CryptoUtils.RandomString(32)) + .Build(); + + private static readonly Lazy Started = new(StartAsync); + + /// Connection string of the migrated database, which the container does not create by itself. + public static string ConnectionString => + new NpgsqlConnectionStringBuilder(SharedContainer.GetConnectionString()) { Database = "openshock" }.ConnectionString; + + /// Starts and migrates the database once; later calls wait for the same start. + public static Task WarmUpAsync() => Started.Value; + + private static async Task StartAsync() + { + await SharedContainer.StartAsync(); + + await using var services = new ServiceCollection().AddLogging().BuildServiceProvider(); + await new ApplicationBuilder(services).ApplyPendingOpenShockMigrations(new DatabaseOptions { Conn = ConnectionString }); + } + + public Task InitializeAsync() => WarmUpAsync(); + + public ValueTask DisposeAsync() => SharedContainer.DisposeAsync(); +} diff --git a/IntegrationTests.Shared/RedisFixture.cs b/IntegrationTests.Shared/RedisFixture.cs new file mode 100644 index 00000000..209f60b3 --- /dev/null +++ b/IntegrationTests.Shared/RedisFixture.cs @@ -0,0 +1,24 @@ +using Testcontainers.Redis; +using TUnit.Core.Interfaces; + +namespace OpenShock.IntegrationTests.Shared; + +/// +/// The one Redis-compatible store of a test session. Static for the same reason as . +/// +public sealed class RedisFixture : IAsyncInitializer, IAsyncDisposable +{ + private static readonly RedisContainer SharedContainer = new RedisBuilder(image: ContainerImages.Dragonfly) + .WithCommand("--notify_keyspace_events=Ex") + .Build(); + + private static readonly Lazy Started = new(() => SharedContainer.StartAsync()); + + public RedisContainer Container => SharedContainer; + + public static Task WarmUpAsync() => Started.Value; + + public Task InitializeAsync() => WarmUpAsync(); + + public ValueTask DisposeAsync() => SharedContainer.DisposeAsync(); +} diff --git a/IntegrationTests.Shared/UniqueNames.cs b/IntegrationTests.Shared/UniqueNames.cs new file mode 100644 index 00000000..e58ef63e --- /dev/null +++ b/IntegrationTests.Shared/UniqueNames.cs @@ -0,0 +1,15 @@ +namespace OpenShock.IntegrationTests.Shared; + +/// +/// Names that cannot collide with another test's, since every test in a session shares one database. +/// +public static class UniqueNames +{ + /// Format: {prefix}-{8hex}@test.org. + public static string Email(string prefix) => $"{prefix}-{Suffix()}@test.org"; + + /// Lowercase {prefix}{8hex}. + public static string Username(string prefix) => $"{prefix}{Suffix()}".ToLowerInvariant(); + + private static string Suffix() => Guid.NewGuid().ToString("N")[..8]; +} diff --git a/OpenShockBackend.slnx b/OpenShockBackend.slnx index 44e928f4..7222dea3 100644 --- a/OpenShockBackend.slnx +++ b/OpenShockBackend.slnx @@ -7,6 +7,7 @@ + \ No newline at end of file