From ff947194553c78a257617c4952633a6485a93186 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 9 Nov 2026 08:53:37 +0100 Subject: [PATCH] Setup-pagina verschijnt niet meer als de setup-status niet te lezen is De route-guard las elke fout (429, 500, 503, 404) als 'niet geinitialiseerd' en stuurde naar de setup-pagina. Nu geen gok: bij een onleesbare status geen doorverwijzing. De statuslezing valt onder de ruimere limiter in plaats van de strikte login-limiter (die 5 per minuut deelt met echte inlogpogingen). De loginpagina meldt als het CMS uitgeschakeld of in onderhoud is. Co-Authored-By: Claude Sonnet 5.5 --- aidlc-docs/active-features.md | 1 + .../bug-fix.md | 41 +++++++++ .../src/features/auth/pages/LoginPage.tsx | 16 ++++ .../src/features/setup/setupGuard.test.tsx | 88 +++++++++++++++++++ frontend/src/i18n/locales/en/translation.json | 3 + frontend/src/i18n/locales/nl/translation.json | 3 + frontend/src/router.tsx | 10 ++- .../Controllers/SetupRateLimitTests.cs | 26 ++++++ .../Controllers/SetupController.cs | 4 +- 9 files changed, 188 insertions(+), 4 deletions(-) create mode 100644 aidlc-docs/bugs/setup-page-after-failed-status-read/bug-fix.md create mode 100644 frontend/src/features/setup/setupGuard.test.tsx create mode 100644 src/SlpModularCms.Modules.Identity.Tests/Controllers/SetupRateLimitTests.cs diff --git a/aidlc-docs/active-features.md b/aidlc-docs/active-features.md index 914b1e6..412a9c8 100644 --- a/aidlc-docs/active-features.md +++ b/aidlc-docs/active-features.md @@ -15,3 +15,4 @@ | Feature | Identity e-mail notifications (identity-email-notifications) | 🔵 Inception (wacht op antwoorden) | feature/identity-email-notifications | Core (IEmailSender), Identity, Frontend | 2026-11-08 | | Bug | [owner-cannot-promote-requester-identity](bugs/owner-cannot-promote-requester-identity/bug-fix.md) | ✅ Complete (wacht op ASF test deploy) | feature/identity-email-notifications | Identity (UsersController) | 2026-11-08 | | Bug | [availability-gate-blocks-website-and-admin](bugs/availability-gate-blocks-website-and-admin/bug-fix.md) | ✅ Complete (wacht op deploy) | feature/identity-email-notifications | Availability (middleware) | 2026-11-09 | +| Bug | [setup-page-after-failed-status-read](bugs/setup-page-after-failed-status-read/bug-fix.md) | ✅ Complete (wacht op deploy) | feature/identity-email-notifications | Frontend (router guard, login), Identity (Setup limiter) | 2026-11-09 | diff --git a/aidlc-docs/bugs/setup-page-after-failed-status-read/bug-fix.md b/aidlc-docs/bugs/setup-page-after-failed-status-read/bug-fix.md new file mode 100644 index 0000000..67411c5 --- /dev/null +++ b/aidlc-docs/bugs/setup-page-after-failed-status-read/bug-fix.md @@ -0,0 +1,41 @@ +# Bug Fix: the setup page appears when the setup status cannot be read + +- **Slug**: setup-page-after-failed-status-read +- **Status**: Complete (pending deploy) +- **Issue**: None (reported by Bryan via "CMS & API", 2026-11-09; seen on ASF with the CMS switched off by the master, earlier on SlpSoftware) +- **Branch**: feature/identity-email-notifications +- **Started**: 2026-11-09 +- **Documentation Language**: English +- **Conversation Language**: Dutch (user language) + +## Report + +After the master switched ASF to "not available", the admin showed the SETUP page ("create first account") instead of the dashboard or a notice. Expected: a failure to read the setup status must never show the setup page; a switched-off CMS shows that it is off. + +## Root Cause + +The admin's root route guard (`router.tsx`, `beforeLoad`) asks `GET /api/v1/Setup/status` on every page load. For any error other than a network failure it logged "assuming not initialized" and redirected to `/setup`. So a 429, 500, 503 or 404 answer, which says nothing about the system, sent people to the setup page of a system that already has its owner. + +Two things made such errors likely: (1) since the optional setup token (U2) `GET Setup/status` was under the strict `login` rate limiter (5 a minute per client address, shared with real login attempts), so a few reloads used it up and the 429 that followed was read as "not set up"; (2) with the old availability gate a disabled CMS also answered 503 for much more than the API (fixed separately, 701091f). + +I could not read the browser's actual response in Bryan's session, so the status code he got is not known; the guard turned every non-network error into the setup page, which is the defect whichever status it was. + +**Confirmed with user**: relayed by "CMS & API". + +## The Fix + +- `router.tsx`: when the status cannot be read, the guard no longer guesses. A network failure still counts as "set up" (unchanged, so `/setup` leads to login); any other error means "unknown": no redirect either way, the normal pages deal with it. +- `SetupController.GetStatus` moves to the generous `refresh` limiter (20 a minute); the owner creation stays under the strict `login` one. +- Login page: when the CMS is disabled or in maintenance (open endpoint `/Availability/status`) a notice says so, with the message from the master and "only administrators can sign in right now"; the form stays (administrators pass the gate). + +## Verification + +**Path used**: Automated test framework. `setupGuard.test.tsx`: with the status answering 429, 500, 503, 404 or an empty 200 the login page is shown and the setup form is not; on a visitor already on `/setup` nothing moves; a readable `initialized: false` still leads to setup; the login notice for NotAvailable (with message) and Maintenance, nothing while Available. `SetupRateLimitTests`: status under `refresh`, owner creation under `login`. + +**Before the fix**: 5 of the 6 error cases fail (the setup page appears); after: all pass. Frontend 390, Identity 141 green. + +## Result + +- **PR(s)**: None +- **Commit(s)**: see branch history +- **Completed**: 2026-11-09 diff --git a/frontend/src/features/auth/pages/LoginPage.tsx b/frontend/src/features/auth/pages/LoginPage.tsx index 3e86457..2e94392 100644 --- a/frontend/src/features/auth/pages/LoginPage.tsx +++ b/frontend/src/features/auth/pages/LoginPage.tsx @@ -11,6 +11,7 @@ import { useAuth } from '@/features/auth/context/auth-context'; import { NetworkError, ProblemDetailsError } from '@/lib/api-client'; import { loginFormSchema, type LoginFormData } from '@/features/auth/schemas/auth'; import { useSystemCapabilities } from '@/features/system/services/useSystemCapabilities'; +import { useAvailabilityStatus } from '@/features/availability/services/useAvailability'; import { Link } from '@tanstack/react-router'; export function LoginPage() { @@ -20,6 +21,8 @@ export function LoginPage() { const search = useSearch({ strict: false }) as { redirect?: string }; const [serverError, setServerError] = useState(null); const { data: capabilities } = useSystemCapabilities(); + const { data: availability } = useAvailabilityStatus(); + const cmsOff = availability !== undefined && availability.status !== 'Available'; const { register, @@ -55,6 +58,19 @@ export function LoginPage() { {t('login.subtitle')} + {cmsOff && ( +
+

