diff --git a/README.md b/README.md index 0b958a84..1a11cc92 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ It is designed for teams that want more than "a newer tag exists". The app keeps ## Main UI areas -- **Dashboard**: summary view of the current inventory +- **Dashboard**: what needs attention: containers with updates, advisories in running containers, own base runtime warnings and the last scans - **Observed Images**: repositories and tags discovered from Docker Hub account data - **Runtime Containers**: live workload inventory with update and vulnerability state - **Docker Instances**: configured engines plus usage history diff --git a/docs/UNIT_TESTS.md b/docs/UNIT_TESTS.md index c9ffa60a..d46fed15 100644 --- a/docs/UNIT_TESTS.md +++ b/docs/UNIT_TESTS.md @@ -80,6 +80,7 @@ MSTest with **NSubstitute** (`Substitute.For()`) for collaborators that cross - `TestOptionsMonitor` with `ListenerRegistration` (`Data/`) — the options monitor of a reloadable configuration; `Reload` replaces `CurrentValue` and calls the `OnChange` listeners - `TestDevelopmentConfiguration` (`Data/`) — the development configuration files - `SaveChangesFailingDbContext` (`Data/`) — a database whose save fails +- `SetRecordingDbContext` (`Data/`) — a database that records which entity sets the code asks for - `GatedSaveChangesDbContext` (`Data/`, created by `SqliteTestDatabase.CreateGatedSaveChangesDbContext`) — a database whose first save of an added vulnerability finding signals `SaveEntered` and waits for `ReleaseSave` before touching the database - `ScanLockObserver` (`Helper/`) — a scan lock registry observer: `WaitUntilWaitingAsync` yields until a second reference of a key exists or the run's task has completed - `SqliteTestDatabase` (`Data/` of both test projects) — the PostgreSQL database, as SQLite @@ -307,7 +308,7 @@ await using (testContext) var component = testContext.Render(); var markup = component.Markup; - Assert.Contains("Observed Images", markup, "The Observed Images metric tile must render"); + Assert.Contains("Observed Images", markup, "The Observed Images inventory cell must render"); } ``` diff --git a/docs/areas/web-ui.md b/docs/areas/web-ui.md index a878e6be..36a3c91c 100644 --- a/docs/areas/web-ui.md +++ b/docs/areas/web-ui.md @@ -37,7 +37,7 @@ to read the state the other areas compute and to start manual scans; it computes - Timestamps are shown in UTC as `yyyy-MM-dd HH:mm UTC`, the same for every browser and independent of the time zone and culture of the server process. The resource chart labels are UTC too: the first and the last label read `MM-dd HH:mm UTC`, the visible labels between them `HH:mm`. -- The scan status chips of the dashboard, scan history, observed image, My Images, runtime container and image detail +- The scan status chips of the scan history, observed image, My Images, runtime container and image detail pages share one color mapping: `Succeeded` green, `Partial` and `Pending` orange, `Failed` red, `Running` blue; any other value, such as `NotSet` or `NotScanned`, stays neutral. The chip text is the status name. - While a page loads its data it shows placeholder skeletons; a list without data shows an explanatory empty state. A @@ -74,7 +74,7 @@ to read the state the other areas compute and to start manual scans; it computes | Route | Page | Shows | | --- | --- | --- | -| `/` | Dashboard | Counts of my images, manual observed images, Docker instances, runtime containers and shared base images; active update findings; active derived-runtime warnings of own images; active vulnerability findings of currently running containers with a per-severity breakdown; a configuration hint for vulnerability scanning; the 10 most recent scan runs (observed image scans, runtime container scans and vulnerability refreshes, [Scan runs](scan-engine.md#scan-runs)) | +| `/` | Dashboard | What needs attention: a headline sentence with the counts, the containers with an available update, the advisories of running containers, the own images with a base runtime warning, the last 10 scans and a strip of inventory counts; a configuration hint for vulnerability scanning (see [Dashboard](#dashboard)) | | `/my-images` | My Images | Images discovered from the configured Docker Hub account, with latest scan status and message, number of running containers, derived-runtime hint and vulnerability status | | `/my-images/{id}` | My Image details | One observed image: reference, latest scan, derived-runtime hint, running containers, base image chain, update findings with tag candidates, and — when there are any — vulnerability findings and its 20 most recent scan runs | | `/observed-images` | Observed Images | The registration form and the manually registered images with latest scan, active update findings, derived-runtime hint and vulnerability status | @@ -172,6 +172,51 @@ to read the state the other areas compute and to start manual scans; it computes - Scheduled background runs do not send this signal: their results become visible when a page is opened or navigated to again (the top bar also refreshes on every navigation). No page polls the server. +### Dashboard + +The page `/` opens with the headline sentence `{updates}, {runtime warnings} and {vulnerabilities} need attention.`: +only the parts with a count above 0 appear, joined with `, ` and ` and `, and `needs` stands for a single part of count +1. The parts are colored (updates and runtime warnings orange, vulnerabilities red), the rest of the sentence is not; +with no count at all the headline reads `Everything is up to date.`. Below it the sub line +`{n} protected assets on {m} Docker instances · last activity {time}` sums manual observed images, own images and current +containers, and shows the start of the newest recorded scan run in UTC (`no scans yet` without one); a single asset or +instance uses the singular. The vulnerability configuration hint follows. + +Each count is the number of the entries it counts, not of findings: + +| Panel | Counts | Listed | Order | Footer | +| ----- | ------ | ------ | ----- | ------ | +| Updates available | Current containers with the update state `Update available` | 5 | Container name, instance name, container id | `{n} more in Runtime Containers`, else `Open Runtime Containers` | +| Vulnerabilities | Distinct active advisories that affect at least one current container; the severity bar counts the same advisories | 4 | Severity, CVSS score (none last), affected containers, advisory id | `{n} more in Vulnerabilities`, else `Open Vulnerabilities` | +| Own base runtime warnings | Own images (source Discovery) with a base runtime alert | 5 | Name | `{n} more in My Images` when more exist, else none | +| Last 10 scans | The ten newest scan runs | 10 | Newest first | `Open scan history` | + +A panel without an entry shows no count and its empty text (`No updates available.`, `No vulnerabilities in running +containers.` without the bar, `No runtime warnings.`). The *Own base runtime warnings* panel is hidden when no Docker Hub +account is configured and no warning exists. An update row shows the container name, the instance name, and the current +tag (with the resolved version of an alias such as `latest (1.25.3)`) followed by `→` and the available tag when one is +known; it opens the container's detail page. A vulnerability row shows the affected packages (the advisory id when it +names none, which a screen reader announces with the row anyway), the severity chip and `Fixed in {versions}` or `No fix +available`, then `{n} running containers`; the severity, score, packages and fixed versions come from all active +findings of the advisory, as the Vulnerabilities page shows them, and a row opens `/vulnerabilities`. A warning row shows +the image name and the alert summary and opens the image's detail page. Texts from Docker, registries and scanners are +shown as text. + +With no update, no runtime warning and no vulnerability the three panels give way to one `Nothing to do` panel with +`No updates available, no own base runtime warnings and no vulnerabilities in running containers.`, followed by *Last 10 +scans*, both over the full width. Otherwise the panels stand in three columns and stack in the order Updates available, +Vulnerabilities, Own base runtime warnings, Last 10 scans on a narrow screen. + +*Last 10 scans* draws one segment per run, colored by status, with the tooltip `{type} · {target} · {status} · {start}` +(the target and its separator left out when the run has none). The strip is announced as an image named by the counts +(`8 succeeded, 1 partial, 1 failed`); below it the same counts above 0 stand in the order succeeded, running, pending, +partial, failed joined with ` · `, the failed count emphasized. When one of the runs is `Failed` or `Partial` and has an +error message, a line `{target} · {message}` names the newest such run, the message as stored. Without a run the panel +shows `No scans have been recorded yet.` and no strip. The inventory strip below shows `My Images` (only with a Docker +Hub account), `Observed Images`, `Runtime Containers`, `Docker Instances` and `Base Images` (only above 0), each with its +figure and a link to its page. While the data loads, skeletons in the shape of the headline, three panels and the strip +stand in. + ### Vulnerability configuration hint The dashboard shows at most one hint about vulnerability scanning: @@ -199,7 +244,7 @@ never their values. - Text and status labels keep a contrast of at least 4.5:1 against their background in both themes; filled buttons and MudBlazor status chips of the dark theme draw their label in the dark page color; the shared status chips take theirs from the tone's chip color pair. -- Text is set in Inter; page titles, entity names, the figures of the dashboard's metric cards and the product name +- Text is set in Inter; page titles, entity names, the figures of the dashboard's inventory strip and the product name are set in Space Grotesk. Both fonts and the styles are served by the application itself; the browser loads nothing from another host for them, and until a font has loaded the text shows in a fallback font. @@ -294,6 +339,8 @@ never their values. - [0079](../decisions/0079-statuses-map-to-tones-in-one-mapping-beside-the-chip-colors-of-unconverted-pages.md) — Statuses map to tones in one mapping, beside the chip colors of unconverted pages. +- [0080](../decisions/0080-the-dashboard-counts-the-containers-advisories-and-own-images-it-lists.md) — The dashboard + counts the containers, advisories and own images it lists. ## Not here diff --git a/docs/decisions/0080-the-dashboard-counts-the-containers-advisories-and-own-images-it-lists.md b/docs/decisions/0080-the-dashboard-counts-the-containers-advisories-and-own-images-it-lists.md new file mode 100644 index 00000000..9bf60a5a --- /dev/null +++ b/docs/decisions/0080-the-dashboard-counts-the-containers-advisories-and-own-images-it-lists.md @@ -0,0 +1,40 @@ +# 0080: The dashboard counts the containers, advisories and own images it lists + +- **Status:** Accepted +- **Date:** 2026-11-29 +- **Area:** Web UI +- **Source:** Issue #453 +- **Supersedes:** — + +## Context + +The dashboard of the flat refresh (#450) lists concrete items under a headline sentence: running containers with an +available update, advisories that affect running containers, and own images with a base runtime alert. Until now it +showed counts of findings: every active update finding (of all types, also of images no container runs), the active +vulnerability findings of running containers (one advisory counted once per image version), and the active +derived-runtime findings of own images. A finding count beside a list of other things cannot agree with the list's +length or with its "N more" link. The issue left the choice to the spec. + +## Options considered + +1. **Count what is listed (chosen)** — the headline, the panel count and the "more" figure are one number per list; + update findings of images no container runs and findings of image versions no container runs no longer appear on + the dashboard, only on Observed Images, My Images and Vulnerabilities. +2. **Keep the finding counts and give each list a second figure for its length** — nothing disappears from the + dashboard, but every panel shows two numbers that differ for reasons the user cannot see there, and the headline + names neither. + +## Decision + +The dashboard's counts are the number of running containers in the update state *Update available*, the number of +distinct active advisories affecting at least one running container, and the number of own images with a base +runtime alert; its lists show the first entries of the same sets, with the values the Runtime Containers, +Vulnerabilities and My Images pages compute for them. The rules are stated in [Web UI](../areas/web-ui.md). + +## Consequences + +The headline can read *Everything is up to date.* while an observed image no container runs has an update finding; +the all-clear text therefore speaks of available updates, not of update findings. An advisory row shows the severity, +packages and fixed versions of all its active findings, as the Vulnerabilities page does, also when some come from +image versions no container runs. Showing findings of non-running images on the dashboard again needs a list of its +own, not a change of these counts. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index c30ec413..11a43c9c 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -140,4 +140,5 @@ once in the [area document](../areas/README.md) of the record's area, and the re | [0077](0077-the-dark-theme-tokens-apply-to-the-whole-document-while-the-layout-is-dark.md) | The dark theme's tokens apply to the whole document while the layout is dark | Accepted | 2026-11-28 | | [0078](0078-mudblazor-elevation-shadows-are-switched-off-in-the-theme.md) | MudBlazor elevation shadows are switched off in the theme | Accepted | 2026-11-28 | | [0079](0079-statuses-map-to-tones-in-one-mapping-beside-the-chip-colors-of-unconverted-pages.md) | Statuses map to tones in one mapping, beside the chip colors of unconverted pages | Accepted | 2026-11-28 | +| [0080](0080-the-dashboard-counts-the-containers-advisories-and-own-images-it-lists.md) | The dashboard counts the containers, advisories and own images it lists | Accepted | 2026-11-29 | \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/DashboardSkeleton.razor b/src/DockerUpdateGuard/Components/Common/DashboardSkeleton.razor new file mode 100644 index 00000000..ed5a7205 --- /dev/null +++ b/src/DockerUpdateGuard/Components/Common/DashboardSkeleton.razor @@ -0,0 +1,10 @@ +
+ +
+ @for (var index = 0; index < 3; index++) + { + + } +
+ +
\ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/DashboardSkeleton.razor.cs b/src/DockerUpdateGuard/Components/Common/DashboardSkeleton.razor.cs new file mode 100644 index 00000000..55212de4 --- /dev/null +++ b/src/DockerUpdateGuard/Components/Common/DashboardSkeleton.razor.cs @@ -0,0 +1,6 @@ +namespace DockerUpdateGuard.Components.Common; + +/// +/// Skeleton placeholder that mirrors the dashboard while data is loading +/// +public sealed partial class DashboardSkeleton; \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/MetricGridSkeleton.razor b/src/DockerUpdateGuard/Components/Common/MetricGridSkeleton.razor deleted file mode 100644 index 59328078..00000000 --- a/src/DockerUpdateGuard/Components/Common/MetricGridSkeleton.razor +++ /dev/null @@ -1,8 +0,0 @@ - - @for (var index = 0; index < Cards; index++) - { - - - - } - \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/MetricGridSkeleton.razor.cs b/src/DockerUpdateGuard/Components/Common/MetricGridSkeleton.razor.cs deleted file mode 100644 index fece7fdd..00000000 --- a/src/DockerUpdateGuard/Components/Common/MetricGridSkeleton.razor.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Microsoft.AspNetCore.Components; - -namespace DockerUpdateGuard.Components.Common; - -/// -/// Skeleton placeholder that mirrors the dashboard metric-card grid while data is loading -/// -public sealed partial class MetricGridSkeleton -{ - #region Properties - - /// - /// Number of placeholder metric cards to render - /// - [Parameter] - public int Cards { get; set; } = 6; - - #endregion // Properties -} \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/PageHeaderSkeleton.razor b/src/DockerUpdateGuard/Components/Common/PageHeaderSkeleton.razor deleted file mode 100644 index 7cdac9cc..00000000 --- a/src/DockerUpdateGuard/Components/Common/PageHeaderSkeleton.razor +++ /dev/null @@ -1,10 +0,0 @@ -
-
-
- - - - -
-
-
\ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Common/PageHeaderSkeleton.razor.cs b/src/DockerUpdateGuard/Components/Common/PageHeaderSkeleton.razor.cs deleted file mode 100644 index 6caaa23b..00000000 --- a/src/DockerUpdateGuard/Components/Common/PageHeaderSkeleton.razor.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace DockerUpdateGuard.Components.Common; - -/// -/// Skeleton placeholder that mirrors the page header while data is loading -/// -public sealed partial class PageHeaderSkeleton; \ No newline at end of file diff --git a/src/DockerUpdateGuard/Components/Pages/Dashboard.razor b/src/DockerUpdateGuard/Components/Pages/Dashboard.razor index c9673ace..210dc40d 100644 --- a/src/DockerUpdateGuard/Components/Pages/Dashboard.razor +++ b/src/DockerUpdateGuard/Components/Pages/Dashboard.razor @@ -11,119 +11,76 @@ } else { - - + } } else { - - - - - - Operations cockpit - Dashboard - Track image freshness, runtime drift, and vulnerability posture from one place. - - - - + var headlineSegments = DashboardTextFormatter.GetHeadlineSegments(_dashboard.UpdateCount, _dashboard.RuntimeWarningCount, _dashboard.VulnerabilityCount); + var scanCounts = DashboardScanStripFormatter.GetStatusCounts(_dashboard.RecentScans); + var problemScan = DashboardScanStripFormatter.FindLatestProblemScan(_dashboard.RecentScans); + var isAllClear = _dashboard.UpdateCount == 0 && _dashboard.RuntimeWarningCount == 0 && _dashboard.VulnerabilityCount == 0; + var showRuntimeWarnings = _showMyImages || _dashboard.RuntimeWarningCount > 0; - - @if (_showMyImages) - { - - - -
- -
- My Images - @_dashboard.MyImageCount -
-
-
- } - - - -
- -
- Observed Images - @_dashboard.ObservedImageCount -
-
-
- - - -
- -
- Docker Instances - @_dashboard.DockerInstanceCount -
-
-
- - - -
- -
- Runtime Containers - @_dashboard.RuntimeContainerCount -
-
-
- @if (_dashboard.BaseImageCount > 0) + RenderFragment scanPanel = @ + + @if (_dashboard.RecentScans.Count == 0) + { +

No scans have been recorded yet.

+ } + else + { + +

+ @for (var index = 0; index < scanCounts.Count; index++) + { + @if (index > 0) + { + · + } + + @if (scanCounts[index].Status == "Failed") + { + @DashboardScanStripFormatter.FormatCountText(scanCounts[index]) + } + else + { + @DashboardScanStripFormatter.FormatCountText(scanCounts[index]) + } + } +

+ @if (problemScan is not null) { - - - -
- -
- Shared Base Images - @_dashboard.BaseImageCount -
-
-
+

@DashboardScanStripFormatter.FormatProblemScanLine(problemScan)

} - - -
- -
- Update Findings - @_dashboard.ActiveUpdateFindingCount -
-
- - -
- -
- Own Base Runtime Warnings - @_dashboard.OwnImageBaseRuntimeWarningCount -
-
- - - -
- -
- Vulnerabilities - @_dashboard.ActiveVulnerabilityFindingCount - -
-
-
-
+ } + Open scan history + +; + + +
+

+ @foreach (var segment in headlineSegments) + { + @if (segment.Tone is StatusTone.Warning or StatusTone.Danger or StatusTone.Success) + { + @segment.Text + } + else + { + @segment.Text + } + } +

+

@DashboardTextFormatter.FormatSubLine(_dashboard)

