diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 69c2804f..1dc2cbb0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -393,7 +393,8 @@ Blazor Server (**Interactive Server** render mode, applied at the `App` root — no WebAssembly, no Auto mode) with **MudBlazor** as the component library, plus a hand-rolled CSS token layer (`wwwroot\app.css`) on top of it. Pages, routes and what each page shows or triggers are specified in -[Web UI](areas/web-ui.md). +[Web UI](areas/web-ui.md); the list and detail page layouts in +[List pages](areas/list-pages.md) and [Detail pages](areas/detail-pages.md). - **Design tokens** (`wwwroot\app.css`) are the `--dug-*` custom properties for colors, radii, fonts and the transition. The light values sit in @@ -434,8 +435,7 @@ Pages, routes and what each page shows or triggers are specified in fairly wide surface (one method per page/section). - **`Components\Common`** holds cross-page building blocks: loading skeletons (the detail page skeleton among them) and the vulnerability - widgets shared between the - Vulnerabilities page and image/container detail pages, the + widgets shared between the image and container detail pages, the `ContainerActionConfirmation` dialog, the resource history chart (SVG paths from one path builder shared with the Runtime Containers list, [decision 0083](decisions/0083-resource-histories-are-drawn-as-svg-sparklines-from-one-shared-path-builder.md)), diff --git a/docs/areas/README.md b/docs/areas/README.md index 916a7eeb..01ebc486 100644 --- a/docs/areas/README.md +++ b/docs/areas/README.md @@ -41,5 +41,6 @@ operator or another component can rely on — formats, limits, error behavior, g | [Scan engine](scan-engine.md) | Background jobs and their intervals, dynamic own-image interval, overlap rules, scan runs, crash recovery, retention and cleanup, single-instance assumption | What a scan evaluates (the feature areas) | | [Web UI](web-ui.md) | Pages and routes, what each page shows and triggers, dashboard refresh, error and not-found pages, theme | How the shown values are computed (the feature areas) | | [Detail pages](detail-pages.md) | Layout and contents of the detail pages: header, details column, panels in order, resource history charts | Routes, actions table, shared display and errors (Web UI); how values are computed (the feature areas) | +| [List pages](list-pages.md) | Layout and contents of the list pages, so far Vulnerabilities: header, severity overview, filters, table, expanded rows, pager | Routes, actions table, shared display and errors (Web UI); how values are computed (the feature areas) | | [Telemetry](telemetry.md) | Logs, traces and metrics, OTLP export, activity and instrument names, inventory gauges, what never reaches telemetry | Deployment of the observability stack (`INSTALL.md`) | diff --git a/docs/areas/list-pages.md b/docs/areas/list-pages.md new file mode 100644 index 00000000..7ba0b89b --- /dev/null +++ b/docs/areas/list-pages.md @@ -0,0 +1,71 @@ +# List pages + +## Scope + +The layout and contents of the list pages, so far the Vulnerabilities page: its header, the severity overview, the +filters, the table, the expanded rows and the pager. Users rely on it to see how the active advisories are spread +over the severities and to find the ones that matter. + +## Behavior + +### Vulnerabilities page header and panel + +- The page header shows the title `Vulnerabilities` and the description `Active advisories across all images, with the + images and running containers each one affects.`, without an eyebrow. One panel `Active advisories` follows; it has + no description line. +- The panel title is followed by a muted count: `{n}` for the number of advisories, or `{matching} of {all}` while a + filter hides some of them. A filter that hides nothing shows `{n}`. +- Under the title the severity bar and its legend show every active advisory once, at its highest severity; an + advisory without a known severity counts as low. The bar is at most 360 px wide and does not follow the filters. +- On the right of the panel header stand the field `Filter` (placeholder `Advisory, title or package`, clearable) and + the select `Severity` (`All`, `Critical`, `High`, `Medium`, `Low`), each with its label above. The filter field + matches the advisory identifier, the title and the packages, case-insensitively. The severity select lists an + advisory without a known severity only under `All`. +- Without any active advisory the page shows the empty panel `No active vulnerability findings have been recorded + yet.` with no count and no bar. While loading it shows the table skeleton of the panel; a failed load shows the + alert of [Web UI](web-ui.md#limits-and-errors). + +### Table + +- A row shows the expand button; the advisory identifier in semibold, as a link that opens in a new tab only when the + reference is an absolute `http` or `https` address, with the title below it when there is one; the severity as a + chip in the tone of the severity, with `CVSS {score}` (one decimal) below it when a score exists; the packages and + the fixed versions joined with a comma, or `—`; the number of affected images and of running containers. An advisory + without a known severity reads `Unknown` in the low tone. Rows carry no colored rail. +- The expand button shows a downward chevron and is announced as `Show affected images` with `aria-expanded` false. + Activated, the row and a detail below it take the subtle surface background; the detail, indented to the start of the + *Advisory* column, shows the label `Affected images` and one image reference per line, linked to the image's detail + page when the image is an observed image and plain text otherwise. The button then shows an upward chevron and is + announced as `Hide affected images` with `aria-expanded` true. A row that a filter hides stays expanded when it shows + again. +- A filter without a match shows `No advisories match the current filter.`, a count `0 of {all}` and no pager. + +### Paging + +- The pager shows only when more than 25 advisories match. It stands right-aligned below a hairline: `Rows per page` + with a select (25, 50, 100), the range (`1–25 of 31`, with an en dash) and the two buttons `Previous page` and + `Next page`. A button that cannot move is disabled and keeps a muted icon and its border. +- A change of the filter text, the severity or the rows per page shows the first page. A page size the client sends + that is not 25, 50 or 100 is ignored. The chosen size stays when the pager hides and returns. + +### Layout + +- Below 960 px each row is a card that keeps its expand button, and the filter field and the severity select each + take the full width of the panel header. Long values, such as a package name or an image reference, wrap + inside the card instead of widening it. From 960 px the field is 260 px and the select 150 px wide. + +## Limits and errors + +- Paging is done on the page, not by the table component: the table is given only the rows of the shown page. +- The page shows the error and empty states above and no other. + +## Related decisions + +- [`decisions/0084-the-vulnerabilities-page-pages-its-advisories-itself-and-draws-its-own-pager.md`](../decisions/0084-the-vulnerabilities-page-pages-its-advisories-itself-and-draws-its-own-pager.md) + — the page keeps the page index and size and draws its own pager. + +## Not here + +- Routes, the actions table, shared display and error behavior in [Web UI](web-ui.md). +- How severities, CVSS scores and fix status are computed in [Vulnerabilities](vulnerabilities.md). +- The detail pages in [Detail pages](detail-pages.md); the other list pages join this area when they are converted. \ No newline at end of file diff --git a/docs/areas/web-ui.md b/docs/areas/web-ui.md index 1ef07170..d7da12d0 100644 --- a/docs/areas/web-ui.md +++ b/docs/areas/web-ui.md @@ -85,7 +85,7 @@ to read the state the other areas compute and to start manual scans; it computes | `/docker-instances` | Docker Instances | Configured Docker instances with endpoint, connection kind, latest runtime scan status and time, current resource usage and number of containers; with exactly one instance its current usage and usage history are shown on this page directly | | `/docker-instances/{id}` | Docker Instance detail | The containers currently observed on one instance with linked own image and resource usage | | `/base-images` | Shared Base Images | Base images used by two or more enabled images or containers, with the images built on them, the containers and number of enabled observed images that use them, and their vulnerability status | -| `/vulnerabilities` | Vulnerabilities | Active advisories across all images, one row per advisory, with severity and CVSS score, affected packages, fixed versions, number of affected images and running containers; a row expands to the affected images | +| `/vulnerabilities` | Vulnerabilities | Active advisories across all images, one row per advisory, with severity and CVSS score, affected packages, fixed versions, number of affected images and running containers; a row expands to the affected images; a severity bar of all advisories ([List pages](list-pages.md)) | | `/scan-history` | Scan History | The 20 most recent scan runs (observed image scans, runtime container scans and vulnerability refreshes, [Scan runs](scan-engine.md#scan-runs)) with type, status, trigger, target, start time and error message | | `/error` | Error | "Unexpected error" — the request could not be completed | | `/not-found` | Not found | "Page not found" with a link back to the dashboard | @@ -93,10 +93,6 @@ to read the state the other areas compute and to start manual scans; it computes - Detail routes accept only identifiers in GUID format (the container identifier of the runtime container route is free text); any other path renders the not-found page. - Resource usage histories on detail pages show up to the 48 most recent samples of the last 24 hours. -- The Vulnerabilities page filters by free text (advisory identifier, title or package, case-insensitive) and by - severity (All, Critical, High, Medium, Low), shows 25 rows per page with page sizes 25, 50 and 100, and links an - advisory to its reference only when the reference is an absolute `http` or `https` address; the link opens in a - new tab. - Which values the pages show and how they are computed (update state, recommended tag, vulnerability status, derived runtime, base image chain, resource values) is owned by the feature areas listed under *Not here*. @@ -319,7 +315,8 @@ never their values. the latest-scan columns and the detail pages. - If the connection to the server is lost, the page stops being interactive until the browser reconnects or the page is reloaded. -- Lists are not paged except the Vulnerabilities page; all other lists show every item or the fixed number stated +- Lists are not paged except the Vulnerabilities page ([List pages](list-pages.md)) and the vulnerability findings tables of the detail + pages (25 rows per page, page sizes 25, 50 and 100, a pager above 25 findings); all other lists show every item or the fixed number stated above. ## Related decisions @@ -349,6 +346,7 @@ never their values. ## Not here +- The layout and contents of the list pages in [List pages](list-pages.md). - How update states, recommended tags, tag candidates and manual tag preferences are evaluated in [Update detection](update-detection.md). - Image registration rules and reference formats in [Image catalog](image-catalog.md). diff --git a/docs/decisions/0084-the-vulnerabilities-page-pages-its-advisories-itself-and-draws-its-own-pager.md b/docs/decisions/0084-the-vulnerabilities-page-pages-its-advisories-itself-and-draws-its-own-pager.md new file mode 100644 index 00000000..b4b660c7 --- /dev/null +++ b/docs/decisions/0084-the-vulnerabilities-page-pages-its-advisories-itself-and-draws-its-own-pager.md @@ -0,0 +1,40 @@ +# 0084: The Vulnerabilities page pages its advisories itself and draws its own pager + +- **Status:** Accepted +- **Date:** 2026-12-01 +- **Area:** List pages +- **Source:** Issue #457 +- **Supersedes:** — + +## Context + +The flat refresh (#450) gives the Vulnerabilities page a pager with `Rows per page`, the range `1–25 of 31` (en dash) +and exactly two 44 × 44 px icon buttons named `Previous page` and `Next page` (#457). The page used MudBlazor's +`MudTablePager`, which in 9.14.0 documents the range format `{first_item}-{last_item} of {all_items}` (hyphen), has +first- and last-page buttons beside previous and next, and gives no documented way to name its buttons. MudTable's own +paging (`CurrentPage`, `RowsPerPage`) is documented as requiring a `MudTablePager` in `PagerContent`. A change of the +filter has to show the first page, which MudTable's paging does not promise. + +## Options considered + +1. **The page keeps the page index and size, hands MudTable only the rows of the current page and draws the pager + itself** — texts, buttons and names are the page's own and testable; the first page after a filter change is the + page's own rule. The paging arithmetic is new code, kept in one formatter other list pages can share. +2. **`MudTablePager` restyled** — a custom `InfoFormat` and `RowsPerPageString`, the first- and last-page buttons + hidden by CSS — keeps MudBlazor's paging, but the buttons' accessible names and the reset to the first page rest on + undocumented markup and behavior that a MudBlazor update can change. +3. **A custom pager inside `PagerContent` bound to MudTable's `CurrentPage` and `RowsPerPage`** — keeps MudTable's + slicing, but relies on paging that is documented only together with `MudTablePager`. + +## Decision + +The Vulnerabilities page holds the page index and the page size, gives MudTable the rows of the current page only +and renders its own pager below the table; the range text and the last-page test come from one shared formatter in +`UI`. The resulting behavior is described in [List pages](../areas/list-pages.md). + +## Consequences + +- The page's pager no longer follows MudBlazor's pager; other tables still use `MudTablePager` until their refresh + issue moves them. +- MudTable gets no `PagerContent` and renders every row it is given, as the Runtime Containers table already does. +- A page size the client sends that is not one of 25, 50 and 100 is ignored. \ No newline at end of file diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 0b05838a..af1b2319 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -149,4 +149,5 @@ once in the [area document](../areas/README.md) of the record's area, and the re | [0081](0081-the-navigation-row-shows-from-1360-px-and-a-drawer-below.md) | The navigation row shows from 1360 px, and a drawer below | Accepted | 2026-11-29 | | [0082](0082-the-runtime-container-list-names-the-highest-active-severity-and-keeps-a-failed-checks-status-beside-it.md) | The runtime container list names the highest active severity and keeps a failed check's status beside it | Accepted | 2026-11-30 | | [0083](0083-resource-histories-are-drawn-as-svg-sparklines-from-one-shared-path-builder.md) | Resource histories are drawn as SVG sparklines from one shared path builder | Accepted | 2026-11-30 | +| [0084](0084-the-vulnerabilities-page-pages-its-advisories-itself-and-draws-its-own-pager.md) | The Vulnerabilities page pages its advisories itself and draws its own pager | Accepted | 2026-12-01 | diff --git a/src/DockerUpdateGuard/Components/Common/SectionPanel.razor b/src/DockerUpdateGuard/Components/Common/SectionPanel.razor index 5ed3b465..77f3f2a7 100644 --- a/src/DockerUpdateGuard/Components/Common/SectionPanel.razor +++ b/src/DockerUpdateGuard/Components/Common/SectionPanel.razor @@ -1,6 +1,19 @@
-

