From 38647d3623dedd4f0a6a1b84ae0eb20fe5f30d3e Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 8 Nov 2026 00:32:22 +0100 Subject: [PATCH] fix(web): render a 404 page for unknown routes (#294) Co-authored-by: Arnaud Dartois --- skills/ui-unknown-route/SKILL.md | 17 ++++++ src/Heimdall.Web/Program.cs | 49 ++++++++++++++++ .../Pages/PageRenderTests.cs | 56 +++++++++++++++++++ 3 files changed, 122 insertions(+) create mode 100644 skills/ui-unknown-route/SKILL.md diff --git a/skills/ui-unknown-route/SKILL.md b/skills/ui-unknown-route/SKILL.md new file mode 100644 index 0000000..1d3135f --- /dev/null +++ b/skills/ui-unknown-route/SKILL.md @@ -0,0 +1,17 @@ +--- +name: ui-unknown-route +description: Diagnose and verify unknown-route rendering in Heimdall's interactive Blazor UI. +--- + +# Unknown UI routes + +Heimdall renders its root `Routes` component in an interactive server circuit with prerendering disabled (`Components/App.razor`). In .NET 10, configure `Router.NotFoundPage`; the legacy `` fragment is not supported by Blazor Web Apps. Unknown direct browser requests have no matched endpoint and cannot start the circuit, so `Program` must render a small static HTML 404 using the same `NotFoundPage_*` resources and `/dashboard` link. Skip API, hub, health, Hangfire, non-HTML, and file-like requests so their 404 responses keep their native format. + +The reusable interactive error screen is `Components/Pages/NotFound.razor`. It owns its `MainLayout`, title/body localization, and the return link to `/dashboard`. Keep it assigned as `Router.NotFoundPage` for client-side unknown navigation. Keep the static HTTP fallback's resource keys and link target aligned with this component. + +## Acceptance workflow + +1. In `tests/Heimdall.E2E.Tests/Pages/PageRenderTests.cs`, verify a direct unknown URL returns HTTP 404 and displays the localized title and return link in its static response. +2. Verify client-side navigation from a known route to an unknown URL (for example `Blazor.navigateTo(...)`) and confirm the same page renders. +3. Confirm `/not-found` and a known route still render. Verify API 404 responses remain API responses and do not receive the UI document, even when the request accepts HTML. +4. Run the focused Playwright E2E tests and the disposable Central + PostgreSQL Compose acceptance from `compose-disposable-recipe`. Use generated credentials, unique project/port/volume/image names, probe the route through a browser after the health check, and verify cleanup of project resources and every exact local image tag. diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index f5ce381..a12e411 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -850,6 +850,55 @@ public partial class Program localizationOptions.RequestCultureProviders.Insert(1, new CookieRequestCultureProvider()); app.UseRequestLocalization(localizationOptions); + // Unknown browser routes have no endpoint and cannot start the interactive + // Blazor circuit. Render the same localized NotFound content as a static + // 404 document; preserve native API, hub, health, Hangfire, and asset errors. + app.UseStatusCodePages(async statusCodeContext => + { + var context = statusCodeContext.HttpContext; + var path = context.Request.Path; + var isNonUiResponse = path.StartsWithSegments("/api") + || path.StartsWithSegments("/hubs") + || path.StartsWithSegments("/healthz") + || path.StartsWithSegments("/hangfire") + || Path.HasExtension(path.Value) + || !context.Request.Headers.Accept.Any(value => + value?.Contains("text/html", StringComparison.OrdinalIgnoreCase) == true); + if (context.Response.StatusCode != StatusCodes.Status404NotFound || isNonUiResponse) return; + + var text = context.RequestServices.GetRequiredService(); + var encoder = System.Text.Encodings.Web.HtmlEncoder.Default; + var title = encoder.Encode(text["NotFoundPage_Title"]); + var message = encoder.Encode(text["NotFoundPage_Body"]); + var back = encoder.Encode(text["NotFoundPage_Back"]); + context.Response.ContentType = "text/html; charset=utf-8"; + var document = $$""" + + + + + + {{title}} + + + +
+

{{title}}

+

{{message}}

+ {{back}} +
+ + + """; + await context.Response.WriteAsync(document); + }); + // Hangfire dashboard — Admin uniquement (policy AdminJobs). // MapHangfireDashboard est utilisé car UseHangfireDashboard avec // DashboardOptions.Authorization n'existe pas pour les policies ASP.NET. diff --git a/tests/Heimdall.E2E.Tests/Pages/PageRenderTests.cs b/tests/Heimdall.E2E.Tests/Pages/PageRenderTests.cs index 2d3e0dd..7b83177 100644 --- a/tests/Heimdall.E2E.Tests/Pages/PageRenderTests.cs +++ b/tests/Heimdall.E2E.Tests/Pages/PageRenderTests.cs @@ -106,4 +106,60 @@ public class PageRenderTests : E2ETestBase var text = await body.TextContentAsync(); text.ShouldNotBeNull(); } + + [Fact] + public async Task Unknown_route_renders_not_found_after_direct_load_and_client_navigation() + { + var directUrl = $"{BaseUrl}/not-a-route-qa"; + var directResponseTask = Page.WaitForResponseAsync(response => response.Url == directUrl); + try + { + await Page.GotoAsync(directUrl, new PageGotoOptions + { + WaitUntil = WaitUntilState.DOMContentLoaded, + Timeout = 15000, + }); + } + catch (PlaywrightException) + { + // Playwright reports the expected HTTP 404 as a navigation exception. + } + var directResponse = await directResponseTask; + + await Page.GetByRole(AriaRole.Heading, new() { Name = "Page introuvable" }) + .WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 15000 }); + var backLink = Page.GetByRole(AriaRole.Link, new() { Name = "Retour" }); + (await backLink.IsVisibleAsync()).ShouldBeTrue(); + (await backLink.GetAttributeAsync("href")).ShouldBe("/dashboard"); + directResponse.Status.ShouldBe(404); + + await Page.GotoAsync($"{BaseUrl}/not-found"); + await WaitForBlazorCircuitAsync(); + await Page.EvaluateAsync("Blazor.navigateTo('/not-a-route-navigation-qa')"); + await Page.WaitForURLAsync("**/not-a-route-navigation-qa"); + await Page.GetByRole(AriaRole.Heading, new() { Name = "Page introuvable" }) + .WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 15000 }); + + await LoginViaUiAsync(); + var authenticatedResponseTask = Page.WaitForResponseAsync(response => + response.Url == $"{BaseUrl}/not-a-route-authenticated-qa"); + try + { + await Page.GotoAsync($"{BaseUrl}/not-a-route-authenticated-qa"); + } + catch (PlaywrightException) + { + // The server returns HTTP 404 while rendering the not-found page. + } + var authenticatedResponse = await authenticatedResponseTask; + authenticatedResponse.Status.ShouldBe(404); + await Page.GetByRole(AriaRole.Heading, new() { Name = "Page introuvable" }) + .WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 15000 }); + + using var apiClient = new HttpClient(); + apiClient.DefaultRequestHeaders.Accept.ParseAdd("text/html"); + var apiNotFound = await apiClient.GetAsync($"{BaseUrl}/api/not-a-route-qa"); + apiNotFound.StatusCode.ShouldBe(System.Net.HttpStatusCode.NotFound); + (await apiNotFound.Content.ReadAsStringAsync()).ShouldNotContain("Page introuvable"); + } }