+
@if (_dashboard.VulnerabilityConfigurationHint == VulnerabilityConfigurationHintKind.ScanningDisabled) { @@ -138,111 +95,157 @@ else } - - - -
- Update pressure - Images and containers that currently need attention. -
- - - Active update findings - @_dashboard.ActiveUpdateFindingCount - - - Active vulnerability findings (running containers) - @_dashboard.ActiveVulnerabilityFindingCount - - - - Own base runtime warnings - @_dashboard.OwnImageBaseRuntimeWarningCount - - -
-
- - -
- Coverage snapshot - How much of the estate is currently observed. -
- - @if (_showMyImages) - { - - - My images - @_dashboard.MyImageCount - - - } - - - Observed images - @_dashboard.ObservedImageCount - - - - - Runtime containers - @_dashboard.RuntimeContainerCount - - - - - Docker instances - @_dashboard.DockerInstanceCount - - - @if (_dashboard.BaseImageCount > 0) - { - - - Shared base images - @_dashboard.BaseImageCount - - - } - -
-
-
- - -
- Recent scans - Latest observed image scans, runtime container scans and vulnerability refreshes. -
- - @if (_dashboard.RecentScans.Count == 0) +
+ @if (isAllClear) { - - No scans have been recorded yet. - +
+ +

No updates available, no own base runtime warnings and no vulnerabilities in running containers.

+
+ @scanPanel +
} else { - - - Type - Status - Target - Started - Error - - - @context.Type - - @context.Status - - @context.SubjectName - @TimestampFormatter.Format(context.StartedAtUtc) - @context.ErrorMessage - - +
+ + + @if (_dashboard.UpdateCount > 0) + { + @_dashboard.UpdateCount + } + + + @if (_dashboard.Updates.Count == 0) + { +

No updates available.

+ } + else + { + + } + @DashboardTextFormatter.FormatFooterLink(_dashboard.UpdateCount, _dashboard.Updates.Count, "Runtime Containers") +
+
+
+
+ + + @if (_dashboard.VulnerabilityCount > 0) + { + @_dashboard.VulnerabilityCount + } + + + + @if (_dashboard.Vulnerabilities.Count == 0) + { +

No vulnerabilities in running containers.

+ } + else + { + + } + @DashboardTextFormatter.FormatFooterLink(_dashboard.VulnerabilityCount, _dashboard.Vulnerabilities.Count, "Vulnerabilities") +
+
+
+
+ @if (showRuntimeWarnings) + { + + + @if (_dashboard.RuntimeWarningCount > 0) + { + @_dashboard.RuntimeWarningCount + } + + + @if (_dashboard.RuntimeWarnings.Count == 0) + { +

No runtime warnings.

+ } + else + { + + } + @if (_dashboard.RuntimeWarningCount > _dashboard.RuntimeWarnings.Count) + { + @DashboardTextFormatter.FormatFooterLink(_dashboard.RuntimeWarningCount, _dashboard.RuntimeWarnings.Count, "My Images") + } +
+
+ } + @scanPanel +
+ } +
+ +
+ @if (_showMyImages) + { + + My Images + @_dashboard.MyImageCount + + } + + Observed Images + @_dashboard.ObservedImageCount + + + Runtime Containers + @_dashboard.RuntimeContainerCount + + + Docker Instances + @_dashboard.DockerInstanceCount + + @if (_dashboard.BaseImageCount > 0) + { + + Base Images + @_dashboard.BaseImageCount + } - +
} diff --git a/src/DockerUpdateGuard/Components/Pages/Dashboard.razor.cs b/src/DockerUpdateGuard/Components/Pages/Dashboard.razor.cs index 4c551d4b..1cb19c64 100644 --- a/src/DockerUpdateGuard/Components/Pages/Dashboard.razor.cs +++ b/src/DockerUpdateGuard/Components/Pages/Dashboard.razor.cs @@ -33,7 +33,7 @@ public sealed partial class Dashboard : IDisposable private DashboardViewData? _dashboard; /// - /// Whether the My Images tile should be shown + /// Whether the My Images cell and the runtime warnings panel should be shown /// private bool _showMyImages; @@ -81,9 +81,9 @@ public sealed partial class Dashboard : IDisposable #region Static methods /// - /// Resolve the overview route for a dashboard metric card + /// Resolve the overview route for a dashboard inventory cell /// - /// Metric card label + /// Inventory cell label /// Navigation target private static string GetMetricNavigationTarget(string metricLabel) { @@ -93,9 +93,8 @@ private static string GetMetricNavigationTarget(string metricLabel) "Observed Images" => "/observed-images", "Docker Instances" => "/docker-instances", "Runtime Containers" => "/runtime-containers", - "Shared Base Images" => "/base-images", - "Vulnerabilities" => "/vulnerabilities", - _ => throw new ArgumentOutOfRangeException(nameof(metricLabel), metricLabel, "Dashboard metric cards must map to known overview routes"), + "Base Images" => "/base-images", + _ => throw new ArgumentOutOfRangeException(nameof(metricLabel), metricLabel, "Dashboard inventory cells must map to known overview routes"), }; } diff --git a/src/DockerUpdateGuard/UI/ApplicationViewService.cs b/src/DockerUpdateGuard/UI/ApplicationViewService.cs index 59713487..5771ccf3 100644 --- a/src/DockerUpdateGuard/UI/ApplicationViewService.cs +++ b/src/DockerUpdateGuard/UI/ApplicationViewService.cs @@ -34,6 +34,21 @@ public sealed class ApplicationViewService : IApplicationViewService, IDisposabl /// private const int SharedBaseImageMinimumUsageCount = 2; + /// + /// Maximum number of containers with an available update listed on the dashboard + /// + private const int DashboardUpdateLimit = 5; + + /// + /// Maximum number of advisories listed on the dashboard + /// + private const int DashboardVulnerabilityLimit = 4; + + /// + /// Maximum number of own images with a base runtime warning listed on the dashboard + /// + private const int DashboardRuntimeWarningLimit = 5; + /// /// Resource-history window /// @@ -376,6 +391,117 @@ private static void ApplyImageVulnerabilityData(RuntimeContainerDetailViewData d detail.VulnerabilityFindings = vulnerabilityAssessmentDetail.Findings; } + /// + /// Resolve the version tags of a current container snapshot, preferring the values stored on the snapshot over its tag candidates + /// + /// Current container snapshot with its image version + /// Tag candidates of the snapshot's update findings + /// Resolved version tag and available update version tag + private static (string? ResolvedVersionTag, string? AvailableUpdateVersionTag) ResolveRuntimeContainerTags(ContainerSnapshot entity, List tagCandidates) + { + var imageVersion = entity.ImageVersion; + + var resolvedVersionTag = string.IsNullOrWhiteSpace(entity.ResolvedVersionTag) == false + ? entity.ResolvedVersionTag + : TagCandidateViewHelper.ResolveResolvedVersionTag(imageVersion.Tag, + imageVersion.Digest, + tagCandidates); + var availableUpdateVersionTag = string.IsNullOrWhiteSpace(entity.AvailableUpdateVersionTag) == false + ? entity.AvailableUpdateVersionTag + : TagCandidateViewHelper.ResolveAvailableUpdateVersionTag(tagCandidates, + resolvedVersionTag ?? imageVersion.Tag); + + return (resolvedVersionTag, availableUpdateVersionTag); + } + + /// + /// Count the current containers running the image versions an advisory affects + /// + /// Active findings sharing the same advisory identifier + /// Running container counts by image version identifier + /// Number of affected containers + private static int CountAffectedContainers(IEnumerable advisoryFindings, Dictionary containerCountsByImageVersion) + { + return advisoryFindings.Select(entity => entity.ImageVersionId) + .Distinct() + .Sum(imageVersionId => GetCountOrZero(containerCountsByImageVersion, imageVersionId)); + } + + /// + /// Select the distinct affected packages of an advisory + /// + /// Active findings sharing the same advisory identifier + /// Affected packages ordered by name + private static List SelectAffectedPackages(IEnumerable advisoryFindings) + { + return [ + .. advisoryFindings.Select(entity => entity.AffectedPackage) + .Where(package => string.IsNullOrWhiteSpace(package) == false) + .Select(package => package!) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(package => package, StringComparer.OrdinalIgnoreCase) + ]; + } + + /// + /// Select the distinct fixed versions of an advisory + /// + /// Active findings sharing the same advisory identifier + /// Fixed versions ordered by value + private static List SelectFixedVersions(IEnumerable advisoryFindings) + { + return [ + .. advisoryFindings.Select(entity => entity.FixedVersion) + .Where(fixedVersion => string.IsNullOrWhiteSpace(fixedVersion) == false) + .Select(fixedVersion => fixedVersion!) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(fixedVersion => fixedVersion, StringComparer.OrdinalIgnoreCase) + ]; + } + + /// + /// Find the base runtime alert of an observed image: its own newest finding, else that of a current container of its repository + /// + /// Observed image with its current image version + /// Latest derived base runtime finding by observed image identifier + /// Latest derived base runtime finding by repository key + /// Base runtime alert or null + private static UpdateFinding? FindBaseRuntimeAlert(ObservedImage entity, + Dictionary observedAlertLookup, + Dictionary runtimeAlertLookup) + { + var repositoryKey = CreateRepositoryKey(entity.CurrentImageVersion); + + observedAlertLookup.TryGetValue(entity.Id, out var observedAlert); + runtimeAlertLookup.TryGetValue(repositoryKey, out var runtimeAlert); + + return observedAlert ?? runtimeAlert; + } + + /// + /// Create a dashboard advisory entry from the active findings of one advisory + /// + /// Active findings sharing the same advisory identifier + /// Running container counts by image version identifier + /// Dashboard advisory entry + private static DashboardVulnerabilityItemData CreateDashboardVulnerabilityItem(IGrouping advisoryGroup, + Dictionary containerCountsByImageVersion) + { + var representativeFinding = advisoryGroup.OrderByDescending(entity => entity.Severity) + .ThenByDescending(entity => entity.CvssScore ?? decimal.MinValue) + .First(); + + return new DashboardVulnerabilityItemData + { + AdvisoryId = representativeFinding.AdvisoryId, + Severity = advisoryGroup.Max(entity => entity.Severity).ToString(), + CvssScore = advisoryGroup.Max(entity => entity.CvssScore), + AffectedPackages = SelectAffectedPackages(advisoryGroup), + FixedVersions = SelectFixedVersions(advisoryGroup), + AffectedContainerCount = CountAffectedContainers(advisoryGroup, containerCountsByImageVersion), + }; + } + #endregion // Static methods #region Methods @@ -1148,7 +1274,7 @@ private VulnerabilityOverviewItemData CreateVulnerabilityOverviewItem(IGrouping< var affectedImageVersions = advisoryGroup.GroupBy(entity => entity.ImageVersionId) .Select(imageGroup => CreateAffectedImage(imageGroup.First().ImageVersion)) .ToList(); - var affectedContainerCount = affectedImageVersions.Sum(entity => GetCountOrZero(containerCountsByImageVersion, entity.ImageVersionId)); + var affectedContainerCount = CountAffectedContainers(advisoryGroup, containerCountsByImageVersion); var affectedImages = affectedImageVersions.GroupBy(entity => ImageReferenceFormatter.GetReference(entity.ImageReference), StringComparer.OrdinalIgnoreCase) .Select(referenceGroup => SelectRepresentativeAffectedImage(referenceGroup)) .OrderBy(entity => entity.ImageReference, StringComparer.OrdinalIgnoreCase) @@ -1161,20 +1287,8 @@ private VulnerabilityOverviewItemData CreateVulnerabilityOverviewItem(IGrouping< Severity = advisoryGroup.Max(entity => entity.Severity).ToString(), CvssScore = advisoryGroup.Max(entity => entity.CvssScore), ReferenceUrl = VulnerabilityViewMapper.SanitizeHttpUrl(representativeFinding.ReferenceUrl), - AffectedPackages = [ - .. advisoryGroup.Select(entity => entity.AffectedPackage) - .Where(package => string.IsNullOrWhiteSpace(package) == false) - .Select(package => package!) - .Distinct(StringComparer.OrdinalIgnoreCase) - .OrderBy(package => package, StringComparer.OrdinalIgnoreCase) - ], - FixedVersions = [ - .. advisoryGroup.Select(entity => entity.FixedVersion) - .Where(fixedVersion => string.IsNullOrWhiteSpace(fixedVersion) == false) - .Select(fixedVersion => fixedVersion!) - .Distinct(StringComparer.OrdinalIgnoreCase) - .OrderBy(fixedVersion => fixedVersion, StringComparer.OrdinalIgnoreCase) - ], + AffectedPackages = SelectAffectedPackages(advisoryGroup), + FixedVersions = SelectFixedVersions(advisoryGroup), AffectedImages = affectedImages, AffectedContainerCount = affectedContainerCount, }; @@ -1232,15 +1346,7 @@ private RuntimeContainerListItemData MapRuntimeContainerListItem(ContainerSnapsh var baseImageVulnerabilitySummary = VulnerabilityViewMapper.SummarizeBaseImageVulnerabilities(baseImageRelationships); var availableTagCandidates = tagCandidates ?? []; - var resolvedVersionTag = string.IsNullOrWhiteSpace(entity.ResolvedVersionTag) == false - ? entity.ResolvedVersionTag - : TagCandidateViewHelper.ResolveResolvedVersionTag(imageVersion.Tag, - imageVersion.Digest, - availableTagCandidates); - var availableUpdateVersionTag = string.IsNullOrWhiteSpace(entity.AvailableUpdateVersionTag) == false - ? entity.AvailableUpdateVersionTag - : TagCandidateViewHelper.ResolveAvailableUpdateVersionTag(availableTagCandidates, - resolvedVersionTag ?? imageVersion.Tag); + var (resolvedVersionTag, availableUpdateVersionTag) = ResolveRuntimeContainerTags(entity, availableTagCandidates); return new RuntimeContainerListItemData { @@ -1356,11 +1462,7 @@ private ObservedImageListItemData MapObservedImageListItem(ObservedImage entity, Dictionary runtimeLinkLookup) { var repositoryKey = CreateRepositoryKey(entity.CurrentImageVersion); - - observedAlertLookup.TryGetValue(entity.Id, out var observedAlert); - runtimeAlertLookup.TryGetValue(repositoryKey, out var runtimeAlert); - - var baseRuntimeAlert = observedAlert ?? runtimeAlert; + var baseRuntimeAlert = FindBaseRuntimeAlert(entity, observedAlertLookup, runtimeAlertLookup); baseImageRelationshipsByChildVersion.TryGetValue(entity.CurrentImageVersionId, out var baseImageRelationships); @@ -1798,6 +1900,133 @@ private RuntimeContainerDetailViewData CreateRuntimeContainerDetail(Guid dockerI }; } + /// + /// Load the dashboard's containers with an available update, limited to the first entries by container and instance name + /// + /// Current container snapshots + /// Cancellation token + /// Number of all such containers and the listed entries + private async Task<(int TotalCount, List Items)> LoadDashboardUpdatesAsync(IReadOnlyList latestSnapshots, + CancellationToken cancellationToken) + { + var updateSnapshots = latestSnapshots.Where(entity => entity.UpdateAssessmentStatus == UpdateAssessmentStatus.UpdateAvailable) + .OrderBy(entity => entity.Name, StringComparer.OrdinalIgnoreCase) + .ThenBy(entity => entity.DockerInstance.Name, StringComparer.OrdinalIgnoreCase) + .ThenBy(entity => entity.ContainerId, StringComparer.Ordinal) + .ToList(); + var shownSnapshots = updateSnapshots.Take(DashboardUpdateLimit).ToList(); + var latestFindings = await LoadLatestUpdateFindingsAsync([.. shownSnapshots.Select(entity => entity.Id)], cancellationToken).ConfigureAwait(false); + var tagCandidatesBySnapshot = GroupTagCandidatesBySnapshot(latestFindings); + var items = new List(); + + foreach (var entity in shownSnapshots) + { + tagCandidatesBySnapshot.TryGetValue(entity.Id, out var tagCandidates); + + var (resolvedVersionTag, availableUpdateVersionTag) = ResolveRuntimeContainerTags(entity, tagCandidates ?? []); + + items.Add(new DashboardUpdateItemData + { + DockerInstanceId = entity.DockerInstanceId, + ContainerId = entity.ContainerId, + ContainerName = entity.Name, + DockerInstanceName = entity.DockerInstance.Name, + CurrentTag = entity.ImageVersion.Tag, + ResolvedVersionTag = resolvedVersionTag, + AvailableUpdateVersionTag = availableUpdateVersionTag, + }); + } + + return (updateSnapshots.Count, items); + } + + /// + /// Load the dashboard's advisories of the running image versions with the values of all their active findings + /// + /// Current container snapshots + /// Cancellation token + /// Number of all such advisories, the listed entries and the severity summary of all of them + private async Task<(int TotalCount, List Items, VulnerabilitySeveritySummaryViewData SeveritySummary)> LoadDashboardVulnerabilitiesAsync(IReadOnlyList latestSnapshots, + CancellationToken cancellationToken) + { + var runtimeImageVersionIds = latestSnapshots.Select(entity => entity.ImageVersionId) + .Distinct() + .ToList(); + var runningAdvisoryIds = await _dbContext.VulnerabilityFindings.Where(entity => entity.IsActive + && runtimeImageVersionIds.Contains(entity.ImageVersionId)) + .Select(entity => entity.AdvisoryId) + .Distinct() + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + + if (runningAdvisoryIds.Count == 0) + { + return (0, [], new VulnerabilitySeveritySummaryViewData()); + } + + var lowerCaseAdvisoryIds = runningAdvisoryIds.Select(advisoryId => advisoryId.ToLowerInvariant()) + .Distinct() + .ToList(); + var advisoryFindings = await DashboardVulnerabilityQuery.CreateAdvisoryFindingsQuery(_dbContext, lowerCaseAdvisoryIds) + .ToListAsync(cancellationToken) + .ConfigureAwait(false); + var containerCountsByImageVersion = latestSnapshots.GroupBy(entity => entity.ImageVersionId) + .ToDictionary(group => group.Key, group => group.Count()); + var advisories = advisoryFindings.GroupBy(entity => entity.AdvisoryId, StringComparer.OrdinalIgnoreCase) + .Select(group => (Severity: group.Max(entity => entity.Severity), + Item: CreateDashboardVulnerabilityItem(group, containerCountsByImageVersion))) + .OrderByDescending(entry => entry.Severity) + .ThenByDescending(entry => entry.Item.CvssScore ?? decimal.MinValue) + .ThenByDescending(entry => entry.Item.AffectedContainerCount) + .ThenBy(entry => entry.Item.AdvisoryId, StringComparer.OrdinalIgnoreCase) + .ToList(); + var severitySummary = new VulnerabilitySeveritySummaryViewData + { + CriticalCount = advisories.Count(entry => entry.Severity == VulnerabilitySeverity.Critical), + HighCount = advisories.Count(entry => entry.Severity == VulnerabilitySeverity.High), + MediumCount = advisories.Count(entry => entry.Severity == VulnerabilitySeverity.Medium), + LowCount = advisories.Count(entry => entry.Severity == VulnerabilitySeverity.Low), + }; + + severitySummary.OtherCount = advisories.Count - severitySummary.TotalCount; + + return (advisories.Count, [.. advisories.Take(DashboardVulnerabilityLimit).Select(entry => entry.Item)], severitySummary); + } + + /// + /// Load the dashboard's own images with a base runtime warning, limited to the first entries by name + /// + /// Current container snapshots + /// Cancellation token + /// Number of all such images and the listed entries + private async Task<(int TotalCount, List Items)> LoadDashboardRuntimeWarningsAsync(IReadOnlyList latestSnapshots, + CancellationToken cancellationToken) + { + var observedImages = await LoadObservedImagesAsync(RegistrationSource.Discovery, cancellationToken).ConfigureAwait(false); + var latestSnapshotIds = latestSnapshots.Select(entity => entity.Id) + .ToList(); + var repositoryKeyBySnapshotId = latestSnapshots.ToDictionary(entity => entity.Id, + CreateRepositoryKey); + var derivedBaseRuntimeFindings = await LoadDerivedBaseRuntimeFindingsAsync([.. observedImages.Select(entity => entity.Id)], latestSnapshotIds, cancellationToken).ConfigureAwait(false); + var runtimeAlertLookup = CreateRuntimeAlertLookup(derivedBaseRuntimeFindings, repositoryKeyBySnapshotId); + var observedAlertLookup = CreateObservedAlertLookup(derivedBaseRuntimeFindings); + var warnings = observedImages.Select(entity => (Image: entity, Alert: FindBaseRuntimeAlert(entity, observedAlertLookup, runtimeAlertLookup))) + .Where(entry => entry.Alert is not null) + .OrderBy(entry => entry.Image.Name, StringComparer.OrdinalIgnoreCase) + .ThenBy(entry => entry.Image.Id) + .ToList(); + + return (warnings.Count, [ + .. warnings.Take(DashboardRuntimeWarningLimit) + .Select(entry => new DashboardRuntimeWarningItemData + { + Id = entry.Image.Id, + Name = entry.Image.Name, + BaseRuntimeAlertSummary = entry.Alert!.Summary, + }) + ]); + } + #endregion // Methods #region IApplicationViewService @@ -1813,34 +2042,9 @@ public async Task GetDashboardAsync(CancellationToken cancell var dockerInstanceCount = await _dbContext.DockerInstances.CountAsync(cancellationToken).ConfigureAwait(false); var latestRuntimeContainerSnapshots = await GetLatestContainerSnapshotsAsync(cancellationToken).ConfigureAwait(false); var sharedBaseImages = await GetSharedBaseImageEntriesAsync(latestRuntimeContainerSnapshots, cancellationToken).ConfigureAwait(false); - var activeUpdateFindingCount = await _dbContext.UpdateFindings.CountAsync(entity => entity.IsActive, cancellationToken).ConfigureAwait(false); - var ownImageBaseRuntimeWarningCount = await _dbContext.UpdateFindings.Join(_dbContext.ObservedImages.Where(entity => entity.Source == RegistrationSource.Discovery), - finding => finding.ObservedImageId, - observedImage => (Guid?)observedImage.Id, - (finding, observedImage) => new - { - finding.IsActive, - finding.Type, - }) - .CountAsync(entity => entity.IsActive - && entity.Type == UpdateFindingType.DerivedBaseRuntimeUpdate, - cancellationToken) - .ConfigureAwait(false); - var runtimeImageVersionIds = latestRuntimeContainerSnapshots.Select(entity => entity.ImageVersionId) - .Distinct() - .ToList(); - - // Scoped to current runtime containers so the dashboard reflects live exposure; the fleet-wide - // vulnerability inventory (including retired image versions) remains available on /vulnerabilities. - var runtimeVulnerabilitySeveritySummaries = await LoadActiveVulnerabilitySeveritySummariesAsync(runtimeImageVersionIds, cancellationToken).ConfigureAwait(false); - var vulnerabilitySeveritySummary = new VulnerabilitySeveritySummaryViewData - { - CriticalCount = runtimeVulnerabilitySeveritySummaries.Values.Sum(summary => summary.CriticalCount), - HighCount = runtimeVulnerabilitySeveritySummaries.Values.Sum(summary => summary.HighCount), - MediumCount = runtimeVulnerabilitySeveritySummaries.Values.Sum(summary => summary.MediumCount), - LowCount = runtimeVulnerabilitySeveritySummaries.Values.Sum(summary => summary.LowCount), - OtherCount = runtimeVulnerabilitySeveritySummaries.Values.Sum(summary => summary.OtherCount), - }; + var updates = await LoadDashboardUpdatesAsync(latestRuntimeContainerSnapshots, cancellationToken).ConfigureAwait(false); + var vulnerabilities = await LoadDashboardVulnerabilitiesAsync(latestRuntimeContainerSnapshots, cancellationToken).ConfigureAwait(false); + var runtimeWarnings = await LoadDashboardRuntimeWarningsAsync(latestRuntimeContainerSnapshots, cancellationToken).ConfigureAwait(false); var vulnerabilityConfigurationHint = await GetVulnerabilityConfigurationHintCoreAsync(cancellationToken).ConfigureAwait(false); return new DashboardViewData @@ -1850,10 +2054,13 @@ public async Task GetDashboardAsync(CancellationToken cancell DockerInstanceCount = dockerInstanceCount, RuntimeContainerCount = latestRuntimeContainerSnapshots.Count, BaseImageCount = sharedBaseImages.Count, - ActiveUpdateFindingCount = activeUpdateFindingCount, - OwnImageBaseRuntimeWarningCount = ownImageBaseRuntimeWarningCount, - ActiveVulnerabilityFindingCount = vulnerabilitySeveritySummary.TotalCount, - VulnerabilitySeveritySummary = vulnerabilitySeveritySummary, + UpdateCount = updates.TotalCount, + Updates = updates.Items, + VulnerabilityCount = vulnerabilities.TotalCount, + Vulnerabilities = vulnerabilities.Items, + VulnerabilityAdvisorySeveritySummary = vulnerabilities.SeveritySummary, + RuntimeWarningCount = runtimeWarnings.TotalCount, + RuntimeWarnings = runtimeWarnings.Items, VulnerabilityScanningEnabled = _optionsMonitor.CurrentValue.Vulnerabilities.Enabled, VulnerabilityConfigurationHint = vulnerabilityConfigurationHint, RecentScans = recentScans, diff --git a/src/DockerUpdateGuard/UI/DashboardHeadlineSegmentData.cs b/src/DockerUpdateGuard/UI/DashboardHeadlineSegmentData.cs new file mode 100644 index 00000000..56ee4ad7 --- /dev/null +++ b/src/DockerUpdateGuard/UI/DashboardHeadlineSegmentData.cs @@ -0,0 +1,21 @@ +namespace DockerUpdateGuard.UI; + +/// +/// One coloured part of the dashboard headline +/// +public class DashboardHeadlineSegmentData +{ + #region Properties + + /// + /// Segment text + /// + public string Text { get; set; } = string.Empty; + + /// + /// Segment tone + /// + public StatusTone Tone { get; set; } + + #endregion // Properties +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/DashboardRuntimeWarningItemData.cs b/src/DockerUpdateGuard/UI/DashboardRuntimeWarningItemData.cs new file mode 100644 index 00000000..44cd3bb3 --- /dev/null +++ b/src/DockerUpdateGuard/UI/DashboardRuntimeWarningItemData.cs @@ -0,0 +1,26 @@ +namespace DockerUpdateGuard.UI; + +/// +/// Dashboard list item of an own image with a base runtime warning +/// +public class DashboardRuntimeWarningItemData +{ + #region Properties + + /// + /// Observed image identifier + /// + public Guid Id { get; set; } + + /// + /// Image name + /// + public string Name { get; set; } = string.Empty; + + /// + /// Summary of the base runtime alert + /// + public string BaseRuntimeAlertSummary { get; set; } = string.Empty; + + #endregion // Properties +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/DashboardScanCountData.cs b/src/DockerUpdateGuard/UI/DashboardScanCountData.cs new file mode 100644 index 00000000..e20e77d2 --- /dev/null +++ b/src/DockerUpdateGuard/UI/DashboardScanCountData.cs @@ -0,0 +1,21 @@ +namespace DockerUpdateGuard.UI; + +/// +/// Number of recent scans with one status +/// +public class DashboardScanCountData +{ + #region Properties + + /// + /// Scan status + /// + public string Status { get; set; } = string.Empty; + + /// + /// Number of scans with the status + /// + public int Count { get; set; } + + #endregion // Properties +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/DashboardScanStripFormatter.cs b/src/DockerUpdateGuard/UI/DashboardScanStripFormatter.cs new file mode 100644 index 00000000..d0800b7b --- /dev/null +++ b/src/DockerUpdateGuard/UI/DashboardScanStripFormatter.cs @@ -0,0 +1,113 @@ +namespace DockerUpdateGuard.UI; + +/// +/// Composes the texts and names of the dashboard scan strip +/// +public static class DashboardScanStripFormatter +{ + #region Constants + + /// + /// Name of the pending status, also the CSS name of every unknown status + /// + private const string PendingStatus = "Pending"; + + #endregion // Constants + + #region Fields + + /// + /// Scan statuses in display order + /// + private static readonly string[] _statusOrder = ["Succeeded", "Running", PendingStatus, "Partial", "Failed"]; + + #endregion // Fields + + #region Methods + + /// + /// Counts the scans per status in display order + /// + /// Recent scans + /// Status counts + public static IReadOnlyList GetStatusCounts(IReadOnlyList scans) + { + return [ + .. _statusOrder.Select(status => new DashboardScanCountData + { + Status = status, + Count = scans.Count(scan => scan.Status == status), + }) + .Where(count => count.Count > 0) + ]; + } + + /// + /// Formats one status count + /// + /// Status count + /// Count text + public static string FormatCountText(DashboardScanCountData count) + { + return $"{count.Count} {count.Status.ToLowerInvariant()}"; + } + + /// + /// Formats the accessible label of the strip + /// + /// Status counts + /// Label text + public static string FormatStripLabel(IReadOnlyList counts) + { + return string.Join(", ", counts.Select(FormatCountText)); + } + + /// + /// Formats the title of a strip segment + /// + /// Scan + /// Title text + public static string FormatSegmentTitle(ScanHistoryItemData scan) + { + var subject = string.IsNullOrEmpty(scan.SubjectName) ? string.Empty : $"{scan.SubjectName} · "; + + return $"{scan.Type} · {subject}{scan.Status} · {TimestampFormatter.Format(scan.StartedAtUtc)}"; + } + + /// + /// Maps a scan status to its segment CSS name + /// + /// Scan status + /// CSS name + public static string GetSegmentCssName(string status) + { + return _statusOrder.Contains(status) && status != PendingStatus + ? status.ToLowerInvariant() + : PendingStatus.ToLowerInvariant(); + } + + /// + /// Finds the first failed or partial scan with an error message + /// + /// Recent scans + /// Scan or null + public static ScanHistoryItemData? FindLatestProblemScan(IReadOnlyList scans) + { + return scans.FirstOrDefault(scan => (scan.Status == "Failed" || scan.Status == "Partial") + && string.IsNullOrEmpty(scan.ErrorMessage) == false); + } + + /// + /// Formats the line describing a problem scan + /// + /// Problem scan + /// Line text + public static string FormatProblemScanLine(ScanHistoryItemData scan) + { + var subject = string.IsNullOrEmpty(scan.SubjectName) ? string.Empty : $"{scan.SubjectName} · "; + + return $"{subject}{scan.ErrorMessage}"; + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/DashboardTextFormatter.cs b/src/DockerUpdateGuard/UI/DashboardTextFormatter.cs new file mode 100644 index 00000000..ba5132ae --- /dev/null +++ b/src/DockerUpdateGuard/UI/DashboardTextFormatter.cs @@ -0,0 +1,159 @@ +namespace DockerUpdateGuard.UI; + +/// +/// Composes the user-visible texts of the dashboard +/// +public static class DashboardTextFormatter +{ + #region Methods + + /// + /// Builds the coloured parts of the headline + /// + /// Number of updates + /// Number of runtime warnings + /// Number of vulnerabilities + /// Headline segments + public static IReadOnlyList GetHeadlineSegments(int updateCount, int runtimeWarningCount, int vulnerabilityCount) + { + var parts = new List(); + + if (updateCount > 0) + { + parts.Add(CreateSegment(FormatCount(updateCount, "update", "updates"), StatusTone.Warning)); + } + + if (runtimeWarningCount > 0) + { + parts.Add(CreateSegment(FormatCount(runtimeWarningCount, "runtime warning", "runtime warnings"), StatusTone.Warning)); + } + + if (vulnerabilityCount > 0) + { + parts.Add(CreateSegment(FormatCount(vulnerabilityCount, "vulnerability", "vulnerabilities"), StatusTone.Danger)); + } + + if (parts.Count == 0) + { + return [CreateSegment("Everything is up to date.", StatusTone.Success)]; + } + + var segments = new List(); + + for (var index = 0; index < parts.Count; index++) + { + if (index > 0) + { + segments.Add(CreateSegment(index == parts.Count - 1 ? " and " : ", ", StatusTone.Neutral)); + } + + segments.Add(parts[index]); + } + + var isSingleItem = parts.Count == 1 && (updateCount + runtimeWarningCount + vulnerabilityCount) == 1; + + segments.Add(CreateSegment(isSingleItem ? " needs attention." : " need attention.", StatusTone.Neutral)); + + return segments; + } + + /// + /// Formats a count with its singular or plural noun + /// + /// Count + /// Singular noun + /// Plural noun + /// Count text + public static string FormatCount(int count, string singular, string plural) + { + return $"{count} {(count == 1 ? singular : plural)}"; + } + + /// + /// Formats the sub line under the headline + /// + /// Dashboard view data + /// Sub line text + public static string FormatSubLine(DashboardViewData dashboard) + { + var assetCount = dashboard.ObservedImageCount + dashboard.MyImageCount + dashboard.RuntimeContainerCount; + var lastActivity = dashboard.RecentScans.Count > 0 + ? TimestampFormatter.Format(dashboard.RecentScans[0].StartedAtUtc) + : "no scans yet"; + + return $"{FormatCount(assetCount, "protected asset", "protected assets")} on {FormatCount(dashboard.DockerInstanceCount, "Docker instance", "Docker instances")} · last activity {lastActivity}"; + } + + /// + /// Formats the footer link text of a list + /// + /// Total number of entries + /// Number of shown entries + /// Name of the target page + /// Footer link text + public static string FormatFooterLink(int totalCount, int shownCount, string pageName) + { + return totalCount > shownCount + ? $"{totalCount - shownCount} more in {pageName}" + : $"Open {pageName}"; + } + + /// + /// Formats the current tag of an update row + /// + /// Update item + /// Current tag text + public static string FormatCurrentTag(DashboardUpdateItemData item) + { + return string.IsNullOrWhiteSpace(item.ResolvedVersionTag) + ? item.CurrentTag + : $"{item.CurrentTag} ({item.ResolvedVersionTag})"; + } + + /// + /// Formats the title of a vulnerability row + /// + /// Vulnerability item + /// Title text + public static string FormatVulnerabilityTitle(DashboardVulnerabilityItemData item) + { + return item.AffectedPackages.Count > 0 + ? string.Join(", ", item.AffectedPackages) + : item.AdvisoryId; + } + + /// + /// Formats the detail line of a vulnerability row + /// + /// Vulnerability item + /// Detail text + public static string FormatVulnerabilityDetail(DashboardVulnerabilityItemData item) + { + var fix = item.FixedVersions.Count > 0 + ? $"Fixed in {string.Join(", ", item.FixedVersions)}" + : "No fix available"; + + return $"{fix} · {FormatCount(item.AffectedContainerCount, "running container", "running containers")}"; + } + + #endregion // Methods + + #region Static methods + + /// + /// Creates a headline segment + /// + /// Segment text + /// Segment tone + /// Headline segment + private static DashboardHeadlineSegmentData CreateSegment(string text, StatusTone tone) + { + return new DashboardHeadlineSegmentData + { + Text = text, + Tone = tone, + }; + } + + #endregion // Static methods +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/DashboardUpdateItemData.cs b/src/DockerUpdateGuard/UI/DashboardUpdateItemData.cs new file mode 100644 index 00000000..e7d3733c --- /dev/null +++ b/src/DockerUpdateGuard/UI/DashboardUpdateItemData.cs @@ -0,0 +1,46 @@ +namespace DockerUpdateGuard.UI; + +/// +/// Dashboard list item of a running container with an available update +/// +public class DashboardUpdateItemData +{ + #region Properties + + /// + /// Docker instance identifier + /// + public Guid DockerInstanceId { get; set; } + + /// + /// Container identifier + /// + public string ContainerId { get; set; } = string.Empty; + + /// + /// Container name + /// + public string ContainerName { get; set; } = string.Empty; + + /// + /// Docker instance name + /// + public string DockerInstanceName { get; set; } = string.Empty; + + /// + /// Tag the container currently runs + /// + public string CurrentTag { get; set; } = string.Empty; + + /// + /// Version tag the current tag resolves to + /// + public string? ResolvedVersionTag { get; set; } + + /// + /// Version tag of the available update + /// + public string? AvailableUpdateVersionTag { get; set; } + + #endregion // Properties +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/DashboardViewData.cs b/src/DockerUpdateGuard/UI/DashboardViewData.cs index ce8e0c3d..9b82ca28 100644 --- a/src/DockerUpdateGuard/UI/DashboardViewData.cs +++ b/src/DockerUpdateGuard/UI/DashboardViewData.cs @@ -33,24 +33,39 @@ public class DashboardViewData public int BaseImageCount { get; set; } /// - /// Active update finding count + /// Number of running containers with an available update /// - public int ActiveUpdateFindingCount { get; set; } + public int UpdateCount { get; set; } /// - /// Active derived base-runtime warnings for own images + /// Running containers with an available update, as shown on the dashboard /// - public int OwnImageBaseRuntimeWarningCount { get; set; } + public IReadOnlyList Updates { get; set; } = []; /// - /// Active vulnerability finding count for image versions currently backing a runtime container + /// Number of active advisories on running image versions /// - public int ActiveVulnerabilityFindingCount { get; set; } + public int VulnerabilityCount { get; set; } /// - /// Active vulnerability finding counts per severity for image versions currently backing a runtime container + /// Active advisories on running image versions, as shown on the dashboard /// - public VulnerabilitySeveritySummaryViewData VulnerabilitySeveritySummary { get; set; } = new(); + public IReadOnlyList Vulnerabilities { get; set; } = []; + + /// + /// Advisory counts per severity for the active advisories on running image versions + /// + public VulnerabilitySeveritySummaryViewData VulnerabilityAdvisorySeveritySummary { get; set; } = new(); + + /// + /// Number of own images with a base runtime warning + /// + public int RuntimeWarningCount { get; set; } + + /// + /// Own images with a base runtime warning, as shown on the dashboard + /// + public IReadOnlyList RuntimeWarnings { get; set; } = []; /// /// Indicates whether vulnerability scanning is enabled diff --git a/src/DockerUpdateGuard/UI/DashboardVulnerabilityItemData.cs b/src/DockerUpdateGuard/UI/DashboardVulnerabilityItemData.cs new file mode 100644 index 00000000..823ef36d --- /dev/null +++ b/src/DockerUpdateGuard/UI/DashboardVulnerabilityItemData.cs @@ -0,0 +1,41 @@ +namespace DockerUpdateGuard.UI; + +/// +/// Dashboard list item of an active advisory on running image versions +/// +public class DashboardVulnerabilityItemData +{ + #region Properties + + /// + /// Advisory identifier + /// + public string AdvisoryId { get; set; } = string.Empty; + + /// + /// Advisory severity + /// + public string Severity { get; set; } = string.Empty; + + /// + /// CVSS score + /// + public decimal? CvssScore { get; set; } + + /// + /// Affected packages + /// + public IReadOnlyList AffectedPackages { get; set; } = []; + + /// + /// Fixed versions + /// + public IReadOnlyList FixedVersions { get; set; } = []; + + /// + /// Number of running containers affected + /// + public int AffectedContainerCount { get; set; } + + #endregion // Properties +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/UI/DashboardVulnerabilityQuery.cs b/src/DockerUpdateGuard/UI/DashboardVulnerabilityQuery.cs new file mode 100644 index 00000000..5f3c76f5 --- /dev/null +++ b/src/DockerUpdateGuard/UI/DashboardVulnerabilityQuery.cs @@ -0,0 +1,38 @@ +using DockerUpdateGuard.Data; +using DockerUpdateGuard.Data.Entities; + +using Microsoft.EntityFrameworkCore; + +namespace DockerUpdateGuard.UI; + +/// +/// Database queries of the dashboard's advisory list +/// +internal static class DashboardVulnerabilityQuery +{ + #region Methods + + /// + /// Create the query of the active findings of advisories, matching the advisory identifiers ignoring letter case and loading only the columns the dashboard needs + /// + /// Database context + /// Advisory identifiers in lower case + /// Query of untracked findings projected to the needed columns + internal static IQueryable CreateAdvisoryFindingsQuery(DockerUpdateGuardDbContext dbContext, List lowerCaseAdvisoryIds) + { + return dbContext.VulnerabilityFindings.Where(entity => entity.IsActive + && lowerCaseAdvisoryIds.Contains(entity.AdvisoryId.ToLower())) + .AsNoTracking() + .Select(entity => new VulnerabilityFinding + { + AdvisoryId = entity.AdvisoryId, + ImageVersionId = entity.ImageVersionId, + Severity = entity.Severity, + CvssScore = entity.CvssScore, + AffectedPackage = entity.AffectedPackage, + FixedVersion = entity.FixedVersion, + }); + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/DockerUpdateGuard/wwwroot/app.css b/src/DockerUpdateGuard/wwwroot/app.css index 39d78656..3a139124 100644 --- a/src/DockerUpdateGuard/wwwroot/app.css +++ b/src/DockerUpdateGuard/wwwroot/app.css @@ -1252,6 +1252,235 @@ a { } } +.dug-visually-hidden { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +.dug-dashboard__headline { + margin: 0; + font-family: var(--dug-font-display); + font-size: 34px; + font-weight: 600; + line-height: 1.25; + color: var(--dug-text); +} + +.dug-dashboard__headline-part--warning { + color: var(--dug-attention); +} + +.dug-dashboard__headline-part--danger { + color: var(--dug-danger); +} + +.dug-dashboard__headline-part--success { + color: var(--dug-success); +} + +.dug-dashboard__subline { + margin: 4px 0 0; + color: var(--dug-text-muted); + font-size: 14px; +} + +.dug-dashboard__columns { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 16px; + align-items: start; +} + +.dug-dashboard__column { + display: flex; + flex-direction: column; + gap: 16px; + min-width: 0; +} + +.dug-dashboard__column--wide { + grid-column: 1 / -1; +} + +.dug-dashboard__count--warning, +.dug-dashboard__count--danger { + font-size: 15px; + font-weight: 600; +} + +.dug-dashboard__count--warning { + color: var(--dug-attention); +} + +.dug-dashboard__count--danger { + color: var(--dug-danger); +} + +.dug-dashboard__list { + margin: 0; + padding: 0; + list-style: none; +} + +.dug-dashboard__row { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 2px 12px; + padding: 10px 0; + border-top: 1px solid var(--dug-border-inner); + color: var(--dug-text); + text-decoration: none; +} + +.dug-dashboard__row:hover, +.dug-dashboard__row:focus-visible { + background: var(--dug-surface-subtle); +} + +.dug-dashboard__row-title { + min-width: 0; + overflow-wrap: anywhere; + font-weight: 600; +} + +.dug-dashboard__row-aside { + color: var(--dug-text-muted); + font-size: 13px; +} + +.dug-dashboard__row-detail { + grid-column: 1 / -1; + color: var(--dug-text-muted); + font-size: 13px; + overflow-wrap: anywhere; +} + +.dug-dashboard__row-target { + color: var(--dug-link); + font-weight: 600; +} + +.dug-dashboard__footer-link { + display: inline-block; + margin-top: 12px; + color: var(--dug-link); + font-size: 13px; + font-weight: 600; + text-decoration: none; +} + +.dug-dashboard__footer-link:hover, +.dug-dashboard__footer-link:focus-visible { + text-decoration: underline; +} + +.dug-dashboard__empty { + margin: 0; + color: var(--dug-text-muted); +} + +.dug-dashboard__scan-counts { + margin: 12px 0 0; + color: var(--dug-text-muted); + font-size: 13px; +} + +.dug-dashboard__scan-failed { + color: var(--dug-danger); +} + +.dug-dashboard__scan-problem { + margin: 4px 0 0; + color: var(--dug-text-muted); + font-size: 13px; + overflow-wrap: anywhere; +} + +.dug-scan-strip { + display: flex; + gap: 3px; + height: 24px; +} + +.dug-scan-strip__segment { + flex: 1 1 0; + min-width: 0; + border-radius: var(--dug-radius-sm); +} + +.dug-scan-strip__segment--succeeded { + background: var(--dug-scan-succeeded); +} + +.dug-scan-strip__segment--partial { + background: var(--dug-scan-partial); +} + +.dug-scan-strip__segment--failed { + background: var(--dug-scan-failed); +} + +.dug-scan-strip__segment--running { + background: var(--dug-primary); +} + +.dug-scan-strip__segment--pending { + background: var(--dug-border-control); +} + +.dug-inventory { + display: flex; + flex-wrap: wrap; + background: var(--dug-surface); + border: 1px solid var(--dug-border); + border-radius: var(--dug-radius-lg); +} + +.dug-inventory__cell { + display: flex; + flex: 1 1 140px; + flex-direction: column; + gap: 2px; + padding: 14px 20px; + color: var(--dug-text); + text-decoration: none; +} + +.dug-inventory__cell:hover, +.dug-inventory__cell:focus-visible { + background: var(--dug-surface-subtle); +} + +.dug-inventory__label { + color: var(--dug-text-muted); + font-size: 13px; +} + +.dug-inventory__value { + font-family: var(--dug-font-display); + font-size: 22px; + font-weight: 600; +} + +.dug-dashboard-skeleton { + display: flex; + flex-direction: column; + gap: 16px; +} + +@media (max-width: 959.98px) { + .dug-dashboard__columns { + grid-template-columns: minmax(0, 1fr); + } +} + @media (prefers-reduced-motion: reduce) { *, *::before, diff --git a/src/GlobalSuppressions.cs b/src/GlobalSuppressions.cs index b00fd35a..7475ae24 100644 --- a/src/GlobalSuppressions.cs +++ b/src/GlobalSuppressions.cs @@ -18,4 +18,7 @@ [assembly: SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "MudThemeProvider is a child Razor component captured via @ref; the Blazor render tree owns and disposes it, not the parent layout.", Scope = "member", Target = "~F:DockerUpdateGuard.Components.Layout.MainLayout._themeProvider")] -[assembly: SuppressMessage("Minor Code Smell", "S1125:Boolean literals should not be redundant", Justification = "Comparing against false is the binding code style of this repository (see .github/instructions/csharp.instructions.md).")] \ No newline at end of file +[assembly: SuppressMessage("Minor Code Smell", "S1125:Boolean literals should not be redundant", Justification = "Comparing against false is the binding code style of this repository (see .github/instructions/csharp.instructions.md).")] + +[assembly: SuppressMessage("Globalization", "CA1304:Specify CultureInfo", Justification = "EF Core translates string.ToLower() to the SQL lower() function; ToLowerInvariant and the culture overload do not translate on Npgsql, and the advisory identifiers are matched ignoring letter case in the database.", Scope = "member", Target = "~M:DockerUpdateGuard.UI.DashboardVulnerabilityQuery.CreateAdvisoryFindingsQuery(DockerUpdateGuard.Data.DockerUpdateGuardDbContext,System.Collections.Generic.List{System.String})~System.Linq.IQueryable{DockerUpdateGuard.Data.Entities.VulnerabilityFinding}")] +[assembly: SuppressMessage("Globalization", "CA1311:Specify a culture or use an invariant version", Justification = "EF Core translates string.ToLower() to the SQL lower() function; ToLowerInvariant and the culture overload do not translate on Npgsql, and the advisory identifiers are matched ignoring letter case in the database.", Scope = "member", Target = "~M:DockerUpdateGuard.UI.DashboardVulnerabilityQuery.CreateAdvisoryFindingsQuery(DockerUpdateGuard.Data.DockerUpdateGuardDbContext,System.Collections.Generic.List{System.String})~System.Linq.IQueryable{DockerUpdateGuard.Data.Entities.VulnerabilityFinding}")] \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/AppStylesheetDashboardTests.cs b/src/Tests/DockerUpdateGuard.Tests/AppStylesheetDashboardTests.cs new file mode 100644 index 00000000..6a9a12c3 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/AppStylesheetDashboardTests.cs @@ -0,0 +1,105 @@ +using System.Text.RegularExpressions; + +using DockerUpdateGuard.Tests.Helper; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for the dashboard rules of the shipped stylesheet wwwroot/app.css +/// +[TestClass] +public partial class AppStylesheetDashboardTests +{ + #region Constants + + /// + /// Shipped stylesheet below the host project directory + /// + private const string StylesheetPath = "wwwroot/app.css"; + + /// + /// Time limit of the literal color pattern in milliseconds + /// + private const int RegexTimeoutMilliseconds = 5000; + + #endregion // Constants + + #region Static methods + + /// + /// Match a literal color in a rule body: hex, rgb(), rgba(), hsl() or hsla() + /// + /// Regular expression + [GeneratedRegex(@"#[0-9a-fA-F]{3,8}\b|rgba?\(|hsla?\(", RegexOptions.None, RegexTimeoutMilliseconds)] + private static partial Regex CreateLiteralColorPattern(); + + #endregion // Static methods + + #region Methods + + /// + /// Verify each scan strip segment takes its color from a status token + /// + /// Segment CSS name + /// Expected token, or empty when only a token is required + [TestMethod] + [TestCategory("AC6")] + [DataRow("succeeded", "var(--dug-scan-succeeded)")] + [DataRow("partial", "var(--dug-scan-partial)")] + [DataRow("failed", "var(--dug-scan-failed)")] + [DataRow("running", "")] + [DataRow("pending", "")] + public void AppStylesheetDashboardScanSegmentsUseStatusTokens(string cssName, string expectedToken) + { + var declarations = StylesheetReader.GetDeclarations(StylesheetReader.ReadHostFile(StylesheetPath), $".dug-scan-strip__segment--{cssName}"); + + var hasBackground = declarations.TryGetValue("background", out var background) || declarations.TryGetValue("background-color", out background); + + Assert.IsTrue(hasBackground, $"The {cssName} segment must set a background"); + Assert.StartsWith("var(--dug-", background!, $"The {cssName} segment must use a --dug- token"); + + if (expectedToken.Length > 0) + { + Assert.AreEqual(expectedToken, background, $"The {cssName} segment must use its status token"); + } + } + + /// + /// Verify the dashboard rules exist and use no literal colors + /// + [TestMethod] + [TestCategory("AC10")] + public void AppStylesheetDashboardRulesUseOnlyTokenColors() + { + var rules = StylesheetReader.GetRules(StylesheetReader.ReadHostFile(StylesheetPath)) + .Where(rule => rule.Selector.Contains(".dug-dashboard", StringComparison.Ordinal) + || rule.Selector.Contains(".dug-scan-strip", StringComparison.Ordinal) + || rule.Selector.Contains(".dug-inventory", StringComparison.Ordinal)) + .ToList(); + var literalColors = rules.Where(rule => CreateLiteralColorPattern().IsMatch(rule.Body)) + .Select(rule => rule.Selector) + .ToList(); + + Assert.IsNotEmpty(rules, "The stylesheet must hold the dashboard rules"); + Assert.IsEmpty(literalColors, $"Dashboard rules must use tokens only: {string.Join(", ", literalColors)}"); + } + + /// + /// Verify the visually hidden helper and the headline rules exist + /// + /// Selector + [TestMethod] + [TestCategory("AC10")] + [DataRow(".dug-visually-hidden")] + [DataRow(".dug-dashboard__headline")] + [DataRow(".dug-scan-strip")] + [DataRow(".dug-inventory")] + public void AppStylesheetDashboardRuleExists(string selector) + { + var declarations = StylesheetReader.GetDeclarations(StylesheetReader.ReadHostFile(StylesheetPath), selector); + + Assert.IsNotEmpty(declarations, $"The stylesheet must hold a rule for {selector}"); + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/ApplicationViewServiceDashboardTests.cs b/src/Tests/DockerUpdateGuard.Tests/ApplicationViewServiceDashboardTests.cs new file mode 100644 index 00000000..ca46799e --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/ApplicationViewServiceDashboardTests.cs @@ -0,0 +1,703 @@ +using DockerUpdateGuard.Configuration; +using DockerUpdateGuard.Data; +using DockerUpdateGuard.Data.Entities; +using DockerUpdateGuard.Data.Queries; +using DockerUpdateGuard.Data.Repositories; +using DockerUpdateGuard.Images; +using DockerUpdateGuard.Tests.Data; +using DockerUpdateGuard.UI; + +using Microsoft.EntityFrameworkCore; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for the lists and counts of the dashboard of +/// +[TestClass] +public class ApplicationViewServiceDashboardTests +{ + #region Properties + + /// + /// Test context providing information about and functionality for the current test run + /// + public TestContext TestContext { get; set; } + + #endregion // Properties + + #region Static methods + + /// + /// Create the in-memory database options of a test + /// + /// Database context options + private static DbContextOptions CreateOptions() + { + return new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + } + + /// + /// Create the view service over a database context + /// + /// Database context + /// Application view service + private static ApplicationViewService CreateService(DockerUpdateGuardDbContext dbContext) + { + return new ApplicationViewService(dbContext, + new ImageReferenceParser(), + new TestOptionsMonitor(new DockerUpdateGuardOptions()), + new SharedBaseImageQueryService(dbContext)); + } + + /// + /// Create an image version of the Docker Hub repository + /// + /// Database context + /// Repository path + /// Image tag + /// Image digest + /// Image version + private static async Task AddImageVersionAsync(DockerUpdateGuardDbContext dbContext, + string repository, + string tag, + string digest) + { + var imageCatalogRepository = new ImageCatalogRepository(dbContext); + + return await imageCatalogRepository.GetOrCreateImageVersionAsync("docker.io", + repository, + tag, + digest, + cancellationToken: CancellationToken.None) + .ConfigureAwait(false); + } + + /// + /// Create a Docker instance + /// + /// Database context + /// Instance name + /// Docker instance + private static DockerInstance AddDockerInstance(DockerUpdateGuardDbContext dbContext, string name) + { + var dockerInstance = new DockerInstance + { + Name = name, + EndpointUri = $"https://{name.ToLowerInvariant()}.example.test", + ConnectionKind = DockerConnectionKind.Https, + }; + + dbContext.DockerInstances.Add(dockerInstance); + + return dockerInstance; + } + + /// + /// Create a running container snapshot with an update state + /// + /// Database context + /// Docker instance running the container + /// Image version the container runs + /// Container identifier and name, separated by a slash + /// Update assessment status + /// Container snapshot + private static ContainerSnapshot AddContainer(DockerUpdateGuardDbContext dbContext, + DockerInstance dockerInstance, + ImageVersion imageVersion, + string containerKey, + UpdateAssessmentStatus status) + { + var parts = containerKey.Split('/'); + var snapshot = new ContainerSnapshot + { + DockerInstance = dockerInstance, + ImageVersionId = imageVersion.Id, + ContainerId = parts[0], + Name = parts[1], + Status = ContainerRuntimeStatus.Running, + IsRunning = true, + UpdateAssessmentStatus = status, + AvailableUpdateVersionTag = status == UpdateAssessmentStatus.UpdateAvailable ? "2.0.0" : null, + }; + + dbContext.ContainerSnapshots.Add(snapshot); + + return snapshot; + } + + /// + /// Create an active vulnerability finding + /// + /// Database context + /// Affected image version + /// Advisory identifier + /// Finding severity + /// Finding score + /// Vulnerability finding + private static VulnerabilityFinding AddVulnerability(DockerUpdateGuardDbContext dbContext, + ImageVersion imageVersion, + string advisoryId, + VulnerabilitySeverity severity, + decimal? cvssScore) + { + var finding = new VulnerabilityFinding + { + ImageVersionId = imageVersion.Id, + AdvisoryId = advisoryId, + Title = $"Title of {advisoryId}", + Severity = severity, + CvssScore = cvssScore, + Source = VulnerabilitySource.Trivy, + IsActive = true, + }; + + dbContext.VulnerabilityFindings.Add(finding); + + return finding; + } + + /// + /// Create an observed image of a repository + /// + /// Database context + /// Current image version + /// Image name + /// Registration source + /// Observed image + private static ObservedImage AddObservedImage(DockerUpdateGuardDbContext dbContext, + ImageVersion imageVersion, + string name, + RegistrationSource source) + { + var observedImage = new ObservedImage + { + Name = name, + CurrentImageVersionId = imageVersion.Id, + Source = source, + }; + + dbContext.ObservedImages.Add(observedImage); + + return observedImage; + } + + /// + /// Create an active update finding of a type + /// + /// Database context + /// Scan run that recorded the finding + /// Subject image version + /// Finding type + /// Update finding + private static UpdateFinding AddUpdateFinding(DockerUpdateGuardDbContext dbContext, + ScanRun scanRun, + ImageVersion imageVersion, + UpdateFindingType type) + { + var finding = new UpdateFinding + { + ScanRun = scanRun, + SubjectImageVersionId = imageVersion.Id, + Type = type, + Summary = $"Summary of {type}", + IsActive = true, + }; + + dbContext.UpdateFindings.Add(finding); + + return finding; + } + + /// + /// Create an own image with an active base runtime alert recorded on the image itself + /// + /// Database context + /// Scan run that recorded the alert + /// Image name, also used as repository and alert summary + /// Observed image + private static async Task AddOwnImageWithAlertAsync(DockerUpdateGuardDbContext dbContext, ScanRun scanRun, string name) + { + var imageVersion = await AddImageVersionAsync(dbContext, $"company/{name.ToLowerInvariant()}", "1.0.0", $"sha256:{name.ToLowerInvariant()}").ConfigureAwait(false); + var observedImage = AddObservedImage(dbContext, imageVersion, name, RegistrationSource.Discovery); + var alert = AddUpdateFinding(dbContext, scanRun, imageVersion, UpdateFindingType.DerivedBaseRuntimeUpdate); + + alert.ObservedImage = observedImage; + alert.Summary = $"Alert of {name}"; + + return observedImage; + } + + /// + /// Create a scan run that update findings can refer to + /// + /// Database context + /// Scan run + private static ScanRun AddScanRun(DockerUpdateGuardDbContext dbContext) + { + var scanRun = new ScanRun + { + Type = ScanRunType.ObservedImage, + Status = ScanRunStatus.Succeeded, + TriggerSource = ScanTriggerSource.Manual, + }; + + dbContext.ScanRuns.Add(scanRun); + + return scanRun; + } + + /// + /// Describe the listed update entries as instance, container name and container identifier + /// + /// Dashboard view data + /// Descriptions in list order + private static List DescribeUpdates(DashboardViewData dashboard) + { + return [.. dashboard.Updates.Select(entity => $"{entity.DockerInstanceName}/{entity.ContainerName}/{entity.ContainerId}")]; + } + + #endregion // Static methods + + #region Methods + + /// + /// Verify the updates list holds the first five running containers with an available update in the stated order + /// + /// Task + [TestMethod] + [TestCategory("AC3")] + public async Task ApplicationViewServiceDashboardUpdatesListsUpdateAvailableContainersInOrderAsync() + { + var dbContext = new DockerUpdateGuardDbContext(CreateOptions()); + + await using (dbContext.ConfigureAwait(false)) + { + var plainImage = await AddImageVersionAsync(dbContext, "company/api", "1.0.0", "sha256:plain").ConfigureAwait(false); + var aliasImage = await AddImageVersionAsync(dbContext, "networlddev/f1-telemetry", "latest", "sha256:new").ConfigureAwait(false); + var alpha = AddDockerInstance(dbContext, "alpha"); + var zeta = AddDockerInstance(dbContext, "Zeta"); + var scanRun = AddScanRun(dbContext); + + AddContainer(dbContext, zeta, plainImage, "c-api-z/Api", UpdateAssessmentStatus.UpdateAvailable); + AddContainer(dbContext, alpha, plainImage, "Z-1/db", UpdateAssessmentStatus.UpdateAvailable); + AddContainer(dbContext, alpha, plainImage, "a-1/db", UpdateAssessmentStatus.UpdateAvailable); + AddContainer(dbContext, alpha, plainImage, "c-zoo/zookeeper", UpdateAssessmentStatus.UpdateAvailable); + AddContainer(dbContext, alpha, plainImage, "c-api-a/api", UpdateAssessmentStatus.UpdateAvailable); + AddContainer(dbContext, alpha, plainImage, "c-worker/worker", UpdateAssessmentStatus.UpdateAvailable); + + var aliasContainer = AddContainer(dbContext, alpha, aliasImage, "c-cache/cache", UpdateAssessmentStatus.UpdateAvailable); + + aliasContainer.AvailableUpdateVersionTag = "2.5.0"; + + var updateFinding = AddUpdateFinding(dbContext, scanRun, aliasImage, UpdateFindingType.RuntimeImageUpdate); + + updateFinding.ContainerSnapshot = aliasContainer; + updateFinding.TagCandidates.Add(new TagCandidate + { + Tag = "latest", + Digest = "sha256:new", + Rank = 1, + IsRecommended = true, + }); + updateFinding.TagCandidates.Add(new TagCandidate + { + Tag = "2.4.1", + Digest = "sha256:new", + Rank = 2, + PublishedAtUtc = new DateTimeOffset(2025, 06, 02, 12, 00, 00, TimeSpan.Zero), + }); + updateFinding.TagCandidates.Add(new TagCandidate + { + Tag = "2021.11.28", + Digest = "sha256:new", + Rank = 3, + PublishedAtUtc = new DateTimeOffset(2021, 11, 28, 12, 00, 00, TimeSpan.Zero), + }); + + await dbContext.SaveChangesAsync(TestContext.CancellationToken).ConfigureAwait(false); + + var dashboard = await CreateService(dbContext).GetDashboardAsync(TestContext.CancellationToken).ConfigureAwait(false); + + Assert.AreEqual(7, + dashboard.UpdateCount, + "The count must hold every running container with an available update"); + Assert.AreSequenceEqual(["alpha/api/c-api-a", "Zeta/Api/c-api-z", "alpha/cache/c-cache", "alpha/db/Z-1", "alpha/db/a-1"], + DescribeUpdates(dashboard), + "The list must hold the first five containers by name and instance ignoring letter case, then by ordinal container id"); + + var aliasEntry = dashboard.Updates.Single(entity => entity.ContainerId == "c-cache"); + + Assert.AreEqual("latest", aliasEntry.CurrentTag, "The current tag must be the tag of the running image version"); + Assert.AreEqual("2.4.1", aliasEntry.ResolvedVersionTag, "The alias must resolve to the version of its tag candidates"); + Assert.AreEqual("2.5.0", aliasEntry.AvailableUpdateVersionTag, "The available tag must be the stored update version"); + Assert.AreEqual(alpha.Id, aliasEntry.DockerInstanceId, "The entry must carry the Docker instance identifier for the detail link"); + + var plainEntry = dashboard.Updates.Single(entity => entity.ContainerId == "c-api-a"); + + Assert.AreEqual("1.0.0", plainEntry.CurrentTag, "The current tag of a plain version must be its tag"); + Assert.AreEqual("2.0.0", plainEntry.AvailableUpdateVersionTag, "The available tag must be the stored update version"); + } + } + + /// + /// Verify only the state Update available counts and that update findings do not + /// + /// Task + [TestMethod] + [TestCategory("AC3")] + [TestCategory("AC9")] + public async Task ApplicationViewServiceDashboardUpdatesIgnoresOtherUpdateStatesAsync() + { + var dbContext = new DockerUpdateGuardDbContext(CreateOptions()); + + await using (dbContext.ConfigureAwait(false)) + { + var imageVersion = await AddImageVersionAsync(dbContext, "company/api", "1.0.0", "sha256:api").ConfigureAwait(false); + var observedVersion = await AddImageVersionAsync(dbContext, "company/observed", "1.0.0", "sha256:observed").ConfigureAwait(false); + var dockerInstance = AddDockerInstance(dbContext, "alpha"); + var scanRun = AddScanRun(dbContext); + var observedImage = AddObservedImage(dbContext, observedVersion, "Observed", RegistrationSource.Manual); + var statuses = Enum.GetValues() + .Where(status => status != UpdateAssessmentStatus.UpdateAvailable) + .ToList(); + + foreach (var status in statuses) + { + var container = AddContainer(dbContext, dockerInstance, imageVersion, $"c-{status}/{status}", status); + + AddUpdateFinding(dbContext, scanRun, imageVersion, UpdateFindingType.RuntimeImageUpdate).ContainerSnapshot = container; + } + + AddContainer(dbContext, dockerInstance, imageVersion, "c-available/available", UpdateAssessmentStatus.UpdateAvailable); + AddUpdateFinding(dbContext, scanRun, observedVersion, UpdateFindingType.TagRecommendation).ObservedImage = observedImage; + + await dbContext.SaveChangesAsync(TestContext.CancellationToken).ConfigureAwait(false); + + var dashboard = await CreateService(dbContext).GetDashboardAsync(TestContext.CancellationToken).ConfigureAwait(false); + + Assert.AreEqual(1, + dashboard.UpdateCount, + "Only the running container with the state Update available must count, never an update finding or another state"); + Assert.AreSequenceEqual(["alpha/available/c-available"], + DescribeUpdates(dashboard), + "Only the container with the state Update available must be listed"); + } + } + + /// + /// Verify the vulnerabilities list holds four advisories of running containers in the stated order and counts all of them + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + [TestCategory("AC9")] + public async Task ApplicationViewServiceDashboardVulnerabilitiesListsRunningAdvisoriesInOrderAsync() + { + var dbContext = new DockerUpdateGuardDbContext(CreateOptions()); + + await using (dbContext.ConfigureAwait(false)) + { + var single = await AddImageVersionAsync(dbContext, "company/single", "1.0.0", "sha256:single").ConfigureAwait(false); + var shared = await AddImageVersionAsync(dbContext, "company/double", "1.0.0", "sha256:double").ConfigureAwait(false); + var retired = await AddImageVersionAsync(dbContext, "company/single", "0.9.0", "sha256:retired").ConfigureAwait(false); + var dockerInstance = AddDockerInstance(dbContext, "alpha"); + + AddContainer(dbContext, dockerInstance, single, "c1/one", UpdateAssessmentStatus.UpToDate); + AddContainer(dbContext, dockerInstance, shared, "c2/two", UpdateAssessmentStatus.UpToDate); + AddContainer(dbContext, dockerInstance, shared, "c3/three", UpdateAssessmentStatus.UpToDate); + AddVulnerability(dbContext, single, "CVE-1", VulnerabilitySeverity.Critical, 3.0m); + AddVulnerability(dbContext, shared, "CVE-2", VulnerabilitySeverity.High, 9.0m); + AddVulnerability(dbContext, single, "CVE-3", VulnerabilitySeverity.High, 9.0m); + AddVulnerability(dbContext, single, "cve-4", VulnerabilitySeverity.High, 7.0m); + AddVulnerability(dbContext, single, "CVE-5", VulnerabilitySeverity.High, 7.0m); + AddVulnerability(dbContext, shared, "CVE-6", VulnerabilitySeverity.Medium, 9.9m); + AddVulnerability(dbContext, retired, "CVE-7", VulnerabilitySeverity.Critical, 10.0m); + + await dbContext.SaveChangesAsync(TestContext.CancellationToken).ConfigureAwait(false); + + var dashboard = await CreateService(dbContext).GetDashboardAsync(TestContext.CancellationToken).ConfigureAwait(false); + + Assert.AreEqual(6, + dashboard.VulnerabilityCount, + "The count must hold every advisory of a running container and no advisory of a retired image version only"); + Assert.AreSequenceEqual(["CVE-1", "CVE-2", "CVE-3", "cve-4"], + dashboard.Vulnerabilities.Select(entity => entity.AdvisoryId).ToList(), + "The list must hold four advisories by severity, score, container count and advisory identifier ignoring letter case"); + Assert.AreSequenceEqual([1, 2, 1, 1], + dashboard.Vulnerabilities.Select(entity => entity.AffectedContainerCount).ToList(), + "Each entry must carry the number of running containers it affects"); + Assert.AreSequenceEqual(["Critical", "High", "High", "High"], + dashboard.Vulnerabilities.Select(entity => entity.Severity).ToList(), + "Each entry must carry its severity"); + Assert.AreEqual(3.0m, dashboard.Vulnerabilities[0].CvssScore, "Each entry must carry its score"); + Assert.AreEqual(1, dashboard.VulnerabilityAdvisorySeveritySummary.CriticalCount, "The severity summary must count the critical advisory of a running container"); + Assert.AreEqual(4, dashboard.VulnerabilityAdvisorySeveritySummary.HighCount, "The severity summary must count the advisories, not their findings"); + Assert.AreEqual(1, dashboard.VulnerabilityAdvisorySeveritySummary.MediumCount, "The severity summary must count the medium advisory"); + Assert.AreEqual(6, dashboard.VulnerabilityAdvisorySeveritySummary.TotalCount, "The severity summary must cover exactly the counted advisories"); + } + } + + /// + /// Verify severity, score, packages and fixed versions of an advisory come from all its active findings + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task ApplicationViewServiceDashboardVulnerabilitiesTakeValuesFromAllActiveFindingsAsync() + { + var dbContext = new DockerUpdateGuardDbContext(CreateOptions()); + + await using (dbContext.ConfigureAwait(false)) + { + var current = await AddImageVersionAsync(dbContext, "company/api", "2.0.0", "sha256:current").ConfigureAwait(false); + var retired = await AddImageVersionAsync(dbContext, "company/api", "1.0.0", "sha256:retired").ConfigureAwait(false); + var dockerInstance = AddDockerInstance(dbContext, "alpha"); + + AddContainer(dbContext, dockerInstance, current, "c1/api", UpdateAssessmentStatus.UpToDate); + + var runningFinding = AddVulnerability(dbContext, current, "CVE-2026-1000", VulnerabilitySeverity.Medium, 5.0m); + var retiredFinding = AddVulnerability(dbContext, retired, "CVE-2026-1000", VulnerabilitySeverity.High, 8.0m); + var inactiveFinding = AddVulnerability(dbContext, current, "CVE-2026-1000", VulnerabilitySeverity.Critical, 9.9m); + + runningFinding.AffectedPackage = "libA"; + runningFinding.FixedVersion = "1.0"; + retiredFinding.AffectedPackage = "libB"; + retiredFinding.FixedVersion = "2.0"; + inactiveFinding.AffectedPackage = "libInactive"; + inactiveFinding.FixedVersion = "9.9"; + inactiveFinding.IsActive = false; + AddVulnerability(dbContext, retired, "CVE-2026-2000", VulnerabilitySeverity.Critical, 10.0m); + + await dbContext.SaveChangesAsync(TestContext.CancellationToken).ConfigureAwait(false); + + var dashboard = await CreateService(dbContext).GetDashboardAsync(TestContext.CancellationToken).ConfigureAwait(false); + + Assert.HasCount(1, dashboard.Vulnerabilities, "Only the advisory of a running container must be listed"); + + var entry = dashboard.Vulnerabilities[0]; + + Assert.AreEqual(1, dashboard.VulnerabilityCount, "An advisory only on a retired image version must not count"); + Assert.AreEqual("CVE-2026-1000", entry.AdvisoryId, "The listed advisory must be the one running containers are affected by"); + Assert.AreEqual("High", entry.Severity, "The severity must be the highest of the active findings, also those of retired image versions"); + Assert.AreEqual(8.0m, entry.CvssScore, "The score must be the highest of the active findings, also those of retired image versions"); + Assert.AreSequenceEqual(["libA", "libB"], + entry.AffectedPackages.ToList(), + "The packages must come from all active findings and never from an inactive one"); + Assert.AreSequenceEqual(["1.0", "2.0"], + entry.FixedVersions.ToList(), + "The fixed versions must come from all active findings and never from an inactive one"); + Assert.AreEqual(1, entry.AffectedContainerCount, "Only running containers must count as affected"); + Assert.AreEqual(1, dashboard.VulnerabilityAdvisorySeveritySummary.HighCount, "The severity bar must use the same severity as the entry"); + Assert.AreEqual(0, dashboard.VulnerabilityAdvisorySeveritySummary.CriticalCount, "The critical advisory of a retired image version must not reach the bar"); + } + } + + /// + /// Verify an advisory without a score and an unknown severity sort last and the unknown severity counts as other + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task ApplicationViewServiceDashboardVulnerabilitiesSortUnscoredAndUnknownSeverityLastAsync() + { + var dbContext = new DockerUpdateGuardDbContext(CreateOptions()); + + await using (dbContext.ConfigureAwait(false)) + { + var imageVersion = await AddImageVersionAsync(dbContext, "company/api", "1.0.0", "sha256:api").ConfigureAwait(false); + var dockerInstance = AddDockerInstance(dbContext, "alpha"); + + AddContainer(dbContext, dockerInstance, imageVersion, "c1/api", UpdateAssessmentStatus.UpToDate); + AddVulnerability(dbContext, imageVersion, "CVE-UNKNOWN", VulnerabilitySeverity.NotSet, 10.0m); + AddVulnerability(dbContext, imageVersion, "CVE-LOW", VulnerabilitySeverity.Low, 1.0m); + AddVulnerability(dbContext, imageVersion, "CVE-UNSCORED", VulnerabilitySeverity.High, null); + AddVulnerability(dbContext, imageVersion, "CVE-SCORED", VulnerabilitySeverity.High, 0.5m); + + await dbContext.SaveChangesAsync(TestContext.CancellationToken).ConfigureAwait(false); + + var dashboard = await CreateService(dbContext).GetDashboardAsync(TestContext.CancellationToken).ConfigureAwait(false); + + Assert.AreSequenceEqual(["CVE-SCORED", "CVE-UNSCORED", "CVE-LOW", "CVE-UNKNOWN"], + dashboard.Vulnerabilities.Select(entity => entity.AdvisoryId).ToList(), + "An advisory without a score must sort after a scored one of the same severity and an unknown severity must sort last"); + Assert.IsNull(dashboard.Vulnerabilities[1].CvssScore, "An advisory without a score must keep it empty"); + Assert.AreEqual(1, + dashboard.VulnerabilityAdvisorySeveritySummary.OtherCount, + "An advisory of unknown severity must count as other in the severity summary"); + } + } + + /// + /// Verify the runtime warnings hold own images with an alert by name, also an alert derived from a running container + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task ApplicationViewServiceDashboardRuntimeWarningsListsOwnImagesWithAlertAsync() + { + var dbContext = new DockerUpdateGuardDbContext(CreateOptions()); + + await using (dbContext.ConfigureAwait(false)) + { + var scanRun = AddScanRun(dbContext); + var names = new[] { "foxtrot", "alpha", "Echo", "Golf", "Bravo", "delta" }; + var ownImages = new List(); + + foreach (var name in names) + { + ownImages.Add(await AddOwnImageWithAlertAsync(dbContext, scanRun, name).ConfigureAwait(false)); + } + + var runtimeImage = await AddImageVersionAsync(dbContext, "company/charlie", "1.0.0", "sha256:charlie").ConfigureAwait(false); + var runtimeVersion = await AddImageVersionAsync(dbContext, "company/charlie", "1.1.0", "sha256:charlie-running").ConfigureAwait(false); + var charlie = AddObservedImage(dbContext, runtimeImage, "charlie", RegistrationSource.Discovery); + var dockerInstance = AddDockerInstance(dbContext, "alpha"); + var container = AddContainer(dbContext, dockerInstance, runtimeVersion, "c1/charlie", UpdateAssessmentStatus.UpToDate); + var runtimeAlert = AddUpdateFinding(dbContext, scanRun, runtimeVersion, UpdateFindingType.DerivedBaseRuntimeUpdate); + + runtimeAlert.ContainerSnapshot = container; + runtimeAlert.Summary = "Alert of charlie"; + + var quietVersion = await AddImageVersionAsync(dbContext, "company/zulu", "1.0.0", "sha256:zulu").ConfigureAwait(false); + var manualVersion = await AddImageVersionAsync(dbContext, "company/manual", "1.0.0", "sha256:manual").ConfigureAwait(false); + var manualImage = AddObservedImage(dbContext, manualVersion, "aaa-manual", RegistrationSource.Manual); + + AddObservedImage(dbContext, quietVersion, "zulu", RegistrationSource.Discovery); + AddUpdateFinding(dbContext, scanRun, manualVersion, UpdateFindingType.DerivedBaseRuntimeUpdate).ObservedImage = manualImage; + + await dbContext.SaveChangesAsync(TestContext.CancellationToken).ConfigureAwait(false); + + var dashboard = await CreateService(dbContext).GetDashboardAsync(TestContext.CancellationToken).ConfigureAwait(false); + + Assert.AreEqual(7, + dashboard.RuntimeWarningCount, + "The count must hold every own image with an alert, also one derived from a running container, and no manual image"); + Assert.AreSequenceEqual(["alpha", "Bravo", "charlie", "delta", "Echo"], + dashboard.RuntimeWarnings.Select(entity => entity.Name).ToList(), + "The list must hold the first five own images by name ignoring letter case"); + Assert.AreEqual("Alert of charlie", + dashboard.RuntimeWarnings.Single(entity => entity.Name == "charlie").BaseRuntimeAlertSummary, + "The summary of an alert derived from a running container must be shown"); + Assert.AreEqual(ownImages.Single(entity => entity.Name == "alpha").Id, + dashboard.RuntimeWarnings[0].Id, + "The entry must carry the image identifier for the detail link"); + Assert.AreEqual("Alert of alpha", + dashboard.RuntimeWarnings[0].BaseRuntimeAlertSummary, + "The summary of the image's own alert must be shown"); + Assert.AreEqual(charlie.Id, + dashboard.RuntimeWarnings.Single(entity => entity.Name == "charlie").Id, + "The entry of the derived alert must carry the identifier of the own image"); + } + } + + /// + /// Verify each count equals the set it counts and each list is cut to its limit + /// + /// Task + [TestMethod] + [TestCategory("AC9")] + public async Task ApplicationViewServiceDashboardCountsEqualListedSetsAsync() + { + var dbContext = new DockerUpdateGuardDbContext(CreateOptions()); + + await using (dbContext.ConfigureAwait(false)) + { + var imageA = await AddImageVersionAsync(dbContext, "company/a", "1.0.0", "sha256:a").ConfigureAwait(false); + var imageB = await AddImageVersionAsync(dbContext, "company/b", "1.0.0", "sha256:b").ConfigureAwait(false); + var dockerInstance = AddDockerInstance(dbContext, "alpha"); + var scanRun = AddScanRun(dbContext); + + for (var index = 1; index <= 6; index++) + { + AddContainer(dbContext, dockerInstance, imageA, $"c{index}/container-{index}", UpdateAssessmentStatus.UpdateAvailable); + } + + AddContainer(dbContext, dockerInstance, imageB, "cb/container-b", UpdateAssessmentStatus.UpToDate); + AddVulnerability(dbContext, imageA, "CVE-1", VulnerabilitySeverity.Critical, 9.0m); + AddVulnerability(dbContext, imageB, "CVE-1", VulnerabilitySeverity.Critical, 9.0m); + AddVulnerability(dbContext, imageA, "CVE-2", VulnerabilitySeverity.High, 8.0m); + AddVulnerability(dbContext, imageA, "CVE-3", VulnerabilitySeverity.High, 7.0m); + AddVulnerability(dbContext, imageA, "CVE-4", VulnerabilitySeverity.Medium, 5.0m); + AddVulnerability(dbContext, imageA, "CVE-5", VulnerabilitySeverity.Low, 2.0m); + + foreach (var name in new[] { "one", "two", "three", "four", "five", "six" }) + { + await AddOwnImageWithAlertAsync(dbContext, scanRun, name).ConfigureAwait(false); + } + + await dbContext.SaveChangesAsync(TestContext.CancellationToken).ConfigureAwait(false); + + var dashboard = await CreateService(dbContext).GetDashboardAsync(TestContext.CancellationToken).ConfigureAwait(false); + + Assert.AreEqual(6, dashboard.UpdateCount, "The update count must be the number of containers with an available update"); + Assert.HasCount(5, dashboard.Updates, "The update list must stop at five entries"); + Assert.AreEqual(5, dashboard.VulnerabilityCount, "The vulnerability count must count an advisory once, however many findings it has"); + Assert.HasCount(4, dashboard.Vulnerabilities, "The vulnerability list must stop at four entries"); + Assert.AreEqual(5, + dashboard.VulnerabilityAdvisorySeveritySummary.TotalCount, + "The severity summary must cover the same advisories as the count"); + Assert.AreEqual(6, dashboard.RuntimeWarningCount, "The runtime warning count must be the number of own images with an alert"); + Assert.HasCount(5, dashboard.RuntimeWarnings, "The runtime warning list must stop at five entries"); + Assert.AreEqual(1, + dashboard.UpdateCount - dashboard.Updates.Count, + "The remainder of the update list must be the count minus the shown entries"); + Assert.AreEqual(1, + dashboard.VulnerabilityCount - dashboard.Vulnerabilities.Count, + "The remainder of the vulnerability list must be the count minus the shown entries"); + Assert.AreEqual(1, + dashboard.RuntimeWarningCount - dashboard.RuntimeWarnings.Count, + "The remainder of the runtime warning list must be the count minus the shown entries"); + } + } + + /// + /// Verify the dashboard builds its lists without asking for a resource sample set, and that the seam sees such a request + /// + /// Task + [TestMethod] + [TestCategory("AC10")] + public async Task ApplicationViewServiceDashboardRequestsNoResourceSampleSetsAsync() + { + var dbContext = new SetRecordingDbContext(CreateOptions()); + + await using (dbContext.ConfigureAwait(false)) + { + var imageVersion = await AddImageVersionAsync(dbContext, "company/api", "1.0.0", "sha256:api").ConfigureAwait(false); + var dockerInstance = AddDockerInstance(dbContext, "alpha"); + + AddContainer(dbContext, dockerInstance, imageVersion, "c1/api", UpdateAssessmentStatus.UpdateAvailable); + AddVulnerability(dbContext, imageVersion, "CVE-1", VulnerabilitySeverity.High, 7.0m); + + await dbContext.SaveChangesAsync(TestContext.CancellationToken).ConfigureAwait(false); + + dbContext.ResetRequestedEntityTypes(); + + var service = CreateService(dbContext); + var dashboard = await service.GetDashboardAsync(TestContext.CancellationToken).ConfigureAwait(false); + var requestedByDashboard = dbContext.RequestedEntityTypes; + + Assert.HasCount(1, dashboard.Updates, "The lists must be built while the resource bound is checked"); + Assert.Contains(typeof(ContainerSnapshot), + requestedByDashboard, + "The recording must see the container snapshots the dashboard reads"); + Assert.DoesNotContain(typeof(RuntimeContainerResourceSample), + requestedByDashboard, + "The dashboard must not read the resource samples of containers"); + Assert.DoesNotContain(typeof(DockerInstanceResourceSample), + requestedByDashboard, + "The dashboard must not read the resource samples of Docker instances"); + + dbContext.ResetRequestedEntityTypes(); + + await service.GetRuntimeContainersAsync(TestContext.CancellationToken).ConfigureAwait(false); + + Assert.Contains(typeof(RuntimeContainerResourceSample), + dbContext.RequestedEntityTypes, + "The recording must see the resource samples the Runtime Containers page reads"); + } + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/ApplicationViewServiceTests.cs b/src/Tests/DockerUpdateGuard.Tests/ApplicationViewServiceTests.cs index 1e2e17db..57d8a287 100644 --- a/src/Tests/DockerUpdateGuard.Tests/ApplicationViewServiceTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/ApplicationViewServiceTests.cs @@ -723,15 +723,15 @@ public async Task ApplicationViewServiceDashboardReturnsAggregateCountsAsync() Assert.AreEqual(1, dashboard.RuntimeContainerCount, "The dashboard must report the runtime container count"); - Assert.AreEqual(3, - dashboard.ActiveUpdateFindingCount, - "The dashboard must report the active update finding count"); + Assert.AreEqual(0, + dashboard.UpdateCount, + "The dashboard must count running containers with an available update, not update findings"); Assert.AreEqual(1, - dashboard.OwnImageBaseRuntimeWarningCount, + dashboard.RuntimeWarningCount, "The dashboard must only count derived base-runtime warnings for own images"); Assert.AreEqual(1, - dashboard.ActiveVulnerabilityFindingCount, - "The dashboard must report the active vulnerability finding count"); + dashboard.VulnerabilityCount, + "The dashboard must count the active advisories of the running image versions"); Assert.HasCount(1, dashboard.RecentScans, "The dashboard must include the recent scan entry"); @@ -820,14 +820,14 @@ await dbContext.SaveChangesAsync(CancellationToken.None) .ConfigureAwait(false); Assert.AreEqual(1, - dashboard.ActiveVulnerabilityFindingCount, - "The dashboard must exclude active findings for image versions not used by current runtime containers"); + dashboard.VulnerabilityCount, + "The dashboard must exclude advisories only found on image versions not used by current runtime containers"); Assert.AreEqual(0, - dashboard.VulnerabilitySeveritySummary.CriticalCount, - "The dashboard must exclude the critical finding from the retired image version"); + dashboard.VulnerabilityAdvisorySeveritySummary.CriticalCount, + "The dashboard must exclude the critical advisory of the retired image version"); Assert.AreEqual(1, - dashboard.VulnerabilitySeveritySummary.HighCount, - "The dashboard must retain the high finding from the current runtime image version"); + dashboard.VulnerabilityAdvisorySeveritySummary.HighCount, + "The dashboard must retain the high advisory of the current runtime image version"); } } diff --git a/src/Tests/DockerUpdateGuard.Tests/DashboardPersistentStateTests.cs b/src/Tests/DockerUpdateGuard.Tests/DashboardPersistentStateTests.cs new file mode 100644 index 00000000..26cd83e6 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/DashboardPersistentStateTests.cs @@ -0,0 +1,76 @@ +using Bunit; + +using DockerUpdateGuard.Configuration; +using DockerUpdateGuard.Tests.Helper; +using DockerUpdateGuard.UI; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +using NSubstitute; + +using DashboardPage = DockerUpdateGuard.Components.Pages.Dashboard; + +namespace DockerUpdateGuard.Tests; + +/// +/// Persistent-state tests for +/// +[TestClass] +public class DashboardPersistentStateTests +{ + #region Constants + + /// + /// Persistent-state key used by the page + /// + private const string StateKey = "Dashboard.State"; + + #endregion // Constants + + #region Methods + + /// + /// Verify the page reuses the prerendered dashboard without loading it again + /// + /// Task + [TestMethod] + [TestCategory("AC10")] + public async Task DashboardWithPersistedStateDoesNotLoadAgain() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var viewService = Substitute.For(); + + testContext.Services.AddSingleton(viewService); + testContext.Services.AddSingleton(new DashboardRefreshState()); + testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions())); + + var persistentState = testContext.GetPersistentComponentState(); + + persistentState.Persist(StateKey, + new DashboardViewData + { + UpdateCount = 1, + Updates = [ + new DashboardUpdateItemData + { + ContainerId = "restored-id", + ContainerName = "restored-container", + DockerInstanceName = "docker-a", + CurrentTag = "1.0" + } + ] + }); + + var component = testContext.Render(); + + Assert.Contains("restored-container", component.Markup, "The page must render the dashboard restored from persistent state"); + await viewService.DidNotReceive().GetDashboardAsync(Arg.Any()).ConfigureAwait(false); + } + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/DashboardRenderTests.cs b/src/Tests/DockerUpdateGuard.Tests/DashboardRenderTests.cs index 64e66493..171c37e7 100644 --- a/src/Tests/DockerUpdateGuard.Tests/DashboardRenderTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/DashboardRenderTests.cs @@ -25,47 +25,61 @@ public class DashboardRenderTests #region Methods /// - /// Verify the recent scans description names only the run types that are recorded + /// Verify the info banner is rendered when vulnerability scanning is disabled /// /// Task [TestMethod] - [TestCategory("AC2")] - public async Task DashboardRecentScansDescriptionNamesOnlyRecordedRunTypes() + [TestCategory("AC10")] + public async Task DashboardWithDisabledVulnerabilityScanningRendersInfoBanner() { var testContext = BlazorTestContextFactory.Create(); await using (testContext) { - var viewService = Substitute.For(); + var markup = RenderDashboardMarkup(testContext, VulnerabilityConfigurationHintKind.ScanningDisabled); - viewService.GetDashboardAsync(Arg.Any()) - .Returns(Task.FromResult(new DashboardViewData())); + Assert.Contains("Vulnerability scanning is disabled", + markup, + "The dashboard must explain how to enable vulnerability scanning when it is switched off"); + Assert.Contains("DockerUpdateGuard:Vulnerabilities:Enabled", + markup, + "The disabled banner must name the configuration key that enables vulnerability scanning"); + } + } - testContext.Services.AddSingleton(viewService); - testContext.Services.AddSingleton(new DashboardRefreshState()); - testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions())); + /// + /// Verify no configuration banner is rendered for a correctly configured provider + /// + /// Task + [TestMethod] + [TestCategory("AC10")] + public async Task DashboardWithConfiguredVulnerabilityProviderRendersNoBanner() + { + var testContext = BlazorTestContextFactory.Create(); - var component = testContext.Render(); - var header = component.FindAll(".section-header") - .Single(element => element.QuerySelector("h5")?.TextContent.Trim() == "Recent scans"); - var description = header.QuerySelector(".section-description")!.TextContent.Trim(); - var lowerCaseDescription = description.ToLowerInvariant(); - - Assert.AreEqual("Latest observed image scans, runtime container scans and vulnerability refreshes.", - description, - "The description must name exactly the recorded run types"); - Assert.DoesNotContain("discovery", lowerCaseDescription, "The description must not claim discovery runs"); - Assert.DoesNotContain("cleanup", lowerCaseDescription, "The description must not claim cleanup runs"); + await using (testContext) + { + var markup = RenderDashboardMarkup(testContext, VulnerabilityConfigurationHintKind.None); + + Assert.DoesNotContain("Vulnerability scanning is disabled", + markup, + "The disabled banner must not be rendered while vulnerability scanning is enabled"); + Assert.DoesNotContain("DockerUpdateGuard:Vulnerabilities:TrivyBaseUrl", + markup, + "The misconfiguration banner must not be rendered for a correctly configured provider"); } } /// - /// Verify the number metric tiles render for the phone two-up grid, including the optional My Images and Base Images tiles + /// Verify a failed first load shows the fixed error alert in place of the skeleton and logs the failure once /// /// Task [TestMethod] - public async Task DashboardWithConfiguredAccountRendersMetricTiles() + [TestCategory("AC10")] + public async Task DashboardLoadFailureShowsFixedErrorAndLogs() { + var exception = new InvalidOperationException("secret text"); + var logger = new TestLogger(); var testContext = BlazorTestContextFactory.Create(); await using (testContext) @@ -73,286 +87,893 @@ public async Task DashboardWithConfiguredAccountRendersMetricTiles() var viewService = Substitute.For(); viewService.GetDashboardAsync(Arg.Any()) - .Returns(Task.FromResult(new DashboardViewData - { - ObservedImageCount = 3, - MyImageCount = 2, - DockerInstanceCount = 1, - RuntimeContainerCount = 5, - BaseImageCount = 4, - ActiveUpdateFindingCount = 1, - OwnImageBaseRuntimeWarningCount = 0, - ActiveVulnerabilityFindingCount = 2, - })); - - var options = Options.Create(new DockerUpdateGuardOptions - { - DockerHub = - { - UserName = "octocat", - Pat = "token", - }, - }); + .Returns(Task.FromException(exception)); testContext.Services.AddSingleton(viewService); testContext.Services.AddSingleton(new DashboardRefreshState()); - testContext.Services.AddSingleton(options); - testContext.AddBunitPersistentComponentState(); + testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions())); + testContext.Services.AddSingleton>(logger); - var component = testContext.Render(); - var markup = component.Markup; + var page = testContext.Render(); - Assert.Contains("My Images", markup, "The My Images tile must render when a Docker Hub account is configured"); - Assert.Contains("Shared Base Images", markup, "The Shared Base Images tile must render when shared base images exist"); - Assert.Contains("Observed Images", markup, "The Observed Images metric tile must render"); - Assert.Contains("metric-value", markup, "The number metric tiles must render their values"); - Assert.Contains("metric-card__icon", markup, "The metric tiles must render an icon badge"); + await DetailPageAssert.AssertLoadErrorAsync(page, "Loading the dashboard failed: unexpected error", "secret text").ConfigureAwait(false); + DetailPageAssert.AssertLoadLoggedOnce(logger, "LoadDashboard", exception); } } /// - /// Verify the dashboard names the shared base images tile and summary card and links the tile to the page + /// Verify a refresh signal whose reload fails keeps the shown dashboard, shows no alert and logs the failure once /// /// Task [TestMethod] - [TestCategory("AC7")] - public async Task DashboardWithSharedBaseImagesRendersSharedBaseImagesLabelsAsync() + [TestCategory("AC10")] + public async Task DashboardFailedRefreshKeepsDashboardAndLogs() { + var exception = new InvalidOperationException("secret text"); + var logger = new TestLogger(); + var refreshState = new DashboardRefreshState(); var testContext = BlazorTestContextFactory.Create(); await using (testContext) { var viewService = Substitute.For(); + var dashboard = new DashboardViewData + { + RecentScans = [ + new ScanHistoryItemData + { + Type = "Runtime", + Status = "Succeeded", + SubjectName = "kept-scan-subject", + StartedAtUtc = DateTimeOffset.UtcNow, + }, + ], + }; viewService.GetDashboardAsync(Arg.Any()) - .Returns(Task.FromResult(new DashboardViewData - { - BaseImageCount = 2, - })); + .Returns(Task.FromResult(dashboard), Task.FromException(exception)); testContext.Services.AddSingleton(viewService); - testContext.Services.AddSingleton(new DashboardRefreshState()); + testContext.Services.AddSingleton(refreshState); testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions())); - testContext.AddBunitPersistentComponentState(); + testContext.Services.AddSingleton>(logger); - var component = testContext.Render(); - var tileLink = component.FindAll("a").SingleOrDefault(link => link.GetAttribute("href") == "/base-images"); + var page = testContext.Render(); + var alertCount = page.FindAll(".mud-alert").Count; + + Assert.Contains("kept-scan-subject", page.Markup, "The first load must show the dashboard"); + + await page.InvokeAsync(() => refreshState.NotifyChanged()).ConfigureAwait(false); + await page.WaitForAssertionAsync(() => DetailPageAssert.AssertLoadLoggedOnce(logger, "LoadDashboard", exception), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); - Assert.IsNotNull(tileLink, "The shared base images tile must link to the base images page"); - Assert.Contains("Shared Base Images", tileLink.TextContent, "The metric tile must read Shared Base Images"); - Assert.Contains("Shared base images", component.Markup, "The summary card must read Shared base images"); + Assert.Contains("kept-scan-subject", page.Markup, "A failed reload must keep the dashboard shown"); + Assert.HasCount(alertCount, page.FindAll(".mud-alert"), "A failed reload must show no alert"); + Assert.DoesNotContain("secret text", page.Markup, "A failed reload must not show the exception's text"); } } /// - /// Verify the info banner is rendered when vulnerability scanning is disabled + /// Verify the headline shows the counted parts in their tones /// /// Task [TestMethod] - public async Task DashboardWithDisabledVulnerabilityScanningRendersInfoBanner() + [TestCategory("AC1")] + public async Task DashboardWithCountsRendersHeadlineWithColoredParts() { var testContext = BlazorTestContextFactory.Create(); await using (testContext) { - var markup = RenderDashboardMarkup(testContext, VulnerabilityConfigurationHintKind.ScanningDisabled); + var component = RenderDashboard(testContext, CreateDashboard()); + + var headline = component.Find("h1.dug-dashboard__headline"); + var warningParts = component.FindAll("h1 .dug-dashboard__headline-part--warning") + .Select(element => element.TextContent.Trim()) + .ToList(); + var dangerParts = component.FindAll("h1 .dug-dashboard__headline-part--danger") + .Select(element => element.TextContent.Trim()) + .ToList(); + + Assert.AreEqual("7 updates, 2 runtime warnings and 31 vulnerabilities need attention.", + Normalize(headline.TextContent), + "The headline must name the three counted parts"); + Assert.AreSequenceEqual(new List + { + "7 updates", + "2 runtime warnings" + }, + warningParts, + "Updates and runtime warnings must be colored with the warning tone"); + Assert.AreSequenceEqual(new List + { + "31 vulnerabilities" + }, + dangerParts, + "Vulnerabilities must be colored with the danger tone"); + } + } - Assert.Contains("Vulnerability scanning is disabled", - markup, - "The dashboard must explain how to enable vulnerability scanning when it is switched off"); - Assert.Contains("DockerUpdateGuard:Vulnerabilities:Enabled", - markup, - "The disabled banner must name the configuration key that enables vulnerability scanning"); + /// + /// Verify the headline counts equal the counts of the panels + /// + /// Task + [TestMethod] + [TestCategory("AC9")] + public async Task DashboardHeadlineCountsEqualPanelCounts() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = RenderDashboard(testContext, CreateDashboard()); + + var updatesCount = FindPanel(component, "Updates available").QuerySelector(".dug-dashboard__count--warning")!.TextContent.Trim(); + var vulnerabilitiesCount = FindPanel(component, "Vulnerabilities").QuerySelector(".dug-dashboard__count--danger")!.TextContent.Trim(); + var warningsCount = FindPanel(component, "Own base runtime warnings").QuerySelector(".dug-dashboard__count--warning")!.TextContent.Trim(); + var headline = Normalize(component.Find("h1.dug-dashboard__headline").TextContent); + + Assert.AreEqual("7", updatesCount, "The updates panel must show the update count"); + Assert.AreEqual("31", vulnerabilitiesCount, "The vulnerabilities panel must show the vulnerability count"); + Assert.AreEqual("2", warningsCount, "The runtime warnings panel must show the warning count"); + Assert.Contains($"{updatesCount} updates", headline, "The headline must use the updates panel count"); + Assert.Contains($"{warningsCount} runtime warnings", headline, "The headline must use the warnings panel count"); + Assert.Contains($"{vulnerabilitiesCount} vulnerabilities", headline, "The headline must use the vulnerabilities panel count"); } } /// - /// Verify no configuration banner is rendered for a correctly configured provider + /// Verify the sub line shows assets, instances and the latest activity in UTC /// /// Task [TestMethod] - public async Task DashboardWithConfiguredVulnerabilityProviderRendersNoBanner() + [TestCategory("AC2")] + public async Task DashboardWithRecentScanRendersSubLineWithUtcActivity() { var testContext = BlazorTestContextFactory.Create(); await using (testContext) { - var markup = RenderDashboardMarkup(testContext, VulnerabilityConfigurationHintKind.None); + var dashboard = CreateDashboard(); - Assert.DoesNotContain("Vulnerability scanning is disabled", - markup, - "The disabled banner must not be rendered while vulnerability scanning is enabled"); - Assert.DoesNotContain("DockerUpdateGuard:Vulnerabilities:TrivyBaseUrl", - markup, - "The misconfiguration banner must not be rendered for a correctly configured provider"); + dashboard.ObservedImageCount = 10; + dashboard.MyImageCount = 3; + dashboard.RuntimeContainerCount = 30; + dashboard.DockerInstanceCount = 2; + dashboard.RecentScans = [CreateScan("Succeeded", "Runtime", "local", new DateTimeOffset(2026, 11, 14, 11, 42, 0, TimeSpan.FromHours(2)))]; + + var component = RenderDashboard(testContext, dashboard); + + Assert.AreEqual("43 protected assets on 2 Docker instances · last activity 2026-11-14 09:42 UTC", + Normalize(component.Find("p.dug-dashboard__subline").TextContent), + "The sub line must show the protected assets, the instances and the latest activity in UTC"); } } /// - /// Verify the recent scans table shows the scan start in UTC with the zone suffix + /// Verify the updates panel renders rows, links and the footer /// + /// Total update count + /// Number of shown entries + /// Expected footer text /// Task [TestMethod] [TestCategory("AC3")] - public async Task DashboardWithRecentScanRendersStartedInUtcAsync() + [DataRow(7, 5, "2 more in Runtime Containers")] + [DataRow(3, 3, "Open Runtime Containers")] + public async Task DashboardUpdatesPanelRendersRowsLinksAndFooter(int total, int shown, string expectedFooter) { var testContext = BlazorTestContextFactory.Create(); await using (testContext) { - var viewService = Substitute.For(); + var dashboard = CreateDashboard(); + var instanceId = Guid.NewGuid(); + + dashboard.UpdateCount = total; + dashboard.Updates = [.. Enumerable.Range(1, shown).Select(index => CreateUpdate($"web-{index}", instanceId))]; + + var component = RenderDashboard(testContext, dashboard); + + var panel = FindPanel(component, "Updates available"); + var rows = panel.QuerySelectorAll("ul.dug-dashboard__list > li > a.dug-dashboard__row"); + var firstRow = rows[0]; + var footer = panel.QuerySelector("a.dug-dashboard__footer-link")!; + + Assert.HasCount(shown, rows, "The panel must render one row per shown update"); + Assert.AreEqual($"/runtime-containers/{instanceId}/container-web-1", + firstRow.GetAttribute("href"), + "The row must link to the container detail"); + Assert.AreEqual("web-1", firstRow.QuerySelector(".dug-dashboard__row-title")!.TextContent.Trim(), "The row title must be the container name"); + Assert.AreEqual("docker-a", firstRow.QuerySelector(".dug-dashboard__row-aside")!.TextContent.Trim(), "The row aside must be the instance name"); + Assert.Contains("latest (1.25.3)", Normalize(firstRow.QuerySelector(".dug-dashboard__row-detail")!.TextContent), "The detail must show the current tag with its resolved version"); + Assert.Contains("→", firstRow.QuerySelector(".dug-dashboard__row-detail")!.TextContent, "The detail must show an arrow to the available tag"); + Assert.AreEqual("1.26.0", firstRow.QuerySelector(".dug-dashboard__row-target")!.TextContent.Trim(), "The available tag must be marked as target"); + Assert.AreEqual(expectedFooter, footer.TextContent.Trim(), "The footer must name the remainder or offer to open the page"); + Assert.AreEqual("/runtime-containers", footer.GetAttribute("href"), "The footer must open the Runtime Containers page"); + } + } - viewService.GetDashboardAsync(Arg.Any()) - .Returns(Task.FromResult(new DashboardViewData - { - RecentScans = [ - new ScanHistoryItemData - { - Type = "Runtime", - Status = "Succeeded", - SubjectName = "local", - StartedAtUtc = new DateTimeOffset(2026, 11, 23, 23, 27, 0, TimeSpan.FromHours(2)), - }, - ], - })); + /// + /// Verify an update row without an available tag shows the current tag only + /// + /// Task + [TestMethod] + [TestCategory("AC3")] + public async Task DashboardUpdatesPanelWithoutAvailableTagRendersCurrentTagOnly() + { + var testContext = BlazorTestContextFactory.Create(); - testContext.Services.AddSingleton(viewService); - testContext.Services.AddSingleton(new DashboardRefreshState()); - testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions())); - testContext.AddBunitPersistentComponentState(); + await using (testContext) + { + var dashboard = CreateDashboard(); + var update = CreateUpdate("web-1", Guid.NewGuid()); - var component = testContext.Render(); + update.AvailableUpdateVersionTag = null; + update.ResolvedVersionTag = null; + update.CurrentTag = "1.25.3"; + dashboard.UpdateCount = 1; + dashboard.Updates = [update]; + + var component = RenderDashboard(testContext, dashboard); + + var detail = FindPanel(component, "Updates available").QuerySelector(".dug-dashboard__row-detail")!; - Assert.Contains("2026-11-23 21:27 UTC", component.Markup, "The recent scan start must be shown in UTC with the zone suffix"); + Assert.AreEqual("1.25.3", Normalize(detail.TextContent), "The detail must show the current tag only"); + Assert.IsNull(detail.QuerySelector(".dug-dashboard__row-target"), "No target must be rendered without an available tag"); } } /// - /// Verify a failed first load shows the fixed error alert in place of the skeleton and logs the failure once + /// Verify an updates panel without entries shows its empty text and no count /// /// Task [TestMethod] - [TestCategory("AC1")] - [TestCategory("AC2")] - public async Task DashboardLoadFailureShowsFixedErrorAndLogs() + [TestCategory("AC3")] + public async Task DashboardUpdatesPanelWithoutEntriesRendersEmptyTextWithoutCount() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var dashboard = CreateDashboard(); + + dashboard.UpdateCount = 0; + dashboard.Updates = []; + + var component = RenderDashboard(testContext, dashboard); + + var panel = FindPanel(component, "Updates available"); + + Assert.AreEqual("No updates available.", panel.QuerySelector("p.dug-dashboard__empty")!.TextContent.Trim(), "The panel must show its empty text"); + Assert.IsNull(panel.QuerySelector("[class*='dug-dashboard__count--']"), "The panel must show no count at 0"); + Assert.IsNull(panel.QuerySelector("a.dug-dashboard__row"), "The panel must show no row"); + } + } + + /// + /// Verify the vulnerabilities panel renders the bar, rows, accessible identifier, link and footer + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task DashboardVulnerabilitiesPanelRendersBarRowsAndAccessibleIdentifier() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var dashboard = CreateDashboard(); + + dashboard.VulnerabilityCount = 5; + dashboard.VulnerabilityAdvisorySeveritySummary = new VulnerabilitySeveritySummaryViewData + { + CriticalCount = 2, + HighCount = 3 + }; + dashboard.Vulnerabilities = [ + new DashboardVulnerabilityItemData + { + AdvisoryId = "CVE-2026-0001", + Severity = "Critical", + AffectedPackages = ["openssl", "libssl3"], + FixedVersions = ["3.0.1"], + AffectedContainerCount = 2 + } + ]; + + var component = RenderDashboard(testContext, dashboard); + + var panel = FindPanel(component, "Vulnerabilities"); + var row = panel.QuerySelector("ul.dug-dashboard__list > li > a.dug-dashboard__row")!; + var footer = panel.QuerySelector("a.dug-dashboard__footer-link")!; + + Assert.IsNotNull(panel.QuerySelector(".dug-severity"), "The panel must render the severity bar"); + Assert.AreEqual("/vulnerabilities", row.GetAttribute("href"), "The row must open the Vulnerabilities page"); + Assert.Contains("openssl, libssl3", row.QuerySelector(".dug-dashboard__row-title")!.TextContent, "The title must name the affected packages"); + Assert.AreEqual("CVE-2026-0001", row.QuerySelector("span.dug-visually-hidden")!.TextContent.Trim(), "The advisory identifier must be announced with the row"); + Assert.AreEqual("Critical", row.QuerySelector(".dug-dashboard__row-aside .dug-chip")!.TextContent.Trim(), "The severity must be shown as a chip"); + Assert.AreEqual("Fixed in 3.0.1 · 2 running containers", + Normalize(row.QuerySelector(".dug-dashboard__row-detail")!.TextContent), + "The detail must show the fix and the container count"); + Assert.AreEqual("4 more in Vulnerabilities", footer.TextContent.Trim(), "The footer must name the remainder"); + Assert.AreEqual("/vulnerabilities", footer.GetAttribute("href"), "The footer must open the Vulnerabilities page"); + } + } + + /// + /// Verify a vulnerabilities panel without entries shows its empty text and no bar + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task DashboardVulnerabilitiesPanelWithoutEntriesRendersEmptyTextWithoutBar() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var dashboard = CreateDashboard(); + + dashboard.VulnerabilityCount = 0; + dashboard.Vulnerabilities = []; + dashboard.VulnerabilityAdvisorySeveritySummary = new VulnerabilitySeveritySummaryViewData(); + + var component = RenderDashboard(testContext, dashboard); + + var panel = FindPanel(component, "Vulnerabilities"); + + Assert.AreEqual("No vulnerabilities in running containers.", panel.QuerySelector("p.dug-dashboard__empty")!.TextContent.Trim(), "The panel must show its empty text"); + Assert.IsNull(panel.QuerySelector(".dug-severity"), "The panel must render no severity bar"); + Assert.IsNull(panel.QuerySelector("[class*='dug-dashboard__count--']"), "The panel must show no count at 0"); + } + } + + /// + /// Verify the runtime warnings panel renders rows, link and footer + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task DashboardRuntimeWarningsPanelRendersRowsAndFooter() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var dashboard = CreateDashboard(); + var imageId = Guid.NewGuid(); + + dashboard.RuntimeWarningCount = 7; + dashboard.RuntimeWarnings = [ + new DashboardRuntimeWarningItemData + { + Id = imageId, + Name = "company/api", + BaseRuntimeAlertSummary = "Base runtime 8.0 is outdated" + } + ]; + + var component = RenderDashboard(testContext, dashboard, true); + + var panel = FindPanel(component, "Own base runtime warnings"); + var row = panel.QuerySelector("ul.dug-dashboard__list > li > a.dug-dashboard__row")!; + var footer = panel.QuerySelector("a.dug-dashboard__footer-link")!; + + Assert.AreEqual($"/my-images/{imageId}", row.GetAttribute("href"), "The row must open the image detail"); + Assert.Contains("company/api", row.TextContent, "The row must show the image name"); + Assert.Contains("Base runtime 8.0 is outdated", row.TextContent, "The row must show the alert summary"); + Assert.AreEqual("6 more in My Images", footer.TextContent.Trim(), "The footer must name the remainder"); + Assert.AreEqual("/my-images", footer.GetAttribute("href"), "The footer must open the My Images page"); + } + } + + /// + /// Verify the runtime warnings panel has no footer when all entries are shown + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task DashboardRuntimeWarningsPanelWithAllEntriesShownRendersNoFooter() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = RenderDashboard(testContext, CreateDashboard(), true); + + var panel = FindPanel(component, "Own base runtime warnings"); + + Assert.AreEqual(2, + panel.QuerySelectorAll("a.dug-dashboard__row").Length, + "The panel must show both warnings"); + Assert.IsNull(panel.QuerySelector("a.dug-dashboard__footer-link"), "The panel must have no footer when nothing remains"); + } + } + + /// + /// Verify the runtime warnings panel is hidden without an account and without warnings + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task DashboardRuntimeWarningsPanelWithoutAccountAndWarningsIsHidden() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var dashboard = CreateDashboard(); + + dashboard.RuntimeWarningCount = 0; + dashboard.RuntimeWarnings = []; + + var component = RenderDashboard(testContext, dashboard); + + var titles = component.FindAll("section.dug-panel h2") + .Select(title => title.TextContent.Trim()) + .ToList(); + + Assert.DoesNotContain("Own base runtime warnings", titles, "The runtime warnings panel must not be rendered"); + Assert.Contains("Updates available", titles, "The other panels must still be rendered"); + } + } + + /// + /// Verify the runtime warnings panel with an account and without warnings shows its empty text + /// + /// Task + [TestMethod] + [TestCategory("AC5")] + public async Task DashboardRuntimeWarningsPanelWithAccountAndNoWarningsRendersEmptyText() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var dashboard = CreateDashboard(); + + dashboard.RuntimeWarningCount = 0; + dashboard.RuntimeWarnings = []; + + var component = RenderDashboard(testContext, dashboard, true); + + var panel = FindPanel(component, "Own base runtime warnings"); + + Assert.AreEqual("No runtime warnings.", panel.QuerySelector("p.dug-dashboard__empty")!.TextContent.Trim(), "The panel must show its empty text"); + Assert.IsNull(panel.QuerySelector("[class*='dug-dashboard__count--']"), "The panel must show no count at 0"); + } + } + + /// + /// Verify the scan panel renders the strip, the count line, the problem line and the link + /// + /// Task + [TestMethod] + [TestCategory("AC6")] + public async Task DashboardScanPanelRendersStripCountsProblemLineAndLink() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var dashboard = CreateDashboard(); + var failed = CreateScan("Failed", "Registry", "nginx:latest", new DateTimeOffset(2026, 11, 14, 9, 42, 0, TimeSpan.Zero)); + + failed.ErrorMessage = "registry unreachable"; + dashboard.RecentScans = [ + failed, + CreateScan("Succeeded", "Vulnerability refresh", null, new DateTimeOffset(2026, 11, 14, 8, 0, 0, TimeSpan.Zero)), + CreateScan("Succeeded", "Runtime", "local", new DateTimeOffset(2026, 11, 14, 7, 0, 0, TimeSpan.Zero)), + CreateScan("Running", "Runtime", "local", new DateTimeOffset(2026, 11, 14, 6, 0, 0, TimeSpan.Zero)) + ]; + + var component = RenderDashboard(testContext, dashboard); + + var panel = FindPanel(component, "Last 10 scans"); + var strip = panel.QuerySelector("div.dug-scan-strip")!; + var segments = strip.QuerySelectorAll("span[class*='dug-scan-strip__segment--']"); + var classNames = segments.Select(segment => segment.ClassName!.Split(' ').Single(name => name.StartsWith("dug-scan-strip__segment--", StringComparison.Ordinal))) + .ToList(); + var footer = panel.QuerySelector("a.dug-dashboard__footer-link")!; + + Assert.AreEqual("img", strip.GetAttribute("role"), "The strip must be announced as an image"); + Assert.AreEqual("2 succeeded, 1 running, 1 failed", strip.GetAttribute("aria-label"), "The strip must be named by the counts"); + Assert.AreSequenceEqual(new List + { + "dug-scan-strip__segment--failed", + "dug-scan-strip__segment--succeeded", + "dug-scan-strip__segment--succeeded", + "dug-scan-strip__segment--running" + }, + classNames, + "The segments must follow the run order, newest first, with one status class each"); + Assert.AreEqual("Registry · nginx:latest · Failed · 2026-11-14 09:42 UTC", segments[0].GetAttribute("title"), "The segment must carry the tooltip text"); + Assert.AreEqual("Vulnerability refresh · Succeeded · 2026-11-14 08:00 UTC", segments[1].GetAttribute("title"), "A run without a target must leave out the target"); + Assert.AreEqual("2 succeeded · 1 running · 1 failed", Normalize(panel.QuerySelector("p.dug-dashboard__scan-counts")!.TextContent), "The count line must list the counts"); + Assert.AreEqual("1 failed", panel.QuerySelector("p.dug-dashboard__scan-counts strong.dug-dashboard__scan-failed")!.TextContent.Trim(), "The failed count must be emphasized"); + Assert.AreEqual("nginx:latest · registry unreachable", Normalize(panel.QuerySelector("p.dug-dashboard__scan-problem")!.TextContent), "The problem line must name the newest failed run"); + Assert.AreEqual("Open scan history", footer.TextContent.Trim(), "The footer must offer the scan history"); + Assert.AreEqual("/scan-history", footer.GetAttribute("href"), "The footer must open the scan history"); + } + } + + /// + /// Verify the scan panel without runs shows its empty text and keeps the link + /// + /// Task + [TestMethod] + [TestCategory("AC6")] + public async Task DashboardScanPanelWithoutRunsRendersEmptyText() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var dashboard = CreateDashboard(); + + dashboard.RecentScans = []; + + var component = RenderDashboard(testContext, dashboard); + + var panel = FindPanel(component, "Last 10 scans"); + + Assert.AreEqual("No scans have been recorded yet.", panel.QuerySelector("p.dug-dashboard__empty")!.TextContent.Trim(), "The panel must show its empty text"); + Assert.IsNull(panel.QuerySelector("div.dug-scan-strip"), "The panel must show no strip"); + Assert.IsNull(panel.QuerySelector("p.dug-dashboard__scan-counts"), "The panel must show no count line"); + Assert.IsNotNull(panel.QuerySelector("a.dug-dashboard__footer-link[href='/scan-history']"), "The scan history link must stay"); + } + } + + /// + /// Verify the inventory strip shows its cells under the visibility rules + /// + /// Whether a Docker Hub account is configured + /// Number of shared base images + /// Expected labels joined with a comma + /// Task + [TestMethod] + [TestCategory("AC7")] + [DataRow(true, 2, "My Images,Observed Images,Runtime Containers,Docker Instances,Base Images")] + [DataRow(false, 2, "Observed Images,Runtime Containers,Docker Instances,Base Images")] + [DataRow(true, 0, "My Images,Observed Images,Runtime Containers,Docker Instances")] + [DataRow(false, 0, "Observed Images,Runtime Containers,Docker Instances")] + public async Task DashboardInventoryStripRendersCellsWithVisibilityRules(bool withAccount, int baseImageCount, string expectedLabels) + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var dashboard = CreateDashboard(); + + dashboard.BaseImageCount = baseImageCount; + dashboard.ObservedImageCount = 3; + + var component = RenderDashboard(testContext, dashboard, withAccount); + + var cells = component.FindAll("section.dug-inventory a.dug-inventory__cell"); + var labels = cells.Select(cell => cell.QuerySelector(".dug-inventory__label")!.TextContent.Trim()) + .ToList(); + var observed = cells.Single(cell => cell.QuerySelector(".dug-inventory__label")!.TextContent.Trim() == "Observed Images"); + + Assert.AreEqual(expectedLabels, string.Join(",", labels), "The strip must show the cells its visibility rules allow"); + Assert.AreEqual("/observed-images", observed.GetAttribute("href"), "The cell must link to its page"); + Assert.AreEqual("3", observed.QuerySelector(".dug-inventory__value")!.TextContent.Trim(), "The cell must show its figure"); + } + } + + /// + /// Verify the all-clear state replaces the list panels by the nothing-to-do panel + /// + /// Task + [TestMethod] + [TestCategory("AC8")] + public async Task DashboardWithoutFindingsRendersNothingToDoPanel() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = RenderDashboard(testContext, CreateAllClearDashboard(), true); + + var titles = component.FindAll("section.dug-panel h2") + .Select(title => title.TextContent.Trim()) + .ToList(); + var nothingToDo = FindPanel(component, "Nothing to do"); + + Assert.AreEqual("Everything is up to date.", Normalize(component.Find("h1.dug-dashboard__headline").TextContent), "The headline must be the all-clear sentence"); + Assert.AreEqual("No updates available, no own base runtime warnings and no vulnerabilities in running containers.", + Normalize(nothingToDo.QuerySelector("p.dug-dashboard__empty")!.TextContent), + "The panel must explain the all-clear state"); + Assert.AreSequenceEqual(new List + { + "Nothing to do", + "Last 10 scans" + }, + titles, + "Only the nothing-to-do panel and the scan panel must remain"); + Assert.IsNotNull(component.Find("section.dug-inventory"), "The inventory strip must stay"); + } + } + + /// + /// Verify the all-clear state keeps the scanning disabled hint + /// + /// Task + [TestMethod] + [TestCategory("AC8")] + public async Task DashboardWithoutFindingsAndScanningDisabledRendersHintAndAllClear() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var dashboard = CreateAllClearDashboard(); + + dashboard.VulnerabilityScanningEnabled = false; + dashboard.VulnerabilityConfigurationHint = VulnerabilityConfigurationHintKind.ScanningDisabled; + + var component = RenderDashboard(testContext, dashboard); + + Assert.Contains("Vulnerability scanning is disabled", component.Markup, "The hint must be shown with the all-clear state"); + Assert.AreEqual("Everything is up to date.", Normalize(component.Find("h1.dug-dashboard__headline").TextContent), "The headline must be the all-clear sentence"); + Assert.IsNotNull(FindPanel(component, "Nothing to do"), "The nothing-to-do panel must be shown"); + } + } + + /// + /// Verify the dashboard shows its skeleton while loading + /// + /// Task + [TestMethod] + [TestCategory("AC10")] + public async Task DashboardWhileLoadingRendersDashboardSkeleton() { - var exception = new InvalidOperationException("secret text"); - var logger = new TestLogger(); var testContext = BlazorTestContextFactory.Create(); await using (testContext) { + var completion = new TaskCompletionSource(); var viewService = Substitute.For(); viewService.GetDashboardAsync(Arg.Any()) - .Returns(Task.FromException(exception)); + .Returns(completion.Task); testContext.Services.AddSingleton(viewService); testContext.Services.AddSingleton(new DashboardRefreshState()); testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions())); - testContext.Services.AddSingleton>(logger); - var page = testContext.Render(); + var component = testContext.Render(); - await DetailPageAssert.AssertLoadErrorAsync(page, "Loading the dashboard failed: unexpected error", "secret text").ConfigureAwait(false); - DetailPageAssert.AssertLoadLoggedOnce(logger, "LoadDashboard", exception); + Assert.IsNotNull(component.Find(".dug-dashboard-skeleton__headline"), "The skeleton must be shown while loading"); + Assert.IsEmpty(component.FindAll("h1.dug-dashboard__headline"), "No headline must be shown while loading"); + + completion.SetResult(CreateDashboard()); } } /// - /// Verify a refresh signal whose reload fails keeps the shown dashboard, shows no alert and logs the failure once + /// Verify a refresh signal reloads the dashboard /// /// Task [TestMethod] - [TestCategory("AC7")] - public async Task DashboardFailedRefreshKeepsDashboardAndLogs() + [TestCategory("AC10")] + public async Task DashboardRefreshSignalReloadsDashboard() { - var exception = new InvalidOperationException("secret text"); - var logger = new TestLogger(); var refreshState = new DashboardRefreshState(); var testContext = BlazorTestContextFactory.Create(); await using (testContext) { var viewService = Substitute.For(); - var dashboard = new DashboardViewData - { - RecentScans = [ - new ScanHistoryItemData - { - Type = "Runtime", - Status = "Succeeded", - SubjectName = "kept-scan-subject", - StartedAtUtc = DateTimeOffset.UtcNow, - }, - ], - }; + var first = CreateDashboard(); + var second = CreateDashboard(); + first.Updates = [CreateUpdate("first-container", Guid.NewGuid())]; + second.Updates = [CreateUpdate("second-container", Guid.NewGuid())]; viewService.GetDashboardAsync(Arg.Any()) - .Returns(Task.FromResult(dashboard), Task.FromException(exception)); + .Returns(Task.FromResult(first), Task.FromResult(second)); testContext.Services.AddSingleton(viewService); testContext.Services.AddSingleton(refreshState); testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions())); - testContext.Services.AddSingleton>(logger); - - var page = testContext.Render(); - var alertCount = page.FindAll(".mud-alert").Count; - Assert.Contains("kept-scan-subject", page.Markup, "The first load must show the dashboard"); + var component = testContext.Render(); - await page.InvokeAsync(() => refreshState.NotifyChanged()).ConfigureAwait(false); - await page.WaitForAssertionAsync(() => DetailPageAssert.AssertLoadLoggedOnce(logger, "LoadDashboard", exception), TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); + Assert.Contains("first-container", component.Markup, "The first load must show the first dashboard"); - Assert.Contains("kept-scan-subject", page.Markup, "A failed reload must keep the dashboard shown"); - Assert.HasCount(alertCount, page.FindAll(".mud-alert"), "A failed reload must show no alert"); - Assert.DoesNotContain("secret text", page.Markup, "A failed reload must not show the exception's text"); + await component.InvokeAsync(() => refreshState.NotifyChanged()).ConfigureAwait(false); + await component.WaitForAssertionAsync(() => Assert.Contains("second-container", component.Markup, "The refresh must show the reloaded dashboard"), + TimeSpan.FromSeconds(DetailPageAssert.WaitSeconds)).ConfigureAwait(false); } } /// - /// Verify the recent scans table shows the scan status in a chip of its color + /// Verify texts from outside are rendered as text and never as markup /// - /// Scan status - /// Expected chip color class /// Task [TestMethod] - [TestCategory("AC4")] - [DataRow("Succeeded", "mud-chip-color-success")] - [DataRow("Partial", "mud-chip-color-warning")] - public async Task DashboardRecentScanStatusChipShowsStatusColorAsync(string status, string expectedColorClass) + [TestCategory("AC10")] + public async Task DashboardRendersExternalTextAsText() { var testContext = BlazorTestContextFactory.Create(); await using (testContext) { - var viewService = Substitute.For(); + var dashboard = CreateDashboard(); + var update = CreateUpdate("", Guid.NewGuid()); + var failed = CreateScan("Failed", "Registry", "", DateTimeOffset.UtcNow); + + failed.ErrorMessage = "boom"; + update.AvailableUpdateVersionTag = "2"; + dashboard.Updates = [update]; + dashboard.Vulnerabilities = [ + new DashboardVulnerabilityItemData + { + AdvisoryId = "CVE", + Severity = "High", + AffectedPackages = ["pkg"] + } + ]; + dashboard.RecentScans = [failed]; + + var component = RenderDashboard(testContext, dashboard); + + Assert.IsEmpty(component.FindAll("script"), "A container name must not become a script element"); + Assert.IsEmpty(component.FindAll("img"), "A scan target must not become an image element"); + Assert.IsEmpty(component.FindAll("main b, main i, main u, main em"), "Texts must not create formatting elements"); + Assert.Contains("", FindPanel(component, "Updates available").TextContent, "The container name must be shown as text"); + Assert.Contains("boom", component.Find("p.dug-dashboard__scan-problem").TextContent, "The error message must be shown as text"); + } + } - viewService.GetDashboardAsync(Arg.Any()) - .Returns(Task.FromResult(new DashboardViewData - { - RecentScans = [ - new ScanHistoryItemData - { - Type = "Registry", - Status = status, - StartedAtUtc = DateTimeOffset.UtcNow, - } - ], - })); + #endregion // Methods - testContext.Services.AddSingleton(viewService); - testContext.Services.AddSingleton(new DashboardRefreshState()); - testContext.Services.AddSingleton(Options.Create(new DockerUpdateGuardOptions())); - testContext.AddBunitPersistentComponentState(); + #region Helper methods - var page = testContext.Render(); + /// + /// Collapse runs of whitespace and trim a text + /// + /// Text + /// Normalized text + private static string Normalize(string text) + { + return string.Join(" ", text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)); + } + + /// + /// Find the panel with a title + /// + /// Rendered page + /// Panel title + /// Panel element + private static AngleSharp.Dom.IElement FindPanel(IRenderedComponent component, string title) + { + return component.FindAll("section.dug-panel") + .Single(panel => panel.QuerySelector("h2")?.TextContent.Trim() == title); + } + + /// + /// Render the dashboard with the given data + /// + /// bUnit test context + /// Dashboard data + /// Whether a Docker Hub account is configured + /// Rendered page + private static IRenderedComponent RenderDashboard(BunitContext testContext, DashboardViewData dashboard, bool withAccount = false) + { + var viewService = Substitute.For(); + var options = new DockerUpdateGuardOptions(); - await ScanStatusChipAssert.AssertChipAsync(page, - root => ScanStatusChipAssert.FindSectionCellChips(root, "Recent scans", "Status"), - status, - expectedColorClass).ConfigureAwait(false); + if (withAccount) + { + options.DockerHub.UserName = "octocat"; + options.DockerHub.Pat = "token"; } + + viewService.GetDashboardAsync(Arg.Any()) + .Returns(Task.FromResult(dashboard)); + + testContext.Services.AddSingleton(viewService); + testContext.Services.AddSingleton(new DashboardRefreshState()); + testContext.Services.AddSingleton(Options.Create(options)); + testContext.AddBunitPersistentComponentState(); + + return testContext.Render(); + } + + /// + /// Create a dashboard with an entry in every list: 7 updates, 31 vulnerabilities and 2 runtime warnings, of which 1 is listed + /// + /// Dashboard data + private static DashboardViewData CreateDashboard() + { + return new DashboardViewData + { + UpdateCount = 7, + Updates = [CreateUpdate("web-1", Guid.NewGuid())], + VulnerabilityCount = 31, + Vulnerabilities = [ + new DashboardVulnerabilityItemData + { + AdvisoryId = "CVE-2026-0001", + Severity = "High", + AffectedContainerCount = 1 + } + ], + VulnerabilityAdvisorySeveritySummary = new VulnerabilitySeveritySummaryViewData + { + HighCount = 31 + }, + RuntimeWarningCount = 2, + RuntimeWarnings = [ + new DashboardRuntimeWarningItemData + { + Id = Guid.NewGuid(), + Name = "company/api", + BaseRuntimeAlertSummary = "Base runtime is outdated" + }, + new DashboardRuntimeWarningItemData + { + Id = Guid.NewGuid(), + Name = "company/worker", + BaseRuntimeAlertSummary = "Base runtime is outdated" + } + ], + VulnerabilityScanningEnabled = true + }; + } + + /// + /// Create a dashboard without any finding + /// + /// Dashboard data + private static DashboardViewData CreateAllClearDashboard() + { + return new DashboardViewData + { + VulnerabilityScanningEnabled = true, + RecentScans = [CreateScan("Succeeded", "Runtime", "local", DateTimeOffset.UtcNow)] + }; + } + + /// + /// Create an update entry with an alias tag and an available tag + /// + /// Container name + /// Docker instance identifier + /// Update entry + private static DashboardUpdateItemData CreateUpdate(string containerName, Guid instanceId) + { + return new DashboardUpdateItemData + { + DockerInstanceId = instanceId, + ContainerId = $"container-{containerName}", + ContainerName = containerName, + DockerInstanceName = "docker-a", + CurrentTag = "latest", + ResolvedVersionTag = "1.25.3", + AvailableUpdateVersionTag = "1.26.0" + }; + } + + /// + /// Create a scan + /// + /// Status + /// Type + /// Target + /// Start + /// Scan + private static ScanHistoryItemData CreateScan(string status, string type, string? subjectName, DateTimeOffset startedAtUtc) + { + return new ScanHistoryItemData + { + Id = Guid.NewGuid(), + Status = status, + Type = type, + SubjectName = subjectName, + StartedAtUtc = startedAtUtc + }; } /// @@ -381,5 +1002,5 @@ private static string RenderDashboardMarkup(BunitContext testContext, Vulnerabil return component.Markup; } - #endregion // Methods + #endregion // Helper methods } \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/DashboardScanStripFormatterTests.cs b/src/Tests/DockerUpdateGuard.Tests/DashboardScanStripFormatterTests.cs new file mode 100644 index 00000000..3c31cc78 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/DashboardScanStripFormatterTests.cs @@ -0,0 +1,267 @@ +using DockerUpdateGuard.UI; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for +/// +[TestClass] +public class DashboardScanStripFormatterTests +{ + #region Methods + + /// + /// Verify counts above zero are returned in the fixed status order + /// + [TestMethod] + [TestCategory("AC6")] + public void DashboardScanStripFormatterGetStatusCountsReturnsCountsAboveZeroInStatusOrder() + { + var scans = new List + { + CreateScan("Failed"), + CreateScan("Succeeded"), + CreateScan("Partial"), + CreateScan("Succeeded"), + CreateScan("Running"), + CreateScan("Succeeded"), + CreateScan("NotSet") + }; + + var counts = DashboardScanStripFormatter.GetStatusCounts(scans); + + var actual = counts.Select(count => $"{count.Status}={count.Count}") + .ToList(); + + Assert.AreSequenceEqual(new List + { + "Succeeded=3", + "Running=1", + "Partial=1", + "Failed=1" + }, + actual, + "Counts must follow the order succeeded, running, pending, partial, failed, skip zero counts and ignore other statuses"); + } + + /// + /// Verify one status count text + /// + [TestMethod] + [TestCategory("AC6")] + public void DashboardScanStripFormatterFormatCountTextReturnsCountAndLowerCaseStatus() + { + var text = DashboardScanStripFormatter.FormatCountText(new() + { + Status = "Succeeded", + Count = 8 + }); + + Assert.AreEqual("8 succeeded", + text, + "The count text must hold the count and the lower-case status"); + } + + /// + /// Verify the strip label joins the counts with commas + /// + [TestMethod] + [TestCategory("AC6")] + public void DashboardScanStripFormatterFormatStripLabelJoinsCountsWithCommas() + { + var counts = new List + { + new() + { + Status = "Succeeded", + Count = 8 + }, + new() + { + Status = "Partial", + Count = 1 + }, + new() + { + Status = "Failed", + Count = 1 + } + }; + + var label = DashboardScanStripFormatter.FormatStripLabel(counts); + + Assert.AreEqual("8 succeeded, 1 partial, 1 failed", + label, + "The strip label must list the counts joined with commas"); + } + + /// + /// Verify the segment title holds type, target, status and the UTC start + /// + [TestMethod] + [TestCategory("AC6")] + public void DashboardScanStripFormatterFormatSegmentTitleReturnsTypeTargetStatusAndUtcStart() + { + var scan = new ScanHistoryItemData + { + Type = "Registry scan", + SubjectName = "nginx:latest", + Status = "Failed", + StartedAtUtc = new DateTimeOffset(2026, 11, 14, 11, 42, 0, TimeSpan.FromHours(2)) + }; + + var title = DashboardScanStripFormatter.FormatSegmentTitle(scan); + + Assert.AreEqual("Registry scan · nginx:latest · Failed · 2026-11-14 09:42 UTC", + title, + "The segment title must hold type, target, status and the start in UTC"); + } + + /// + /// Verify the segment title leaves out a missing target with its separator + /// + /// Target + [TestMethod] + [TestCategory("AC6")] + [DataRow(null)] + [DataRow("")] + public void DashboardScanStripFormatterFormatSegmentTitleWithoutTargetLeavesOutTargetAndSeparator(string? subjectName) + { + var scan = new ScanHistoryItemData + { + Type = "Vulnerability refresh", + SubjectName = subjectName, + Status = "Succeeded", + StartedAtUtc = new DateTimeOffset(2026, 11, 14, 9, 42, 0, TimeSpan.Zero) + }; + + var title = DashboardScanStripFormatter.FormatSegmentTitle(scan); + + Assert.AreEqual("Vulnerability refresh · Succeeded · 2026-11-14 09:42 UTC", + title, + "A run without a target must not leave a doubled separator"); + } + + /// + /// Verify the status maps to its CSS name and unknown statuses to pending + /// + /// Status + /// Expected CSS name + [TestMethod] + [TestCategory("AC6")] + [DataRow("Succeeded", "succeeded")] + [DataRow("Partial", "partial")] + [DataRow("Failed", "failed")] + [DataRow("Running", "running")] + [DataRow("Pending", "pending")] + [DataRow("NotSet", "pending")] + public void DashboardScanStripFormatterGetSegmentCssNameMapsStatus(string status, string expected) + { + var cssName = DashboardScanStripFormatter.GetSegmentCssName(status); + + Assert.AreEqual(expected, + cssName, + "Each known status must map to its CSS name and any other status to pending"); + } + + /// + /// Verify the newest failed or partial run with a message is found + /// + [TestMethod] + [TestCategory("AC6")] + public void DashboardScanStripFormatterFindLatestProblemScanReturnsNewestFailedOrPartialWithMessage() + { + var newestWithoutMessage = CreateScan("Failed"); + var expected = CreateScan("Partial", "second run message"); + var older = CreateScan("Failed", "older message"); + var scans = new List + { + CreateScan("Succeeded", "ignored message"), + newestWithoutMessage, + expected, + older + }; + + var scan = DashboardScanStripFormatter.FindLatestProblemScan(scans); + + Assert.AreSame(expected, + scan, + "The first failed or partial run with an error message must be returned"); + } + + /// + /// Verify no problem run is returned when none has a message + /// + [TestMethod] + [TestCategory("AC6")] + public void DashboardScanStripFormatterFindLatestProblemScanWithoutMessageReturnsNull() + { + var scans = new List + { + CreateScan("Failed"), + CreateScan("Partial", string.Empty), + CreateScan("Succeeded", "message of a good run") + }; + + var scan = DashboardScanStripFormatter.FindLatestProblemScan(scans); + + Assert.IsNull(scan, + "Failed or partial runs without a message and other runs must not be returned"); + } + + /// + /// Verify the problem line holds target and message + /// + [TestMethod] + [TestCategory("AC6")] + public void DashboardScanStripFormatterFormatProblemScanLineWithTargetReturnsTargetAndMessage() + { + var scan = CreateScan("Failed", "registry unreachable"); + scan.SubjectName = "nginx:latest"; + + var line = DashboardScanStripFormatter.FormatProblemScanLine(scan); + + Assert.AreEqual("nginx:latest · registry unreachable", + line, + "The problem line must hold the target and the stored message"); + } + + /// + /// Verify the problem line of a run without a target is the message alone + /// + [TestMethod] + [TestCategory("AC6")] + public void DashboardScanStripFormatterFormatProblemScanLineWithoutTargetReturnsMessageOnly() + { + var scan = CreateScan("Partial", " token expired now"); + + var line = DashboardScanStripFormatter.FormatProblemScanLine(scan); + + Assert.AreEqual(" token expired now", + line, + "A run without a target must show the message as stored"); + } + + #endregion // Methods + + #region Static methods + + /// + /// Create a scan with a status and an optional message + /// + /// Status + /// Error message + /// Scan + private static ScanHistoryItemData CreateScan(string status, string? errorMessage = null) + { + return new ScanHistoryItemData + { + Id = Guid.NewGuid(), + Type = "Registry scan", + Status = status, + ErrorMessage = errorMessage + }; + } + + #endregion // Static methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/DashboardSkeletonTests.cs b/src/Tests/DockerUpdateGuard.Tests/DashboardSkeletonTests.cs new file mode 100644 index 00000000..39342107 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/DashboardSkeletonTests.cs @@ -0,0 +1,37 @@ +using Bunit; + +using DockerUpdateGuard.Components.Common; +using DockerUpdateGuard.Tests.Helper; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for +/// +[TestClass] +public class DashboardSkeletonTests +{ + #region Methods + + /// + /// Verify the skeleton has the shape of the dashboard: headline, three panels and the strip + /// + /// Task + [TestMethod] + [TestCategory("AC10")] + public async Task DashboardSkeletonRendersHeadlinePanelsAndStrip() + { + var testContext = BlazorTestContextFactory.Create(); + + await using (testContext) + { + var component = testContext.Render(); + + Assert.HasCount(1, component.FindAll(".dug-dashboard-skeleton__headline"), "The skeleton must render one headline placeholder"); + Assert.HasCount(3, component.FindAll(".dug-dashboard-skeleton__panel"), "The skeleton must render three panel placeholders"); + Assert.HasCount(1, component.FindAll(".dug-dashboard-skeleton__strip"), "The skeleton must render one strip placeholder"); + } + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/DashboardTests.cs b/src/Tests/DockerUpdateGuard.Tests/DashboardTests.cs index f62db6e8..0227737e 100644 --- a/src/Tests/DockerUpdateGuard.Tests/DashboardTests.cs +++ b/src/Tests/DockerUpdateGuard.Tests/DashboardTests.cs @@ -33,7 +33,7 @@ public class DashboardTests [DataRow("Observed Images", "/observed-images")] [DataRow("Docker Instances", "/docker-instances")] [DataRow("Runtime Containers", "/runtime-containers")] - [DataRow("Shared Base Images", "/base-images")] + [DataRow("Base Images", "/base-images")] public void DashboardGetMetricNavigationTargetKnownMetricReturnsExpectedRoute(string metricLabel, string expectedRoute) { var route = _getMetricNavigationTargetMethod.Invoke(null, [metricLabel]) as string; @@ -43,5 +43,18 @@ public void DashboardGetMetricNavigationTargetKnownMetricReturnsExpectedRoute(st $"The dashboard metric card '{metricLabel}' must navigate to '{expectedRoute}'"); } + /// + /// Verify an unknown dashboard metric label is rejected + /// + [TestMethod] + [TestCategory("AC7")] + public void DashboardGetMetricNavigationTargetUnknownMetricThrowsArgumentOutOfRange() + { + var exception = Assert.ThrowsExactly(() => _getMetricNavigationTargetMethod.Invoke(null, ["Unknown"]), + "An unknown metric label must make the route resolver throw"); + + Assert.IsInstanceOfType(exception.InnerException, "The resolver must reject an unknown metric label with an ArgumentOutOfRangeException"); + } + #endregion // Methods } \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/DashboardTextFormatterTests.cs b/src/Tests/DockerUpdateGuard.Tests/DashboardTextFormatterTests.cs new file mode 100644 index 00000000..95b37b27 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/DashboardTextFormatterTests.cs @@ -0,0 +1,306 @@ +using DockerUpdateGuard.UI; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests for +/// +[TestClass] +public class DashboardTextFormatterTests +{ + #region Methods + + /// + /// Verify every combination of zero and non-zero counts composes the headline sentence + /// + /// Number of updates + /// Number of runtime warnings + /// Number of vulnerabilities + /// Expected sentence + [TestMethod] + [TestCategory("AC1")] + [DataRow(0, 0, 0, "Everything is up to date.")] + [DataRow(1, 0, 0, "1 update needs attention.")] + [DataRow(0, 1, 0, "1 runtime warning needs attention.")] + [DataRow(0, 0, 1, "1 vulnerability needs attention.")] + [DataRow(2, 0, 0, "2 updates need attention.")] + [DataRow(0, 3, 0, "3 runtime warnings need attention.")] + [DataRow(0, 0, 4, "4 vulnerabilities need attention.")] + [DataRow(1, 1, 0, "1 update and 1 runtime warning need attention.")] + [DataRow(1, 0, 1, "1 update and 1 vulnerability need attention.")] + [DataRow(0, 1, 1, "1 runtime warning and 1 vulnerability need attention.")] + [DataRow(7, 2, 0, "7 updates and 2 runtime warnings need attention.")] + [DataRow(7, 0, 31, "7 updates and 31 vulnerabilities need attention.")] + [DataRow(0, 2, 31, "2 runtime warnings and 31 vulnerabilities need attention.")] + [DataRow(1, 1, 1, "1 update, 1 runtime warning and 1 vulnerability need attention.")] + [DataRow(7, 2, 31, "7 updates, 2 runtime warnings and 31 vulnerabilities need attention.")] + public void DashboardTextFormatterGetHeadlineSegmentsCountCombinationReturnsSentence(int updateCount, int runtimeWarningCount, int vulnerabilityCount, string expectedSentence) + { + var segments = DashboardTextFormatter.GetHeadlineSegments(updateCount, runtimeWarningCount, vulnerabilityCount); + + var sentence = string.Concat(segments.Select(segment => segment.Text)); + + Assert.AreEqual(expectedSentence, + sentence, + "The headline segments must concatenate to the composed sentence"); + } + + /// + /// Verify only the counted parts are colored in the headline + /// + [TestMethod] + [TestCategory("AC1")] + public void DashboardTextFormatterGetHeadlineSegmentsTonesOnlyTheParts() + { + var segments = DashboardTextFormatter.GetHeadlineSegments(7, 2, 31); + + var updates = segments.Single(segment => segment.Text == "7 updates"); + var warnings = segments.Single(segment => segment.Text == "2 runtime warnings"); + var vulnerabilities = segments.Single(segment => segment.Text == "31 vulnerabilities"); + var connectors = segments.Where(segment => segment.Text != updates.Text && segment.Text != warnings.Text && segment.Text != vulnerabilities.Text) + .ToList(); + + Assert.AreEqual(StatusTone.Warning, + updates.Tone, + "The updates part must use the warning tone"); + Assert.AreEqual(StatusTone.Warning, + warnings.Tone, + "The runtime warnings part must use the warning tone"); + Assert.AreEqual(StatusTone.Danger, + vulnerabilities.Tone, + "The vulnerabilities part must use the danger tone"); + Assert.IsNotEmpty(connectors, + "The headline must hold connector segments between and after the parts"); + Assert.IsTrue(connectors.All(segment => segment.Tone == StatusTone.Neutral), + "Connectors and the closing words must use the neutral tone"); + } + + /// + /// Verify the all-clear sentence uses the success tone + /// + [TestMethod] + [TestCategory("AC1")] + public void DashboardTextFormatterGetHeadlineSegmentsWithoutCountsReturnsSuccessSentence() + { + var segments = DashboardTextFormatter.GetHeadlineSegments(0, 0, 0); + + Assert.HasCount(1, + segments, + "The all-clear headline must be one segment"); + Assert.AreEqual(StatusTone.Success, + segments[0].Tone, + "The all-clear sentence must use the success tone"); + } + + /// + /// Verify the count text uses the singular only for one + /// + /// Count + /// Expected text + [TestMethod] + [TestCategory("AC1")] + [DataRow(0, "0 updates")] + [DataRow(1, "1 update")] + [DataRow(2, "2 updates")] + public void DashboardTextFormatterFormatCountPicksSingularOnlyForOne(int count, string expected) + { + var text = DashboardTextFormatter.FormatCount(count, "update", "updates"); + + Assert.AreEqual(expected, + text, + "The count must be followed by the singular only for a count of 1"); + } + + /// + /// Verify the sub line names assets, instances and the UTC start of the newest run + /// + [TestMethod] + [TestCategory("AC2")] + public void DashboardTextFormatterFormatSubLineWithScanReturnsAssetsInstancesAndUtcTime() + { + var dashboard = new DashboardViewData + { + ObservedImageCount = 10, + MyImageCount = 3, + RuntimeContainerCount = 30, + DockerInstanceCount = 2, + RecentScans = [ + new ScanHistoryItemData + { + StartedAtUtc = new DateTimeOffset(2026, 11, 14, 11, 42, 0, TimeSpan.FromHours(2)) + }, + new ScanHistoryItemData + { + StartedAtUtc = new DateTimeOffset(2026, 11, 13, 8, 0, 0, TimeSpan.Zero) + } + ] + }; + + var text = DashboardTextFormatter.FormatSubLine(dashboard); + + Assert.AreEqual("43 protected assets on 2 Docker instances · last activity 2026-11-14 09:42 UTC", + text, + "The sub line must sum the assets and show the newest run's start in UTC"); + } + + /// + /// Verify the sub line without a recorded run + /// + [TestMethod] + [TestCategory("AC2")] + public void DashboardTextFormatterFormatSubLineWithoutScanReturnsNoScansYet() + { + var dashboard = new DashboardViewData + { + ObservedImageCount = 1, + MyImageCount = 1, + RuntimeContainerCount = 2, + DockerInstanceCount = 3 + }; + + var text = DashboardTextFormatter.FormatSubLine(dashboard); + + Assert.AreEqual("4 protected assets on 3 Docker instances · last activity no scans yet", + text, + "Without a recorded run the sub line must end with no scans yet"); + } + + /// + /// Verify the singular forms of the sub line + /// + [TestMethod] + [TestCategory("AC2")] + public void DashboardTextFormatterFormatSubLineSingleInstanceAndAssetUsesSingular() + { + var dashboard = new DashboardViewData + { + RuntimeContainerCount = 1, + DockerInstanceCount = 1 + }; + + var text = DashboardTextFormatter.FormatSubLine(dashboard); + + Assert.AreEqual("1 protected asset on 1 Docker instance · last activity no scans yet", + text, + "One asset and one instance must use the singular nouns"); + } + + /// + /// Verify the current tag of an alias is followed by its resolved version + /// + /// Current tag + /// Resolved version + /// Expected text + [TestMethod] + [TestCategory("AC3")] + [DataRow("latest", "1.25.3", "latest (1.25.3)")] + [DataRow("1.25.3", null, "1.25.3")] + [DataRow("1.25.3", "", "1.25.3")] + public void DashboardTextFormatterFormatCurrentTagWithAliasAppendsResolvedVersion(string currentTag, string? resolvedVersionTag, string expected) + { + var item = new DashboardUpdateItemData + { + CurrentTag = currentTag, + ResolvedVersionTag = resolvedVersionTag + }; + + var text = DashboardTextFormatter.FormatCurrentTag(item); + + Assert.AreEqual(expected, + text, + "The resolved version must follow the current tag in parentheses only when present"); + } + + /// + /// Verify the footer names the remainder or offers to open the page + /// + /// Total entries + /// Shown entries + /// Expected text + [TestMethod] + [TestCategory("AC3")] + [TestCategory("AC4")] + [DataRow(7, 5, "2 more in Runtime Containers")] + [DataRow(6, 5, "1 more in Runtime Containers")] + [DataRow(5, 5, "Open Runtime Containers")] + [DataRow(3, 3, "Open Runtime Containers")] + [DataRow(0, 0, "Open Runtime Containers")] + public void DashboardTextFormatterFormatFooterLinkReturnsRemainderOrOpenText(int totalCount, int shownCount, string expected) + { + var text = DashboardTextFormatter.FormatFooterLink(totalCount, shownCount, "Runtime Containers"); + + Assert.AreEqual(expected, + text, + "The footer must name the remainder when more entries exist than shown, else offer to open the page"); + } + + /// + /// Verify the vulnerability title joins the packages or falls back to the advisory identifier + /// + [TestMethod] + [TestCategory("AC4")] + public void DashboardTextFormatterFormatVulnerabilityTitleWithPackagesJoinsPackages() + { + var item = new DashboardVulnerabilityItemData + { + AdvisoryId = "CVE-2026-0001", + AffectedPackages = ["openssl", "libssl3"] + }; + + var text = DashboardTextFormatter.FormatVulnerabilityTitle(item); + + Assert.AreEqual("openssl, libssl3", + text, + "The title must join the affected packages with a comma"); + } + + /// + /// Verify the vulnerability title without packages is the advisory identifier + /// + [TestMethod] + [TestCategory("AC4")] + public void DashboardTextFormatterFormatVulnerabilityTitleWithoutPackagesReturnsAdvisoryId() + { + var item = new DashboardVulnerabilityItemData + { + AdvisoryId = "CVE-2026-0001", + AffectedPackages = [] + }; + + var text = DashboardTextFormatter.FormatVulnerabilityTitle(item); + + Assert.AreEqual("CVE-2026-0001", + text, + "Without packages the title must be the advisory identifier"); + } + + /// + /// Verify the vulnerability detail line for fixes and container counts + /// + /// Fixed versions joined with a semicolon + /// Affected container count + /// Expected text + [TestMethod] + [TestCategory("AC4")] + [DataRow("3.0.1;3.0.2", 2, "Fixed in 3.0.1, 3.0.2 · 2 running containers")] + [DataRow("3.0.1", 1, "Fixed in 3.0.1 · 1 running container")] + [DataRow("", 1, "No fix available · 1 running container")] + [DataRow("", 4, "No fix available · 4 running containers")] + public void DashboardTextFormatterFormatVulnerabilityDetailReturnsFixAndContainerCount(string fixedVersions, int containerCount, string expected) + { + var item = new DashboardVulnerabilityItemData + { + AdvisoryId = "CVE-2026-0001", + FixedVersions = fixedVersions.Split(';', StringSplitOptions.RemoveEmptyEntries), + AffectedContainerCount = containerCount + }; + + var text = DashboardTextFormatter.FormatVulnerabilityDetail(item); + + Assert.AreEqual(expected, + text, + "The detail must name the fixed versions or no fix and the affected running container count"); + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/DashboardVulnerabilityQueryTests.cs b/src/Tests/DockerUpdateGuard.Tests/DashboardVulnerabilityQueryTests.cs new file mode 100644 index 00000000..a1bb7f50 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/DashboardVulnerabilityQueryTests.cs @@ -0,0 +1,39 @@ +using DockerUpdateGuard.Data; +using DockerUpdateGuard.UI; + +using Microsoft.EntityFrameworkCore; + +namespace DockerUpdateGuard.Tests; + +/// +/// Tests of the dashboard's advisory query against the PostgreSQL provider +/// +[TestClass] +public class DashboardVulnerabilityQueryTests +{ + #region Methods + + /// + /// Verify the query translates on the PostgreSQL provider and matches the advisory identifiers in lower case + /// + /// Task + [TestMethod] + [TestCategory("AC4")] + public async Task DashboardVulnerabilityQueryAdvisoryFindingsQueryTranslatesOnNpgsqlWithLowerCaseMatchAsync() + { + var options = new DbContextOptionsBuilder().UseNpgsql("Host=127.0.0.1;Port=1;Database=dug") + .Options; + var dbContext = new DockerUpdateGuardDbContext(options); + + await using (dbContext.ConfigureAwait(false)) + { + var sql = DashboardVulnerabilityQuery.CreateAdvisoryFindingsQuery(dbContext, ["cve-1", "cve-2"]) + .ToQueryString(); + + Assert.Contains("lower(", sql, "The advisory identifiers must be compared in lower case by the database"); + Assert.Contains("= ANY", sql, "The identifiers must be matched as a list"); + } + } + + #endregion // Methods +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/Data/SetRecordingDbContext.cs b/src/Tests/DockerUpdateGuard.Tests/Data/SetRecordingDbContext.cs new file mode 100644 index 00000000..3cffd979 --- /dev/null +++ b/src/Tests/DockerUpdateGuard.Tests/Data/SetRecordingDbContext.cs @@ -0,0 +1,87 @@ +using DockerUpdateGuard.Data; + +using Microsoft.EntityFrameworkCore; + +namespace DockerUpdateGuard.Tests.Data; + +/// +/// Database context that records the entity types whose sets the code under test asks for +/// +internal sealed class SetRecordingDbContext : DockerUpdateGuardDbContext +{ + #region Fields + + /// + /// Entity types whose sets were requested since the last reset + /// + private readonly HashSet _requestedEntityTypes = []; + + /// + /// Guard of the recorded entity types + /// + private readonly Lock _lock = new(); + + #endregion // Fields + + #region Constructors + + /// + /// Constructor + /// + /// Context options + public SetRecordingDbContext(DbContextOptions options) + : base(options) + { + } + + #endregion // Constructors + + #region Properties + + /// + /// Entity types whose sets were requested since the last reset + /// + public IReadOnlyCollection RequestedEntityTypes + { + get + { + lock (_lock) + { + return [.. _requestedEntityTypes]; + } + } + } + + #endregion // Properties + + #region Methods + + /// + /// Forget the entity types requested so far, for example after seeding the data + /// + public void ResetRequestedEntityTypes() + { + lock (_lock) + { + _requestedEntityTypes.Clear(); + } + } + + #endregion // Methods + + #region DbContext + + /// + public override DbSet Set() + where TEntity : class + { + lock (_lock) + { + _requestedEntityTypes.Add(typeof(TEntity)); + } + + return base.Set(); + } + + #endregion // DbContext +} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/MetricGridSkeletonTests.cs b/src/Tests/DockerUpdateGuard.Tests/MetricGridSkeletonTests.cs deleted file mode 100644 index 70c94691..00000000 --- a/src/Tests/DockerUpdateGuard.Tests/MetricGridSkeletonTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -using Bunit; - -using DockerUpdateGuard.Components.Common; -using DockerUpdateGuard.Tests.Helper; - -namespace DockerUpdateGuard.Tests; - -/// -/// Tests for -/// -[TestClass] -public class MetricGridSkeletonTests -{ - #region Methods - - /// - /// Verify the metric grid skeleton renders the requested number of card placeholders - /// - /// Task - [TestMethod] - public async Task MetricGridSkeletonRendersRequestedCardCount() - { - var testContext = BlazorTestContextFactory.Create(); - - await using (testContext) - { - var component = testContext.Render(parameters => parameters.Add(skeleton => skeleton.Cards, 4)); - - Assert.AreEqual(4, MarkupTestHelper.CountOccurrences(component.Markup, "dug-skeleton-card"), "The metric grid skeleton must render one card placeholder per requested card"); - } - } - - /// - /// Verify the metric grid skeleton defaults to six card placeholders - /// - /// Task - [TestMethod] - public async Task MetricGridSkeletonDefaultRendersSixCards() - { - var testContext = BlazorTestContextFactory.Create(); - - await using (testContext) - { - var component = testContext.Render(); - - Assert.AreEqual(6, MarkupTestHelper.CountOccurrences(component.Markup, "dug-skeleton-card"), "The metric grid skeleton must render six card placeholders by default"); - } - } - - #endregion // Methods -} \ No newline at end of file diff --git a/src/Tests/DockerUpdateGuard.Tests/PageHeaderSkeletonTests.cs b/src/Tests/DockerUpdateGuard.Tests/PageHeaderSkeletonTests.cs deleted file mode 100644 index c6a2b45d..00000000 --- a/src/Tests/DockerUpdateGuard.Tests/PageHeaderSkeletonTests.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Bunit; - -using DockerUpdateGuard.Components.Common; -using DockerUpdateGuard.Tests.Helper; - -namespace DockerUpdateGuard.Tests; - -/// -/// Tests for -/// -[TestClass] -public class PageHeaderSkeletonTests -{ - #region Methods - - /// - /// Verify the header skeleton has the shape of the page header with two placeholder bars - /// - /// Task - [TestMethod] - [TestCategory("AC6")] - public async Task PageHeaderSkeletonRendersPageHeaderShape() - { - var testContext = BlazorTestContextFactory.Create(); - - await using (testContext) - { - var component = testContext.Render(); - var markup = component.Markup; - - Assert.HasCount(1, component.FindAll("header.dug-page-header"), "The header skeleton must render the page header element"); - Assert.DoesNotContain("hero-panel", markup, "The header skeleton must no longer render the hero panel"); - Assert.AreEqual(2, MarkupTestHelper.CountSkeletons(markup), "The header skeleton must render a title and a description bar"); - } - } - - #endregion // Methods -} \ No newline at end of file