|
| 1 | +using System.Collections.Concurrent; |
| 2 | +using System.Net; |
| 3 | +using System.Text; |
| 4 | +using System.Text.Json; |
| 5 | +using Microsoft.Extensions.DependencyInjection; |
| 6 | +using OpenShock.Common.Constants; |
| 7 | +using OpenShock.Common.OpenShockDb; |
| 8 | +using OpenShock.Common.Services.Session; |
| 9 | +using OpenShock.Common.Utils; |
| 10 | + |
| 11 | +namespace OpenShock.API.IntegrationTests.Helpers; |
| 12 | + |
| 13 | +public static class TestHelper |
| 14 | +{ |
| 15 | + private static readonly JsonSerializerOptions JsonOptions = new() |
| 16 | + { |
| 17 | + PropertyNamingPolicy = JsonNamingPolicy.CamelCase |
| 18 | + }; |
| 19 | + |
| 20 | + /// <summary> |
| 21 | + /// Cache BCrypt hashes to avoid repeated expensive hashing across tests. |
| 22 | + /// BCrypt is synchronous and CPU-bound; hashing in every test causes thread pool |
| 23 | + /// starvation on CI runners with fewer cores, leading to test server timeouts. |
| 24 | + /// </summary> |
| 25 | + private static readonly ConcurrentDictionary<string, string> PasswordHashCache = new(); |
| 26 | + |
| 27 | + /// <summary> |
| 28 | + /// Creates a user directly in DB, creates a session via ISessionService, returns auth info. |
| 29 | + /// This bypasses signup/login endpoints entirely to avoid rate limiting. |
| 30 | + /// </summary> |
| 31 | + public static async Task<AuthenticatedUser> CreateAndLoginUser( |
| 32 | + WebApplicationFactory factory, |
| 33 | + string username, |
| 34 | + string email, |
| 35 | + string password) |
| 36 | + { |
| 37 | + // 1. Create user directly in DB |
| 38 | + var userId = await CreateUserInDb(factory, username, email, password); |
| 39 | + |
| 40 | + // 2. Create session via ISessionService (stored in Redis) |
| 41 | + await using var scope = factory.Services.CreateAsyncScope(); |
| 42 | + var sessionService = scope.ServiceProvider.GetRequiredService<ISessionService>(); |
| 43 | + var session = await sessionService.CreateSessionAsync(userId, "IntegrationTest", "127.0.0.1"); |
| 44 | + |
| 45 | + return new AuthenticatedUser(userId, username, email, session.Token); |
| 46 | + } |
| 47 | + |
| 48 | + /// <summary> |
| 49 | + /// Creates an HttpClient that sends the session cookie for authentication. |
| 50 | + /// </summary> |
| 51 | + public static HttpClient CreateAuthenticatedClient(WebApplicationFactory factory, string sessionToken) |
| 52 | + { |
| 53 | + var client = factory.CreateClient(new Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryClientOptions |
| 54 | + { |
| 55 | + AllowAutoRedirect = false, |
| 56 | + HandleCookies = false |
| 57 | + }); |
| 58 | + client.DefaultRequestHeaders.Add("Cookie", $"{AuthConstants.UserSessionCookieName}={sessionToken}"); |
| 59 | + return client; |
| 60 | + } |
| 61 | + |
| 62 | + /// <summary> |
| 63 | + /// Creates an HttpClient that sends an API token header for authentication. |
| 64 | + /// </summary> |
| 65 | + public static HttpClient CreateApiTokenClient(WebApplicationFactory factory, string apiToken) |
| 66 | + { |
| 67 | + var client = factory.CreateClient(new Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryClientOptions |
| 68 | + { |
| 69 | + AllowAutoRedirect = false, |
| 70 | + HandleCookies = false |
| 71 | + }); |
| 72 | + client.DefaultRequestHeaders.Add(AuthConstants.ApiTokenHeaderName, apiToken); |
| 73 | + return client; |
| 74 | + } |
| 75 | + |
| 76 | + /// <summary> |
| 77 | + /// Creates an HttpClient that sends a hub/device token header for authentication. |
| 78 | + /// </summary> |
| 79 | + public static HttpClient CreateHubTokenClient(WebApplicationFactory factory, string hubToken) |
| 80 | + { |
| 81 | + var client = factory.CreateClient(new Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryClientOptions |
| 82 | + { |
| 83 | + AllowAutoRedirect = false, |
| 84 | + HandleCookies = false |
| 85 | + }); |
| 86 | + client.DefaultRequestHeaders.Add(AuthConstants.HubTokenHeaderName, hubToken); |
| 87 | + return client; |
| 88 | + } |
| 89 | + |
| 90 | + /// <summary> |
| 91 | + /// Creates a user directly in the DB (bypasses signup endpoint). |
| 92 | + /// </summary> |
| 93 | + public static async Task<Guid> CreateUserInDb( |
| 94 | + WebApplicationFactory factory, |
| 95 | + string username, |
| 96 | + string email, |
| 97 | + string password, |
| 98 | + bool activated = true) |
| 99 | + { |
| 100 | + await using var scope = factory.Services.CreateAsyncScope(); |
| 101 | + var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>(); |
| 102 | + |
| 103 | + var userId = Guid.CreateVersion7(); |
| 104 | + var hash = PasswordHashCache.GetOrAdd(password, HashingUtils.HashPassword); |
| 105 | + db.Users.Add(new User |
| 106 | + { |
| 107 | + Id = userId, |
| 108 | + Name = username, |
| 109 | + Email = email, |
| 110 | + PasswordHash = hash, |
| 111 | + ActivatedAt = activated ? DateTime.UtcNow : null |
| 112 | + }); |
| 113 | + await db.SaveChangesAsync(); |
| 114 | + return userId; |
| 115 | + } |
| 116 | + |
| 117 | + /// <summary> |
| 118 | + /// Creates a device in the DB for a given user. Returns (deviceId, deviceToken). |
| 119 | + /// </summary> |
| 120 | + public static async Task<(Guid DeviceId, string Token)> CreateDeviceInDb( |
| 121 | + WebApplicationFactory factory, |
| 122 | + Guid ownerId, |
| 123 | + string name = "TestDevice") |
| 124 | + { |
| 125 | + await using var scope = factory.Services.CreateAsyncScope(); |
| 126 | + var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>(); |
| 127 | + |
| 128 | + var deviceId = Guid.CreateVersion7(); |
| 129 | + var token = CryptoUtils.RandomAlphaNumericString(256); |
| 130 | + db.Devices.Add(new Device |
| 131 | + { |
| 132 | + Id = deviceId, |
| 133 | + Name = name, |
| 134 | + OwnerId = ownerId, |
| 135 | + Token = token, |
| 136 | + CreatedAt = DateTime.UtcNow |
| 137 | + }); |
| 138 | + await db.SaveChangesAsync(); |
| 139 | + return (deviceId, token); |
| 140 | + } |
| 141 | + |
| 142 | + /// <summary> |
| 143 | + /// Creates an API token in the DB for a given user. Returns the raw token string. |
| 144 | + /// </summary> |
| 145 | + public static async Task<(Guid TokenId, string RawToken)> CreateApiTokenInDb( |
| 146 | + WebApplicationFactory factory, |
| 147 | + Guid userId, |
| 148 | + string name = "TestToken", |
| 149 | + List<Common.Models.PermissionType>? permissions = null) |
| 150 | + { |
| 151 | + await using var scope = factory.Services.CreateAsyncScope(); |
| 152 | + var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>(); |
| 153 | + |
| 154 | + var rawToken = CryptoUtils.RandomAlphaNumericString(AuthConstants.ApiTokenLength); |
| 155 | + var tokenId = Guid.CreateVersion7(); |
| 156 | + db.ApiTokens.Add(new ApiToken |
| 157 | + { |
| 158 | + Id = tokenId, |
| 159 | + UserId = userId, |
| 160 | + Name = name, |
| 161 | + TokenHash = HashingUtils.HashToken(rawToken), |
| 162 | + CreatedByIp = IPAddress.Loopback, |
| 163 | + Permissions = permissions ?? [Common.Models.PermissionType.Shockers_Use] |
| 164 | + }); |
| 165 | + await db.SaveChangesAsync(); |
| 166 | + return (tokenId, rawToken); |
| 167 | + } |
| 168 | + |
| 169 | + public static StringContent JsonContent(object obj) |
| 170 | + { |
| 171 | + return new StringContent(JsonSerializer.Serialize(obj, JsonOptions), Encoding.UTF8, "application/json"); |
| 172 | + } |
| 173 | +} |
| 174 | + |
| 175 | +public sealed record AuthenticatedUser(Guid Id, string Username, string Email, string SessionToken); |
0 commit comments