@Title

+ @if (TitleContent is not null || SubtitleContent is not null) + { +
+
+

@Title

+ @TitleContent +
+ @SubtitleContent +
+ } + else + { +

@Title

+ } @if (HeaderContent is not null) {
@HeaderContent
diff --git a/src/DockerUpdateGuard/Components/Common/SectionPanel.razor.cs b/src/DockerUpdateGuard/Components/Common/SectionPanel.razor.cs index ba274c2d..92f96228 100644 --- a/src/DockerUpdateGuard/Components/Common/SectionPanel.razor.cs +++ b/src/DockerUpdateGuard/Components/Common/SectionPanel.razor.cs @@ -22,6 +22,18 @@ public partial class SectionPanel [Parameter] public string? Meta { get; set; } + /// + /// Content shown beside the title heading + /// + [Parameter] + public RenderFragment? TitleContent { get; set; } + + /// + /// Content shown below the title heading + /// + [Parameter] + public RenderFragment? SubtitleContent { get; set; } + /// /// Header content shown instead of the meta text /// diff --git a/src/DockerUpdateGuard/Components/Pages/Vulnerabilities.razor b/src/DockerUpdateGuard/Components/Pages/Vulnerabilities.razor index 95e2c8e1..1fb1e48e 100644 --- a/src/DockerUpdateGuard/Components/Pages/Vulnerabilities.razor +++ b/src/DockerUpdateGuard/Components/Pages/Vulnerabilities.razor @@ -3,13 +3,7 @@ Vulnerabilities - + @if (_items is null) { @@ -31,112 +25,152 @@ else { var filteredItems = GetFilteredItems(); + var pageItems = GetPageItems(filteredItems); - -
- Active advisories - One row per CVE, sorted by severity, CVSS score, and the number of affected images. -
- - + + + · @VulnerabilityOverviewFormatter.FormatAdvisoryCount(filteredItems.Count, _items.Count) + + +
+ +
+
+ +
- - - + @foreach (var severity in SeverityFilterOptions) { @severity } - - - - - - Advisory - Severity - Package - Fixed version - Affected images - Running containers - - - - - - - @if (string.IsNullOrWhiteSpace(context.ReferenceUrl) == false) - { - @context.AdvisoryId - } - else - { - @context.AdvisoryId - } - @if (string.IsNullOrWhiteSpace(context.Title) == false) - { - @context.Title - } - - - @context.Severity - @if (context.CvssScore.HasValue) +
+
+ + + + + Advisory + Severity + Package + Fixed version + Affected images + Running containers + + + + + + +
+ @if (string.IsNullOrWhiteSpace(context.ReferenceUrl) == false) + { + @context.AdvisoryId + } + else + { + @context.AdvisoryId + } + @if (string.IsNullOrWhiteSpace(context.Title) == false) + { + @context.Title + } +
+
+ +
+ + @if (context.CvssScore.HasValue) + { + CVSS @context.CvssScore.Value.ToString("F1") + } +
+
+ @(context.AffectedPackages.Count == 0 ? "—" : string.Join(", ", context.AffectedPackages)) + @(context.FixedVersions.Count == 0 ? "—" : string.Join(", ", context.FixedVersions)) + @context.AffectedImages.Count + @context.AffectedContainerCount +
+ + @if (IsExpanded(context)) { - CVSS @context.CvssScore.Value.ToString("F1") - } - - @(context.AffectedPackages.Count == 0 ? "—" : string.Join(", ", context.AffectedPackages)) - @(context.FixedVersions.Count == 0 ? "—" : string.Join(", ", context.FixedVersions)) - @context.AffectedImages.Count - @context.AffectedContainerCount - - - @if (IsExpanded(context)) - { - - - - @foreach (var affectedImage in context.AffectedImages) - { - @if (affectedImage.ObservedImageId.HasValue) - { - @ImageReferenceFormatter.GetReference(affectedImage.ImageReference) - } - else + + + + + Affected images + @foreach (var affectedImage in context.AffectedImages) { - @ImageReferenceFormatter.GetReference(affectedImage.ImageReference) + @if (affectedImage.ObservedImageId.HasValue) + { + @ImageReferenceFormatter.GetReference(affectedImage.ImageReference) + } + else + { + @ImageReferenceFormatter.GetReference(affectedImage.ImageReference) + } } - } - - - - } - - - No advisories match the current filter. - - - @if (filteredItems.Count > 25) - { - - } - -
-
+
+ + + } + + + No advisories match the current filter. + + + @if (filteredItems.Count > _pageSizeOptions[0]) + { +
+ + @TablePagingFormatter.FormatRange(_pageIndex, _pageSize, filteredItems.Count) + + +
+ } + + } - + \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Pages/Vulnerabilities.razor.cs b/src/DockerUpdateGuard/Components/Pages/Vulnerabilities.razor.cs index 35b59122..469d684e 100644 --- a/src/DockerUpdateGuard/Components/Pages/Vulnerabilities.razor.cs +++ b/src/DockerUpdateGuard/Components/Pages/Vulnerabilities.razor.cs @@ -2,8 +2,6 @@ using Microsoft.AspNetCore.Components; -using MudBlazor; - namespace DockerUpdateGuard.Components.Pages; /// @@ -62,6 +60,16 @@ public sealed partial class Vulnerabilities : IDisposable /// private string _severityFilter = AllSeveritiesFilterValue; + /// + /// Zero-based index of the shown page + /// + private int _pageIndex; + + /// + /// Number of rows per page + /// + private int _pageSize = _pageSizeOptions[0]; + /// /// Message of the last failed load, null when the last load completed /// @@ -98,33 +106,6 @@ public sealed partial class Vulnerabilities : IDisposable #region Static methods - /// - /// Resolve the chip color for a vulnerability severity label - /// - /// Severity label - /// Chip color - private static Color GetSeverityColor(string severity) - { - return VulnerabilityDisplayFormatter.GetSeverityColor(severity); - } - - /// - /// Resolve the severity-rail CSS class for a vulnerability severity label - /// - /// Severity label - /// Severity-rail CSS class - private static string GetSeverityRailClass(string severity) - { - return severity.ToUpperInvariant() switch - { - "CRITICAL" => "dug-rail-critical", - "HIGH" => "dug-rail-high", - "MEDIUM" => "dug-rail-medium", - "LOW" => "dug-rail-low", - _ => string.Empty, - }; - } - /// /// Resolve the detail page link for an affected image /// @@ -219,6 +200,59 @@ private void ToggleExpanded(VulnerabilityOverviewItemData item) } } + /// + /// Resolve the items of the shown page + /// + /// Items matching the filter + /// Items of the shown page + private List GetPageItems(List filteredItems) + { + return [.. filteredItems.Skip(_pageIndex * _pageSize).Take(_pageSize)]; + } + + /// + /// Show the first page + /// + private void ShowFirstPage() + { + _pageIndex = 0; + } + + /// + /// Show the previous page + /// + private void ShowPreviousPage() + { + if (_pageIndex > 0) + { + _pageIndex--; + } + } + + /// + /// Show the next page + /// + private void ShowNextPage() + { + if (TablePagingFormatter.IsLastPage(_pageIndex, _pageSize, GetFilteredItems().Count) == false) + { + _pageIndex++; + } + } + + /// + /// Change the page size when the client sent one of the offered sizes and show the first page + /// + /// Change event data + private void ChangePageSize(ChangeEventArgs args) + { + if (int.TryParse(args.Value?.ToString(), out var size) && _pageSizeOptions.Contains(size)) + { + _pageSize = size; + ShowFirstPage(); + } + } + /// /// Persist the current vulnerability overview so the interactive render can reuse the prerendered data /// diff --git a/src/DockerUpdateGuard/UI/TablePagingFormatter.cs b/src/DockerUpdateGuard/UI/TablePagingFormatter.cs new file mode 100644 index 00000000..62374691 --- /dev/null +++ b/src/DockerUpdateGuard/UI/TablePagingFormatter.cs @@ -0,0 +1,38 @@ +namespace DockerUpdateGuard.UI; + +/// +/// Composes the paging texts and state of list tables +/// +internal static class TablePagingFormatter +{ + #region Methods + + /// + /// Formats the range of rows shown on a page + /// + /// Zero-based page index + /// Rows per page + /// Total rows + /// Range text + public static string FormatRange(int pageIndex, int pageSize, int totalCount) + { + var first = totalCount == 0 ? 0 : (pageIndex * pageSize) + 1; + var last = Math.Min((pageIndex + 1) * pageSize, totalCount); + + return $"{first}\u2013{last} of {totalCount}"; + } + + /// + /// Determines whether the page is the last one + /// + /// Zero-based page index + /// Rows per page + /// Total rows + /// True for the last page + public static bool IsLastPage(int pageIndex, int pageSize, int totalCount) + { + return (pageIndex + 1) * pageSize >= totalCount; + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/VulnerabilityDisplayFormatter.cs b/src/DockerUpdateGuard/UI/VulnerabilityDisplayFormatter.cs index e676f3af..295a88fc 100644 --- a/src/DockerUpdateGuard/UI/VulnerabilityDisplayFormatter.cs +++ b/src/DockerUpdateGuard/UI/VulnerabilityDisplayFormatter.cs @@ -9,23 +9,6 @@ internal static class VulnerabilityDisplayFormatter { #region Static methods - /// - /// Resolve the chip color for a vulnerability severity label - /// - /// Severity label - /// Chip color - public static Color GetSeverityColor(string? severity) - { - return severity?.ToUpperInvariant() switch - { - "CRITICAL" => Color.Error, - "HIGH" => Color.Warning, - "MEDIUM" => Color.Info, - "LOW" => Color.Success, - _ => Color.Default, - }; - } - /// /// Resolve the chip color for a vulnerability assessment status, weighted by the highest active severity /// diff --git a/src/DockerUpdateGuard/UI/VulnerabilityOverviewFormatter.cs b/src/DockerUpdateGuard/UI/VulnerabilityOverviewFormatter.cs new file mode 100644 index 00000000..654b177e --- /dev/null +++ b/src/DockerUpdateGuard/UI/VulnerabilityOverviewFormatter.cs @@ -0,0 +1,66 @@ +using DockerUpdateGuard.Data.Entities; + +namespace DockerUpdateGuard.UI; + +/// +/// Composes the summaries and texts of the vulnerabilities page +/// +internal static class VulnerabilityOverviewFormatter +{ + #region Methods + + /// + /// Counts the findings of the given items per severity + /// + /// Vulnerability overview items + /// Severity summary + public static VulnerabilitySeveritySummaryViewData CreateSeveritySummary(IEnumerable items) + { + return VulnerabilityViewMapper.CreateSeveritySummary(items.GroupBy(item => ParseSeverity(item.Severity)) + .Select(group => new KeyValuePair(group.Key, group.Count()))); + } + + /// + /// Formats the advisory count of the page header + /// + /// Advisories matching the filter + /// All advisories + /// Count text + public static string FormatAdvisoryCount(int matchingCount, int totalCount) + { + return matchingCount == totalCount ? $"{totalCount}" : $"{matchingCount} of {totalCount}"; + } + + /// + /// Formats a severity for display + /// + /// Severity name, if any + /// Display text + public static string FormatSeverity(string? severity) + { + var parsed = ParseSeverity(severity); + + return parsed == VulnerabilitySeverity.NotSet ? "Unknown" : parsed.ToString(); + } + + #endregion // Methods + + #region Static methods + + /// + /// Parses a severity text, mapping an unknown or numeric text to not set + /// + /// Severity name, if any + /// Parsed severity + private static VulnerabilitySeverity ParseSeverity(string? severity) + { + if (Enum.TryParse(severity, true, out var parsed) && Enum.IsDefined(parsed)) + { + return parsed; + } + + return VulnerabilitySeverity.NotSet; + } + + #endregion // Static methods +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/wwwroot/app.css b/src/DockerUpdateGuard/wwwroot/app.css index d848e3b2..0f7dd796 100644 --- a/src/DockerUpdateGuard/wwwroot/app.css +++ b/src/DockerUpdateGuard/wwwroot/app.css @@ -882,6 +882,25 @@ a { font-weight: 600; } +.dug-panel__title-group { + display: flex; + flex-direction: column; + gap: 8px; + min-width: 0; +} + +.dug-panel__title-row { + display: flex; + align-items: baseline; + gap: 8px; +} + +@media (max-width: 959.98px) { + .dug-panel__title-group ~ .dug-panel__header-content { + flex-basis: 100%; + } +} + .dug-panel__meta { color: var(--dug-text-muted); font-size: 13px; @@ -991,20 +1010,120 @@ a { font-size: 16px; } -.dug-rail-critical { - box-shadow: inset 3px 0 0 var(--dug-sev-critical); +.vulnerabilities-count { + color: var(--dug-text-muted); + font-size: 13px; +} + +.vulnerabilities-severity { + max-width: 360px; } -.dug-rail-high { - box-shadow: inset 3px 0 0 var(--dug-sev-high); +.vulnerabilities-filters { + display: flex; + flex-wrap: wrap; + gap: 12px; } -.dug-rail-medium { - box-shadow: inset 3px 0 0 var(--dug-sev-medium); +.vulnerabilities-filters .vulnerabilities-filters__search { + flex-basis: 260px; } -.dug-rail-low { - box-shadow: inset 3px 0 0 var(--dug-sev-low); +.vulnerabilities-filters .vulnerabilities-filters__severity { + flex-basis: 150px; +} + +.vulnerabilities-filters .mud-input-control > .mud-input-control-input-container > .mud-input-label { + font-size: 13px; + font-weight: 500; +} + +@media (max-width: 959.98px) { + .vulnerabilities-filters .vulnerabilities-filters__search, + .vulnerabilities-filters .vulnerabilities-filters__severity { + flex-basis: 100%; + } +} + +.vulnerabilities-table .mud-table-body .mud-table-cell { + padding-top: 8px; + padding-bottom: 8px; + vertical-align: middle; +} + +.section-table .mud-table-body .vulnerabilities-table__expand.mud-button-root { + border: none; +} + +.vulnerabilities-table__id { + font-weight: 600; +} + +.vulnerabilities-table .mud-table-body .vulnerabilities-table__row--expanded, +.vulnerabilities-table .mud-table-body .vulnerabilities-table__row--expanded .mud-table-cell { + background: var(--dug-surface-subtle); +} + +.vulnerabilities-table .mud-table-body .vulnerabilities-table__detail, +.vulnerabilities-table .mud-table-body .vulnerabilities-table__detail .mud-table-cell { + background: var(--dug-surface-subtle); +} + +@media (max-width: 959.98px) { + .vulnerabilities-table .mud-table-body .vulnerabilities-table__detail-spacer { + display: none; + } + + .vulnerabilities-table .mud-table-body .mud-table-cell { + min-width: 0; + overflow-wrap: anywhere; + } + + .vulnerabilities-table .mud-table-body .mud-table-cell::before { + flex-shrink: 0; + } + + .vulnerabilities-table .mud-table-body .vulnerabilities-table__value { + min-width: 0; + text-align: end; + } + + .vulnerabilities-table .mud-table-body .mud-table-cell.vulnerabilities-table__detail-content { + display: block; + } +} + +.dug-pager { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: flex-end; + gap: 16px; + padding: 8px 20px; + border-top: 1px solid var(--dug-border); + color: var(--dug-text-muted); + font-size: 13px; +} + +.dug-pager__size { + display: inline-flex; + align-items: center; + gap: 8px; +} + +.dug-pager__select { + height: 44px; + padding: 0 8px; + border: 1px solid var(--dug-border-control); + border-radius: var(--dug-radius-md); + background: var(--dug-surface); + color: var(--dug-text); + font: inherit; +} + +.dug-pager__button:disabled { + color: var(--dug-text-muted) !important; + border: 1px solid var(--dug-border); } .runtime-containers-table .runtime-containers-table__container, diff --git a/src/Tests/DockerUpdateGuard.Tests/AppStylesheetVulnerabilitiesTests.cs b/src/Tests/DockerUpdateGuard.Tests/AppStylesheetVulnerabilitiesTests.cs new file mode 100644 index 00000000..dbc95a23 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/AppStylesheetVulnerabilitiesTests.cs @@ -0,0 +1,201 @@ +using DockerUpdateGuard.Tests.Helper; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for the rules of wwwroot/app.css that style the Vulnerabilities page +/// +[TestClass] +public class AppStylesheetVulnerabilitiesTests +{ + #region Constants + + /// + /// Shipped stylesheet below the host project directory + /// + private const string StylesheetPath = "wwwroot/app.css"; + + /// + /// Media context of the card layout of table rows + /// + private const string CardContext = "@media (max-width: 959.98px)"; + + /// + /// Subtle surface value + /// + private const string SubtleSurface = "var(--dug-surface-subtle)"; + + #endregion // Constants + + #region Methods + + /// + /// Verify the stylesheet has no severity rail rule in any context + /// + [TestMethod] + [TestCategory("AC4")] + public void AppStylesheetVulnerabilitiesHasNoRailRule() + { + var rails = GetEntries().Where(rule => rule.Entry.Contains("dug-rail-", StringComparison.Ordinal)) + .Select(rule => rule.Entry) + .ToList(); + + Assert.IsEmpty(rails, $"The stylesheet must have no rail rule, found: {string.Join(", ", rails)}"); + } + + /// + /// Verify an expanded row and its detail use the subtle surface background + /// + /// Class of the row or the detail + [TestMethod] + [TestCategory("AC5")] + [DataRow("vulnerabilities-table__row--expanded")] + [DataRow("vulnerabilities-table__detail")] + public void AppStylesheetVulnerabilitiesExpandedRowAndDetailUseSubtleSurface(string className) + { + var backgrounds = GetEntries().Where(rule => rule.Entry.Contains(className, StringComparison.Ordinal)) + .SelectMany(rule => StylesheetReader.GetDeclarationList(rule.Body)) + .Where(declaration => declaration.Name is "background" or "background-color") + .Select(declaration => declaration.Value) + .ToList(); + + Assert.Contains(SubtleSurface, backgrounds, $"A rule for '{className}' must set the subtle surface background"); + } + + /// + /// Verify the filters have fixed widths from 960 px and take the full width below it + /// + [TestMethod] + [TestCategory("AC8")] + public void AppStylesheetVulnerabilitiesFiltersTakeFullWidthBelow960Pixels() + { + var filterRules = GetEntries().Where(rule => rule.Entry.Contains("vulnerabilities-filters", StringComparison.Ordinal)) + .ToList(); + + var wide = filterRules.Where(rule => rule.Context != CardContext) + .SelectMany(rule => StylesheetReader.GetDeclarationList(rule.Body)) + .Select(declaration => declaration.Value) + .ToList(); + + var narrow = filterRules.Where(rule => rule.Context == CardContext) + .SelectMany(rule => StylesheetReader.GetDeclarationList(rule.Body)) + .Where(declaration => declaration.Name == "flex-basis") + .Select(declaration => declaration.Value) + .ToList(); + + Assert.Contains("260px", wide, "The filter field must be 260 px wide from 960 px"); + Assert.Contains("150px", wide, "The severity select must be 150 px wide from 960 px"); + Assert.Contains("100%", narrow, "The fields must take the full width below 960 px"); + } + + /// + /// Verify the expand and pager buttons stay 44 by 44 px, the page select is 44 px high and a disabled pager button keeps its border and muted color + /// + [TestMethod] + [TestCategory("AC8")] + public void AppStylesheetVulnerabilitiesButtonsAreFortyFourPixels() + { + var expand = GetDeclarations(entry => entry.Contains("vulnerabilities-table__expand", StringComparison.Ordinal) && entry.Contains(":disabled", StringComparison.Ordinal) == false); + var select = GetDeclarations(entry => entry.EndsWith("dug-pager__select", StringComparison.Ordinal)); + var disabled = GetDeclarations(entry => entry.Contains("dug-pager__button:disabled", StringComparison.Ordinal)); + var buttons = GetDeclarations(entry => entry == ".section-table .mud-table-body .mud-icon-button" || entry == ".dug-icon-button"); + + Assert.AreEqual("44px", buttons.GetValueOrDefault("width"), "Table and pager icon buttons must be 44 px wide"); + Assert.AreEqual("44px", buttons.GetValueOrDefault("height"), "Table and pager icon buttons must be 44 px high"); + Assert.IsNotEmpty(expand, "The expand button must have a page rule"); + Assert.IsTrue(expand.GetValueOrDefault("width", "44px") == "44px" && expand.GetValueOrDefault("height", "44px") == "44px", "The expand rule must not shrink the button"); + Assert.AreEqual("none", expand.GetValueOrDefault("border"), "The expand button must have no border"); + Assert.AreEqual("44px", select.GetValueOrDefault("height"), "The page size select must be 44 px high"); + Assert.AreEqual("var(--dug-text-muted) !important", disabled.GetValueOrDefault("color"), "A disabled pager button must be muted and the override must stay important"); + Assert.IsTrue(disabled.GetValueOrDefault("border", string.Empty).StartsWith("1px", StringComparison.Ordinal), "A disabled pager button must keep its 1 px border"); + } + + /// + /// Verify below 960 px the cells shrink and wrap long values, the label keeps its width and the value group sits at the end + /// + [TestMethod] + [TestCategory("AC8")] + public void AppStylesheetVulnerabilitiesCardCellsWrapLongValues() + { + var cell = GetCardDeclarations(".vulnerabilities-table .mud-table-body .mud-table-cell"); + var label = GetCardDeclarations(".vulnerabilities-table .mud-table-body .mud-table-cell::before"); + var value = GetCardDeclarations(".vulnerabilities-table .mud-table-body .vulnerabilities-table__value"); + + Assert.AreEqual("0", cell.GetValueOrDefault("min-width"), "A card cell must be allowed to shrink"); + Assert.AreEqual("anywhere", cell.GetValueOrDefault("overflow-wrap"), "A card cell must wrap at any character"); + Assert.AreEqual("0", label.GetValueOrDefault("flex-shrink"), "The label must keep its width"); + Assert.AreEqual("0", value.GetValueOrDefault("min-width"), "The value group must be allowed to shrink"); + Assert.AreEqual("end", value.GetValueOrDefault("text-align"), "The value group must sit at the end of the line"); + } + + /// + /// Verify the detail content cell is a block below 960 px only, with the selector specific enough to beat the card cell rule + /// + [TestMethod] + [TestCategory("AC8")] + public void AppStylesheetVulnerabilitiesDetailContentIsBlockBelow960Pixels() + { + const string selector = ".vulnerabilities-table .mud-table-body .mud-table-cell.vulnerabilities-table__detail-content"; + + var rules = GetEntries().Where(rule => rule.Entry == selector).ToList(); + + Assert.IsNotEmpty(rules, "A rule with the four-class selector must exist"); + Assert.IsTrue(rules.All(rule => rule.Context == CardContext), "The rule must apply below 960 px only"); + Assert.AreEqual("block", GetCardDeclarations(selector).GetValueOrDefault("display"), "The detail content must be a block"); + } + + #endregion // Methods + + #region Helper methods + + /// + /// Merge the declarations of the top-level rules whose selector entry matches + /// + /// Selector entry predicate + /// Property name to value, later rules winning + private static Dictionary GetDeclarations(Func match) + { + var merged = new Dictionary(); + + foreach (var rule in GetEntries().Where(rule => rule.Context.Length == 0 && match(rule.Entry))) + { + foreach (var (name, value) in StylesheetReader.GetDeclarationList(rule.Body)) + { + merged[name] = value; + } + } + + return merged; + } + + /// + /// Merge the declarations of the rules with exactly the given selector entry inside the card media query + /// + /// Selector entry + /// Property name to value, later rules winning + private static Dictionary GetCardDeclarations(string selector) + { + var merged = new Dictionary(); + + foreach (var rule in GetEntries().Where(rule => rule.Context == CardContext && rule.Entry == selector)) + { + foreach (var (name, value) in StylesheetReader.GetDeclarationList(rule.Body)) + { + merged[name] = value; + } + } + + return merged; + } + + /// + /// Read every selector of every rule of the stylesheet, in every media context + /// + /// Selector, rule body and media context + private static List<(string Entry, string Body, string Context)> GetEntries() + { + return [.. StylesheetReader.GetRules(StylesheetReader.ReadHostFile(StylesheetPath)).SelectMany(rule => StylesheetReader.SplitTopLevel(rule.Selector, ',').Select(entry => (entry, rule.Body, rule.Context)))]; + } + + #endregion // Helper methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/SectionPanelTests.cs b/src/Tests/DockerUpdateGuard.Tests/SectionPanelTests.cs index 26d484c1..e636911f 100644 --- a/src/Tests/DockerUpdateGuard.Tests/SectionPanelTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/SectionPanelTests.cs @@ -98,6 +98,56 @@ public async Task SectionPanelFlushAddsFlushClass() } } + /// + /// Verify the title and subtitle content render beside and below the title heading in a title group + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task SectionPanelTitleAndSubtitleContentRenderBesideAndBelowTitle() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = testContext.Render(parameters => parameters.Add(panel => panel.Title, "Active advisories") + .Add(panel => panel.TitleContent, CreateFragment("· 31")) + .Add(panel => panel.SubtitleContent, CreateFragment("
Bar
")) + .Add(panel => panel.HeaderContent, CreateFragment("
Filters
"))); + + var titleGroup = component.Find(".dug-panel__header > .dug-panel__title-group"); + var titleRow = titleGroup.QuerySelector(":scope > .dug-panel__title-row"); + + Assert.IsNotNull(titleRow, "The title group must hold the title row"); + Assert.AreEqual("Active advisories", titleRow.QuerySelector(":scope > h2.dug-panel__title")?.TextContent, "The heading must hold the title text only"); + Assert.AreEqual("· 31", titleRow.QuerySelector(":scope > #count")?.TextContent, "The title content must render in the title row beside the heading"); + Assert.AreEqual("Bar", titleGroup.QuerySelector(":scope > #bar")?.TextContent, "The subtitle content must render in the title group"); + Assert.IsNull(titleRow.QuerySelector("#bar"), "The subtitle content must render below the title row"); + Assert.IsNull(component.Find("h2").QuerySelector("#count"), "The title content must not render inside the heading"); + Assert.AreEqual("Filters", component.Find(".dug-panel__header > .dug-panel__header-content #filters").TextContent, "The header content must stay a sibling of the title group"); + } + } + + /// + /// Verify a panel without title or subtitle content renders the heading alone, directly in the header + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task SectionPanelWithoutTitleFragmentsRendersHeadingAlone() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = testContext.Render(parameters => parameters.Add(panel => panel.Title, "Findings")); + + Assert.IsEmpty(component.FindAll(".dug-panel__title-group"), "No title group must render without title or subtitle content"); + Assert.IsEmpty(component.FindAll(".dug-panel__title-row"), "No title row must render without title or subtitle content"); + Assert.AreEqual("Findings", component.Find(".dug-panel__header > h2.dug-panel__title").TextContent, "The heading must be a direct child of the header"); + } + } + #endregion // Methods #region Static methods diff --git a/src/Tests/DockerUpdateGuard.Tests/TablePagingFormatterTests.cs b/src/Tests/DockerUpdateGuard.Tests/TablePagingFormatterTests.cs new file mode 100644 index 00000000..103bbb7e --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/TablePagingFormatterTests.cs @@ -0,0 +1,59 @@ +using DockerUpdateGuard.UI; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for +/// +[TestClass] +public class TablePagingFormatterTests +{ + #region Methods + + /// + /// Verify the range text uses an en dash and clamps the last page to the total + /// + /// Zero-based page index + /// Rows per page + /// Total rows + /// Expected text + [TestMethod] + [TestCategory("AC7")] + [DataRow(0, 25, 31, "1–25 of 31")] + [DataRow(1, 25, 31, "26–31 of 31")] + [DataRow(0, 25, 10, "1–10 of 10")] + [DataRow(0, 25, 25, "1–25 of 25")] + [DataRow(1, 50, 120, "51–100 of 120")] + [DataRow(2, 50, 120, "101–120 of 120")] + public void TablePagingFormatterFormatRangeReturnsExpectedText(int pageIndex, int pageSize, int totalCount, string expected) + { + var text = TablePagingFormatter.FormatRange(pageIndex, pageSize, totalCount); + + Assert.AreEqual(expected, text, $"Page {pageIndex} of size {pageSize} over {totalCount} rows must format as '{expected}'"); + } + + /// + /// Verify the last-page test + /// + /// Zero-based page index + /// Rows per page + /// Total rows + /// Expected result + [TestMethod] + [TestCategory("AC7")] + [DataRow(0, 25, 31, false)] + [DataRow(1, 25, 31, true)] + [DataRow(0, 25, 25, true)] + [DataRow(0, 25, 26, false)] + [DataRow(0, 25, 0, true)] + [DataRow(1, 50, 100, true)] + [DataRow(0, 50, 100, false)] + public void TablePagingFormatterIsLastPageReturnsExpectedResult(int pageIndex, int pageSize, int totalCount, bool expected) + { + var isLast = TablePagingFormatter.IsLastPage(pageIndex, pageSize, totalCount); + + Assert.AreEqual(expected, isLast, $"Page {pageIndex} of size {pageSize} over {totalCount} rows must give {expected}"); + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/VulnerabilitiesPersistentStateTests.cs b/src/Tests/DockerUpdateGuard.Tests/VulnerabilitiesPersistentStateTests.cs index 7c07c0d7..d1685602 100644 --- a/src/Tests/DockerUpdateGuard.Tests/VulnerabilitiesPersistentStateTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/VulnerabilitiesPersistentStateTests.cs @@ -33,6 +33,7 @@ public class VulnerabilitiesPersistentStateTests /// /// Task [TestMethod] + [TestCategory("AC6")] public async Task VulnerabilitiesRestoresFromPersistentState() { var testContext = BlazorTestContextFactory.Create(); @@ -67,6 +68,7 @@ public async Task VulnerabilitiesRestoresFromPersistentState() /// /// Task [TestMethod] + [TestCategory("AC6")] public async Task VulnerabilitiesPersistsLoadedStateForPrerender() { var testContext = BlazorTestContextFactory.Create(); diff --git a/src/Tests/DockerUpdateGuard.Tests/VulnerabilitiesRenderTests.cs b/src/Tests/DockerUpdateGuard.Tests/VulnerabilitiesRenderTests.cs new file mode 100644 index 00000000..f0251a2f --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/VulnerabilitiesRenderTests.cs @@ -0,0 +1,776 @@ +using AngleSharp.Dom; +using AngleSharp.Html.Dom; + +using Bunit; + +using DockerUpdateGuard.Tests.Helper; +using DockerUpdateGuard.UI; + +using Microsoft.Extensions.DependencyInjection; + +using MudBlazor; + +using NSubstitute; + +using VulnerabilitiesPage = DockerUpdateGuard.Components.Pages.Vulnerabilities; + +namespace DockerUpdateGuard.Tests; + +/// +/// Rendering tests for +/// +[TestClass] +public class VulnerabilitiesRenderTests +{ + #region Constants + + /// + /// Selector of the free-text filter input + /// + private const string FilterInput = "input[placeholder='Advisory, title or package']"; + + /// + /// Selector of the expand button of a row + /// + private const string ExpandButton = ".vulnerabilities-table__expand"; + + /// + /// Selector of the next-page button + /// + private const string NextButton = ".dug-pager button[aria-label='Next page']"; + + /// + /// Selector of the previous-page button + /// + private const string PreviousButton = ".dug-pager button[aria-label='Previous page']"; + + /// + /// Selector of the page-size select + /// + private const string PageSizeSelect = "select.dug-pager__select"; + + /// + /// Selector of the pager + /// + private const string Pager = ".dug-pager"; + + #endregion // Constants + + #region Methods + + /// + /// Verify the page shows the page header without eyebrow, one panel and the labelled filters in the panel header + /// + /// Task + [TestMethod] + [TestCategory("AC1")] + public async Task VulnerabilitiesRendersPageHeaderAndOnePanelWithFilters() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(31)); + + Assert.AreEqual("Vulnerabilities", page.Find("h1.dug-page-header__title").TextContent.Trim(), "The page header must show the title"); + Assert.AreEqual("Active advisories across all images, with the images and running containers each one affects.", + page.Find("p.dug-page-header__description").TextContent.Trim(), + "The page header must show the description"); + Assert.DoesNotContain("Fleet-wide security posture", page.Markup, "The eyebrow must be gone"); + Assert.IsEmpty(page.FindAll(".page-eyebrow"), "No eyebrow element must render"); + Assert.HasCount(1, page.FindAll("section.dug-panel"), "The page must show one panel"); + Assert.AreEqual("Active advisories", page.Find("section.dug-panel h2.dug-panel__title").TextContent.Trim(), "The heading must name the panel only"); + Assert.DoesNotContain("One row per CVE", page.Markup, "The panel must have no description line"); + Assert.IsNotNull(page.Find(".dug-panel__title-group .vulnerabilities-severity .dug-severity"), "The severity bar must sit under the title"); + Assert.IsNotNull(page.Find(".dug-panel__header .dug-panel__header-content .vulnerabilities-filters"), "The filters must sit in the panel header"); + Assert.HasCount(1, page.FindAll(".vulnerabilities-filters input[placeholder='Advisory, title or package']"), "The filter field must carry its placeholder"); + + var labels = page.FindAll(".vulnerabilities-filters label").Select(label => label.TextContent.Trim()).ToList(); + + Assert.AreSequenceEqual(["Filter", "Severity"], labels, "The fields must carry the labels Filter and Severity"); + + var options = page.FindComponents>().Select(item => item.Instance.Value).ToList(); + + Assert.AreSequenceEqual(["All", "Critical", "High", "Medium", "Low"], options, "The select must offer its five options"); + + await page.Find(FilterInput).InputAsync("zlib").ConfigureAwait(false); + + Assert.IsNotEmpty(page.FindAll(".vulnerabilities-filters .mud-input-clear-button"), "The filter field must be clearable"); + } + } + + /// + /// Verify the title shows the total when no filter is set + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task VulnerabilitiesTitleCountWithoutFilterShowsTotal() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(31)); + + Assert.AreEqual("Active advisories · 31", GetTitle(page), "The title must show the total without a filter"); + Assert.AreEqual("·31", RemoveSpaces(page.Find(".vulnerabilities-count").TextContent), "The count must sit in its own muted element"); + } + } + + /// + /// Verify the title shows the matching count of the total while a filter hides advisories and the total again when it is cleared + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task VulnerabilitiesTitleCountWithHidingFilterShowsMatchingOfTotal() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(31)); + + await page.Find(FilterInput).InputAsync("zlib").ConfigureAwait(false); + + Assert.AreEqual("Active advisories · 4 of 31", GetTitle(page), "A hiding text filter must show the matching count of the total"); + Assert.HasCount(4, page.FindAll(ExpandButton), "The table must list the four matches"); + + await page.Find(FilterInput).InputAsync(string.Empty).ConfigureAwait(false); + + Assert.AreEqual("Active advisories · 31", GetTitle(page), "A cleared filter must show the total again"); + + await SelectSeverityAsync(page, "Critical").ConfigureAwait(false); + + Assert.AreEqual("Active advisories · 4 of 31", GetTitle(page), "A hiding severity must show the matching count of the total"); + } + } + + /// + /// Verify a filter that hides nothing shows the total alone + /// + /// Task + [TestMethod] + [TestCategory("AC2")] + public async Task VulnerabilitiesTitleCountWithFilterHidingNothingShowsTotal() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(31)); + + await page.Find(FilterInput).InputAsync("CVE-2026").ConfigureAwait(false); + + Assert.AreEqual("Active advisories · 31", GetTitle(page), "A filter that matches every advisory must show the total only"); + } + } + + /// + /// Verify the severity bar and its legend show all advisories while a filter hides some + /// + /// Task + [TestMethod] + [TestCategory("AC3")] + public async Task VulnerabilitiesSeverityBarCountsAllAdvisoriesWhileFiltered() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(31)); + string[] expected = ["4 critical", "6 high", "8 medium", "13 low"]; + + Assert.AreSequenceEqual(expected, GetLegend(page), "The legend must count every advisory once, an unknown severity as low"); + + await page.Find(FilterInput).InputAsync("zlib").ConfigureAwait(false); + + Assert.HasCount(4, page.FindAll(ExpandButton), "The filter must hide advisories"); + Assert.AreSequenceEqual(expected, GetLegend(page), "The legend must not follow the filter"); + } + } + + /// + /// Verify every row shows the severity chip in the tone of its severity and the cells of the table + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task VulnerabilitiesRowShowsSeverityChipAndCells() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var item = new VulnerabilityOverviewItemData + { + AdvisoryId = "CVE-2026-9001", + Title = "Heap overflow", + Severity = "High", + CvssScore = 7.5m, + ReferenceUrl = "https://example.com/CVE-2026-9001", + AffectedPackages = ["openssl", "zlib"], + FixedVersions = ["3.0.1"], + AffectedImages = [CreateImage(Guid.NewGuid(), false), CreateImage(null, false)], + AffectedContainerCount = 5 + }; + + var page = RenderPage(testContext, [item]); + + Assert.IsEmpty(page.FindAll("[class*='dug-rail-']"), "No element may carry a rail class"); + + var severityCell = page.Find("td[data-label='Severity']"); + + Assert.AreEqual("High", severityCell.QuerySelector(".dug-chip.dug-chip--high")?.TextContent.Trim(), "The severity must be a chip in the high tone"); + Assert.AreEqual("CVSS 7.5", severityCell.QuerySelector(".table-secondary")?.TextContent.Trim(), "The CVSS score must show below the chip"); + Assert.AreEqual("CVE-2026-9001", page.Find("td[data-label='Advisory'] a.table-link").TextContent.Trim(), "The advisory identifier must show"); + Assert.AreEqual("Heap overflow", page.Find("td[data-label='Advisory'] .table-secondary").TextContent.Trim(), "The title must show below the identifier"); + Assert.AreEqual("openssl, zlib", page.Find("td[data-label='Package']").TextContent.Trim(), "The packages must be joined with a comma"); + Assert.AreEqual("3.0.1", page.Find("td[data-label='Fixed version']").TextContent.Trim(), "The fixed version must show"); + Assert.AreEqual("2", page.Find("td[data-label='Affected images']").TextContent.Trim(), "The affected image count must show"); + Assert.AreEqual("5", page.Find("td[data-label='Running containers']").TextContent.Trim(), "The running container count must show"); + } + } + + /// + /// Verify an advisory without a known severity shows an Unknown chip in the low tone + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task VulnerabilitiesUnknownSeverityShowsUnknownLowChip() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, + [ + new VulnerabilityOverviewItemData + { + AdvisoryId = "CVE-2026-9002", + Severity = "NotSet" + } + ]); + + var chip = page.Find("td[data-label='Severity'] .dug-chip"); + + Assert.AreEqual("Unknown", chip.TextContent.Trim(), "An unknown severity must read Unknown"); + Assert.IsTrue(chip.ClassList.Contains("dug-chip--low"), "An unknown severity must use the low tone"); + Assert.AreEqual("—", page.Find("td[data-label='Package']").TextContent.Trim(), "A missing package must show a dash"); + } + } + + /// + /// Verify a collapsed expand button is named Show affected images and announces collapsed + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task VulnerabilitiesExpandButtonCollapsedIsNamedShowAffectedImages() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(3)); + + var button = page.Find(ExpandButton); + + Assert.AreEqual("Show affected images", button.GetAttribute("aria-label"), "A collapsed button must be named Show affected images"); + Assert.AreEqual("false", button.GetAttribute("aria-expanded"), "A collapsed button must announce aria-expanded false"); + Assert.IsEmpty(page.FindAll(".vulnerabilities-table__detail"), "No detail must render while collapsed"); + Assert.IsEmpty(page.FindAll(".vulnerabilities-table__row--expanded"), "No row may carry the expanded class while collapsed"); + } + } + + /// + /// Verify an expanded row is named Hide affected images, shows the detail with linked and plain images and collapses again + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task VulnerabilitiesExpandButtonExpandedIsNamedHideAndShowsDetail() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var observedId = Guid.NewGuid(); + var item = new VulnerabilityOverviewItemData + { + AdvisoryId = "CVE-2026-9003", + Severity = "Low", + AffectedImages = [CreateImage(observedId, false), CreateImage(null, false, "registry.example/plain:2")] + }; + + var page = RenderPage(testContext, [item]); + + await page.Find(ExpandButton).ClickAsync().ConfigureAwait(false); + + var button = page.Find(ExpandButton); + var detail = page.Find("tr.vulnerabilities-table__detail"); + + Assert.AreEqual("Hide affected images", button.GetAttribute("aria-label"), "An expanded button must be named Hide affected images"); + Assert.AreEqual("true", button.GetAttribute("aria-expanded"), "An expanded button must announce aria-expanded true"); + Assert.IsNotEmpty(page.FindAll("tr.vulnerabilities-table__row--expanded"), "The expanded row must carry the expanded class"); + Assert.IsNotNull(detail.QuerySelector("td.vulnerabilities-table__detail-spacer"), "The detail must start with the spacer cell"); + Assert.AreEqual("Affected images", detail.QuerySelector("td[colspan='6'] .table-secondary")?.TextContent.Trim(), "The detail must show its label"); + + var link = detail.QuerySelector("td[colspan='6'] a.table-link"); + + Assert.AreEqual($"/observed-images/{observedId}", link?.GetAttribute("href"), "An observed image must link to its detail page"); + Assert.AreEqual(1, detail.QuerySelectorAll("a").Length, "Only the observed image must be linked"); + Assert.Contains("registry.example/plain:2", detail.TextContent, "The other image must show as plain text"); + + await page.Find(ExpandButton).ClickAsync().ConfigureAwait(false); + + Assert.AreEqual("Show affected images", page.Find(ExpandButton).GetAttribute("aria-label"), "A second activation must collapse the row"); + Assert.IsEmpty(page.FindAll("tr.vulnerabilities-table__detail"), "The detail must be gone after collapsing"); + } + } + + /// + /// Verify the pager is hidden at 25 matches and all 25 rows are listed + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task VulnerabilitiesPagerHiddenAtTwentyFiveMatches() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(25)); + + Assert.IsEmpty(page.FindAll(Pager), "No pager must show for 25 matches"); + Assert.HasCount(25, page.FindAll(ExpandButton), "All 25 rows must be listed"); + } + } + + /// + /// Verify the pager shows above 25 matches with the size select, the range and only the two named buttons + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task VulnerabilitiesPagerShownAboveTwentyFiveMatchesWithTwoNamedButtons() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(31)); + + var pager = page.Find(Pager); + var sizes = pager.QuerySelectorAll("select.dug-pager__select option").Select(option => option.GetAttribute("value")).ToList(); + + Assert.AreEqual("Rows per page", pager.QuerySelector("label.dug-pager__size")?.TextContent.Trim().Split('\n')[0].Trim(), "The size label must read Rows per page"); + Assert.AreSequenceEqual(["25", "50", "100"], sizes, "The size select must offer 25, 50 and 100"); + Assert.AreEqual("1–25 of 31", pager.QuerySelector(".dug-pager__range")?.TextContent.Trim(), "The range must show the first page"); + Assert.HasCount(2, pager.QuerySelectorAll("button"), "The pager must have only two buttons"); + Assert.IsTrue(page.Find(PreviousButton).HasAttribute("disabled"), "The previous button must be disabled on the first page"); + Assert.IsFalse(page.Find(NextButton).HasAttribute("disabled"), "The next button must be enabled on the first page"); + Assert.HasCount(25, page.FindAll(ExpandButton), "The first page must list 25 rows"); + } + } + + /// + /// Verify the next page shows the remaining rows and disables the next button + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task VulnerabilitiesNextPageShowsRemainingRows() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(31)); + + await page.Find(NextButton).ClickAsync().ConfigureAwait(false); + + var ids = GetRowIds(page); + + Assert.HasCount(6, ids, "The second page must list the remaining six rows"); + Assert.AreEqual("CVE-2026-0026", ids[0], "The second page must start after the first 25 rows"); + Assert.AreEqual("26–31 of 31", page.Find(".dug-pager__range").TextContent.Trim(), "The range must show the second page"); + Assert.IsTrue(page.Find(NextButton).HasAttribute("disabled"), "The next button must be disabled on the last page"); + Assert.IsFalse(page.Find(PreviousButton).HasAttribute("disabled"), "The previous button must be enabled on the last page"); + + await page.Find(PreviousButton).ClickAsync().ConfigureAwait(false); + + Assert.AreEqual("1–25 of 31", page.Find(".dug-pager__range").TextContent.Trim(), "The previous button must show the first page again"); + } + } + + /// + /// Verify a change of the filter text on a later page shows the first page + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task VulnerabilitiesFilterChangeOnLaterPageShowsFirstPage() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(31)); + + await page.Find(NextButton).ClickAsync().ConfigureAwait(false); + await page.Find(FilterInput).InputAsync("libc").ConfigureAwait(false); + + Assert.HasCount(25, page.FindAll(ExpandButton), "A filter change must show the first page of 27 matches"); + Assert.AreEqual("1–25 of 27", page.Find(".dug-pager__range").TextContent.Trim(), "The range must show the first page of the matches"); + } + } + + /// + /// Verify a change of the severity on a later page shows the first page + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task VulnerabilitiesSeverityChangeOnLaterPageShowsFirstPage() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(60, index => index <= 25 ? "Medium" : "Low")); + + await page.Find(NextButton).ClickAsync().ConfigureAwait(false); + await SelectSeverityAsync(page, "Low").ConfigureAwait(false); + + Assert.HasCount(25, page.FindAll(ExpandButton), "A severity change must show the first page of 35 matches"); + Assert.AreEqual("1–25 of 35", page.Find(".dug-pager__range").TextContent.Trim(), "The range must show the first page of the matches"); + } + } + + /// + /// Verify a change of the page size shows the first page with more rows and no further paging by MudBlazor + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task VulnerabilitiesPageSizeChangeShowsFirstPageWithMoreRows() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(60)); + + await page.Find(NextButton).ClickAsync().ConfigureAwait(false); + await page.Find(PageSizeSelect).ChangeAsync("50").ConfigureAwait(false); + + Assert.HasCount(50, page.FindAll(ExpandButton), "The table must list 50 rows of 60 on the first page"); + Assert.AreEqual("1–50 of 60", page.Find(".dug-pager__range").TextContent.Trim(), "The range must show the first page of 50"); + Assert.AreEqual("CVE-2026-0001", GetRowIds(page)[0], "The first page must start with the first advisory"); + } + } + + /// + /// Verify the page size select shows the chosen size again after a filter hid the pager + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task VulnerabilitiesPageSizeSurvivesPagerHiddenByFilter() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(60)); + + await page.Find(PageSizeSelect).ChangeAsync("50").ConfigureAwait(false); + await page.Find(FilterInput).InputAsync("CVE-2026-0001").ConfigureAwait(false); + + Assert.IsEmpty(page.FindAll(Pager), "The filter must hide the pager"); + + await page.Find(FilterInput).InputAsync(string.Empty).ConfigureAwait(false); + + Assert.AreEqual("50", GetSelectedSize(page), "The select must show the chosen size again"); + Assert.HasCount(50, page.FindAll(ExpandButton), "The table must list 50 rows again"); + } + } + + /// + /// Verify a page size that is not offered is ignored + /// + /// Task + [TestMethod] + [TestCategory("AC7")] + public async Task VulnerabilitiesUnlistedPageSizeIsIgnored() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(60)); + + await page.Find(PageSizeSelect).ChangeAsync("30").ConfigureAwait(false); + + Assert.HasCount(25, page.FindAll(ExpandButton), "An unlisted size must leave 25 rows"); + + await page.Find(PageSizeSelect).ChangeAsync("many").ConfigureAwait(false); + + Assert.HasCount(25, page.FindAll(ExpandButton), "A non-numeric size must leave 25 rows"); + Assert.AreEqual("1–25 of 60", page.Find(".dug-pager__range").TextContent.Trim(), "The range must stay on 25 rows"); + } + } + + /// + /// Verify the table uses the card layout below 960 px and keeps the expand button in the row + /// + /// Task + [TestMethod] + [TestCategory("AC8")] + public async Task VulnerabilitiesRendersCardLayoutBreakpointWithExpandButton() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, CreateItems(3)); + + Assert.IsNotEmpty(page.FindAll(".vulnerabilities-table.mud-sm-table"), "The table must use the small card breakpoint (class mud-sm-table)"); + Assert.IsEmpty(page.FindAll(".mud-md-table"), "The table must not use the medium breakpoint"); + Assert.HasCount(3, page.FindAll("tr td .vulnerabilities-table__expand"), "Every row must hold its expand button in a cell"); + } + } + + /// + /// Verify the advisory and severity cells group their contents in one value element + /// + /// Task + [TestMethod] + [TestCategory("AC8")] + public async Task VulnerabilitiesAdvisoryAndSeverityCellsGroupTheirValues() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var item = new VulnerabilityOverviewItemData + { + AdvisoryId = "CVE-2026-9101", + Title = "Long title", + Severity = "Critical", + CvssScore = 9.8m, + ReferenceUrl = "https://example.com/CVE-2026-9101" + }; + + var page = RenderPage(testContext, [item]); + + var advisory = page.FindAll("td[data-label='Advisory'] div.vulnerabilities-table__value"); + var severity = page.FindAll("td[data-label='Severity'] div.vulnerabilities-table__value"); + + Assert.HasCount(1, advisory, "The advisory cell must hold one value group"); + Assert.HasCount(1, severity, "The severity cell must hold one value group"); + Assert.IsNotNull(advisory[0].QuerySelector("a.table-link"), "The advisory group must hold the link"); + Assert.AreEqual("Long title", advisory[0].QuerySelector(".table-secondary")?.TextContent.Trim(), "The advisory group must hold the title"); + Assert.IsNotNull(severity[0].QuerySelector(".dug-chip"), "The severity group must hold the chip"); + Assert.AreEqual("CVSS 9.8", severity[0].QuerySelector(".table-secondary")?.TextContent.Trim(), "The severity group must hold the CVSS line"); + Assert.IsEmpty(page.FindAll("td[data-label='Package'] div.vulnerabilities-table__value"), "Other cells must not get a value group"); + } + } + + /// + /// Verify the content cell of an expanded detail carries the block class + /// + /// Task + [TestMethod] + [TestCategory("AC8")] + public async Task VulnerabilitiesExpandedDetailContentCellCarriesBlockClass() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var item = new VulnerabilityOverviewItemData + { + AdvisoryId = "CVE-2026-9102", + Severity = "Low", + AffectedImages = [CreateImage(Guid.NewGuid(), false)] + }; + + var page = RenderPage(testContext, [item]); + + await page.Find(ExpandButton).ClickAsync().ConfigureAwait(false); + + var content = page.Find("tr.vulnerabilities-table__detail td.vulnerabilities-table__detail-content"); + + Assert.AreEqual("6", content.GetAttribute("colspan"), "The content cell must span six columns"); + Assert.IsFalse(page.Find("td.vulnerabilities-table__detail-spacer").ClassList.Contains("vulnerabilities-table__detail-content"), "The spacer must not carry the content class"); + Assert.AreEqual("Affected images", content.QuerySelector(".table-secondary")?.TextContent.Trim(), "The content cell must hold the detail label"); + } + } + + #endregion // Methods + + #region Static methods + + /// + /// Create overview items: critical first, with the zlib package on the critical ones and libc on all others + /// + /// Number of items + /// Items + private static List CreateItems(int count) + { + return CreateItems(count, GetDefaultSeverity); + } + + /// + /// Create overview items with a severity per one-based index + /// + /// Number of items + /// Severity of the item with the one-based index + /// Items + private static List CreateItems(int count, Func severityOf) + { + return [ + .. Enumerable.Range(1, count) + .Select(index => new VulnerabilityOverviewItemData + { + AdvisoryId = $"CVE-2026-{index:0000}", + Title = $"Advisory title {index}", + Severity = severityOf(index), + AffectedPackages = [severityOf(index) == "Critical" ? "zlib" : "libc"] + }) + ]; + } + + /// + /// Get the default severity of the one-based item index: 4 critical, 6 high, 8 medium, 9 low, 4 not set, then low + /// + /// One-based index + /// Severity text + private static string GetDefaultSeverity(int index) + { + return index switch + { + <= 4 => "Critical", + <= 10 => "High", + <= 18 => "Medium", + <= 27 => "Low", + <= 31 => "NotSet", + _ => "Low" + }; + } + + /// + /// Create an affected image + /// + /// Observed image identifier, if any + /// Whether the image is an own image + /// Image reference + /// Affected image + private static VulnerabilityOverviewAffectedImageData CreateImage(Guid? observedImageId, bool isOwnImage, string reference = "registry.example/app:1") + { + return new VulnerabilityOverviewAffectedImageData + { + ImageVersionId = Guid.NewGuid(), + ImageReference = reference, + ObservedImageId = observedImageId, + IsOwnImage = isOwnImage + }; + } + + /// + /// Render the page with the given advisories + /// + /// Test context + /// Advisories the view service returns + /// Rendered page + private static IRenderedComponent RenderPage(BunitContext testContext, IReadOnlyList items) + { + var viewService = Substitute.For(); + + viewService.GetVulnerabilityOverviewAsync(Arg.Any()) + .Returns(items); + + testContext.Services.AddSingleton(viewService); + + return testContext.Render(); + } + + /// + /// Pick a severity in the severity select + /// + /// Rendered page + /// Severity option + /// Task + private static async Task SelectSeverityAsync(IRenderedComponent page, string severity) + { + var select = page.FindComponent>(); + + await page.InvokeAsync(() => select.Instance.ValueChanged.InvokeAsync(severity)).ConfigureAwait(false); + } + + /// + /// Get the panel title with its count + /// + /// Rendered page + /// Title text, white space collapsed + private static string GetTitle(IRenderedComponent page) + { + var title = page.Find("h2.dug-panel__title").TextContent; + var count = page.Find(".vulnerabilities-count").TextContent; + + return StylesheetReader.CollapseWhitespace($"{title} {count}"); + } + + /// + /// Get the legend texts of the severity bar + /// + /// Rendered page + /// Legend entries + private static List GetLegend(IRenderedComponent page) + { + return [.. page.FindAll(".vulnerabilities-severity .dug-severity__legend span").Select(entry => StylesheetReader.CollapseWhitespace(entry.TextContent))]; + } + + /// + /// Get the advisory identifiers of the listed rows + /// + /// Rendered page + /// Identifiers in row order + private static List GetRowIds(IRenderedComponent page) + { + return [ + .. page.FindAll(ExpandButton) + .Select(button => button.Closest("tr")?.QuerySelector("td[data-label='Advisory'] a.table-link, td[data-label='Advisory'] .vulnerabilities-table__id")?.TextContent.Trim() ?? string.Empty) + ]; + } + + /// + /// Get the page size the pager's select shows + /// + /// Rendered page + /// Selected size text + private static string? GetSelectedSize(IRenderedComponent page) + { + var select = (IHtmlSelectElement)page.Find(PageSizeSelect); + var selected = select.QuerySelectorAll("option").FirstOrDefault(option => option.HasAttribute("selected")); + + return selected?.GetAttribute("value") ?? select.Value; + } + + /// + /// Remove all white space of a text + /// + /// Text + /// Text without white space + private static string RemoveSpaces(string text) + { + return StylesheetReader.CollapseWhitespace(text).Replace(" ", string.Empty, StringComparison.Ordinal); + } + + #endregion // Static methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/VulnerabilitiesTests.cs b/src/Tests/DockerUpdateGuard.Tests/VulnerabilitiesTests.cs index 59fc76bd..8d1beade 100644 --- a/src/Tests/DockerUpdateGuard.Tests/VulnerabilitiesTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/VulnerabilitiesTests.cs @@ -7,6 +7,8 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using MudBlazor; + using NSubstitute; using VulnerabilitiesPage = DockerUpdateGuard.Components.Pages.Vulnerabilities; @@ -26,6 +28,7 @@ public class VulnerabilitiesTests /// /// Task [TestMethod] + [TestCategory("AC6")] public async Task VulnerabilitiesActiveAdvisoriesRendersOverviewRow() { var testContext = BlazorTestContextFactory.Create(); @@ -73,6 +76,7 @@ public async Task VulnerabilitiesActiveAdvisoriesRendersOverviewRow() /// /// Task [TestMethod] + [TestCategory("AC6")] public async Task VulnerabilitiesNoActiveFindingsShowsEmptyState() { var testContext = BlazorTestContextFactory.Create(); @@ -99,6 +103,7 @@ public async Task VulnerabilitiesNoActiveFindingsShowsEmptyState() /// /// Task [TestMethod] + [TestCategory("AC6")] public async Task VulnerabilitiesFreeTextFilterHidesNonMatchingAdvisories() { var testContext = BlazorTestContextFactory.Create(); @@ -127,7 +132,7 @@ public async Task VulnerabilitiesFreeTextFilterHidesNonMatchingAdvisories() var component = testContext.Render(); - await component.Find("input[placeholder='Filter by advisory, package, or title']").InputAsync("7002").ConfigureAwait(false); + await component.Find("input[placeholder='Advisory, title or package']").InputAsync("7002").ConfigureAwait(false); Assert.Contains("CVE-2026-7002", component.Markup, "A matching advisory must remain visible after filtering by text"); Assert.DoesNotContain("CVE-2026-7003", component.Markup, "A non-matching advisory must be hidden after filtering by text"); @@ -135,11 +140,12 @@ public async Task VulnerabilitiesFreeTextFilterHidesNonMatchingAdvisories() } /// - /// Verify a critical advisory row carries the severity-rail CSS class + /// Verify no row carries a severity rail class /// /// Task [TestMethod] - public async Task VulnerabilitiesCriticalAdvisoryRendersSeverityRailClass() + [TestCategory("AC4")] + public async Task VulnerabilitiesRowsCarryNoRailClass() { var testContext = BlazorTestContextFactory.Create(); @@ -152,8 +158,14 @@ public async Task VulnerabilitiesCriticalAdvisoryRendersSeverityRailClass() new() { AdvisoryId = "CVE-2026-7004", - Title = "Critical rail advisory", + Title = "Critical advisory", Severity = "Critical", + }, + new() + { + AdvisoryId = "CVE-2026-7005", + Title = "Low advisory", + Severity = "Low", } ]); @@ -161,7 +173,44 @@ public async Task VulnerabilitiesCriticalAdvisoryRendersSeverityRailClass() var component = testContext.Render(); - Assert.Contains("dug-rail-critical", component.Markup, "A critical advisory row must carry the severity-rail CSS class"); + Assert.DoesNotContain("dug-rail-", component.Markup, "No row may carry a severity rail class"); + Assert.IsNotEmpty(component.FindAll(".vulnerabilities-table__expand"), "The page must render its rows in the reworked table"); + } + } + + /// + /// Verify a filter that matches nothing shows the no-match text, a zero count of the total and no pager + /// + /// Task + [TestMethod] + [TestCategory("AC6")] + public async Task VulnerabilitiesEmptyFilterShowsNoMatchText() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var viewService = Substitute.For(); + + viewService.GetVulnerabilityOverviewAsync(Arg.Any()) + .Returns([ + new() + { + AdvisoryId = "CVE-2026-7006", + Title = "Some advisory", + Severity = "High", + } + ]); + + testContext.Services.AddSingleton(viewService); + + var component = testContext.Render(); + + await component.Find("input[placeholder='Advisory, title or package']").InputAsync("nothing-matches").ConfigureAwait(false); + + Assert.Contains("No advisories match the current filter.", component.Markup, "An empty filter result must show the no-match text"); + Assert.AreEqual("0 of 1", component.Find(".vulnerabilities-count").TextContent.Replace("·", string.Empty, StringComparison.Ordinal).Trim(), "The title must count zero of the total"); + Assert.IsEmpty(component.FindAll(".dug-pager"), "No pager must show without matches"); } } @@ -170,8 +219,7 @@ public async Task VulnerabilitiesCriticalAdvisoryRendersSeverityRailClass() /// /// Task [TestMethod] - [TestCategory("AC1")] - [TestCategory("AC2")] + [TestCategory("AC6")] public async Task VulnerabilitiesLoadFailureShowsFixedErrorAndLogs() { var exception = new InvalidOperationException("secret text"); @@ -195,5 +243,142 @@ public async Task VulnerabilitiesLoadFailureShowsFixedErrorAndLogs() } } + /// + /// Verify the severity filter lists only the advisories of the selected severity + /// + /// Task + [TestMethod] + [TestCategory("AC6")] + public async Task VulnerabilitiesSeverityFilterListsOnlyThatSeverity() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, + [ + CreateItem("CVE-2026-8001", "Critical"), + CreateItem("CVE-2026-8002", "High"), + CreateItem("CVE-2026-8003", "critical"), + CreateItem("CVE-2026-8004", "Low") + ]); + var select = page.FindComponent>(); + + await page.InvokeAsync(() => select.Instance.ValueChanged.InvokeAsync("Critical")).ConfigureAwait(false); + + Assert.AreSequenceEqual(["CVE-2026-8001", "CVE-2026-8003"], GetListedIds(page), "Only the advisories of the selected severity must be listed, ignoring case"); + + await page.InvokeAsync(() => select.Instance.ValueChanged.InvokeAsync("All")).ConfigureAwait(false); + + Assert.HasCount(4, GetListedIds(page), "The All filter must list every advisory again"); + } + } + + /// + /// Verify the page lists the advisories in the order the view service returned them + /// + /// Task + [TestMethod] + [TestCategory("AC6")] + public async Task VulnerabilitiesListsAdvisoriesInServiceOrder() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var page = RenderPage(testContext, + [ + CreateItem("CVE-2026-8012", "Low"), + CreateItem("CVE-2026-8011", "Critical"), + CreateItem("CVE-2026-8013", "High") + ]); + + Assert.AreSequenceEqual(["CVE-2026-8012", "CVE-2026-8011", "CVE-2026-8013"], GetListedIds(page), "The advisories must keep the order of the view service"); + } + } + + /// + /// Verify only an advisory with a reference URL links to it and the others show their identifier as plain text + /// + /// Task + [TestMethod] + [TestCategory("AC6")] + public async Task VulnerabilitiesLinksOnlyAdvisoryWithReference() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var secure = CreateItem("CVE-2026-8021", "High"); + var plain = CreateItem("CVE-2026-8022", "High"); + var blank = CreateItem("CVE-2026-8023", "High"); + var none = CreateItem("CVE-2026-8024", "High"); + + secure.ReferenceUrl = "https://nvd.nist.gov/vuln/detail/CVE-2026-8021"; + plain.ReferenceUrl = "http://example.test/CVE-2026-8022"; + blank.ReferenceUrl = " "; + none.ReferenceUrl = null; + + var page = RenderPage(testContext, [secure, plain, blank, none]); + var links = page.FindAll("td[data-label='Advisory'] a.table-link"); + var plainIds = page.FindAll("td[data-label='Advisory'] span.vulnerabilities-table__id").Select(element => element.TextContent.Trim()).ToList(); + + Assert.AreSequenceEqual(["https://nvd.nist.gov/vuln/detail/CVE-2026-8021", "http://example.test/CVE-2026-8022"], + links.Select(link => link.GetAttribute("href")).ToList(), + "Only an advisory with a http or https reference must link to it"); + Assert.AreEqual("_blank", links[0].GetAttribute("target"), "The reference link must open in a new tab"); + Assert.AreEqual("noopener noreferrer", links[0].GetAttribute("rel"), "The reference link must not leak the opener"); + Assert.AreSequenceEqual(["CVE-2026-8023", "CVE-2026-8024"], plainIds, "An advisory without a reference must show its identifier as plain text"); + } + } + #endregion // Methods + + #region Static methods + + /// + /// Create an overview item + /// + /// Advisory identifier + /// Severity + /// Overview item + private static VulnerabilityOverviewItemData CreateItem(string advisoryId, string severity) + { + return new VulnerabilityOverviewItemData + { + AdvisoryId = advisoryId, + Title = $"Title {advisoryId}", + Severity = severity, + }; + } + + /// + /// Render the page with the given items + /// + /// Test context + /// Overview items + /// Rendered page + private static IRenderedComponent RenderPage(BunitContext testContext, List items) + { + var viewService = Substitute.For(); + + viewService.GetVulnerabilityOverviewAsync(Arg.Any()) + .Returns(items); + + testContext.Services.AddSingleton(viewService); + + return testContext.Render(); + } + + /// + /// Get the advisory identifiers listed in the table, in row order + /// + /// Rendered page + /// Advisory identifiers + private static List GetListedIds(IRenderedComponent page) + { + return [.. page.FindAll("td[data-label='Advisory']").Select(cell => cell.QuerySelector(".table-link, .vulnerabilities-table__id")?.TextContent.Trim() ?? string.Empty)]; + } + + #endregion // Static methods } \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/VulnerabilityDisplayFormatterTests.cs b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityDisplayFormatterTests.cs index 3781f6b6..bf4b6019 100644 --- a/src/Tests/DockerUpdateGuard.Tests/VulnerabilityDisplayFormatterTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityDisplayFormatterTests.cs @@ -12,32 +12,6 @@ public class VulnerabilityDisplayFormatterTests { #region Methods - /// - /// Verify vulnerability severity chip colors map to expected MudBlazor color values - /// - /// Severity label - /// Expected chip color - [TestMethod] - [DataRow("Critical", Color.Error)] - [DataRow("CRITICAL", Color.Error)] - [DataRow("High", Color.Warning)] - [DataRow("HIGH", Color.Warning)] - [DataRow("Medium", Color.Info)] - [DataRow("MEDIUM", Color.Info)] - [DataRow("Low", Color.Success)] - [DataRow("LOW", Color.Success)] - [DataRow("Unknown", Color.Default)] - [DataRow("anything-else", Color.Default)] - [DataRow(null, Color.Default)] - public void VulnerabilityDisplayFormatterGetSeverityColorKnownSeverityReturnsExpectedColor(string? severity, Color expectedColor) - { - var color = VulnerabilityDisplayFormatter.GetSeverityColor(severity); - - Assert.AreEqual(expectedColor, - color, - $"Vulnerability severity '{severity}' must map to Color.{expectedColor}"); - } - /// /// Verify status chip colors without severity information map to expected MudBlazor color values /// diff --git a/src/Tests/DockerUpdateGuard.Tests/VulnerabilityOverviewFormatterTests.cs b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityOverviewFormatterTests.cs new file mode 100644 index 00000000..becb188c --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/VulnerabilityOverviewFormatterTests.cs @@ -0,0 +1,119 @@ +using DockerUpdateGuard.UI; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for +/// +[TestClass] +public class VulnerabilityOverviewFormatterTests +{ + #region Methods + + /// + /// Verify the advisory count shows the total alone when nothing is hidden and the matching count of the total otherwise + /// + /// Matching advisories + /// All advisories + /// Expected text + [TestMethod] + [TestCategory("AC2")] + [DataRow(31, 31, "31")] + [DataRow(4, 31, "4 of 31")] + [DataRow(0, 31, "0 of 31")] + [DataRow(0, 0, "0")] + public void VulnerabilityOverviewFormatterFormatAdvisoryCountReturnsExpectedText(int matchingCount, int totalCount, string expected) + { + var text = VulnerabilityOverviewFormatter.FormatAdvisoryCount(matchingCount, totalCount); + + Assert.AreEqual(expected, text, $"{matchingCount} of {totalCount} advisories must format as '{expected}'"); + } + + /// + /// Verify a mixed list counts each advisory once at its severity and an unknown severity as other + /// + [TestMethod] + [TestCategory("AC3")] + public void VulnerabilityOverviewFormatterCreateSeveritySummaryMixedListCountsEachSeverity() + { + VulnerabilityOverviewItemData[] items = [ + CreateItem("Critical"), + CreateItem("critical"), + CreateItem("High"), + CreateItem("HIGH"), + CreateItem("High"), + CreateItem("Medium"), + CreateItem("Low"), + CreateItem("Low"), + CreateItem("Low"), + CreateItem("Low"), + CreateItem("NotSet"), + CreateItem("whatever"), + CreateItem(string.Empty) + ]; + + var summary = VulnerabilityOverviewFormatter.CreateSeveritySummary(items); + + Assert.AreEqual(2, summary.CriticalCount, "Critical advisories must be counted case-insensitively"); + Assert.AreEqual(3, summary.HighCount, "High advisories must be counted case-insensitively"); + Assert.AreEqual(1, summary.MediumCount, "The medium advisory must be counted"); + Assert.AreEqual(4, summary.LowCount, "Low advisories must be counted"); + Assert.AreEqual(3, summary.OtherCount, "NotSet, an unknown text and an empty text must count as other"); + Assert.AreEqual(13, summary.TotalCount, "Each advisory must be counted exactly once"); + } + + /// + /// Verify an empty list gives an empty summary + /// + [TestMethod] + [TestCategory("AC3")] + public void VulnerabilityOverviewFormatterCreateSeveritySummaryEmptyListReturnsEmptySummary() + { + var summary = VulnerabilityOverviewFormatter.CreateSeveritySummary([]); + + Assert.AreEqual(0, summary.TotalCount, "An empty list must give an empty summary"); + } + + /// + /// Verify the severity text is the canonical name for the four severities and Unknown for anything else + /// + /// Severity text + /// Expected display text + [TestMethod] + [TestCategory("AC4")] + [DataRow("Critical", "Critical")] + [DataRow("critical", "Critical")] + [DataRow("HIGH", "High")] + [DataRow("Medium", "Medium")] + [DataRow("low", "Low")] + [DataRow("NotSet", "Unknown")] + [DataRow("something-else", "Unknown")] + [DataRow("", "Unknown")] + [DataRow(null, "Unknown")] + public void VulnerabilityOverviewFormatterFormatSeverityReturnsExpectedText(string? severity, string expected) + { + var text = VulnerabilityOverviewFormatter.FormatSeverity(severity); + + Assert.AreEqual(expected, text, $"Severity '{severity}' must display as '{expected}'"); + } + + #endregion // Methods + + #region Static methods + + /// + /// Create an overview item with a severity + /// + /// Severity text + /// Overview item + private static VulnerabilityOverviewItemData CreateItem(string severity) + { + return new VulnerabilityOverviewItemData + { + AdvisoryId = "CVE-2026-0001", + Severity = severity + }; + } + + #endregion // Static methods +} \ No newline at end of file