Skip to content

Modern Docker Management, Designed for Everyone

feat: bulk ignore and restore for vulnerability findings (#4158)

Kyle Mendell8dd49f1ac48b
diff --git a/backend/internal/vulnerability/handler.go b/backend/internal/vulnerability/handler.go
index 7f526c111..0115af13b 100644
--- a/backend/internal/vulnerability/handler.go
+++ b/backend/internal/vulnerability/handler.go
@@ -261,6 +261,28 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *VulnerabilityServ
Security: handlerutil.DefaultOperationSecurity(),
}, authz.PermVulnsManage, h.UnignoreVulnerability)
+ middleware.RegisterWithPermission(api, huma.Operation{
+ Middlewares: featureMiddleware,
+ OperationID: "bulk-ignore-vulnerabilities",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/vulnerabilities/ignore/bulk",
+ Summary: "Ignore vulnerabilities in bulk",
+ Description: "Creates ignore records for every active vulnerability matching the given filters",
+ Tags: []string{"Vulnerabilities"},
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, authz.PermVulnsManage, h.BulkIgnoreVulnerabilities)
+
+ middleware.RegisterWithPermission(api, huma.Operation{
+ Middlewares: featureMiddleware,
+ OperationID: "bulk-unignore-vulnerabilities",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/vulnerabilities/unignore/bulk",
+ Summary: "Restore ignored vulnerabilities in bulk",
+ Description: "Removes every ignore record matching the given filters",
+ Tags: []string{"Vulnerabilities"},
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, authz.PermVulnsManage, h.BulkUnignoreVulnerabilities)
+
middleware.RegisterWithPermission(api, huma.Operation{
Middlewares: featureMiddleware,
OperationID: "list-ignored-vulnerabilities",
@@ -583,6 +605,47 @@ func (h *VulnerabilityHandler) UnignoreVulnerability(ctx context.Context, input
}, nil
}
+// BulkIgnoreVulnerabilitiesInput contains the environment and filters for a bulk ignore or restore request.
+type BulkIgnoreVulnerabilitiesInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body vulnerability.BulkVulnerabilityFilters
+}
+
+// BulkIgnoreVulnerabilities ignores every active vulnerability matching the filters for the acting user.
+func (h *VulnerabilityHandler) BulkIgnoreVulnerabilities(ctx context.Context, input *BulkIgnoreVulnerabilitiesInput) (*handlerutil.Out[vulnerability.BulkIgnoreResponse], error) {
+ user, err := handlerutil.RequireUser(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ affected, err := h.vulnerabilityService.BulkIgnoreVulnerabilities(ctx, input.EnvironmentID, &input.Body, user.ID)
+ if err != nil {
+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to ignore vulnerabilities").Error())
+ }
+
+ return &handlerutil.Out[vulnerability.BulkIgnoreResponse]{
+ Body: base.ApiResponse[vulnerability.BulkIgnoreResponse]{
+ Success: true,
+ Data: vulnerability.BulkIgnoreResponse{AffectedCount: affected},
+ },
+ }, nil
+}
+
+// BulkUnignoreVulnerabilities restores every ignored vulnerability matching the filters.
+func (h *VulnerabilityHandler) BulkUnignoreVulnerabilities(ctx context.Context, input *BulkIgnoreVulnerabilitiesInput) (*handlerutil.Out[vulnerability.BulkIgnoreResponse], error) {
+ affected, err := h.vulnerabilityService.BulkUnignoreVulnerabilities(ctx, input.EnvironmentID, &input.Body)
+ if err != nil {
+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to restore vulnerabilities").Error())
+ }
+
+ return &handlerutil.Out[vulnerability.BulkIgnoreResponse]{
+ Body: base.ApiResponse[vulnerability.BulkIgnoreResponse]{
+ Success: true,
+ Data: vulnerability.BulkIgnoreResponse{AffectedCount: affected},
+ },
+ }, nil
+}
+
type ListIgnoredVulnerabilitiesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
diff --git a/backend/internal/vulnerability/vulnerability_ignores.go b/backend/internal/vulnerability/vulnerability_ignores.go
index 9304b36d7..8892175c9 100644
--- a/backend/internal/vulnerability/vulnerability_ignores.go
+++ b/backend/internal/vulnerability/vulnerability_ignores.go
@@ -3,6 +3,7 @@ package vulnerability
import (
"context"
"log/slog"
+ "slices"
"strings"
"emperror.dev/errors"
@@ -10,6 +11,7 @@ import (
"gorm.io/gorm"
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil"
"github.com/getarcaneapp/arcane/types/v2/vulnerability"
)
@@ -96,25 +98,122 @@ func (s *VulnerabilityService) IgnoreVulnerability(ctx context.Context, envID st
return ignore, nil
}
-// UnignoreVulnerability removes an ignore record
+// UnignoreVulnerability removes an ignore record together with any duplicates of its identity, so a finding never stays ignored after a restore.
func (s *VulnerabilityService) UnignoreVulnerability(ctx context.Context, envID string, ignoreID string) error {
if s.db == nil {
return errors.New("database not available")
}
- result := s.db.WithContext(ctx).Where("id = ? AND environment_id = ?", ignoreID, envID).Delete(&VulnerabilityIgnore{})
- if result.Error != nil {
- return errors.WrapIf(result.Error, "failed to delete ignore record")
+ var ignore VulnerabilityIgnore
+ if err := s.db.WithContext(ctx).Where("id = ? AND environment_id = ?", ignoreID, envID).First(&ignore).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return errors.New("ignore record not found")
+ }
+ return errors.WrapIf(err, "failed to load ignore record")
}
- if result.RowsAffected == 0 {
- return errors.New("ignore record not found")
+ result := s.db.WithContext(ctx).Where(
+ "environment_id = ? AND image_id = ? AND vulnerability_id = ? AND pkg_name = ? AND installed_version = ?",
+ envID, ignore.ImageID, ignore.VulnerabilityID, ignore.PkgName, ignore.InstalledVersion,
+ ).Delete(&VulnerabilityIgnore{})
+ if result.Error != nil {
+ return errors.WrapIf(result.Error, "failed to delete ignore record")
}
slog.InfoContext(ctx, "vulnerability unignored", "ignore_id", ignoreID)
return nil
}
+// bulkIgnoreBatchSizeInternal bounds how many ignore rows one insert or delete statement carries.
+const bulkIgnoreBatchSizeInternal = 500
+
+// bulkFilterParamsInternal converts bulk filters into the list query params so matching follows the list and export rules.
+func bulkFilterParamsInternal(filters *vulnerability.BulkVulnerabilityFilters, onlyIgnored bool) pagination.QueryParams {
+ params := pagination.QueryParams{Search: filters.Search, Filters: map[string]string{}}
+ if filters.Severity != "" {
+ params.Filters["severity"] = filters.Severity
+ }
+ if filters.ImageName != "" {
+ params.Filters["imageName"] = filters.ImageName
+ }
+ if filters.FixAvailable {
+ params.Filters["fixAvailable"] = "true"
+ }
+ if onlyIgnored {
+ params.Filters["ignored"] = "true"
+ }
+ return params
+}
+
+// BulkIgnoreVulnerabilities ignores every active finding matching the filters inside one transaction and returns how many ignore records were created.
+func (s *VulnerabilityService) BulkIgnoreVulnerabilities(ctx context.Context, envID string, filters *vulnerability.BulkVulnerabilityFilters, createdBy string) (int, error) {
+ if s.db == nil {
+ return 0, errors.New("database not available")
+ }
+
+ var ignores []VulnerabilityIgnore
+ err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ params := bulkFilterParamsInternal(filters, false)
+ _, q := s.listAllVulnerabilitiesQueryInternal(ctx, tx, envID, &params)
+ var targets []VulnerabilityScanItem
+ if err := q.Distinct("vulnerability_scan_items.image_id", "vulnerability_scan_items.vulnerability_id", "vulnerability_scan_items.pkg_name", "vulnerability_scan_items.installed_version").Scan(&targets).Error; err != nil {
+ return errors.WrapIf(err, "failed to resolve vulnerabilities to ignore")
+ }
+ if len(targets) == 0 {
+ return nil
+ }
+ ignores = make([]VulnerabilityIgnore, 0, len(targets))
+ for _, target := range targets {
+ ignores = append(ignores, VulnerabilityIgnore{
+ EnvironmentID: envID,
+ ImageID: target.ImageID,
+ VulnerabilityID: target.VulnerabilityID,
+ PkgName: target.PkgName,
+ InstalledVersion: target.InstalledVersion,
+ CreatedBy: createdBy,
+ })
+ }
+ return errors.WrapIf(tx.CreateInBatches(&ignores, bulkIgnoreBatchSizeInternal).Error, "failed to create ignore records")
+ })
+ if err != nil {
+ return 0, err
+ }
+
+ slog.InfoContext(ctx, "vulnerabilities ignored in bulk", "environment_id", envID, "affected", len(ignores))
+ return len(ignores), nil
+}
+
+// BulkUnignoreVulnerabilities removes every ignore record matching the filters inside one transaction and returns how many were removed.
+func (s *VulnerabilityService) BulkUnignoreVulnerabilities(ctx context.Context, envID string, filters *vulnerability.BulkVulnerabilityFilters) (int, error) {
+ if s.db == nil {
+ return 0, errors.New("database not available")
+ }
+
+ var affected int64
+ err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ params := bulkFilterParamsInternal(filters, true)
+ _, q := s.listAllVulnerabilitiesQueryInternal(ctx, tx, envID, &params)
+ var ignoreIDs []string
+ if err := q.Distinct("vulnerability_ignores.id").Pluck("vulnerability_ignores.id", &ignoreIDs).Error; err != nil {
+ return errors.WrapIf(err, "failed to resolve ignored vulnerabilities to restore")
+ }
+ for batch := range slices.Chunk(ignoreIDs, bulkIgnoreBatchSizeInternal) {
+ result := tx.Where("environment_id = ? AND id IN ?", envID, batch).Delete(&VulnerabilityIgnore{})
+ if result.Error != nil {
+ return errors.WrapIf(result.Error, "failed to delete ignore records")
+ }
+ affected += result.RowsAffected
+ }
+ return nil
+ })
+ if err != nil {
+ return 0, err
+ }
+
+ slog.InfoContext(ctx, "vulnerabilities unignored in bulk", "environment_id", envID, "affected", affected)
+ return int(affected), nil
+}
+
func applyIgnoredVulnerabilitiesSort(query *gorm.DB, sort string) *gorm.DB {
if sort == "" {
return query.Order("created_at DESC")
diff --git a/backend/internal/vulnerability/vulnerability_ignores_test.go b/backend/internal/vulnerability/vulnerability_ignores_test.go
new file mode 100644
index 000000000..3f394dad3
--- /dev/null
+++ b/backend/internal/vulnerability/vulnerability_ignores_test.go
@@ -0,0 +1,116 @@
+package vulnerability
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ "github.com/getarcaneapp/arcane/types/v2/vulnerability"
+ "github.com/stretchr/testify/require"
+)
+
+// seedBulkIgnoreFixtureInternal stores nginx with 45 findings (more than one page) and redis with three findings covering every filter dimension.
+func seedBulkIgnoreFixtureInternal(t *testing.T, db *database.DB, svc *VulnerabilityService) {
+ t.Helper()
+ nginx := make([]vulnerability.Vulnerability, 0, 45)
+ for i := range 45 {
+ severity := vulnerability.SeverityLow
+ if i%3 == 0 {
+ severity = vulnerability.SeverityHigh
+ }
+ fixed := ""
+ if i%2 == 0 {
+ fixed = "2.0.0"
+ }
+ nginx = append(nginx, vulnerability.Vulnerability{VulnerabilityID: fmt.Sprintf("CVE-N-%03d", i), PkgName: "libnginx", InstalledVersion: "1.0.0", FixedVersion: fixed, Severity: severity, Title: "nginx finding"})
+ }
+ redis := []vulnerability.Vulnerability{
+ {VulnerabilityID: "CVE-R-1", PkgName: "openssl", InstalledVersion: "3.0.0", FixedVersion: "3.0.1", Severity: vulnerability.SeverityCritical, Title: "openssl overflow"},
+ {VulnerabilityID: "CVE-R-2", PkgName: "zlib", InstalledVersion: "1.2.0", Severity: vulnerability.SeverityMedium, Title: "zlib bug"},
+ {VulnerabilityID: "CVE-R-3", PkgName: "curl", InstalledVersion: "8.0.0", FixedVersion: "8.0.1", Severity: vulnerability.SeverityHigh, Title: "curl issue"},
+ }
+ for _, image := range []struct {
+ id, name string
+ vulns []vulnerability.Vulnerability
+ critical int
+ high int
+ }{
+ {"sha256:nginx", "nginx:latest", nginx, 0, 15},
+ {"sha256:redis", "redis:7", redis, 1, 1},
+ } {
+ raw, err := json.Marshal(image.vulns)
+ require.NoError(t, err)
+ require.NoError(t, db.Create(&VulnerabilityScanRecord{
+ ID: image.id, ImageName: image.name, Status: ScanStatusCompleted, ScanTime: time.Now(),
+ CriticalCount: image.critical, HighCount: image.high, TotalCount: len(image.vulns),
+ Vulnerabilities: database.StringSlice{string(raw)},
+ }).Error)
+ }
+ svc.BackfillScanItems(context.Background())
+}
+
+func activeCountInternal(t *testing.T, svc *VulnerabilityService, envID string) int64 {
+ t.Helper()
+ _, page, err := svc.ListAllVulnerabilities(context.Background(), envID, pagination.QueryParams{Start: 0, Limit: 20})
+ require.NoError(t, err)
+ return page.TotalItems
+}
+
+func TestBulkIgnoreVulnerabilities_AllMatchingHonorsFilters(t *testing.T) {
+ ctx := context.Background()
+
+ for _, tc := range []struct {
+ name string
+ filters vulnerability.BulkVulnerabilityFilters
+ expected int
+ }{
+ {name: "no filters covers every page", expected: 48},
+ {name: "severity", filters: vulnerability.BulkVulnerabilityFilters{Severity: "critical,medium"}, expected: 2},
+ {name: "image name", filters: vulnerability.BulkVulnerabilityFilters{ImageName: "redis"}, expected: 3},
+ {name: "fix available", filters: vulnerability.BulkVulnerabilityFilters{FixAvailable: true}, expected: 25},
+ {name: "search", filters: vulnerability.BulkVulnerabilityFilters{Search: "openssl"}, expected: 1},
+ {name: "combined", filters: vulnerability.BulkVulnerabilityFilters{Severity: "high", ImageName: "nginx", FixAvailable: true, Search: "nginx finding"}, expected: 8},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ db := setupVulnerabilityScanTestDB(t)
+ svc := &VulnerabilityService{db: db}
+ seedBulkIgnoreFixtureInternal(t, db, svc)
+
+ before, err := svc.ActionableCountExcludingIgnored(ctx)
+ require.NoError(t, err)
+ require.Equal(t, 17, before)
+
+ affected, err := svc.BulkIgnoreVulnerabilities(ctx, "env-1", &tc.filters, "bob")
+ require.NoError(t, err)
+ require.Equal(t, tc.expected, affected)
+ require.EqualValues(t, 48-tc.expected, activeCountInternal(t, svc, "env-1"))
+ require.EqualValues(t, 48, activeCountInternal(t, svc, "env-2"), "other environments keep their own view")
+
+ var actionableIgnored int64
+ require.NoError(t, db.Model(&VulnerabilityIgnore{}).
+ Joins("JOIN vulnerability_scan_items ON vulnerability_scan_items.image_id = vulnerability_ignores.image_id AND vulnerability_scan_items.vulnerability_id = vulnerability_ignores.vulnerability_id AND vulnerability_scan_items.pkg_name = vulnerability_ignores.pkg_name AND vulnerability_scan_items.installed_version = vulnerability_ignores.installed_version").
+ Where("vulnerability_scan_items.severity IN ?", []string{"CRITICAL", "HIGH"}).
+ Count(&actionableIgnored).Error)
+ after, err := svc.ActionableCountExcludingIgnored(ctx)
+ require.NoError(t, err)
+ require.Equal(t, before-int(actionableIgnored), after)
+
+ // Repeating the request finds nothing left to ignore.
+ affected, err = svc.BulkIgnoreVulnerabilities(ctx, "env-1", &tc.filters, "bob")
+ require.NoError(t, err)
+ require.Zero(t, affected)
+
+ restored, err := svc.BulkUnignoreVulnerabilities(ctx, "env-1", &tc.filters)
+ require.NoError(t, err)
+ require.Equal(t, tc.expected, restored)
+ require.EqualValues(t, 48, activeCountInternal(t, svc, "env-1"))
+ after, err = svc.ActionableCountExcludingIgnored(ctx)
+ require.NoError(t, err)
+ require.Equal(t, before, after)
+ })
+ }
+}
diff --git a/backend/internal/vulnerability/vulnerability_query.go b/backend/internal/vulnerability/vulnerability_query.go
index ab29c546e..08a93bc7d 100644
--- a/backend/internal/vulnerability/vulnerability_query.go
+++ b/backend/internal/vulnerability/vulnerability_query.go
@@ -300,31 +300,14 @@ var listAllVulnerabilitySortColumnsInternal = map[string]string{
"imageName": "vulnerability_scans.image_name",
}
-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) {
+// listAllVulnerabilitiesQueryInternal returns the base query used for counts and the filtered, ordered query on db; it clears params.Sort once ordering is applied.
+func (s *VulnerabilityService) listAllVulnerabilitiesQueryInternal(ctx context.Context, db *gorm.DB, 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"
delete(params.Filters, "ignored")
- base := s.db.WithContext(ctx).
+ base := db.WithContext(ctx).
Model(&VulnerabilityScanItem{}).
Select("vulnerability_scan_items.*", "vulnerability_scans.image_name AS image_name", "COALESCE(vulnerability_ignores.id, '') AS ignore_id").
Joins("JOIN vulnerability_scans ON vulnerability_scans.id = vulnerability_scan_items.image_id AND vulnerability_scans.status = ?", ScanStatusCompleted).
@@ -372,7 +355,7 @@ func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envID
return []vulnerability.VulnerabilityWithImage{}, pagination.BuildResponse(0, 0, params), nil
}
- base, q := s.listAllVulnerabilitiesQueryInternal(ctx, envID, &params)
+ base, q := s.listAllVulnerabilitiesQueryInternal(ctx, s.db.DB, envID, &params)
var totalAvailable int64
if err := base.Count(&totalAvailable).Error; err != nil {
@@ -389,7 +372,20 @@ func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envID
items := make([]vulnerability.VulnerabilityWithImage, 0, len(rows))
for i := range rows {
row := &rows[i]
- item := row.toVulnerabilityWithImageInternal()
+ 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,
+ }
if row.Details != nil && *row.Details != "" {
var details vulnerabilityScanItemDetailsInternal
if err := json.Unmarshal([]byte(*row.Details), &details); err == nil {
@@ -412,7 +408,7 @@ func (s *VulnerabilityService) ExportVulnerabilities(ctx context.Context, envID
return func(func(vulnerability.VulnerabilityWithImage, error) bool) {}, nil
}
- _, q := s.listAllVulnerabilitiesQueryInternal(ctx, envID, &params)
+ _, q := s.listAllVulnerabilitiesQueryInternal(ctx, s.db.DB, envID, &params)
rows, err := q.Rows()
if err != nil {
return nil, errors.WrapIf(err, "failed to export vulnerabilities")
@@ -431,7 +427,21 @@ func (s *VulnerabilityService) ExportVulnerabilities(ctx context.Context, envID
yield(vulnerability.VulnerabilityWithImage{}, errors.WrapIf(err, "failed to export vulnerabilities"))
return
}
- if !yield(row.toVulnerabilityWithImageInternal(), nil) {
+ 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,
+ }
+ if !yield(item, nil) {
return
}
}
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 3b24cfcd1..ce4ea3053 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -882,6 +882,23 @@
"vuln_export_csv": "Export CSV",
"vuln_exporting": "Exporting…",
"vuln_export_failed": "Failed to export vulnerabilities",
+ "vuln_bulk_ignore_selected": "Ignore selected ({count})",
+ "vuln_bulk_ignore_all_matching": "Ignore all matching ({count})",
+ "vuln_bulk_restore_selected": "Restore selected ({count})",
+ "vuln_bulk_restore_all_matching": "Restore all matching ({count})",
+ "vuln_bulk_restore": "Restore",
+ "vuln_bulk_ignore_confirm_title": "Ignore {count} vulnerability(ies)",
+ "vuln_bulk_restore_confirm_title": "Restore {count} vulnerability(ies)",
+ "vuln_bulk_ignore_selected_confirm_message": "Ignore the {count} selected vulnerability(ies) in {environment}? Ignored findings leave the active list and the dashboard count; you can restore them from the ignored view.",
+ "vuln_bulk_ignore_all_matching_confirm_message": "Ignore all {count} vulnerability(ies) matching the current search and filters in {environment}? This covers every page, not only the rows shown here.",
+ "vuln_bulk_restore_selected_confirm_message": "Restore the {count} selected ignored vulnerability(ies) in {environment}? They return to the active list.",
+ "vuln_bulk_restore_all_matching_confirm_message": "Restore all {count} ignored vulnerability(ies) matching the current search and filters in {environment}? This covers every page, not only the rows shown here.",
+ "vuln_bulk_ignore_success": "Ignored {count} vulnerability(ies)",
+ "vuln_bulk_ignore_partial": "Ignored {success} of {total} vulnerability(ies). {failed} failed.",
+ "vuln_bulk_ignore_failed": "Failed to ignore vulnerabilities",
+ "vuln_bulk_restore_success": "Restored {count} vulnerability(ies)",
+ "vuln_bulk_restore_partial": "Restored {success} of {total} vulnerability(ies). {failed} failed.",
+ "vuln_bulk_restore_failed": "Failed to restore 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 d9501053f..94d4ffce2 100644
--- a/frontend/src/lib/services/vulnerability-service.ts
+++ b/frontend/src/lib/services/vulnerability-service.ts
@@ -10,7 +10,9 @@ import type {
VulnerabilityWithImage,
EnvironmentVulnerabilitySummary,
IgnoredVulnerability,
- IgnoreVulnerabilityPayload
+ IgnoreVulnerabilityPayload,
+ BulkVulnerabilityFilters,
+ BulkVulnerabilityActionResponse
} from '#lib/types/environment.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
import { transformPaginationParams } from '#lib/utils/tables.js';
@@ -156,6 +158,22 @@ class VulnerabilityService extends BaseAPIService {
await this.handleResponse(this.api.delete(`/environments/${envId}/vulnerabilities/ignore/${ignoreId}`));
}
+ async bulkIgnoreVulnerabilities(
+ filters: BulkVulnerabilityFilters,
+ environmentId?: string
+ ): Promise<BulkVulnerabilityActionResponse> {
+ const envId = await this.resolveEnvironmentId(environmentId);
+ return this.handleResponse(this.api.post(`/environments/${envId}/vulnerabilities/ignore/bulk`, filters));
+ }
+
+ async bulkUnignoreVulnerabilities(
+ filters: BulkVulnerabilityFilters,
+ environmentId?: string
+ ): Promise<BulkVulnerabilityActionResponse> {
+ const envId = await this.resolveEnvironmentId(environmentId);
+ return this.handleResponse(this.api.post(`/environments/${envId}/vulnerabilities/unignore/bulk`, filters));
+ }
+
/**
* Get a list of ignored vulnerabilities
*/
diff --git a/frontend/src/lib/types/environment.ts b/frontend/src/lib/types/environment.ts
index a0b6efc4f..3989cf2ae 100644
--- a/frontend/src/lib/types/environment.ts
+++ b/frontend/src/lib/types/environment.ts
@@ -213,3 +213,14 @@ export interface IgnoredVulnerability {
createdBy: string;
createdAt: string;
}
+
+export interface BulkVulnerabilityFilters {
+ search?: string;
+ severity?: string;
+ imageName?: string;
+ fixAvailable?: boolean;
+}
+
+export interface BulkVulnerabilityActionResponse {
+ affectedCount: number;
+}
diff --git a/frontend/src/lib/utils/vulnerability.ts b/frontend/src/lib/utils/vulnerability.ts
index 4b08ca6bc..9b0f8e6a9 100644
--- a/frontend/src/lib/utils/vulnerability.ts
+++ b/frontend/src/lib/utils/vulnerability.ts
@@ -1,5 +1,6 @@
import { m } from '#lib/paraglide/messages.js';
import type {
+ BulkVulnerabilityFilters,
SeveritySummary,
Vulnerability,
VulnerabilityScanResult,
@@ -78,6 +79,30 @@ export function mapVulnerabilityRequest(options: SearchPaginationSortRequest): S
};
}
+function joinFilterValue(value: unknown): string | undefined {
+ const joined = Array.isArray(value)
+ ? value
+ .map((entry) => String(entry).trim())
+ .filter(Boolean)
+ .join(',')
+ : String(value ?? '').trim();
+ return joined || undefined;
+}
+
+// Bulk "all matching" requests carry the list filters without pagination or sorting; the ignored toggle is chosen by the endpoint.
+export function toBulkVulnerabilityFilters(options: SearchPaginationSortRequest): BulkVulnerabilityFilters {
+ const request = mapVulnerabilityRequest(options);
+ const filters: BulkVulnerabilityFilters = {};
+ const search = request.search?.trim();
+ if (search) filters.search = search;
+ const severity = joinFilterValue(request.filters?.['severity']);
+ if (severity) filters.severity = severity;
+ const imageName = joinFilterValue(request.filters?.['imageName']);
+ if (imageName) filters.imageName = imageName;
+ if (request.filters?.['fixAvailable'] === 'true' || request.filters?.['fixAvailable'] === true) filters.fixAvailable = true;
+ return filters;
+}
+
function getVulnerabilityKey(vulnerability: VulnerabilityWithImage, index: number): string {
return [
vulnerability.imageId,
diff --git a/frontend/src/routes/(app)/security/+page.svelte b/frontend/src/routes/(app)/security/+page.svelte
index 49ad43a54..bc48e0fbb 100644
--- a/frontend/src/routes/(app)/security/+page.svelte
+++ b/frontend/src/routes/(app)/security/+page.svelte
@@ -33,6 +33,7 @@
let vulnerabilities = $derived<Paginated<VulnerabilityRow>>(data.vulnerabilities);
let requestOptions = $derived<SearchPaginationSortRequest>(data.vulnerabilityRequestOptions);
+ let selectedVulnerabilityIds = $state<string[]>([]);
let showIgnored = $state(false);
let fixAvailable = $state(false);
@@ -111,6 +112,7 @@
async function refreshAll() {
const requestedEnvId = currentEnvId;
+ selectedVulnerabilityIds = [];
if (displayedEnvId !== requestedEnvId) {
summary = null;
vulnerabilities = { data: [], pagination: { totalPages: 0, totalItems: 0, currentPage: 1, itemsPerPage: 20 } };
@@ -413,6 +415,7 @@
<SecurityVulnerabilityTable
bind:vulnerabilities
bind:requestOptions
+ bind:selectedIds={selectedVulnerabilityIds}
{showIgnored}
onToggleIgnored={toggleIgnored}
{fixAvailable}
diff --git a/frontend/src/routes/(app)/security/security-vulnerability-table.svelte b/frontend/src/routes/(app)/security/security-vulnerability-table.svelte
index 5a937fdec..d7d821379 100644
--- a/frontend/src/routes/(app)/security/security-vulnerability-table.svelte
+++ b/frontend/src/routes/(app)/security/security-vulnerability-table.svelte
@@ -14,14 +14,24 @@
import SeverityBadge from '#lib/components/vulnerability/severity-badge.svelte';
import { vulnerabilityService } from '#lib/services/vulnerability-service.js';
import { m } from '#lib/paraglide/messages.js';
- import type { ColumnSpec } from '#lib/components/arcane-table/arcane-table.types.svelte.js';
+ import type { BulkAction, 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, DownloadIcon } from '#lib/icons/index.js';
+ import {
+ ShieldAlertIcon,
+ CodeIcon,
+ CheckIcon,
+ ImagesIcon,
+ EyeOffIcon,
+ EyeOnIcon,
+ DownloadIcon,
+ LayersIcon
+ } 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 { handleApiResultWithCallbacks } from '#lib/utils/api.js';
+ import { bulkConfirmAndRun, confirmAndRun } from '#lib/utils/bulk-actions.js';
import { onMount } from 'svelte';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { hasPermission } from '#lib/utils/auth.js';
@@ -33,6 +43,7 @@
mapVulnerabilityPage,
mapVulnerabilityRequest,
resolveSeverityFilter,
+ toBulkVulnerabilityFilters,
withVulnerabilityToggles
} from '#lib/utils/vulnerability.js';
@@ -41,6 +52,7 @@
let {
vulnerabilities = $bindable(),
requestOptions = $bindable(),
+ selectedIds = $bindable([]),
showIgnored = false,
onToggleIgnored,
fixAvailable = false,
@@ -48,6 +60,7 @@
}: {
vulnerabilities: Paginated<VulnerabilityRow>;
requestOptions: SearchPaginationSortRequest;
+ selectedIds?: string[];
showIgnored?: boolean;
onToggleIgnored?: (checked: boolean) => void | Promise<void>;
fixAvailable?: boolean;
@@ -55,30 +68,148 @@
} = $props();
let imageNameFilterOptions = $state<string[]>([]);
+ let bulkInFlight = $state(false);
let mounted = true;
const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const currentEnvName = $derived(environmentStore.selected?.name || currentEnvId);
const vulnerabilityManagementEnabled = $derived(featureStore.isEnabled('vulnerabilityManagement', currentEnvId));
const canManageVuln = $derived(vulnerabilityManagementEnabled && hasPermission('vulnerabilities:manage', currentEnvId));
+ const matchingCount = $derived(vulnerabilities.pagination?.totalItems ?? vulnerabilities.data.length);
+
+ async function reloadFromFirstPage(requestedEnvId: string) {
+ if (requestedEnvId !== currentEnvId) return;
+ // The rows are already changed on the server; clear before refreshing so a failed reload cannot re-submit them.
+ selectedIds = [];
+ requestOptions = { ...requestOptions, pagination: { ...(requestOptions.pagination ?? { limit: 20 }), page: 1 } };
+ await handleApiResultWithCallbacks({
+ result: await tryCatch(refreshVulnerabilityTable(requestOptions)),
+ message: m.common_refresh_failed({ resource: m.vuln_title() })
+ });
+ }
+
+ function handleBulkSelected(ids: string[]) {
+ if (!canManageVuln) return;
+ const requestedEnvId = currentEnvId;
+ const restore = showIgnored;
+ const rows = new Map(vulnerabilities.data.map((row) => [row.id, row]));
+ const count = ids.length;
+ const environment = currentEnvName;
+ bulkConfirmAndRun({
+ ids,
+ title: restore ? m.vuln_bulk_restore_confirm_title({ count }) : m.vuln_bulk_ignore_confirm_title({ count }),
+ message: restore
+ ? m.vuln_bulk_restore_selected_confirm_message({ count, environment })
+ : m.vuln_bulk_ignore_selected_confirm_message({ count, environment }),
+ confirmLabel: restore ? m.vuln_bulk_restore() : m.common_ignore(),
+ run: async (id) => {
+ const row = rows.get(id);
+ if (!row) return;
+ if (restore) {
+ if (row.ignoreId) await vulnerabilityService.unignoreVulnerability(row.ignoreId, requestedEnvId);
+ return;
+ }
+ await vulnerabilityService.ignoreVulnerability(
+ {
+ imageId: row.imageId || '',
+ vulnerabilityId: row.vulnerabilityId || '',
+ pkgName: row.pkgName || '',
+ installedVersion: row.installedVersion || ''
+ },
+ requestedEnvId
+ );
+ },
+ messages: {
+ success: (n) => (restore ? m.vuln_bulk_restore_success({ count: n }) : m.vuln_bulk_ignore_success({ count: n })),
+ partial: (success, total, failed) =>
+ restore
+ ? m.vuln_bulk_restore_partial({ success, total, failed })
+ : m.vuln_bulk_ignore_partial({ success, total, failed }),
+ failure: () => (restore ? m.vuln_bulk_restore_failed() : m.vuln_bulk_ignore_failed())
+ },
+ setLoading: (loading) => (bulkInFlight = loading),
+ onComplete: async (result) => {
+ if (result.success > 0) await reloadFromFirstPage(requestedEnvId);
+ },
+ clearSelection: () => (selectedIds = [])
+ });
+ }
+
+ function handleBulkAllMatching() {
+ if (!canManageVuln) return;
+ const requestedEnvId = currentEnvId;
+ const restore = showIgnored;
+ const filters = toBulkVulnerabilityFilters(withVulnerabilityToggles(requestOptions, { showIgnored, fixAvailable }));
+ const count = matchingCount;
+ const environment = currentEnvName;
+ confirmAndRun({
+ title: restore ? m.vuln_bulk_restore_confirm_title({ count }) : m.vuln_bulk_ignore_confirm_title({ count }),
+ message: restore
+ ? m.vuln_bulk_restore_all_matching_confirm_message({ count, environment })
+ : m.vuln_bulk_ignore_all_matching_confirm_message({ count, environment }),
+ confirmLabel: restore ? m.vuln_bulk_restore() : m.common_ignore(),
+ setLoading: (loading) => (bulkInFlight = loading),
+ run: () =>
+ restore
+ ? vulnerabilityService.bulkUnignoreVulnerabilities(filters, requestedEnvId)
+ : vulnerabilityService.bulkIgnoreVulnerabilities(filters, requestedEnvId),
+ failureMessage: restore ? m.vuln_bulk_restore_failed() : m.vuln_bulk_ignore_failed(),
+ onSuccess: async ({ affectedCount }) => {
+ toast.success(
+ restore ? m.vuln_bulk_restore_success({ count: affectedCount }) : m.vuln_bulk_ignore_success({ count: affectedCount })
+ );
+ await reloadFromFirstPage(requestedEnvId);
+ }
+ });
+ }
+
+ const bulkActions = $derived.by<BulkAction[]>(() => {
+ if (!canManageVuln) return [];
+ const restore = showIgnored;
+ return [
+ {
+ id: 'bulk-selected',
+ label: restore
+ ? m.vuln_bulk_restore_selected({ count: selectedIds.length })
+ : m.vuln_bulk_ignore_selected({ count: selectedIds.length }),
+ action: 'base',
+ icon: restore ? EyeOnIcon : EyeOffIcon,
+ onClick: handleBulkSelected,
+ loading: bulkInFlight,
+ disabled: bulkInFlight
+ },
+ {
+ id: 'bulk-all-matching',
+ label: restore
+ ? m.vuln_bulk_restore_all_matching({ count: matchingCount })
+ : m.vuln_bulk_ignore_all_matching({ count: matchingCount }),
+ action: 'base',
+ icon: LayersIcon,
+ onClick: handleBulkAllMatching,
+ loading: bulkInFlight,
+ disabled: bulkInFlight || matchingCount === 0
+ }
+ ];
+ });
+
async function handleUnignoreVulnerability(item: VulnerabilityRow) {
if (!canManageVuln) return;
const requestedEnvId = currentEnvId;
const ignoreId = item.ignoreId;
if (!ignoreId) return;
- const operationResult = await tryCatch(
- (async () => {
- await vulnerabilityService.unignoreVulnerability(ignoreId, requestedEnvId);
+ await handleApiResultWithCallbacks({
+ result: await tryCatch(vulnerabilityService.unignoreVulnerability(ignoreId, requestedEnvId)),
+ message: m.vuln_unignore_failed(),
+ onSuccess: async () => {
toast.success(m.vuln_unignore_success());
- await refreshVulnerabilityTable(requestOptions);
- })()
- );
- if (operationResult.error !== null) {
- const error = operationResult.error;
-
- console.error('Failed to unignore vulnerability:', error);
- toast.error(m.vuln_unignore_failed());
- }
+ if (requestedEnvId !== currentEnvId) return;
+ await handleApiResultWithCallbacks({
+ result: await tryCatch(refreshVulnerabilityTable(requestOptions)),
+ message: m.common_refresh_failed({ resource: m.vuln_title() })
+ });
+ }
+ });
}
function deriveImageOptionsFromRows(rows: VulnerabilityRow[]): string[] {
@@ -119,6 +250,8 @@
if (!vulnerabilityManagementEnabled || requestedEnvId !== currentEnvId) return vulnerabilities;
const mapped = mapVulnerabilityPage(response, request);
vulnerabilities = mapped;
+ // Row ids are page-position keys, so replacing the rows invalidates the selection.
+ selectedIds = [];
if (optionsResponse.length === 0) {
imageNameFilterOptions = deriveImageOptionsFromRows(mapped.data ?? []);
@@ -146,33 +279,24 @@
async function handleIgnoreVulnerability(item: VulnerabilityRow) {
if (!canManageVuln) return;
const requestedEnvId = currentEnvId;
- console.log('Ignoring vulnerability:', {
- imageId: item.imageId,
- vulnerabilityId: item.vulnerabilityId,
- pkgName: item.pkgName,
- installedVersion: item.installedVersion
- });
- const operationResult = await tryCatch(
- (async () => {
- const payload = {
- imageId: item.imageId || '',
- vulnerabilityId: item.vulnerabilityId || '',
- pkgName: item.pkgName || '',
- installedVersion: item.installedVersion || ''
- };
- console.log('Sending payload:', payload);
- await vulnerabilityService.ignoreVulnerability(payload, requestedEnvId);
+ const payload = {
+ imageId: item.imageId || '',
+ vulnerabilityId: item.vulnerabilityId || '',
+ pkgName: item.pkgName || '',
+ installedVersion: item.installedVersion || ''
+ };
+ await handleApiResultWithCallbacks({
+ result: await tryCatch(vulnerabilityService.ignoreVulnerability(payload, requestedEnvId)),
+ message: m.vuln_ignore_failed(),
+ onSuccess: async () => {
toast.success(m.vuln_ignore_success({ cve: item.vulnerabilityId }));
- // Refresh the table to remove the ignored vulnerability
- await refreshVulnerabilityTable(requestOptions);
- })()
- );
- if (operationResult.error !== null) {
- const error = operationResult.error;
-
- console.error('Failed to ignore vulnerability:', error);
- toast.error(m.vuln_ignore_failed());
- }
+ if (requestedEnvId !== currentEnvId) return;
+ await handleApiResultWithCallbacks({
+ result: await tryCatch(refreshVulnerabilityTable(requestOptions)),
+ message: m.common_refresh_failed({ resource: m.vuln_title() })
+ });
+ }
+ });
}
const columns = $derived([
@@ -306,6 +430,8 @@
id="security-show-ignored"
checked={showIgnored}
onCheckedChange={async (checked) => {
+ // The view mode decides whether selected rows are ignored or restored, so drop the selection before the rows change.
+ selectedIds = [];
await onToggleIgnored?.(checked === true);
await refreshVulnerabilityTable(requestOptions);
}}
@@ -321,6 +447,7 @@
id="security-fix-available"
checked={fixAvailable}
onCheckedChange={async (checked) => {
+ selectedIds = [];
await onToggleFixAvailable?.(checked === true);
await refreshVulnerabilityTable(requestOptions);
}}
@@ -349,7 +476,9 @@
mobileCard={VulnerabilityMobileCard}
{mobileFields}
persistKey="arcane-security-vuln-table"
- selectionDisabled
+ selectionDisabled={!canManageVuln}
+ bind:selectedIds
+ {bulkActions}
{imageNameFilterOptions}
customToolbarActions={VulnerabilityToolbarActions}
rowActions={canManageVuln ? rowActions : undefined}
diff --git a/types/vulnerability/vulnerability.go b/types/vulnerability/vulnerability.go
index a0a6b8c53..de3d69e30 100644
--- a/types/vulnerability/vulnerability.go
+++ b/types/vulnerability/vulnerability.go
@@ -560,3 +560,34 @@ type IgnoredVulnerability struct {
// CreatedAt is when this ignore record was created
CreatedAt time.Time `json:"createdAt"`
}
+
+// BulkVulnerabilityFilters mirrors the environment list filters for bulk ignore and restore requests; pagination never applies and an empty body covers every matching finding.
+type BulkVulnerabilityFilters struct {
+ // Search is the free-text search applied to CVE, package, version, title, and image fields
+ //
+ // Required: false
+ Search string `json:"search,omitempty"`
+
+ // Severity is a comma-separated severity filter
+ //
+ // Required: false
+ Severity string `json:"severity,omitempty" example:"CRITICAL,HIGH"`
+
+ // ImageName is a comma-separated image name substring filter
+ //
+ // Required: false
+ ImageName string `json:"imageName,omitempty" example:"nginx"`
+
+ // FixAvailable limits matches to vulnerabilities with a fixed version
+ //
+ // Required: false
+ FixAvailable bool `json:"fixAvailable,omitempty"`
+}
+
+// BulkIgnoreResponse reports how many ignore records the request created or removed.
+type BulkIgnoreResponse struct {
+ // AffectedCount is the number of ignore records actually created or removed
+ //
+ // Required: true
+ AffectedCount int `json:"affectedCount"`
+}