+ {availability.status === 'Maintenance' ? t('login.cmsMaintenance') : t('login.cmsDisabled')} +

+ {availability.message ?

{availability.message}

: null} +

{t('login.cmsOffAdminsOnly')}

+
+ )}
{serverError !== null && (
{ + _resetSetupStatusCache(); +}); + +const STATUS = `${API_BASE}/api/v1/Setup/status`; +const AVAILABILITY = `${API_BASE}/api/v1/Availability/status`; + +describe('a setup status that cannot be read never sends anybody to the setup page', () => { + it.each([ + ['429 (rate limited)', () => HttpResponse.json({ status: 429, title: 'Too Many Requests' }, { status: 429 })], + ['500', () => HttpResponse.json({ status: 500 }, { status: 500 })], + ['503 (service unavailable)', () => HttpResponse.json({ status: 503, title: 'Service Unavailable' }, { status: 503 })], + ['404', () => new HttpResponse(null, { status: 404 })], + ['an empty 200', () => new HttpResponse(null, { status: 200 })], + ['a network failure', () => HttpResponse.error()], + ])('%s: the login page is shown, not the setup page', async (_label, respond) => { + mockGuest(); + server.use(http.get(STATUS, respond)); + renderApp('/dashboard'); + + expect(await screen.findByTestId('login-form-submit-button', {}, { timeout: 10000 })).toBeInTheDocument(); + expect(screen.queryByTestId('setup-form')).not.toBeInTheDocument(); + }); + + it('an unreadable status does not move a visitor who is already on the setup page either', async () => { + mockGuest(); + server.use(http.get(STATUS, () => HttpResponse.json({ status: 503 }, { status: 503 }))); + renderApp('/setup'); + + // Nothing can be said about the system, so the router leaves the page where it is. + expect(await screen.findByTestId('setup-form', {}, { timeout: 10000 })).toBeInTheDocument(); + }); + + it('a readable "not initialized" still leads to the setup page (the real first-run case)', async () => { + mockGuest(); + server.use(http.get(STATUS, () => HttpResponse.json({ initialized: false }))); + renderApp('/dashboard'); + + expect(await screen.findByTestId('setup-form', {}, { timeout: 10000 })).toBeInTheDocument(); + }); +}); + +describe('the login page of a CMS that is switched off', () => { + function availability(status: 'Available' | 'Maintenance' | 'NotAvailable', message = '') { + server.use( + http.get(AVAILABILITY, () => + HttpResponse.json({ status, checkedAt: '2026-11-09T00:00:00Z', message, isMasterControlled: false }), + ), + ); + } + + it('says so, with the message, and still offers the login form (administrators pass)', async () => { + mockGuest(); + availability('NotAvailable', 'Uitgeschakeld door de master'); + renderApp('/login'); + + const notice = await screen.findByTestId('login-cms-off', {}, { timeout: 10000 }); + expect(notice).toHaveTextContent(/disabled/i); + expect(notice).toHaveTextContent('Uitgeschakeld door de master'); + expect(notice).toHaveTextContent(/only administrators/i); + expect(screen.getByTestId('login-form-submit-button')).toBeInTheDocument(); + }); + + it('names maintenance as maintenance', async () => { + mockGuest(); + availability('Maintenance'); + renderApp('/login'); + + expect(await screen.findByTestId('login-cms-off', {}, { timeout: 10000 })).toHaveTextContent(/maintenance/i); + }); + + it('shows nothing extra while the CMS is available', async () => { + mockGuest(); + availability('Available'); + renderApp('/login'); + + await screen.findByTestId('login-form-submit-button', {}, { timeout: 10000 }); + expect(screen.queryByTestId('login-cms-off')).not.toBeInTheDocument(); + }); +}); diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index f5de93d..a0e7c2d 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -24,6 +24,9 @@ "title": "Sign in", "subtitle": "Sign in to your SlpModularCms account", "forgotPassword": "Forgot your password?", + "cmsDisabled": "This CMS is disabled.", + "cmsMaintenance": "This CMS is under maintenance.", + "cmsOffAdminsOnly": "Only administrators can sign in right now.", "email": "Email", "emailPlaceholder": "you@example.com", "password": "Password", diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index 4b534b6..f06a873 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -24,6 +24,9 @@ "title": "Inloggen", "subtitle": "Log in op je SlpModularCms-account", "forgotPassword": "Wachtwoord vergeten?", + "cmsDisabled": "Dit CMS is uitgeschakeld.", + "cmsMaintenance": "Dit CMS is in onderhoud.", + "cmsOffAdminsOnly": "Alleen beheerders kunnen nu inloggen.", "email": "E-mail", "emailPlaceholder": "jij@voorbeeld.nl", "password": "Wachtwoord", diff --git a/frontend/src/router.tsx b/frontend/src/router.tsx index 175e6a4..8d89b12 100644 --- a/frontend/src/router.tsx +++ b/frontend/src/router.tsx @@ -110,12 +110,16 @@ const rootRoute = createRootRouteWithContext()({ try { status = await fetchSetupStatus(); } catch (err) { + // The status could not be read (backend unreachable, rate limited, a 5xx, a disabled CMS...). That + // says nothing about whether the system is set up, and guessing "not set up" would send people to + // the setup page of a system that already has its owner. So: no redirect either way. The normal + // pages (login, with its own notice when the CMS is off) deal with the situation. if (err instanceof NetworkError) { - // Backend unreachable: skip setup redirect and show the login page instead. + // Backend unreachable: treat it as set up, so /setup leads to the login page (unchanged behaviour). status = { initialized: true }; } else { - console.warn('[InitGuard] Setup status check failed, assuming not initialized:', err); - status = { initialized: false }; + console.warn('[InitGuard] Setup status could not be read, not redirecting:', err); + return; } } diff --git a/src/SlpModularCms.Modules.Identity.Tests/Controllers/SetupRateLimitTests.cs b/src/SlpModularCms.Modules.Identity.Tests/Controllers/SetupRateLimitTests.cs new file mode 100644 index 0000000..2978cb2 --- /dev/null +++ b/src/SlpModularCms.Modules.Identity.Tests/Controllers/SetupRateLimitTests.cs @@ -0,0 +1,26 @@ +using System.Reflection; +using FluentAssertions; +using Microsoft.AspNetCore.RateLimiting; +using SlpModularCms.Modules.Identity.Controllers; + +namespace SlpModularCms.Modules.Identity.Tests.Controllers; + +public class SetupRateLimitTests +{ + private static string? PolicyOf(string method) => + typeof(SetupController).GetMethod(method)!.GetCustomAttribute()?.PolicyName; + + [Fact] + public void TheStatusRead_IsNotUnderTheStrictLoginLimiter() + { + // The admin reads it on every page load. Under the login limiter (5 a minute, shared with real login + // attempts) a few reloads used it up and the 429 that followed was read as "not set up". + PolicyOf(nameof(SetupController.GetStatus)).Should().Be("refresh"); + } + + [Fact] + public void CreatingTheOwner_StaysUnderTheStrictLoginLimiter() + { + PolicyOf(nameof(SetupController.CreateOwner)).Should().Be("login"); + } +} diff --git a/src/SlpModularCms.Modules.Identity/Controllers/SetupController.cs b/src/SlpModularCms.Modules.Identity/Controllers/SetupController.cs index 681c1b2..70154ab 100644 --- a/src/SlpModularCms.Modules.Identity/Controllers/SetupController.cs +++ b/src/SlpModularCms.Modules.Identity/Controllers/SetupController.cs @@ -29,8 +29,10 @@ public class SetupController : ControllerBase _logger = logger; } + // Read on every page load of the admin: not under the strict login limiter (5 a minute), which also counts real + // login attempts and which, once used up, made the admin read a failed status as "not set up". [HttpGet("status")] - [EnableRateLimiting("login")] + [EnableRateLimiting("refresh")] public async Task GetStatus() { var initialized = await _setupService.IsSystemInitializedAsync();