backend: Enforce notification access and clear push devices
This commit is contained in:
1 parent
ee5f1d3d10
commit
4f95c8a379
12 files changed
+145
-46
No files matched your search
@@ -1,5 +1,6 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Helpdesk.Api.Controllers;
|
||||
using Helpdesk.Application.Auth;
|
||||
using Helpdesk.Domain.Auth;
|
||||
using Helpdesk.Infrastructure.Persistence;
|
||||
@@ -13,11 +14,13 @@ namespace Helpdesk.IntegrationTests;
|
||||
public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||
{
|
||||
[Fact]
|
||||
public async Task ChangingPasswordThroughAnEmailLinkRevokesTheOldSession()
|
||||
public async Task ChangingPasswordThroughAnEmailLinkRevokesTheOldSessionAndRemovesItsDevice()
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
var user = await fixture.RegisterAsync(anonymous);
|
||||
using var oldSession = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).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);
|
||||
|
||||
@@ -31,6 +34,9 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFix
|
||||
var session = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
||||
new LoginRequest(user.Email, newPassword), Cancellation));
|
||||
Assert.Equal(user.Id, session.User.Id);
|
||||
await using var scope = fixture.Services.CreateAsyncScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -57,6 +63,29 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFix
|
||||
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<HelpdeskDbContext>();
|
||||
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()
|
||||
{
|
||||
@@ -64,6 +93,9 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFix
|
||||
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();
|
||||
@@ -87,11 +119,11 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFix
|
||||
var renewed = await ReadAsync<AuthResponse>(first);
|
||||
await ExpectAsync(duplicate, HttpStatusCode.Unauthorized);
|
||||
await using var after = fixture.Services.CreateAsyncScope();
|
||||
var tokens = after.ServiceProvider.GetRequiredService<HelpdeskDbContext>().AuthTokens;
|
||||
Assert.False(await tokens.AnyAsync(token => token.UserId == user.Id && token.RevokedAt == null, Cancellation));
|
||||
var afterDb = after.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
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);
|
||||
using var otherClient = fixture.CreateClient(otherSession.AccessToken);
|
||||
await ExpectAsync(renewedClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||
await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ public sealed class BackendFixture : IAsyncLifetime
|
||||
.Build();
|
||||
private readonly TestEmailSender email = new();
|
||||
private ApiFactory? factory;
|
||||
private int clientNumber;
|
||||
|
||||
internal TokenSaveGate TokenSaves { get; } = new();
|
||||
internal IServiceProvider Services => factory!.Services;
|
||||
@@ -62,7 +63,13 @@ public sealed class BackendFixture : IAsyncLifetime
|
||||
|
||||
internal HttpClient CreateClient(string? accessToken = null)
|
||||
{
|
||||
var client = factory!.CreateClient();
|
||||
// Každý klient simuluje vlastní IP adresu a má vlastní limit požadavků na přihlášení.
|
||||
var address = IPAddress.Parse($"2001:db8::{Interlocked.Increment(ref clientNumber):x}");
|
||||
var server = factory!.Server;
|
||||
var client = new HttpClient(server.CreateHandler(context => context.Connection.RemoteIpAddress = address))
|
||||
{
|
||||
BaseAddress = server.BaseAddress,
|
||||
};
|
||||
if (accessToken is not null)
|
||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
|
||||
return client;
|
||||
|
||||
@@ -5,6 +5,7 @@ using Helpdesk.Application.Catalogs;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Application.Issues;
|
||||
using Helpdesk.Application.Notifications;
|
||||
using Helpdesk.Application.Users;
|
||||
using Helpdesk.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
@@ -66,6 +67,50 @@ public sealed class NotificationTests(BackendFixture fixture) : IClassFixture<Ba
|
||||
Assert.Empty((await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation))).Items);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RoleChangeHidesOtherIssuesAndSkipsQueuedEmail()
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||
var reporterAccount = await fixture.RegisterAsync(anonymous);
|
||||
using var reporter = fixture.CreateClient((await LoginAsync(anonymous, reporterAccount.Email)).AccessToken);
|
||||
var managerSession = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
|
||||
using var manager = fixture.CreateClient(managerSession.AccessToken);
|
||||
const string issues = "/api/v1/issues";
|
||||
const string inbox = "/api/v1/notifications";
|
||||
var categories = await ReadAsync<CategoryDto[]>(reporter.GetAsync("/api/v1/issue-categories", Cancellation));
|
||||
var request = new CreateIssueRequest("Závada v učebně", "Závadu je potřeba prověřit.", categories[0].Id, null, null);
|
||||
|
||||
fixture.FailNextEmail(managerSession.User.Email, "TEST_RECIPIENT_REJECTED", retryable: false);
|
||||
var issue = await ReadAsync<IssueDetail>(reporter.PostAsJsonAsync(issues, request, Cancellation), HttpStatusCode.Created);
|
||||
var before = await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox, Cancellation));
|
||||
var hidden = Assert.Single(before.Items);
|
||||
Assert.Equal(issue.Id, hidden.IssueId);
|
||||
var failed = await WaitForDeliveryAsync(admin, hidden.Id, "FAILED");
|
||||
|
||||
await ExpectAsync(admin.PutAsJsonAsync($"/api/v1/admin/users/{managerSession.User.Id}/role",
|
||||
new ChangeRoleRequest("STUDENT"), Cancellation), HttpStatusCode.NoContent);
|
||||
using var student = fixture.CreateClient((await LoginAsync(anonymous, managerSession.User.Email)).AccessToken);
|
||||
var ownIssue = await ReadAsync<IssueDetail>(student.PostAsJsonAsync(issues, request, Cancellation), HttpStatusCode.Created);
|
||||
await ReadAsync<IssueEventDto>(admin.PostAsJsonAsync($"{issues}/{ownIssue.Id}/comments",
|
||||
new CommentRequest("Komentář k vlastní závadě uživatele."), Cancellation));
|
||||
|
||||
var after = await ReadAsync<PagedResult<NotificationDto>>(student.GetAsync(inbox, Cancellation));
|
||||
Assert.Equal(1, after.TotalCount);
|
||||
Assert.Equal(ownIssue.Id, Assert.Single(after.Items).IssueId);
|
||||
Assert.Equal(1, (await ReadAsync<UnreadCountDto>(student.GetAsync(inbox + "/unread-count", Cancellation))).Count);
|
||||
await ExpectAsync(student.PostAsync($"{inbox}/{hidden.Id}/read", null, Cancellation), HttpStatusCode.NotFound);
|
||||
await ExpectAsync(student.PostAsync(inbox + "/read-all", null, Cancellation), HttpStatusCode.NoContent);
|
||||
Assert.Equal(0, (await ReadAsync<UnreadCountDto>(student.GetAsync(inbox + "/unread-count", Cancellation))).Count);
|
||||
|
||||
await ExpectAsync(admin.PostAsync($"/api/v1/admin/notification-deliveries/{failed.Id}/retry", null, Cancellation),
|
||||
HttpStatusCode.NoContent);
|
||||
await WaitForDeliveryAsync(admin, hidden.Id, "SKIPPED", attempts: 0);
|
||||
await using var scope = fixture.Services.CreateAsyncScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
Assert.Null(await db.Notifications.Where(n => n.Id == hidden.Id).Select(n => n.ReadAt).SingleAsync(Cancellation));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeviceRegistrationPreservesCaseAndTransfersOwnership()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user