Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 1 addition & 11 deletions API.IntegrationTests/API.IntegrationTests.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\API\API.csproj" />
<ProjectReference Include="..\IntegrationTests.Shared\IntegrationTests.Shared.csproj" />
</ItemGroup>

<!-- Props -->
Expand All @@ -12,17 +13,6 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" />
<PackageReference Include="Testcontainers.PostgreSql" />
<PackageReference Include="Testcontainers.Redis" />
<PackageReference Include="TUnit" />
</ItemGroup>

<!-- Git stuff -->
<Target Name="SetHash" AfterTargets="InitializeSourceControlInformation">
<ItemGroup>
<AssemblyAttribute Include="OpenShock.Internal.Common.Utils.GitHashAttribute">
<_Parameter1>$(SourceRevisionId)</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
</Target>
</Project>
16 changes: 11 additions & 5 deletions API.IntegrationTests/AssemblyAttributes.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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)]
Expand All @@ -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);
}
15 changes: 0 additions & 15 deletions API.IntegrationTests/Docker/DockerNetwork.cs

This file was deleted.

52 changes: 0 additions & 52 deletions API.IntegrationTests/Docker/InMemoryDatabase.cs

This file was deleted.

28 changes: 0 additions & 28 deletions API.IntegrationTests/Docker/InMemoryRedis.cs

This file was deleted.

52 changes: 0 additions & 52 deletions API.IntegrationTests/GeoLocatedWebApplicationFactory.cs

This file was deleted.

70 changes: 70 additions & 0 deletions API.IntegrationTests/HeaderIpEnrichmentService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using System.Globalization;
using System.Net;
using Microsoft.AspNetCore.Http;
using OpenShock.Common.Services.Geo;

namespace OpenShock.API.IntegrationTests;

/// <summary>
/// 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
/// <see cref="WebApplicationFactory"/>; production never looks at these headers.
/// </summary>
public sealed class HeaderIpEnrichmentService : IIpEnrichmentService
{
/// <summary>Alpha-2 country the request resolves to.</summary>
public const string CountryHeader = "X-Test-Client-Country";

/// <summary>Location the request resolves to, as <c>latitude,longitude</c> in invariant culture.</summary>
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);
}

/// <summary>Places every request <paramref name="client"/> sends; null leaves that part unresolved.</summary>
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;
}

/// <summary>Places a single request; null leaves that part unresolved.</summary>
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));
}
}
42 changes: 42 additions & 0 deletions API.IntegrationTests/Helpers/OAuthFlowCookieHelper.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
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<IOptionsMonitor<CookieAuthenticationOptions>>().Get(OAuthConstants.FlowScheme);

List<Claim> 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)}";
}
}
21 changes: 1 addition & 20 deletions API.IntegrationTests/Helpers/TestHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -172,26 +173,6 @@ public static StringContent JsonContent(object obj)
{
return new StringContent(JsonSerializer.Serialize(obj, JsonOptions), Encoding.UTF8, "application/json");
}

/// <summary>
/// Generates a unique recipient address so per-test Mailpit lookups never collide with other
/// tests' emails. Format: <c>{prefix}-{8hex}@test.org</c>.
/// </summary>
public static string UniqueEmail(string prefix)
{
var suffix = Guid.NewGuid().ToString("N")[..8];
return $"{prefix}-{suffix}@test.org";
}

/// <summary>
/// Generates a unique username so concurrent tests in the same session never collide on the
/// users.name unique index.
/// </summary>
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);
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,26 @@ namespace OpenShock.API.IntegrationTests.HttpMessageHandlers;

sealed class InterceptedHttpMessageHandler : DelegatingHandler
{
/// <summary>The secret <see cref="WebApplicationFactory"/> configures; anything else is an invalid secret.</summary>
public const string TurnstileSecretKey = "turnstile-secret-key";

private async Task<HttpResponseMessage> 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
{
Expand Down
Loading