Skip to content

Modern Docker Management, Designed for Everyone

feat: add CSV export to the security vulnerabilities table (#3936)

Kyle Mendellaf5538dde929
diff --git a/backend/internal/vulnerability/handler.go b/backend/internal/vulnerability/handler.go
index ae0d61acf..7089a18d3 100644
--- a/backend/internal/vulnerability/handler.go
+++ b/backend/internal/vulnerability/handler.go
@@ -2,8 +2,10 @@ package vulnerability
import (
"context"
+ "fmt"
"log/slog"
"net/http"
+ "time"
"github.com/getarcaneapp/arcane/types/v2/features"
@@ -12,6 +14,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/internal/middleware"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
"github.com/getarcaneapp/arcane/types/v2/base"
@@ -75,6 +78,18 @@ type ListAllVulnerabilitiesInput struct {
Ignored bool `query:"ignored" doc:"Show only ignored vulnerabilities instead of active ones"`
}
+// ExportVulnerabilitiesInput carries the list filters accepted by the CSV export.
+type ExportVulnerabilitiesInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Search string `query:"search" doc:"Search query"`
+ Sort string `query:"sort" doc:"Sort field"`
+ Order string `query:"order" doc:"Sort order"`
+
+ Severity string `query:"severity" doc:"Comma-separated severity filter"`
+ ImageName string `query:"imageName" doc:"Filter by image/repo name (substring)"`
+ Ignored bool `query:"ignored" doc:"Export only ignored vulnerabilities instead of active ones"`
+}
+
type ListAllVulnerabilityImageOptionsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Severity string `query:"severity" doc:"Comma-separated severity filter"`
@@ -200,6 +215,17 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *VulnerabilityServ
Security: handlerutil.DefaultOperationSecurity(),
}, authz.PermVulnsRead, h.ListAllVulnerabilities)
+ middleware.RegisterWithPermission(api, huma.Operation{
+ Middlewares: featureMiddleware,
+ OperationID: "export-environment-vulnerabilities",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/vulnerabilities/export",
+ Summary: "Export environment vulnerabilities",
+ Description: "Downloads every vulnerability matching the given filters as a CSV file",
+ Tags: []string{"Vulnerabilities"},
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, authz.PermVulnsRead, h.ExportVulnerabilities)
+
middleware.RegisterWithPermission(api, huma.Operation{
Middlewares: featureMiddleware,
OperationID: "list-environment-vulnerability-image-options",
@@ -390,7 +416,7 @@ func (h *VulnerabilityHandler) GetEnvironmentSummary(ctx context.Context, input
}
// ListAllVulnerabilities returns a paginated list of vulnerabilities across all images.
-func (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, input *ListAllVulnerabilitiesInput) (*handlerutil.Page[vulnerability.VulnerabilityWithImage], error) {
+func (input *ListAllVulnerabilitiesInput) queryParamsInternal() pagination.QueryParams {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if params.Limit == 0 {
params.Limit = 20
@@ -404,8 +430,11 @@ func (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, input
if input.Ignored {
params.Filters["ignored"] = "true"
}
+ return params
+}
- items, paginationResp, err := h.vulnerabilityService.ListAllVulnerabilities(ctx, input.EnvironmentID, params)
+func (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, input *ListAllVulnerabilitiesInput) (*handlerutil.Page[vulnerability.VulnerabilityWithImage], error) {
+ items, paginationResp, err := h.vulnerabilityService.ListAllVulnerabilities(ctx, input.EnvironmentID, input.queryParamsInternal())
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve vulnerability scan").Error())
}
@@ -423,6 +452,34 @@ func (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, input
}, nil
}
+// ExportVulnerabilities streams every vulnerability matching the filters as a CSV download.
+func (h *VulnerabilityHandler) ExportVulnerabilities(ctx context.Context, input *ExportVulnerabilitiesInput) (*huma.StreamResponse, error) {
+ params := (&ListAllVulnerabilitiesInput{
+ EnvironmentID: input.EnvironmentID,
+ Search: input.Search,
+ Sort: input.Sort,
+ Order: input.Order,
+ Severity: input.Severity,
+ ImageName: input.ImageName,
+ Ignored: input.Ignored,
+ }).queryParamsInternal()
+ items, err := h.vulnerabilityService.ExportVulnerabilities(ctx, input.EnvironmentID, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to export vulnerabilities").Error())
+ }
+ filename := fmt.Sprintf("vulnerabilities-%s-%s.csv", input.EnvironmentID, time.Now().UTC().Format("2006-01-02T15-04-05Z"))
+
+ return &huma.StreamResponse{
+ Body: func(humaCtx huma.Context) {
+ humaCtx.SetHeader("Content-Type", "text/csv; charset=utf-8")
+ humaCtx.SetHeader("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
+ if err := WriteVulnerabilitiesCSV(humaCtx.BodyWriter(), items); err != nil {
+ slog.ErrorContext(ctx, "failed to stream vulnerability export", "error", err)
+ }
+ },
+ }, nil
+}
+
// ListAllVulnerabilityImageOptions returns available image options for vulnerability filtering.
func (h *VulnerabilityHandler) ListAllVulnerabilityImageOptions(ctx context.Context, input *ListAllVulnerabilityImageOptionsInput) (*handlerutil.Out[[]string], error) {
items, err := h.vulnerabilityService.ListAllVulnerabilityImageOptions(ctx, input.Severity)
diff --git a/backend/internal/vulnerability/vulnerability_export.go b/backend/internal/vulnerability/vulnerability_export.go
new file mode 100644
index 000000000..67989bf6b
--- /dev/null
+++ b/backend/internal/vulnerability/vulnerability_export.go
@@ -0,0 +1,51 @@
+package vulnerability
+
+import (
+ "encoding/csv"
+ "io"
+ "iter"
+ "strconv"
+ "strings"
+
+ "emperror.dev/errors"
+ "github.com/getarcaneapp/arcane/types/v2/vulnerability"
+)
+
+var vulnerabilityCSVHeaderInternal = []string{"CVE", "Severity", "Package", "Installed Version", "Fixed Version", "Image", "Ignored"}
+
+// WriteVulnerabilitiesCSV streams items to w as a BOM-prefixed, CRLF-terminated CSV with formula-safe cells.
+func WriteVulnerabilitiesCSV(w io.Writer, items iter.Seq2[vulnerability.VulnerabilityWithImage, error]) error {
+ if _, err := io.WriteString(w, "\xEF\xBB\xBF"); err != nil {
+ return errors.WrapIf(err, "failed to write csv")
+ }
+ writer := csv.NewWriter(w)
+ writer.UseCRLF = true
+ if err := writer.Write(vulnerabilityCSVHeaderInternal); err != nil {
+ return errors.WrapIf(err, "failed to write csv")
+ }
+ for item, err := range items {
+ if err != nil {
+ return err
+ }
+ image := item.ImageName
+ if image == "" {
+ image = item.ImageID
+ }
+ record := []string{item.VulnerabilityID, string(item.Severity), item.PkgName, item.InstalledVersion, item.FixedVersion, image, strconv.FormatBool(item.Ignored)}
+ for j, value := range record {
+ record[j] = csvCellInternal(value)
+ }
+ if err := writer.Write(record); err != nil {
+ return errors.WrapIf(err, "failed to write csv")
+ }
+ }
+ writer.Flush()
+ return errors.WrapIf(writer.Error(), "failed to write csv")
+}
+
+func csvCellInternal(value string) string {
+ if value != "" && strings.ContainsRune("=+-@\t\r", rune(value[0])) {
+ return "'" + value
+ }
+ return value
+}
diff --git a/backend/internal/vulnerability/vulnerability_export_test.go b/backend/internal/vulnerability/vulnerability_export_test.go
new file mode 100644
index 000000000..1cb81f98d
--- /dev/null
+++ b/backend/internal/vulnerability/vulnerability_export_test.go
@@ -0,0 +1,42 @@
+package vulnerability
+
+import (
+ "bytes"
+ "iter"
+ "testing"
+
+ "github.com/getarcaneapp/arcane/types/v2/vulnerability"
+ "github.com/stretchr/testify/require"
+)
+
+func TestWriteVulnerabilitiesCSV(t *testing.T) {
+ items := []vulnerability.VulnerabilityWithImage{
+ {Vulnerability: vulnerability.Vulnerability{VulnerabilityID: "CVE-2026-0001", PkgName: "openssl", InstalledVersion: "3.0.0", FixedVersion: "3.0.1", Severity: vulnerability.SeverityHigh}, ImageID: "img-1", ImageName: "example/security:latest"},
+ {Vulnerability: vulnerability.Vulnerability{VulnerabilityID: "CVE-2026-0002", PkgName: "libc, glibc", Severity: vulnerability.SeverityHigh}, ImageID: "sha256:fallback"},
+ {Vulnerability: vulnerability.Vulnerability{VulnerabilityID: "CVE-2026-0003", PkgName: `pkg "quoted"`, InstalledVersion: "ünïcødé", FixedVersion: "line1\nline2", Severity: vulnerability.SeverityHigh}, ImageID: "img-1", ImageName: "example/security:latest", Ignored: true},
+ {Vulnerability: vulnerability.Vulnerability{VulnerabilityID: `=HYPERLINK("https://evil.example")`, PkgName: "+sum", InstalledVersion: "-1", FixedVersion: "@cmd", Severity: vulnerability.SeverityHigh}, ImageID: "img-1", ImageName: "example/security:latest"},
+ }
+
+ var buf bytes.Buffer
+ require.NoError(t, WriteVulnerabilitiesCSV(&buf, seqInternal(items)))
+ require.Equal(t, "\xEF\xBB\xBF"+
+ "CVE,Severity,Package,Installed Version,Fixed Version,Image,Ignored\r\n"+
+ "CVE-2026-0001,HIGH,openssl,3.0.0,3.0.1,example/security:latest,false\r\n"+
+ "CVE-2026-0002,HIGH,\"libc, glibc\",,,sha256:fallback,false\r\n"+
+ "CVE-2026-0003,HIGH,\"pkg \"\"quoted\"\"\",ünïcødé,\"line1\r\nline2\",example/security:latest,true\r\n"+
+ "\"'=HYPERLINK(\"\"https://evil.example\"\")\",HIGH,'+sum,'-1,'@cmd,example/security:latest,false\r\n", buf.String())
+
+ buf.Reset()
+ require.NoError(t, WriteVulnerabilitiesCSV(&buf, seqInternal(nil)))
+ require.Equal(t, "\xEF\xBB\xBFCVE,Severity,Package,Installed Version,Fixed Version,Image,Ignored\r\n", buf.String())
+}
+
+func seqInternal(items []vulnerability.VulnerabilityWithImage) iter.Seq2[vulnerability.VulnerabilityWithImage, error] {
+ return func(yield func(vulnerability.VulnerabilityWithImage, error) bool) {
+ for _, item := range items {
+ if !yield(item, nil) {
+ return
+ }
+ }
+ }
+}
diff --git a/backend/internal/vulnerability/vulnerability_query.go b/backend/internal/vulnerability/vulnerability_query.go
index 20798b19b..f014ee72f 100644
--- a/backend/internal/vulnerability/vulnerability_query.go
+++ b/backend/internal/vulnerability/vulnerability_query.go
@@ -3,6 +3,7 @@ package vulnerability
import (
"context"
"encoding/json/v2"
+ "iter"
"log/slog"
"sort"
"strings"
@@ -299,16 +300,25 @@ var listAllVulnerabilitySortColumnsInternal = map[string]string{
"imageName": "vulnerability_scans.image_name",
}
-// ListAllVulnerabilities returns a paginated list of vulnerabilities across all scanned images.
-func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envID string, params pagination.QueryParams) ([]vulnerability.VulnerabilityWithImage, pagination.Response, error) {
- if params.Limit == 0 {
- params.Limit = 20
- }
-
- if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) || s.db == nil {
- return []vulnerability.VulnerabilityWithImage{}, pagination.BuildResponse(0, 0, params), nil
+func (row *vulnerabilityScanItemRowInternal) toVulnerabilityWithImageInternal() vulnerability.VulnerabilityWithImage {
+ return vulnerability.VulnerabilityWithImage{
+ VulnerabilityID: row.VulnerabilityID,
+ PkgName: row.PkgName,
+ InstalledVersion: row.InstalledVersion,
+ FixedVersion: row.FixedVersion,
+ Severity: vulnerability.Severity(row.Severity),
+ Class: row.PkgClass,
+ Type: row.PkgType,
+ Title: row.Title,
+ Ignored: row.IgnoreID != "",
+ IgnoreID: row.IgnoreID,
+ ImageID: row.ImageID,
+ ImageName: row.ImageName,
}
+}
+// listAllVulnerabilitiesQueryInternal returns the base query used for counts and the filtered, ordered query; it clears params.Sort once ordering is applied.
+func (s *VulnerabilityService) listAllVulnerabilitiesQueryInternal(ctx context.Context, envID string, params *pagination.QueryParams) (*gorm.DB, *gorm.DB) {
// "ignored" flips the list from active to ignored vulnerabilities, the same
// way the projects list swaps to archived projects.
onlyIgnored := params.Filters["ignored"] == "true"
@@ -329,11 +339,6 @@ func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envID
}
base = base.Session(&gorm.Session{})
- var totalAvailable int64
- if err := base.Count(&totalAvailable).Error; err != nil {
- return nil, pagination.Response{}, errors.WrapIf(err, "failed to count vulnerabilities")
- }
-
q := pagination.ApplyFilter(base, "vulnerability_scan_items.severity", strings.ToUpper(params.Filters["severity"]))
if imageNameParts := splitNonEmptyCSVInternal(params.Filters["imageName"]); len(imageNameParts) > 0 {
clauses := make([]string, 0, len(imageNameParts))
@@ -351,6 +356,26 @@ func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envID
}
params.Sort = ""
+ return base, q
+}
+
+// ListAllVulnerabilities returns a paginated list of vulnerabilities across all scanned images.
+func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envID string, params pagination.QueryParams) ([]vulnerability.VulnerabilityWithImage, pagination.Response, error) {
+ if params.Limit == 0 {
+ params.Limit = 20
+ }
+
+ if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) || s.db == nil {
+ return []vulnerability.VulnerabilityWithImage{}, pagination.BuildResponse(0, 0, params), nil
+ }
+
+ base, q := s.listAllVulnerabilitiesQueryInternal(ctx, envID, &params)
+
+ var totalAvailable int64
+ if err := base.Count(&totalAvailable).Error; err != nil {
+ return nil, pagination.Response{}, errors.WrapIf(err, "failed to count vulnerabilities")
+ }
+
var rows []vulnerabilityScanItemRowInternal
response, err := pagination.PaginateAndSortDB(params, q, &rows)
if err != nil {
@@ -361,20 +386,7 @@ func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envID
items := make([]vulnerability.VulnerabilityWithImage, 0, len(rows))
for i := range rows {
row := &rows[i]
- item := vulnerability.VulnerabilityWithImage{
- VulnerabilityID: row.VulnerabilityID,
- PkgName: row.PkgName,
- InstalledVersion: row.InstalledVersion,
- FixedVersion: row.FixedVersion,
- Severity: vulnerability.Severity(row.Severity),
- Class: row.PkgClass,
- Type: row.PkgType,
- Title: row.Title,
- Ignored: row.IgnoreID != "",
- IgnoreID: row.IgnoreID,
- ImageID: row.ImageID,
- ImageName: row.ImageName,
- }
+ item := row.toVulnerabilityWithImageInternal()
if row.Details != nil && *row.Details != "" {
var details vulnerabilityScanItemDetailsInternal
if err := json.Unmarshal([]byte(*row.Details), &details); err == nil {
@@ -391,6 +403,41 @@ func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envID
return items, response, nil
}
+// ExportVulnerabilities opens a cursor over every vulnerability matching params and yields rows one at a time in the requested order.
+func (s *VulnerabilityService) ExportVulnerabilities(ctx context.Context, envID string, params pagination.QueryParams) (iter.Seq2[vulnerability.VulnerabilityWithImage, error], error) {
+ if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) || s.db == nil {
+ return func(func(vulnerability.VulnerabilityWithImage, error) bool) {}, nil
+ }
+
+ _, q := s.listAllVulnerabilitiesQueryInternal(ctx, envID, &params)
+ rows, err := q.Rows()
+ if err != nil {
+ return nil, errors.WrapIf(err, "failed to export vulnerabilities")
+ }
+
+ return func(yield func(vulnerability.VulnerabilityWithImage, error) bool) {
+ defer func() {
+ if closeErr := rows.Close(); closeErr != nil {
+ slog.WarnContext(ctx, "failed to close vulnerability export cursor", "error", closeErr)
+ }
+ }()
+
+ for rows.Next() {
+ var row vulnerabilityScanItemRowInternal
+ if err := q.ScanRows(rows, &row); err != nil {
+ yield(vulnerability.VulnerabilityWithImage{}, errors.WrapIf(err, "failed to export vulnerabilities"))
+ return
+ }
+ if !yield(row.toVulnerabilityWithImageInternal(), nil) {
+ return
+ }
+ }
+ if err := rows.Err(); err != nil {
+ yield(vulnerability.VulnerabilityWithImage{}, errors.WrapIf(err, "failed to export vulnerabilities"))
+ }
+ }, nil
+}
+
// listAllVulnerabilityRecordBatchSizeInternal bounds how many scan records
// (each carrying a vulnerability blob of up to ~2 MiB) the backfill loads at once.
const listAllVulnerabilityRecordBatchSizeInternal = 25
diff --git a/backend/pkg/libarcane/edge/commands.go b/backend/pkg/libarcane/edge/commands.go
index d9b17c8ba..079e1fae5 100644
--- a/backend/pkg/libarcane/edge/commands.go
+++ b/backend/pkg/libarcane/edge/commands.go
@@ -70,6 +70,7 @@ var commandRoutes = []commandRoute{
{Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/scanner-status", CommandName: "vulnerability.scanner_status"},
{Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/summary", CommandName: "vulnerability.summary"},
{Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/all", CommandName: "vulnerability.all"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/export", CommandName: "vulnerability.export"},
{Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/image-options", CommandName: "vulnerability.image_options"},
{Method: http.MethodPost, PathPattern: "/api/environments/{id}/vulnerabilities/ignore", CommandName: "vulnerability.ignore.create"},
{Method: http.MethodDelete, PathPattern: "/api/environments/{id}/vulnerabilities/ignore/{ignoreId}", CommandName: "vulnerability.ignore.delete"},
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 8a3cc9dcb..0af85253c 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -849,6 +849,9 @@
"security_local_image_unpatchable": "Locally built image — rebuild it to update its packages",
"vuln_show_ignored": "Show ignored",
"vuln_ignored_badge": "Ignored",
+ "vuln_export_csv": "Export CSV",
+ "vuln_exporting": "Exporting…",
+ "vuln_export_failed": "Failed to export vulnerabilities",
"security_patched_ref": "Patched Tag",
"security_fixable_after_patch": "{count} fixable",
"security_verify_scan_pending": "Verifying…",
diff --git a/frontend/src/lib/services/vulnerability-service.ts b/frontend/src/lib/services/vulnerability-service.ts
index 66a73705d..d9501053f 100644
--- a/frontend/src/lib/services/vulnerability-service.ts
+++ b/frontend/src/lib/services/vulnerability-service.ts
@@ -14,6 +14,7 @@ import type {
} from '#lib/types/environment.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import { transformPaginationParams } from '#lib/utils/tables.js';
+import { filenameFromContentDisposition } from '#lib/utils/browser-download.js';
class VulnerabilityService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
@@ -104,6 +105,18 @@ class VulnerabilityService extends BaseAPIService {
return res.data;
}
+ async exportVulnerabilitiesForEnvironment(
+ environmentId: string,
+ options?: SearchPaginationSortRequest
+ ): Promise<{ blob: Blob; filename: string }> {
+ const params = transformPaginationParams(options);
+ const res = await this.api.get(`/environments/${environmentId}/vulnerabilities/export`, { params, responseType: 'blob' });
+ return {
+ blob: res.data,
+ filename: filenameFromContentDisposition(res.headers.get('content-disposition'), 'vulnerabilities.csv')
+ };
+ }
+
/**
* Get available image filter options for environment vulnerabilities.
* This endpoint is independent from rows pagination and currently supports severity-only filtering.
diff --git a/frontend/src/lib/utils/browser-download.ts b/frontend/src/lib/utils/browser-download.ts
index d8b1b4818..43f8e1997 100644
--- a/frontend/src/lib/utils/browser-download.ts
+++ b/frontend/src/lib/utils/browser-download.ts
@@ -12,3 +12,7 @@ export function downloadBlob(data: BlobPart, filename: string): void {
export function filenameFromPath(path: string, fallback = 'download'): string {
return path.split('/').pop() || fallback;
}
+
+export function filenameFromContentDisposition(header: string | null, fallback: string): string {
+ return /filename="?([^";]+)"?/.exec(header ?? '')?.[1] || fallback;
+}
diff --git a/frontend/src/lib/utils/vulnerability.ts b/frontend/src/lib/utils/vulnerability.ts
index c96553eb2..a506e4d0c 100644
--- a/frontend/src/lib/utils/vulnerability.ts
+++ b/frontend/src/lib/utils/vulnerability.ts
@@ -50,6 +50,13 @@ export function getSeverityIconVariant(severity: string): VulnerabilitySeverityI
return severityDisplay.get(severity)?.icon ?? 'gray';
}
+export function withIgnoredFilter(options: SearchPaginationSortRequest, showIgnored: boolean): SearchPaginationSortRequest {
+ const filters = { ...options.filters };
+ if (showIgnored) filters['ignored'] = 'true';
+ else delete filters['ignored'];
+ return { ...options, filters: Object.keys(filters).length ? filters : undefined };
+}
+
export function mapVulnerabilityRequest(options: SearchPaginationSortRequest): SearchPaginationSortRequest {
const filters = { ...(options.filters ?? {}) };
if (filters['vulnSeverity']) {
diff --git a/frontend/src/routes/(app)/security/+page.svelte b/frontend/src/routes/(app)/security/+page.svelte
index f4b63b65e..5f69b7502 100644
--- a/frontend/src/routes/(app)/security/+page.svelte
+++ b/frontend/src/routes/(app)/security/+page.svelte
@@ -22,7 +22,7 @@
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { activityStore } from '#lib/stores/activity.store.svelte.js';
import { hasPermission } from '#lib/utils/auth.js';
- import { mapVulnerabilityPage, mapVulnerabilityRequest } from '#lib/utils/vulnerability.js';
+ import { mapVulnerabilityPage, mapVulnerabilityRequest, withIgnoredFilter } from '#lib/utils/vulnerability.js';
import { useUrlTab } from '#lib/hooks/use-url-tab.svelte.js';
let { data } = $props();
@@ -35,20 +35,6 @@
let requestOptions = $derived<SearchPaginationSortRequest>(data.vulnerabilityRequestOptions);
let showIgnored = $state(false);
- function withIgnoredFilter(options: SearchPaginationSortRequest, show: boolean): SearchPaginationSortRequest {
- const filters = { ...options.filters };
- if (show) {
- filters['ignored'] = 'true';
- } else {
- delete filters['ignored'];
- }
-
- return {
- ...options,
- filters: Object.keys(filters).length > 0 ? filters : undefined
- };
- }
-
function toggleIgnored(next: boolean) {
showIgnored = next;
}
diff --git a/frontend/src/routes/(app)/security/security-vulnerability-table.svelte b/frontend/src/routes/(app)/security/security-vulnerability-table.svelte
index 3a25b7fee..463ae24ab 100644
--- a/frontend/src/routes/(app)/security/security-vulnerability-table.svelte
+++ b/frontend/src/routes/(app)/security/security-vulnerability-table.svelte
@@ -3,6 +3,7 @@
import { tryCatch } from '#lib/utils/try-catch.js';
import ArcaneTable from '#lib/components/arcane-table/arcane-table.svelte';
+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';
import RowActionsMenu from '#lib/components/arcane-table/row-actions-menu.svelte';
// Patching happens on the Patches tab, per image; CVE rows only inspect and ignore.
import * as DropdownMenu from '#lib/components/ui/dropdown-menu/index.js';
@@ -16,20 +17,22 @@
import type { ColumnSpec } from '#lib/components/arcane-table/arcane-table.types.svelte.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import type { VulnerabilityWithImage } from '#lib/types/environment.js';
- import { ShieldAlertIcon, CodeIcon, CheckIcon, ImagesIcon, EyeOffIcon, EyeOnIcon } from '#lib/icons/index.js';
+ import { ShieldAlertIcon, CodeIcon, CheckIcon, ImagesIcon, EyeOffIcon, EyeOnIcon, DownloadIcon } from '#lib/icons/index.js';
import { Switch } from '#lib/components/ui/switch/index.js';
import { Label } from '#lib/components/ui/label/index.js';
import { toast } from 'svelte-sonner';
import { onMount } from 'svelte';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { hasPermission } from '#lib/utils/auth.js';
+ import { downloadBlob } from '#lib/utils/browser-download.js';
import {
getSeverityBadgeVariant,
getSeverityIconVariant,
getSeverityLabel,
mapVulnerabilityPage,
mapVulnerabilityRequest,
- resolveSeverityFilter
+ resolveSeverityFilter,
+ withIgnoredFilter
} from '#lib/utils/vulnerability.js';
type VulnerabilityRow = VulnerabilityWithImage & { id: string };
@@ -47,18 +50,12 @@
} = $props();
let imageNameFilterOptions = $state<string[]>([]);
+ let mounted = true;
const currentEnvId = $derived(environmentStore.selected?.id || '0');
const vulnerabilityManagementEnabled = $derived(featureStore.isEnabled('vulnerabilityManagement', currentEnvId));
const canManageVuln = $derived(vulnerabilityManagementEnabled && hasPermission('vulnerabilities:manage', currentEnvId));
- // The table rebuilds requestOptions from its own filter state on every
- // refresh, so the switch is injected per request instead of stored there.
- function withIgnoredFilter(options: SearchPaginationSortRequest): SearchPaginationSortRequest {
- if (!showIgnored) return options;
- return { ...options, filters: { ...(options.filters ?? {}), ignored: 'true' } };
- }
-
async function handleUnignoreVulnerability(item: VulnerabilityRow) {
if (!canManageVuln) return;
const requestedEnvId = currentEnvId;
@@ -111,7 +108,7 @@
async function refreshVulnerabilityTable(options: SearchPaginationSortRequest) {
if (!vulnerabilityManagementEnabled) return vulnerabilities;
const requestedEnvId = currentEnvId;
- const request = mapVulnerabilityRequest(withIgnoredFilter(options));
+ const request = mapVulnerabilityRequest(withIgnoredFilter(options, showIgnored));
const [response, optionsResponse] = await Promise.all([
vulnerabilityService.getAllVulnerabilitiesForEnvironment(requestedEnvId, request),
@@ -128,6 +125,20 @@
return mapped;
}
+ async function handleExportCsv() {
+ if (!vulnerabilityManagementEnabled) return;
+ const requestedEnvId = currentEnvId;
+ const request = mapVulnerabilityRequest(withIgnoredFilter({ ...requestOptions, pagination: undefined }, showIgnored));
+ const operationResult = await tryCatch(vulnerabilityService.exportVulnerabilitiesForEnvironment(requestedEnvId, request));
+ if (!mounted || requestedEnvId !== currentEnvId) return;
+ if (operationResult.error !== null) {
+ console.error('Failed to export vulnerabilities:', operationResult.error);
+ toast.error(m.vuln_export_failed());
+ return;
+ }
+ downloadBlob(operationResult.data.blob, operationResult.data.filename);
+ }
+
async function handleIgnoreVulnerability(item: VulnerabilityRow) {
if (!canManageVuln) return;
const requestedEnvId = currentEnvId;
@@ -171,6 +182,9 @@
onMount(() => {
void refreshImageNameFilterOptions(requestOptions);
+ return () => {
+ mounted = false;
+ };
});
const mobileFields = [
@@ -279,21 +293,32 @@
</RowActionsMenu>
{/snippet}
-{#snippet IgnoredToolbarAction()}
- <div
- class="flex min-h-9 w-full items-center gap-2 rounded-md border border-border/60 bg-muted/30 px-2.5 py-1.5 md:w-auto md:border-0 md:bg-transparent md:px-1 md:py-0"
- >
- <Switch
- id="security-show-ignored"
- checked={showIgnored}
- onCheckedChange={async (checked) => {
- await onToggleIgnored?.(checked === true);
- await refreshVulnerabilityTable(requestOptions);
- }}
+{#snippet VulnerabilityToolbarActions()}
+ <div class="flex w-full flex-wrap items-center justify-end gap-2 md:w-auto">
+ <div
+ class="flex min-h-9 w-full items-center gap-2 rounded-md border border-border/60 bg-muted/30 px-2.5 py-1.5 md:w-auto md:border-0 md:bg-transparent md:px-1 md:py-0"
+ >
+ <Switch
+ id="security-show-ignored"
+ checked={showIgnored}
+ onCheckedChange={async (checked) => {
+ await onToggleIgnored?.(checked === true);
+ await refreshVulnerabilityTable(requestOptions);
+ }}
+ />
+ <Label for="security-show-ignored" class="mb-0 min-w-0 text-sm font-medium text-muted-foreground">
+ {m.vuln_show_ignored()}
+ </Label>
+ </div>
+ <ArcaneButton
+ action="base"
+ size="sm"
+ icon={DownloadIcon}
+ customLabel={m.vuln_export_csv()}
+ loadingLabel={m.vuln_exporting()}
+ onClickPromise={handleExportCsv}
+ class="h-9 shrink-0"
/>
- <Label for="security-show-ignored" class="mb-0 min-w-0 text-sm font-medium text-muted-foreground">
- {m.vuln_show_ignored()}
- </Label>
</div>
{/snippet}
@@ -307,6 +332,6 @@
persistKey="arcane-security-vuln-table"
selectionDisabled
{imageNameFilterOptions}
- customToolbarActions={IgnoredToolbarAction}
+ customToolbarActions={VulnerabilityToolbarActions}
rowActions={canManageVuln ? rowActions : undefined}
/>
diff --git a/tests/spec/security.spec.ts b/tests/spec/security.spec.ts
index c67657f37..e003c10e1 100644
--- a/tests/spec/security.spec.ts
+++ b/tests/spec/security.spec.ts
@@ -1,3 +1,4 @@
+import { readFile } from 'node:fs/promises';
import { test, expect, type Page } from '../fixtures/test.fixture';
import { openRowActionsMenu } from '../utils/table-actions.util';
@@ -23,6 +24,64 @@ function paginated<T>(data: T[]) {
};
}
+function vulnerabilityResponse(response: { url(): string; request(): { method(): string } }) {
+ const url = new URL(response.url());
+ return response.request().method() === 'GET' && url.pathname.endsWith('/vulnerabilities/all')
+ ? url.searchParams
+ : null;
+}
+
+async function mockSecurityPageData(page: Page, imageNames: string[]) {
+ await page.route(/\/api\/environments\/[^/]+\/vulnerabilities\/summary$/, async (route) => {
+ await route.fulfill({
+ json: {
+ success: true,
+ data: {
+ totalImages: 1,
+ scannedImages: 1,
+ summary: { critical: 0, high: 1, medium: 0, low: 0, unknown: 0, total: 1 }
+ }
+ }
+ });
+ });
+ await page.route(
+ /\/api\/environments\/[^/]+\/vulnerabilities\/image-options(?:\?.*)?$/,
+ async (route) => {
+ await route.fulfill({ json: { success: true, data: imageNames } });
+ }
+ );
+ await page.route(/\/api\/environments\/[^/]+\/images\/patch-targets(?:\?.*)?$/, async (route) => {
+ await route.fulfill({ json: paginated([]) });
+ });
+}
+
+const EXPORT_FILENAME = 'vulnerabilities-0-2026-09-13T10-00-00Z.csv';
+const EXPORT_BODY =
+ 'CVE,Severity,Package,Installed Version,Fixed Version,Image,Ignored\r\nCVE-2026-0001,HIGH,openssl,3.0.0,3.0.1,example/security:latest,false\r\n';
+
+function fulfillExport(route: { fulfill(options: object): Promise<void> }) {
+ return route.fulfill({
+ status: 200,
+ contentType: 'text/csv; charset=utf-8',
+ headers: { 'content-disposition': `attachment; filename="${EXPORT_FILENAME}"` },
+ body: EXPORT_BODY
+ });
+}
+
+function exportButton(page: Page) {
+ return page.getByRole('button', { name: /Export CSV/ });
+}
+
+async function exportCsv(page: Page) {
+ const downloadPromise = page.waitForEvent('download');
+ await exportButton(page).click();
+ const download = await downloadPromise;
+ expect(download.suggestedFilename()).toBe(EXPORT_FILENAME);
+ const path = await download.path();
+ if (!path) throw new Error('Download did not produce a file');
+ return readFile(path, 'utf8');
+}
+
test.describe('Security Page', () => {
test('redirects the old vulnerabilities URL to the security page', async ({ page }) => {
await page.goto(ROUTES.legacyVulnerabilities);
@@ -199,6 +258,259 @@ test.describe('Security Page', () => {
expect(unignoreRequestCount).toBe(1);
});
+ test('exports every matching vulnerability from any page through the backend', async ({
+ page
+ }) => {
+ const image = 'example/security:latest';
+ const rows = ['CVE-2026-0001', 'CVE-2026-0002', 'CVE-2026-0003', 'CVE-2026-0004'].map(
+ (vulnerabilityId) => ({
+ vulnerabilityId,
+ pkgName: 'openssl',
+ installedVersion: '3.0.0',
+ fixedVersion: '3.0.1',
+ severity: 'HIGH',
+ imageId: 'security-image',
+ imageName: image
+ })
+ );
+ const listRequests: URLSearchParams[] = [];
+ const exportRequests: URLSearchParams[] = [];
+
+ await mockSecurityPageData(page, [image]);
+ await page.route(/\/api\/environments\/0\/vulnerabilities\/all(?:\?.*)?$/, async (route) => {
+ const params = new URL(route.request().url()).searchParams;
+ listRequests.push(params);
+ const secondPage = params.get('start') === '20';
+ await route.fulfill({
+ json: {
+ data: secondPage ? rows.slice(2) : rows.slice(0, 2),
+ pagination: {
+ totalPages: 2,
+ totalItems: 22,
+ currentPage: secondPage ? 2 : 1,
+ itemsPerPage: 20
+ }
+ }
+ });
+ });
+ await page.route(/\/api\/environments\/0\/vulnerabilities\/export(?:\?.*)?$/, async (route) => {
+ exportRequests.push(new URL(route.request().url()).searchParams);
+ await fulfillExport(route);
+ });
+
+ await navigateToSecurity(page);
+ const panel = page.getByRole('tabpanel', { name: 'Vulnerabilities' });
+ await expect(page.getByRole('row').filter({ hasText: 'CVE-2026-0001' })).toBeVisible();
+
+ const tableRequest = (matches: (params: URLSearchParams) => boolean) =>
+ page.waitForResponse((response) => {
+ const params = vulnerabilityResponse(response);
+ return params !== null && matches(params);
+ });
+
+ let refreshed = tableRequest((params) => params.get('search') === 'openssl');
+ await panel.getByPlaceholder('Search…').fill('openssl');
+ await refreshed;
+
+ refreshed = tableRequest((params) => params.get('severity') === 'HIGH');
+ await panel.getByTestId('facet-severity-trigger').click();
+ await page.getByTestId('facet-severity-option-HIGH').click();
+ await refreshed;
+ await page.keyboard.press('Escape');
+
+ refreshed = tableRequest((params) => params.get('imageName') === image);
+ await panel.getByTestId('facet-image-trigger').click();
+ await page.getByTestId(`facet-image-option-${image}`).click();
+ await refreshed;
+ await page.keyboard.press('Escape');
+
+ refreshed = tableRequest(
+ (params) => params.get('sort') === 'imageName' && params.get('order') === 'desc'
+ );
+ await panel.getByRole('columnheader', { name: 'Image' }).getByRole('button').click();
+ await page.getByRole('menuitem', { name: 'Desc', exact: true }).click();
+ await refreshed;
+
+ refreshed = tableRequest((params) => params.get('start') === '20');
+ await panel.getByRole('button', { name: 'Go to next page', exact: true }).click();
+ await refreshed;
+ await expect(page.getByRole('row').filter({ hasText: 'CVE-2026-0003' })).toBeVisible();
+
+ const listRequestsBeforeExport = listRequests.length;
+ const content = await exportCsv(page);
+
+ expect(content).toBe(EXPORT_BODY);
+ expect(exportRequests).toHaveLength(1);
+ expect(Object.fromEntries(exportRequests[0])).toEqual({
+ search: 'openssl',
+ severity: 'HIGH',
+ imageName: image,
+ sort: 'imageName',
+ order: 'desc'
+ });
+
+ await expect(page.getByRole('row').filter({ hasText: 'CVE-2026-0003' })).toBeVisible();
+ await expect(page.getByRole('row').filter({ hasText: 'CVE-2026-0001' })).toHaveCount(0);
+ await expect(panel.getByPlaceholder('Search…')).toHaveValue('openssl');
+ expect(listRequests).toHaveLength(listRequestsBeforeExport);
+ });
+
+ test('exports only ignored vulnerabilities when the ignored switch is on', async ({ page }) => {
+ let exportRequest: URLSearchParams | undefined;
+
+ await mockSecurityPageData(page, []);
+ await page.route(/\/api\/environments\/0\/vulnerabilities\/all(?:\?.*)?$/, async (route) => {
+ await route.fulfill({ json: paginated([]) });
+ });
+ await page.route(/\/api\/environments\/0\/vulnerabilities\/export(?:\?.*)?$/, async (route) => {
+ exportRequest = new URL(route.request().url()).searchParams;
+ await fulfillExport(route);
+ });
+
+ await navigateToSecurity(page);
+ const ignoredResponse = page.waitForResponse(
+ (response) => vulnerabilityResponse(response)?.get('ignored') === 'true'
+ );
+ await page.getByRole('switch', { name: 'Show ignored' }).click();
+ await ignoredResponse;
+
+ await exportCsv(page);
+ expect(exportRequest?.get('ignored')).toBe('true');
+ expect(exportRequest?.has('start')).toBe(false);
+ expect(exportRequest?.has('limit')).toBe(false);
+ });
+
+ test('blocks duplicate exports and recovers after a failed export', async ({ page }) => {
+ let exportRequests = 0;
+ let mode: 'hold' | 'fail' | 'ok' = 'hold';
+ let releaseExport = () => {};
+ const held = new Promise<void>((resolve) => {
+ releaseExport = resolve;
+ });
+
+ await mockSecurityPageData(page, []);
+ await page.route(/\/api\/environments\/0\/vulnerabilities\/all(?:\?.*)?$/, async (route) => {
+ await route.fulfill({ json: paginated([]) });
+ });
+ await page.route(/\/api\/environments\/0\/vulnerabilities\/export(?:\?.*)?$/, async (route) => {
+ exportRequests += 1;
+ if (mode === 'hold') await held;
+ if (mode === 'fail') {
+ await route.fulfill({ status: 500, json: { message: 'export unavailable' } });
+ return;
+ }
+ await fulfillExport(route);
+ });
+
+ await navigateToSecurity(page);
+ const button = exportButton(page);
+ await expect(button).toBeEnabled();
+
+ const firstDownload = page.waitForEvent('download');
+ await button.click();
+ await expect(button).toBeDisabled();
+ await button.click({ force: true, timeout: 1000 }).catch(() => undefined);
+ releaseExport();
+ await firstDownload;
+ await expect(button).toBeEnabled();
+ expect(exportRequests).toBe(1);
+
+ mode = 'fail';
+ await button.click();
+ await expect(page.getByText('Failed to export vulnerabilities', { exact: true })).toBeVisible();
+ await expect(button).toBeEnabled();
+
+ mode = 'ok';
+ await exportCsv(page);
+ });
+
+ test('discards an export that finishes after switching environments', async ({ page }) => {
+ const localEnvironment = {
+ id: '0',
+ name: 'Local Test',
+ apiUrl: 'unix:///var/run/docker.sock',
+ status: 'online',
+ enabled: true,
+ isEdge: false
+ };
+ const remoteEnvironment = {
+ id: 'remote-export-test',
+ name: 'Remote Test',
+ apiUrl: 'https://remote.example.invalid',
+ status: 'online',
+ enabled: true,
+ isEdge: false
+ };
+ let releaseExport = () => {};
+ const held = new Promise<void>((resolve) => {
+ releaseExport = resolve;
+ });
+
+ await page.addInitScript(() => {
+ localStorage.removeItem('selectedEnvironmentId');
+ });
+ await page.route(/\/api\/environments(?:\?.*)?$/, async (route) => {
+ await route.fulfill({ json: paginated([localEnvironment, remoteEnvironment]) });
+ });
+ await page.route(/\/api\/stream(?:\?.*)?$/, async (route) => {
+ const channels =
+ new URL(route.request().url()).searchParams.get('channels')?.split(',') ?? [];
+ const timestamp = new Date().toISOString();
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/x-json-stream',
+ body: channels.includes('environments')
+ ? `${JSON.stringify({
+ channel: 'environments',
+ environment: {
+ type: 'snapshot',
+ environments: [localEnvironment, remoteEnvironment],
+ timestamp
+ },
+ timestamp
+ })}\n`
+ : ''
+ });
+ });
+ await page.route(
+ /\/api\/environments\/remote-export-test\/settings(?:\/public)?$/,
+ async (route) => {
+ await route.fulfill({
+ json: [{ key: 'featureVulnerabilityManagementEnabled', value: 'true' }]
+ });
+ }
+ );
+ await mockSecurityPageData(page, []);
+ await page.route(
+ /\/api\/environments\/[^/]+\/vulnerabilities\/all(?:\?.*)?$/,
+ async (route) => {
+ await route.fulfill({ json: paginated([]) });
+ }
+ );
+ await page.route(/\/api\/environments\/0\/vulnerabilities\/export(?:\?.*)?$/, async (route) => {
+ await held;
+ await fulfillExport(route);
+ });
+
+ await navigateToSecurity(page);
+ await exportButton(page).click();
+
+ await page.getByRole('button').filter({ hasText: localEnvironment.name }).first().click();
+ const dialog = page.getByRole('dialog', { name: 'Select Environment' });
+ await expect(dialog).toBeVisible();
+ await dialog.getByRole('button').filter({ hasText: remoteEnvironment.name }).first().click();
+ await expect(
+ page.getByRole('button').filter({ hasText: remoteEnvironment.name }).first()
+ ).toBeVisible();
+
+ releaseExport();
+ const download = await page.waitForEvent('download', { timeout: 1500 }).catch(() => null);
+ expect(download).toBeNull();
+ await expect(page.getByText('Failed to export vulnerabilities', { exact: true })).toHaveCount(
+ 0
+ );
+ });
+
test('starts a valid image patch and explains disabled patch actions', async ({ page }) => {
const now = new Date().toISOString();
let patchPayload: unknown;