using System.Net; using System.Net.Http.Json; using Helpdesk.Api.Controllers; using Helpdesk.Application.Abstractions; using Helpdesk.Application.Auth; using Helpdesk.Domain.Auth; using Helpdesk.Infrastructure.Persistence; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.JsonWebTokens; using static Helpdesk.IntegrationTests.BackendFixture; namespace Helpdesk.IntegrationTests; public sealed class AuthTests(BackendFixture fixture) : IClassFixture { [Fact] public async Task LoginFailuresAreGenericAndLoginLimitAppliesPerClientAndEmail() { using var setup = fixture.CreateClient(); var user = await fixture.RegisterAsync(setup); var unrelated = await fixture.RegisterAsync(setup); using var limitedClient = fixture.CreateClient(); using var otherClient = fixture.CreateClient(); const string login = "/api/v1/auth/login"; const string wrongPassword = "Wrong-integration-password"; var unknown = await ReadAsync(limitedClient.PostAsJsonAsync(login, new LoginRequest("unknown@example.test", wrongPassword), Cancellation), HttpStatusCode.Unauthorized); for (var attempt = 0; attempt < 5; attempt++) { var failure = await ReadAsync(limitedClient.PostAsJsonAsync(login, new LoginRequest($" {user.Email.ToUpperInvariant()} ", wrongPassword), Cancellation), HttpStatusCode.Unauthorized); Assert.Equal((unknown.Status, unknown.Title, unknown.Type), (failure.Status, failure.Title, failure.Type)); } await ExpectAsync(limitedClient.PostAsJsonAsync(login, new LoginRequest(user.Email, Password), Cancellation), HttpStatusCode.TooManyRequests); Assert.Equal(unrelated.Id, (await LoginAsync(limitedClient, unrelated.Email)).User.Id); Assert.Equal(user.Id, (await LoginAsync(otherClient, user.Email)).User.Id); } [Fact] public async Task ResetReplacesALegacyPasswordAndRevokesTheOldSessionAndDevice() { using var anonymous = fixture.CreateClient(); var user = await fixture.RegisterAsync(anonymous); await using var scope = fixture.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); var hasher = scope.ServiceProvider.GetRequiredService(); var legacyPassword = new string('ž', 37); var account = await db.Users.SingleAsync(u => u.Id == user.Id, Cancellation); account.ChangePasswordHash(hasher.Hash(legacyPassword)); await db.SaveChangesAsync(Cancellation); var oldLogin = await ReadAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(user.Email, legacyPassword), Cancellation)); using var oldSession = fixture.CreateClient(oldLogin.AccessToken); await ExpectAsync(oldSession.PostAsJsonAsync("/api/v1/devices", new RegisterDeviceRequest("password-reset-device"), Cancellation), HttpStatusCode.NoContent); await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/forgot-password", new ForgotPasswordRequest(user.Email), Cancellation), HttpStatusCode.NoContent); var newPassword = new string('č', 36); var reset = new ResetPasswordRequest(await fixture.TakeResetTokenAsync(user.Email), newPassword); var validation = await ReadAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset with { NewPassword = newPassword + "a" }, Cancellation), HttpStatusCode.BadRequest); Assert.Contains("72 bajtů", Assert.Single(validation.Errors["newPassword"])); await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.NoContent); await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.BadRequest); await ExpectAsync(oldSession.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized); await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(user.Email, legacyPassword), Cancellation), HttpStatusCode.Unauthorized); var session = await ReadAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(user.Email, newPassword), Cancellation)); Assert.Equal(user.Id, session.User.Id); Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation)); } [Fact] public async Task LogoutRevokesOnlyTheCurrentSession() { using var anonymous = fixture.CreateClient(); var user = await fixture.RegisterAsync(anonymous); var session = await LoginAsync(anonymous, user.Email); var otherSession = await LoginAsync(anonymous, user.Email); using var client = fixture.CreateClient(session.AccessToken); using var otherClient = fixture.CreateClient(otherSession.AccessToken); var refresh = new RefreshTokenRequest(session.RefreshToken); await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/logout", refresh, Cancellation), HttpStatusCode.NoContent); await ExpectAsync(client.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized); await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.OK); var accessId = new JsonWebToken(session.AccessToken).Id; var refreshId = new JsonWebToken(session.RefreshToken).Id; await using var scope = fixture.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); Assert.Equal(2, await db.AuthTokens.CountAsync(token => token.UserId == user.Id && (token.Jti == accessId || token.Jti == refreshId) && token.RevokeReason == RevokeReason.Logout, Cancellation)); } [Fact] public async Task LogoutAllRemovesAllDevicesForTheAccount() { using var anonymous = fixture.CreateClient(); var user = await fixture.RegisterAsync(anonymous); var otherUser = await fixture.RegisterAsync(anonymous); using var first = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken); using var second = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken); using var unrelated = fixture.CreateClient((await LoginAsync(anonymous, otherUser.Email)).AccessToken); const string devices = "/api/v1/devices"; await ExpectAsync(first.PostAsJsonAsync(devices, new RegisterDeviceRequest("logout-first"), Cancellation), HttpStatusCode.NoContent); await ExpectAsync(second.PostAsJsonAsync(devices, new RegisterDeviceRequest("logout-second"), Cancellation), HttpStatusCode.NoContent); await ExpectAsync(unrelated.PostAsJsonAsync(devices, new RegisterDeviceRequest("logout-unrelated"), Cancellation), HttpStatusCode.NoContent); await ExpectAsync(first.PostAsync("/api/v1/auth/logout-all", null, Cancellation), HttpStatusCode.NoContent); await ExpectAsync(first.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized); await ExpectAsync(second.PostAsJsonAsync(devices, new RegisterDeviceRequest("logout-second"), Cancellation), HttpStatusCode.Unauthorized); await using var scope = fixture.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation)); Assert.True(await db.PushDevices.AnyAsync(device => device.UserId == otherUser.Id, Cancellation)); } [Fact] public async Task ConcurrentRefreshRevokesTheNewPairAndOtherSessions() { using var anonymous = fixture.CreateClient(); var user = await fixture.RegisterAsync(anonymous); var session = await LoginAsync(anonymous, user.Email); var otherSession = await LoginAsync(anonymous, user.Email); using var otherClient = fixture.CreateClient(otherSession.AccessToken); await ExpectAsync(otherClient.PostAsJsonAsync("/api/v1/devices", new RegisterDeviceRequest("refresh-replay-device"), Cancellation), HttpStatusCode.NoContent); var refresh = new RefreshTokenRequest(session.RefreshToken); var pause = fixture.TokenSaves.PauseNextSave(); Task first; Task duplicate; try { first = anonymous.PostAsJsonAsync("/api/v1/auth/refresh", refresh, Cancellation); await pause.Entered.Task.WaitAsync(TimeSpan.FromSeconds(15), Cancellation); await using var scope = fixture.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); Assert.Equal(2, await db.AuthTokens.CountAsync(token => token.UserId == user.Id && token.TokenType == TokenType.Refresh && token.RevokedAt == null, Cancellation)); duplicate = anonymous.PostAsJsonAsync("/api/v1/auth/refresh", refresh, Cancellation); } finally { pause.Release(); } var renewed = await ReadAsync(first); await ExpectAsync(duplicate, HttpStatusCode.Unauthorized); await using var after = fixture.Services.CreateAsyncScope(); var afterDb = after.ServiceProvider.GetRequiredService(); Assert.False(await afterDb.AuthTokens.AnyAsync(token => token.UserId == user.Id && token.RevokedAt == null, Cancellation)); Assert.False(await afterDb.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation)); using var renewedClient = fixture.CreateClient(renewed.AccessToken); await ExpectAsync(renewedClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized); await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized); } }