fix(web): render a 404 page for unknown routes (#294)
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 32m0s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 8m15s
Heimdall Gitea / Build and scan agent image (push) Successful in 9m53s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m42s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 28m29s
Heimdall Gitea / CI policy (push) Successful in 2s

Co-authored-by: Arnaud Dartois <admin@tordais.cc>
This commit was merged in pull request #297.
This commit is contained in:
arnaud.dartois authored and Arnaud Dartois committed 2026-11-08 00:32:22 +01:00
1 parent 5bcd4968a8
commit 38647d3623
3 files changed
+122

No files matched your search

+17
View File
@@ -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 `<NotFound>` 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.
+49
View File
@@ -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<UiText>();
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 = $$"""
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{title}}</title>
<style>
body { margin: 0; background: #101828; color: #f9fafb; font: 16px Inter, system-ui, sans-serif; }
main { box-sizing: border-box; max-width: 48rem; margin: 12vh auto; padding: 2rem; }
h1 { color: #60a5fa; font-size: 2.5rem; }
p { color: #cbd5e1; line-height: 1.6; }
a { display: inline-block; margin-top: 1rem; padding: .75rem 1rem; border-radius: .5rem; background: #2563eb; color: white; text-decoration: none; }
</style>
</head>
<body>
<main>
<h1>{{title}}</h1>
<p>{{message}}</p>
<a href="/dashboard">{{back}}</a>
</main>
</body>
</html>
""";
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.
@@ -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");
}
}