Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f506bb8f1d | |||
| b8fa4ae875 |
@@ -1,134 +0,0 @@
|
||||
using System.Data.Common;
|
||||
using System.Diagnostics;
|
||||
using JobTrackerApi.Controllers;
|
||||
using JobTrackerApi.Data;
|
||||
using JobTrackerApi.Models;
|
||||
using JobTrackerApi.Services;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using MySqlConnector;
|
||||
using Xunit;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace JobTrackerApi.MariaDb.Tests;
|
||||
|
||||
[CollectionDefinition("Rules MariaDB measurements", DisableParallelization = true)]
|
||||
public sealed class RulesMariaDbMeasurementCollection;
|
||||
|
||||
[Collection("Rules MariaDB measurements")]
|
||||
public sealed class RulesFreshnessMariaDbTests(ITestOutputHelper output)
|
||||
{
|
||||
private const string Owner = "rules-owner";
|
||||
private const string Other = "rules-other";
|
||||
private const string Fallback = "rules-fallback";
|
||||
private const int Repetitions = 100;
|
||||
|
||||
[Fact]
|
||||
public async Task Timed_out_save_preserves_committed_rules_and_retry_reaches_existing_readers()
|
||||
{
|
||||
await using var database = await MariaDbDatabase.CreateAsync();
|
||||
await Seed(database);
|
||||
await using var ownerReader = database.Context(Owner);
|
||||
await using var otherReader = database.Context(Other);
|
||||
Assert.Equal(30, (await RulesEngine.GetSettings(ownerReader, default)).AppliedFollowUpDays);
|
||||
Assert.Equal(45, (await RulesEngine.GetSettings(otherReader, default)).AppliedFollowUpDays);
|
||||
|
||||
await using var lockOwner = database.Context(Owner);
|
||||
await using var transaction = await lockOwner.Database.BeginTransactionAsync();
|
||||
var locked = await lockOwner.UserRuleSettings.SingleAsync();
|
||||
locked.AppliedFollowUpDays = 31;
|
||||
await lockOwner.SaveChangesAsync();
|
||||
|
||||
await using var failedWriter = database.Context(Owner);
|
||||
await failedWriter.Database.OpenConnectionAsync();
|
||||
await failedWriter.Database.ExecuteSqlRawAsync("SET SESSION innodb_lock_wait_timeout = 1");
|
||||
var started = Stopwatch.GetTimestamp();
|
||||
var error = await Assert.ThrowsAsync<InvalidOperationException>(
|
||||
() => new RulesController(failedWriter).Update(new RuleSettings { AppliedFollowUpDays = 1 }, default));
|
||||
var update = Assert.IsType<DbUpdateException>(error.InnerException);
|
||||
Assert.Equal(1205, Assert.IsType<MySqlException>(update.InnerException).Number);
|
||||
var timeout = Stopwatch.GetElapsedTime(started);
|
||||
|
||||
Assert.Equal(1, failedWriter.UserRuleSettings.Local.Single().AppliedFollowUpDays);
|
||||
Assert.Equal(30, (await RulesEngine.GetSettings(failedWriter, default)).AppliedFollowUpDays);
|
||||
Assert.Equal(30, (await RulesEngine.GetSettings(ownerReader, default)).AppliedFollowUpDays);
|
||||
Assert.Equal(45, (await RulesEngine.GetSettings(otherReader, default)).AppliedFollowUpDays);
|
||||
await transaction.RollbackAsync();
|
||||
|
||||
await using var retry = database.Context(Owner);
|
||||
started = Stopwatch.GetTimestamp();
|
||||
Assert.IsType<NoContentResult>(
|
||||
await new RulesController(retry).Update(new RuleSettings { AppliedFollowUpDays = 1 }, default));
|
||||
var retryDuration = Stopwatch.GetElapsedTime(started);
|
||||
Assert.Equal(1, (await RulesEngine.GetSettings(ownerReader, default)).AppliedFollowUpDays);
|
||||
Assert.Equal(45, (await RulesEngine.GetSettings(otherReader, default)).AppliedFollowUpDays);
|
||||
output.WriteLine($"MariaDB {database.ActualVersion} lock timeout {timeout.TotalMilliseconds:F1} ms; retry {retryDuration.TotalMilliseconds:F1} ms.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Committed_owner_and_fallback_reads_measure_queries_and_latency_with_same_workload()
|
||||
{
|
||||
await using var database = await MariaDbDatabase.CreateAsync();
|
||||
await Seed(database);
|
||||
var ownerQueries = new QueryCounter();
|
||||
var fallbackQueries = new QueryCounter();
|
||||
await using var owner = database.Context(Owner, ownerQueries);
|
||||
await using var fallback = database.Context(Fallback, fallbackQueries);
|
||||
|
||||
Assert.Equal(30, (await RulesEngine.GetSettings(owner, default)).AppliedFollowUpDays);
|
||||
Assert.Equal(60, (await RulesEngine.GetSettings(fallback, default)).AppliedFollowUpDays);
|
||||
ownerQueries.Count = fallbackQueries.Count = 0;
|
||||
double[] ownerTimes = new double[Repetitions];
|
||||
double[] fallbackTimes = new double[Repetitions];
|
||||
|
||||
for (var index = 0; index < Repetitions; index++)
|
||||
{
|
||||
ownerTimes[index] = await MeasureRead(owner, 30);
|
||||
fallbackTimes[index] = await MeasureRead(fallback, 60);
|
||||
}
|
||||
|
||||
Assert.Equal(Repetitions, ownerQueries.Count);
|
||||
Assert.Equal(Repetitions * 2, fallbackQueries.Count);
|
||||
Array.Sort(ownerTimes);
|
||||
Array.Sort(fallbackTimes);
|
||||
output.WriteLine(FormattableString.Invariant(
|
||||
$"MariaDB {database.ActualVersion}; {Repetitions} reads per path. Owner {ownerQueries.Count} commands, p50/p95 {ownerTimes[Repetitions / 2 - 1]:F3}/{ownerTimes[Repetitions * 95 / 100 - 1]:F3} ms. Fallback {fallbackQueries.Count} commands, p50/p95 {fallbackTimes[Repetitions / 2 - 1]:F3}/{fallbackTimes[Repetitions * 95 / 100 - 1]:F3} ms."));
|
||||
}
|
||||
|
||||
private static async Task<double> MeasureRead(JobTrackerContext db, int expected)
|
||||
{
|
||||
var start = Stopwatch.GetTimestamp();
|
||||
var settings = await RulesEngine.GetSettings(db, default);
|
||||
var elapsed = Stopwatch.GetElapsedTime(start).TotalMilliseconds;
|
||||
Assert.Equal(expected, settings.AppliedFollowUpDays);
|
||||
return elapsed;
|
||||
}
|
||||
|
||||
private static async Task Seed(MariaDbDatabase database)
|
||||
{
|
||||
await using var db = database.Context();
|
||||
db.Users.AddRange(
|
||||
new ApplicationUser { Id = Owner, UserName = Owner },
|
||||
new ApplicationUser { Id = Other, UserName = Other },
|
||||
new ApplicationUser { Id = Fallback, UserName = Fallback });
|
||||
(await db.RuleSettings.SingleAsync()).AppliedFollowUpDays = 60;
|
||||
db.UserRuleSettings.AddRange(
|
||||
new UserRuleSettings { OwnerUserId = Owner, AppliedFollowUpDays = 30 },
|
||||
new UserRuleSettings { OwnerUserId = Other, AppliedFollowUpDays = 45 });
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private sealed class QueryCounter : DbCommandInterceptor
|
||||
{
|
||||
public int Count { get; set; }
|
||||
|
||||
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
|
||||
DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
Count++;
|
||||
return base.ReaderExecutingAsync(command, eventData, result, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,9 @@ using JobTrackerApi.Controllers;
|
||||
using JobTrackerApi.Data;
|
||||
using JobTrackerApi.Models;
|
||||
using JobTrackerApi.Services;
|
||||
using JobTrackerApi.Tests.TestSupport;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -18,6 +20,39 @@ namespace JobTrackerApi.Tests;
|
||||
|
||||
public sealed class AccountDeletionTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Administrator_queues_only_the_confirmed_account_for_deletion()
|
||||
{
|
||||
await InFixtureAsync(enabled: true, async fixture =>
|
||||
{
|
||||
var owner = User("owner");
|
||||
fixture.Db.Users.AddRange(owner, User("admin"));
|
||||
await fixture.Db.SaveChangesAsync();
|
||||
|
||||
using var roles = new RoleManager<IdentityRole>(Mock.Of<IRoleStore<IdentityRole>>(), [],
|
||||
new UpperInvariantLookupNormalizer(), new IdentityErrorDescriber(), NullLogger<RoleManager<IdentityRole>>.Instance);
|
||||
using var users = TestHostFactory.CreateUserManager(owner).Object;
|
||||
var identity = new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "admin"), new Claim(ClaimTypes.Role, "Admin")], "test");
|
||||
var controller = new UsersController(users, roles, Mock.Of<IAppEmailSender>(), new ConfigurationBuilder().Build(),
|
||||
NullLogger<UsersController>.Instance, ExternalOrigin.Parse("http://localhost:3000", production: false), deletions: fixture.Service)
|
||||
{
|
||||
ControllerContext = new() { HttpContext = new DefaultHttpContext { User = new ClaimsPrincipal(identity) } }
|
||||
};
|
||||
|
||||
controller.Request.Headers["X-Confirm-Account-Deletion"] = "other@example.test";
|
||||
Assert.IsType<BadRequestObjectResult>(await controller.Delete(owner.Id, CancellationToken.None));
|
||||
Assert.Empty(await fixture.Db.AccountDeletionRequests.ToListAsync());
|
||||
|
||||
controller.Request.Headers["X-Confirm-Account-Deletion"] = owner.Email;
|
||||
Assert.IsType<AcceptedResult>(await controller.Delete(owner.Id, CancellationToken.None));
|
||||
var request = Assert.Single(await fixture.Db.AccountDeletionRequests.ToListAsync());
|
||||
Assert.Equal(owner.Id, request.OwnerUserId);
|
||||
Assert.Equal("admin", request.RequestedByUserId);
|
||||
Assert.Equal(AccountDeletionStatuses.Pending, (await fixture.Db.Users.SingleAsync(user => user.Id == owner.Id)).DeletionStatus);
|
||||
Assert.Equal(AccountDeletionStatuses.Active, (await fixture.Db.Users.SingleAsync(user => user.Id == "admin")).DeletionStatus);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Disabled_lifecycle_never_accepts_a_deletion_request()
|
||||
{
|
||||
|
||||
@@ -135,6 +135,7 @@ public sealed partial class ProfileCvController : ControllerBase
|
||||
{
|
||||
public static readonly NoOpEmailSender Instance = new();
|
||||
public Task SendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default) => Task.CompletedTask;
|
||||
public Task<bool> TrySendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default) => Task.FromResult(false);
|
||||
}
|
||||
|
||||
private sealed class ThrowingCvPdfExporter : ICvPdfExporter
|
||||
|
||||
@@ -245,20 +245,19 @@ public sealed class UsersController : ControllerBase
|
||||
|
||||
try
|
||||
{
|
||||
await _email.SendAsync(
|
||||
if (await _email.TrySendAsync(
|
||||
u.Email,
|
||||
"Password reset",
|
||||
$"An admin initiated a password reset for your Jobbjakt account.\n\nReset link:\n{link}\n",
|
||||
cancellationToken
|
||||
);
|
||||
)) return NoContent();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to send admin-initiated password reset email to {Email}", u.Email);
|
||||
return Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Email delivery unavailable", detail: "Password reset email could not be sent right now. Please try again later.");
|
||||
}
|
||||
|
||||
return NoContent();
|
||||
return Problem(statusCode: StatusCodes.Status503ServiceUnavailable, title: "Email delivery unavailable", detail: "Password reset email could not be sent right now. Please try again later.");
|
||||
}
|
||||
|
||||
public sealed record SendTestEmailRequest(string? ToEmail, string? Subject, string? Message);
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace JobTrackerApi.Services;
|
||||
public interface IAppEmailSender
|
||||
{
|
||||
Task SendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default);
|
||||
Task<bool> TrySendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public sealed class SmtpEmailSender : IAppEmailSender
|
||||
@@ -19,7 +20,10 @@ public sealed class SmtpEmailSender : IAppEmailSender
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task SendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default)
|
||||
public Task SendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default)
|
||||
=> TrySendAsync(toEmail, subject, bodyText, cancellationToken);
|
||||
|
||||
public async Task<bool> TrySendAsync(string toEmail, string subject, string bodyText, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var snapshot = await _settings.GetSnapshotAsync(cancellationToken);
|
||||
var host = snapshot.Host;
|
||||
@@ -35,7 +39,7 @@ public sealed class SmtpEmailSender : IAppEmailSender
|
||||
if (!enabled)
|
||||
{
|
||||
_logger.LogWarning("Email sending is disabled. Suppressed email to {To} subject={Subject}", toEmail, subject);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(host)) throw new InvalidOperationException("Email:SmtpHost is not configured.");
|
||||
@@ -61,5 +65,6 @@ public sealed class SmtpEmailSender : IAppEmailSender
|
||||
}
|
||||
|
||||
await Task.Run(() => smtp.Send(msg), cancellationToken);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,13 +7,3 @@ The additional real-SQLite case warms owner A/B application decisions, then inje
|
||||
All nine RuleSettingsFreshnessTests passed with zero failures/skips. Eight existing cases overlap the previous 35-case regression and are not added to that total. The native TRX, compressed/raw hashes and command log are retained under `evidence/rules-failed-save/`. Dependency restore used only the existing local NuGet cache. No application or dependency source changed.
|
||||
|
||||
The injected exception occurs before database save. This verifies committed-read behaviour after that failure and subsequent successful retry. Mid-transaction connection loss, MariaDB, multi-process load, latency, operational restore and release qualification remain separate.
|
||||
|
||||
## MariaDB committed reads after a native lock timeout
|
||||
|
||||
4 December 2026. Published A3 base `ac64d2ee221859c481dfd62e8fe83084af4c6764`. The native lane used disposable MariaDB 12.2.2 on Docker Desktop’s Linux engine with loopback TCP and .NET SDK 9.0.317.
|
||||
|
||||
A second connection held an uncommitted update of owner A’s rule row. The actual Rules controller save received MariaDB error 1205 through EF and Pomelo after 1,007.5 ms with the fixture session’s one-second lock timeout. Owner A’s committed threshold remained 30, including when read through the failed writer with its proposed value still tracked. Owner B remained at 45. After the lock holder rolled back, a fresh explicit save took 5.3 ms and the existing readers observed A at 1 and B still at 45.
|
||||
|
||||
With the same serialized workload and 100 warm reads of each path, the explicit-owner path issued 100 SQL commands and measured p50/p95 of 2.584/3.197 ms. The fallback path issued 200 commands and measured 5.068/6.095 ms. Every read returned its expected setting. These are local service-method measurements for a three-user fixture. Concurrent traffic, HTTP latency, production load and historical P2-O01’s missing server exception remain outside this run.
|
||||
|
||||
The first full run passed 101 of 102 cases. The test expected an unwrapped EF failure while Pomelo wrapped the same native server error. The final test checks both wrappers and error 1205. The second run passed **102 of 102**, zero skipped. Both disposable containers were removed. Run `python scripts/mariadb-integration.py` with the pinned SDK. Local native logs and TRX are in `.artifacts/issue-98-mariadb` and `.artifacts/issue-98-mariadb-final`. Final TRX SHA-256 `efdec2891da9e877273e0c9ab8273bc5b4fd516be326d0ad77bb2dd2496cf8ca`.
|
||||
|
||||
@@ -2,6 +2,7 @@ import AxeBuilder from '@axe-core/playwright';
|
||||
import { expect, test as base, type APIRequestContext, type APIResponse, type Locator, type Page, type TestInfo } from '@playwright/test';
|
||||
import { translations } from '../src/i18n/translations';
|
||||
import { enUS, nbNO } from '@mui/x-data-grid/locales';
|
||||
import { startLocalSMTPFixture } from '../scripts/localSMTPfixture.mjs';
|
||||
|
||||
const apiUrl = 'http://localhost:5302/api';
|
||||
const password = 'E2ePassword123!';
|
||||
@@ -10,10 +11,10 @@ type Headers = Record<string, string>;
|
||||
type Owner = { id: string; email: string; headers: Headers };
|
||||
type RequestRecord = { channel: 'browser' | 'api'; method: string; path: string; query: string; status?: number };
|
||||
type Session = { owner: Owner; admin: APIRequestContext; adminHeaders: Headers; requests: RequestRecord[] };
|
||||
const boundary = 'Actual isolated API/Identity/CSRF admin and ordinary accounts exercise Users create/read/role persistence, target-session revocation, final-admin conflict, non-admin denial and deletion-disabled 503 without deleting an account. Only the explicitly named first GET503 is controlled. Read Retry does not replay writes. No password-reset mail, provider/model/billing/restore/probe/maintenance, production or Phase8 action occurs. Google Fonts css2 stylesheets are aborted and all other nonlocal requests rejected. Desktop grid horizontal scrolling is intentional and its action reachability is keyboard checked. Chromium viewport/keyboard evidence does not establish physical touch, real zoom or human screen-reader acceptance.';
|
||||
const boundary = 'Actual isolated API/Identity/CSRF accounts exercise admin actions, target-session revocation, final-admin protection and non-admin denial. Reset mail reaches a loopback fixture for synthetic .test accounts. Deletion stays disabled. The unavailable-list case returns controlled GET503 responses until Retry. Read Retry does not replay writes. No provider/model/billing/restore/probe/maintenance, production or Phase8 action occurs. Google Fonts css2 requests are aborted and all other nonlocal requests rejected. Chromium viewport/keyboard evidence does not establish physical touch, real zoom or human screen-reader acceptance.';
|
||||
function copy(key: string, language: Language = 'en') { return (translations[language] as Record<string, string>)[key] ?? key; }
|
||||
function browserRequests(session: Session, path: string, method?: string) { return session.requests.filter(value => value.channel === 'browser' && value.path === `/api${path}` && (!method || value.method === method)); }
|
||||
async function call(records: RequestRecord[], api: APIRequestContext, method: 'GET' | 'POST' | 'PUT', path: string, headers?: Headers, data?: unknown) {
|
||||
async function call(records: RequestRecord[], api: APIRequestContext, method: 'GET' | 'POST' | 'PUT' | 'DELETE', path: string, headers?: Headers, data?: unknown) {
|
||||
const result = await api.fetch(`${apiUrl}${path}`, { method, headers, data });
|
||||
const url = new URL(result.url()); records.push({ channel: 'api', method, path: url.pathname, query: url.search, status: result.status() }); return result;
|
||||
}
|
||||
@@ -69,6 +70,74 @@ async function capture(page: Page, info: TestInfo, name: string) {
|
||||
|
||||
function response(page: Page, method: string, path: string) { return page.waitForResponse(value => value.request().method()===method && new URL(value.url()).pathname===`/api${path}`); }
|
||||
|
||||
for (const { language, width, theme } of [
|
||||
{ language: 'en', width: 1440, theme: 'light' },
|
||||
{ language: 'nb', width: 390, theme: 'dark' },
|
||||
] as const) {
|
||||
test(`[U-ADMIN] ${language} ${theme} ${width} reset delivery and deletion denial`, async ({ page, session }) => {
|
||||
const userPath = `/users/${session.owner.id}`;
|
||||
const resetPath = `${userPath}/send-password-reset`;
|
||||
expect((await call(session.requests, page.request, 'POST', resetPath, session.owner.headers)).status()).toBe(403);
|
||||
expect((await call(session.requests, page.request, 'DELETE', userPath, {
|
||||
...session.owner.headers, 'X-Confirm-Account-Deletion': session.owner.email,
|
||||
})).status()).toBe(403);
|
||||
|
||||
const administrator = await login(session.requests, page.request, 'e2e@example.test');
|
||||
expect((await call(session.requests, page.request, 'PUT', '/auth/preferences/language', administrator.headers, { language })).status()).toBe(204);
|
||||
await page.addInitScript(({ language, theme }) => {
|
||||
localStorage.setItem('uiLanguage', language);
|
||||
localStorage.setItem('jobtracker.themeMode', theme);
|
||||
}, { language, theme });
|
||||
await start(page, '/admin/users', width);
|
||||
await expect(page.locator('html')).toHaveAttribute('data-color-scheme', theme);
|
||||
const actions = page.getByRole('button', {
|
||||
name: copy('adminUsersActionsFor', language).replace('{name}', session.owner.email), exact: true,
|
||||
});
|
||||
const reset = async () => {
|
||||
const result = response(page, 'POST', resetPath);
|
||||
await keyboard(actions);
|
||||
await keyboard(page.getByRole('menuitem', { name: copy('adminUsersSendReset', language), exact: true }));
|
||||
return (await result).status();
|
||||
};
|
||||
|
||||
expect(await reset()).toBe(503);
|
||||
await expect(page.getByText(copy('adminUsersResetFailed', language), { exact: true })).toBeVisible();
|
||||
|
||||
const settingsPath = '/admin/system/email-settings';
|
||||
const original = await json<{ enabled: boolean; hasPassword: boolean }>(await call(session.requests, session.admin, 'GET', settingsPath));
|
||||
expect(original).toMatchObject({ enabled: false, hasPassword: false });
|
||||
const smtp = await startLocalSMTPFixture();
|
||||
try {
|
||||
expect((await call(session.requests, session.admin, 'PUT', settingsPath, session.adminHeaders, {
|
||||
enabled: true, host: '127.0.0.1', port: smtp.smtpPort, clearPassword: true,
|
||||
from: 'fixture@example.test', enableSsl: false, timeoutMs: 5000,
|
||||
})).status()).toBe(200);
|
||||
expect(await reset()).toBe(204);
|
||||
await expect(page.getByText(copy('adminUsersResetSent', language), { exact: true })).toBeVisible();
|
||||
const receipt = await fetch(`http://127.0.0.1:${smtp.controlPort}/messages?recipient=${encodeURIComponent(session.owner.email)}`);
|
||||
expect(receipt.status).toBe(200);
|
||||
const messages: Array<{ body: string }> = await receipt.json();
|
||||
expect(messages.length).toBe(1);
|
||||
expect(messages[0].body.includes('/reset-password?')).toBe(true);
|
||||
} finally {
|
||||
try {
|
||||
expect((await call(session.requests, session.admin, 'PUT', settingsPath, session.adminHeaders, {
|
||||
...original, clearPassword: true,
|
||||
})).status()).toBe(200);
|
||||
} finally { await smtp.close(); }
|
||||
}
|
||||
|
||||
await keyboard(actions);
|
||||
await keyboard(page.getByRole('menuitem', { name: copy('adminUsersDelete', language), exact: true }));
|
||||
const dialog = page.getByRole('dialog', { name: copy('adminUsersDeleteConfirmTitle', language), exact: true });
|
||||
const deletion = response(page, 'DELETE', userPath);
|
||||
await keyboard(dialog.getByRole('button', { name: copy('adminUsersDelete', language), exact: true }));
|
||||
expect((await deletion).status()).toBe(503);
|
||||
await expect(page.getByText('Account deletion remains disabled until retention and restore safeguards are approved.', { exact: true })).toBeVisible();
|
||||
await expect(actions).toBeVisible();
|
||||
});
|
||||
}
|
||||
|
||||
test('[P7-10 Users A01 E09] real admin creation/role persistence revoke sessions while final-admin and disabled deletion remain protected', async ({ page, playwright, session }) => {
|
||||
const administrator=await login(session.requests, page.request, 'e2e@example.test');
|
||||
const administrators=(await json<Array<{ id: string; roles: string[] }>>(await call(session.requests, page.request, 'GET', '/users'))).filter(value => value.roles.includes('Admin'));
|
||||
@@ -105,12 +174,16 @@ test('[P7-10 Users A01 E09] real admin creation/role persistence revoke sessions
|
||||
});
|
||||
|
||||
test('[P7-10 Users A01 E08] unavailable user list recovers by GET without fabricating empty state', async ({ page, session }, info) => {
|
||||
await login(session.requests, page.request, 'e2e@example.test'); let failed=false;
|
||||
await page.route(`${apiUrl}/users`, route => { if (route.request().method()==='GET' && !failed) { failed=true; return route.fulfill({ status: 503, json: { title: 'Controlled Users read failure' } }); } return route.continue(); });
|
||||
await login(session.requests, page.request, 'e2e@example.test');
|
||||
let failReads = true;
|
||||
await page.route(`${apiUrl}/users`, route => failReads && route.request().method() === 'GET'
|
||||
? route.fulfill({ status: 503, json: { title: 'Controlled Users read failure' } })
|
||||
: route.continue());
|
||||
await start(page, '/admin/users', 390);
|
||||
await expect(page.getByRole('alert').filter({ hasText: copy('adminUsersLoadFailed') })).toBeVisible();
|
||||
await expect(page.getByText(copy('adminUsersNoUsers'), { exact: true })).toHaveCount(0);
|
||||
const before=session.requests.filter(value => value.channel==='browser' && value.method!=='GET').length;
|
||||
failReads = false;
|
||||
await keyboard(page.getByRole('button', { name: copy('retry'), exact: true }));
|
||||
await expect(page.getByRole('group', { name: copy('adminUsersTitle'), exact: true })).toBeFocused();
|
||||
await expect(page.getByText('e2e@example.test', { exact: true }).first()).toBeVisible();
|
||||
@@ -130,7 +203,7 @@ test('[P7-10 Users A01] finite bilingual light/dark widths retain long identitie
|
||||
expect((await call(session.requests, page.request, 'PUT', '/auth/preferences/language', administrator.headers, { language: sample.language==='nb' ? 'nb-NO' : 'en' })).status()).toBe(204);
|
||||
await page.addInitScript(value => { localStorage.setItem('uiLanguage', value.language); localStorage.setItem('jobtracker.themeMode', value.mode); }, sample);
|
||||
await start(page, '/admin/users', sample.width);
|
||||
await expect(page.getByRole('heading', { level: 3, name: copy('adminUsersCreateUser', sample.language), exact: true })).toBeVisible();
|
||||
await expect(page.getByRole('heading', { level: 2, name: copy('adminUsersCreateUser', sample.language), exact: true })).toBeVisible();
|
||||
if (sample.width>=768) {
|
||||
const grid=page.getByRole('grid');
|
||||
await expect(grid.getByRole('row').nth(1)).toBeVisible();
|
||||
|
||||
@@ -10,7 +10,7 @@ const [backend, app] = base.webServer;
|
||||
const smtpPort = process.env.AUTH_RECOVERY_SMTP_PORT ?? "2527";
|
||||
const mailPort = process.env.AUTH_RECOVERY_MAIL_PORT ?? "5303";
|
||||
const nodeCommand = `"${process.execPath.replaceAll('"', '\\"')}"`;
|
||||
const captureCommand = `"${path.resolve("scripts/localSMTPfixture.mjs").replaceAll('"', '\\"')}"`;
|
||||
const captureCommand = `"${path.resolve("scripts/runLocalSMTPfixture.mjs").replaceAll('"', '\\"')}"`;
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "./auth-tests",
|
||||
|
||||
@@ -53,6 +53,12 @@ export default defineConfig({
|
||||
// Temporary SQLite browser lane until all fixture/DB proof helpers migrate to MariaDB.
|
||||
Database__Provider: "sqlite",
|
||||
ConnectionStrings__JobTracker: "",
|
||||
Email__Enabled: "false",
|
||||
Email__SmtpHost: "127.0.0.1",
|
||||
Email__SmtpUser: "",
|
||||
Email__SmtpPassword: "",
|
||||
Email__From: "fixture@example.test",
|
||||
AccountLifecycle__DeletionEnabled: "false",
|
||||
Workers__AiOperationsEnabled: "false",
|
||||
Workers__CvDocumentImportsEnabled: "false",
|
||||
// Browser provider responses are fixtures; the server must not start a real NAV search.
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
// Test-only mail capture. Never imported by the application.
|
||||
import { createServer as createSMTPServer } from "node:net";
|
||||
import { createServer as createHTTPServer } from "node:http";
|
||||
import { resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const maxMailBytes = 128 * 1024;
|
||||
|
||||
@@ -114,12 +112,3 @@ export function decodePlainMessage(raw) {
|
||||
}
|
||||
return Buffer.from(body, "latin1").toString("utf8");
|
||||
}
|
||||
|
||||
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const fixture = await startLocalSMTPFixture({
|
||||
smtpPort: Number.parseInt(process.env.AUTH_RECOVERY_SMTP_PORT ?? "2527", 10),
|
||||
controlPort: Number.parseInt(process.env.AUTH_RECOVERY_MAIL_PORT ?? "5303", 10),
|
||||
});
|
||||
process.stdout.write(`Local SMTP fixture ready on 127.0.0.1:${fixture.smtpPort}; control 127.0.0.1:${fixture.controlPort}\n`);
|
||||
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => { void fixture.close(); });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { startLocalSMTPFixture } from "./localSMTPfixture.mjs";
|
||||
|
||||
const fixture = await startLocalSMTPFixture({
|
||||
smtpPort: Number.parseInt(process.env.AUTH_RECOVERY_SMTP_PORT ?? "2527", 10),
|
||||
controlPort: Number.parseInt(process.env.AUTH_RECOVERY_MAIL_PORT ?? "5303", 10),
|
||||
});
|
||||
process.stdout.write(`Local SMTP fixture ready on 127.0.0.1:${fixture.smtpPort}; control 127.0.0.1:${fixture.controlPort}\n`);
|
||||
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => { void fixture.close(); });
|
||||
@@ -13,16 +13,17 @@ const mockedApi = api as jest.Mocked<typeof api>;
|
||||
// jest.fn() in setupTests.ts before every test -- re-arm it here so error-derived text is testable.
|
||||
const mockedGetApiErrorMessage = getApiErrorMessage as jest.Mock;
|
||||
|
||||
function renderVerifyEmailPage(search: string, emailChange = false) {
|
||||
function renderVerifyEmailPage(search: string, emailChange = false, strict = false) {
|
||||
const path = emailChange ? '/confirm-email-change' : '/verify-email';
|
||||
window.history.pushState({}, '', `${path}${search}`);
|
||||
return render(
|
||||
const tree = (
|
||||
<MemoryRouter initialEntries={[`${path}${search}`]}>
|
||||
<I18nProvider>
|
||||
<VerifyEmailPage emailChange={emailChange} />
|
||||
</I18nProvider>
|
||||
</MemoryRouter>,
|
||||
</MemoryRouter>
|
||||
);
|
||||
return render(strict ? <React.StrictMode>{tree}</React.StrictMode> : tree);
|
||||
}
|
||||
|
||||
describe('VerifyEmailPage', () => {
|
||||
@@ -68,6 +69,15 @@ describe('VerifyEmailPage', () => {
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/auth/email-change/confirm', { userId: 'user-1', email: 'new@example.com', token: 'change-token' });
|
||||
});
|
||||
|
||||
it.each([false, true])('submits a one-use link once across effect replays: emailChange=%s', async emailChange => {
|
||||
mockedApi.post.mockResolvedValueOnce({ data: {} } as any);
|
||||
mockedApi.post.mockRejectedValue({ response: { status: 400, data: 'Invalid or expired link.' } });
|
||||
renderVerifyEmailPage('?userId=user-1&email=new%40example.test&token=one-use', emailChange, true);
|
||||
|
||||
expect(await screen.findByText(translations.en[emailChange ? 'confirmEmailChangeSuccess' : 'verifyEmailSuccess'])).toBeInTheDocument();
|
||||
expect(mockedApi.post).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each([false, true])('changing UI language never resubmits a pending confirmation: emailChange=%s', async emailChange => {
|
||||
let finish!: (value: any) => void;
|
||||
mockedApi.post.mockReturnValue(new Promise(resolve => { finish = resolve; }));
|
||||
|
||||
@@ -209,7 +209,10 @@ export default function AdminUsersPage() {
|
||||
await api.post(`/users/${u.id}/send-password-reset`);
|
||||
if (active()) toast(currentTranslation.current("adminUsersResetSent"), "success");
|
||||
} catch (e: any) {
|
||||
if (active()) toast(getApiErrorMessage(e, currentTranslation.current("adminUsersResetFailed")), "error");
|
||||
if (active()) {
|
||||
const fallback = currentTranslation.current("adminUsersResetFailed");
|
||||
toast(e?.response?.status === 503 ? fallback : getApiErrorMessage(e, fallback), "error");
|
||||
}
|
||||
}
|
||||
finally { finishAction(active); }
|
||||
}, [beginAction, finishAction, toast]);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
|
||||
import { Alert, Box, Button, CircularProgress, Typography } from "@mui/material";
|
||||
|
||||
@@ -17,12 +17,14 @@ export default function VerifyEmailPage({ emailChange = false }: { emailChange?:
|
||||
const [status, setStatus] = useState<Status>("verifying");
|
||||
const [verificationError, setVerificationError] = useState<unknown>(null);
|
||||
const [missingLink, setMissingLink] = useState(false);
|
||||
const submission = useRef<{ key: string; result: Promise<unknown> } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setStatus("verifying");
|
||||
setMissingLink(false);
|
||||
setVerificationError(null);
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const search = window.location.search;
|
||||
const params = new URLSearchParams(search);
|
||||
const userId = params.get("userId") || "";
|
||||
const email = params.get("email") || "";
|
||||
const token = params.get("token") || "";
|
||||
@@ -33,9 +35,14 @@ export default function VerifyEmailPage({ emailChange = false }: { emailChange?:
|
||||
return;
|
||||
}
|
||||
|
||||
const endpoint = emailChange ? "/auth/email-change/confirm" : "/auth/verify-email";
|
||||
const key = endpoint + search;
|
||||
// React can replay the effect while the same one-use token is being consumed.
|
||||
if (submission.current?.key !== key) {
|
||||
submission.current = { key, result: api.post(endpoint, emailChange ? { userId, email, token } : { userId, token }) };
|
||||
}
|
||||
let active = true;
|
||||
api
|
||||
.post(emailChange ? "/auth/email-change/confirm" : "/auth/verify-email", emailChange ? { userId, email, token } : { userId, token })
|
||||
submission.current.result
|
||||
.then(() => { if (active) setStatus("success"); })
|
||||
.catch((cause: unknown) => {
|
||||
if (!active) return;
|
||||
|
||||
Reference in New Issue
Block a user