Skip to content

Modern Docker Management, Designed for Everyone

feat: container image vulnerability scanning (#1657)

Kyle Mendell7ce48599f4e5
diff --git a/.husky/pre-commit b/.husky/pre-commit
new file mode 100644
index 000000000..e02c24e2b
--- /dev/null
+++ b/.husky/pre-commit
@@ -0,0 +1 @@
+pnpm lint-staged
\ No newline at end of file
diff --git a/Justfile b/Justfile
index de2a78172..6b6912845 100644
--- a/Justfile
+++ b/Justfile
@@ -951,16 +951,37 @@ _format-go:
_format-just:
just --fmt --unstable
+[group('format')]
+_format-check-frontend:
+ pnpm -C frontend format:check
+
+[group('format')]
+_format-check-go:
+ #!/usr/bin/env bash
+ set -euo pipefail
+
+ unformatted=$(gofmt -l backend cli types)
+ if [ -n "$unformatted" ]; then
+ echo "Unformatted Go files:"
+ echo "$unformatted"
+ exit 1
+ fi
+
[group('format')]
_format-all:
@just _format-frontend
@just _format-go
@just _format-just
-# Format targets. Valid: "frontend", "go", "just", "all".
[group('format')]
-format target="all":
- @just "_format-{{ target }}"
+_format-check-all:
+ @just _format-check-frontend
+ @just _format-check-go
+
+# Format targets. Valid: "frontend", "go", "just", "all". Use --check to verify formatting.
+[group('format')]
+format target="all" check="":
+ @if [ "{{ check }}" = "--check" ]; then just "_format-check-{{ target }}"; else just "_format-{{ target }}"; fi
# Clean build artifacts
[group('repo')]
diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.go
index de50e83c3..9f57cc675 100644
--- a/backend/internal/bootstrap/jobs_bootstrap.go
+++ b/backend/internal/bootstrap/jobs_bootstrap.go
@@ -41,6 +41,9 @@ func registerJobs(appCtx context.Context, newScheduler *pkg_scheduler.JobSchedul
gitOpsSyncJob := pkg_scheduler.NewGitOpsSyncJob(appServices.GitOpsSync, appServices.Settings)
newScheduler.RegisterJob(gitOpsSyncJob)
+ vulnerabilityScanJob := pkg_scheduler.NewVulnerabilityScanJob(appServices.Vulnerability, appServices.Settings)
+ newScheduler.RegisterJob(vulnerabilityScanJob)
+
setupJobScheduleCallbacks(
appServices,
appConfig,
@@ -52,8 +55,9 @@ func registerJobs(appCtx context.Context, newScheduler *pkg_scheduler.JobSchedul
eventCleanupJob,
scheduledPruneJob,
gitOpsSyncJob,
+ vulnerabilityScanJob,
)
- setupSettingsCallbacks(appServices, appConfig, newScheduler, imagePollingJob, autoUpdateJob, environmentHealthJob, fsWatcherJob, scheduledPruneJob)
+ setupSettingsCallbacks(appServices, appConfig, newScheduler, imagePollingJob, autoUpdateJob, environmentHealthJob, fsWatcherJob, scheduledPruneJob, vulnerabilityScanJob)
}
func setupJobScheduleCallbacks(
@@ -67,6 +71,7 @@ func setupJobScheduleCallbacks(
eventCleanupJob *pkg_scheduler.EventCleanupJob,
scheduledPruneJob *pkg_scheduler.ScheduledPruneJob,
gitOpsSyncJob *pkg_scheduler.GitOpsSyncJob,
+ vulnerabilityScanJob *pkg_scheduler.VulnerabilityScanJob,
) {
if appServices.JobSchedule == nil {
return
@@ -86,6 +91,7 @@ func setupJobScheduleCallbacks(
eventCleanupJob,
scheduledPruneJob,
gitOpsSyncJob,
+ vulnerabilityScanJob,
)
}
}
@@ -103,6 +109,7 @@ func handleJobScheduleChangeInternal(
eventCleanupJob *pkg_scheduler.EventCleanupJob,
scheduledPruneJob *pkg_scheduler.ScheduledPruneJob,
gitOpsSyncJob *pkg_scheduler.GitOpsSyncJob,
+ vulnerabilityScanJob *pkg_scheduler.VulnerabilityScanJob,
) {
switch key {
case "pollingInterval":
@@ -136,10 +143,14 @@ func handleJobScheduleChangeInternal(
if err := newScheduler.RescheduleJob(ctx, gitOpsSyncJob); err != nil {
slog.WarnContext(ctx, "Failed to reschedule gitops sync job", "error", err)
}
+ case "vulnerabilityScanInterval":
+ if err := newScheduler.RescheduleJob(ctx, vulnerabilityScanJob); err != nil {
+ slog.WarnContext(ctx, "Failed to reschedule vulnerability-scan job", "error", err)
+ }
}
}
-func setupSettingsCallbacks(appServices *Services, appConfig *config.Config, newScheduler *pkg_scheduler.JobScheduler, imagePollingJob *pkg_scheduler.ImagePollingJob, autoUpdateJob *pkg_scheduler.AutoUpdateJob, environmentHealthJob *pkg_scheduler.EnvironmentHealthJob, fsWatcherJob *pkg_scheduler.FilesystemWatcherJob, scheduledPruneJob *pkg_scheduler.ScheduledPruneJob) {
+func setupSettingsCallbacks(appServices *Services, appConfig *config.Config, newScheduler *pkg_scheduler.JobScheduler, imagePollingJob *pkg_scheduler.ImagePollingJob, autoUpdateJob *pkg_scheduler.AutoUpdateJob, environmentHealthJob *pkg_scheduler.EnvironmentHealthJob, fsWatcherJob *pkg_scheduler.FilesystemWatcherJob, scheduledPruneJob *pkg_scheduler.ScheduledPruneJob, vulnerabilityScanJob *pkg_scheduler.VulnerabilityScanJob) {
appServices.Settings.OnImagePollingSettingsChanged = func(ctx context.Context) {
if err := newScheduler.RescheduleJob(ctx, imagePollingJob); err != nil {
slog.WarnContext(ctx, "Failed to reschedule image-polling job", "error", err)
@@ -171,6 +182,11 @@ func setupSettingsCallbacks(appServices *Services, appConfig *config.Config, new
slog.WarnContext(ctx, "Failed to reschedule scheduled-prune job", "error", err)
}
}
+ appServices.Settings.OnVulnerabilityScanSettingsChanged = func(ctx context.Context) {
+ if err := newScheduler.RescheduleJob(ctx, vulnerabilityScanJob); err != nil {
+ slog.WarnContext(ctx, "Failed to reschedule vulnerability-scan job", "error", err)
+ }
+ }
// Only set up timeout sync callback on main instance (not in agent mode)
if !appConfig.AgentMode {
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.go
index 829aec91a..809db81fb 100644
--- a/backend/internal/bootstrap/router_bootstrap.go
+++ b/backend/internal/bootstrap/router_bootstrap.go
@@ -147,6 +147,7 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)
SystemUpgrade: appServices.SystemUpgrade,
GitRepository: appServices.GitRepository,
GitOpsSync: appServices.GitOpsSync,
+ Vulnerability: appServices.Vulnerability,
Config: cfg,
})
diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.go
index 8cb7c6b15..a1bfb9fdb 100644
--- a/backend/internal/bootstrap/services_bootstrap.go
+++ b/backend/internal/bootstrap/services_bootstrap.go
@@ -41,6 +41,7 @@ type Services struct {
GitRepository *services.GitRepositoryService
GitOpsSync *services.GitOpsSyncService
Font *services.FontService
+ Vulnerability *services.VulnerabilityService
}
func initializeServices(ctx context.Context, db *database.DB, cfg *config.Config, httpClient *http.Client) (svcs *Services, dockerSrvice *services.DockerClientService, err error) {
@@ -62,8 +63,9 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Config
svcs.ContainerRegistry = services.NewContainerRegistryService(db)
svcs.Notification = services.NewNotificationService(db, cfg)
svcs.Apprise = services.NewAppriseService(db, cfg)
+ svcs.Vulnerability = services.NewVulnerabilityService(db, svcs.Docker, svcs.Event, svcs.Settings, svcs.Notification)
svcs.ImageUpdate = services.NewImageUpdateService(db, svcs.Settings, svcs.ContainerRegistry, svcs.Docker, svcs.Event, svcs.Notification)
- svcs.Image = services.NewImageService(db, svcs.Docker, svcs.ContainerRegistry, svcs.ImageUpdate, svcs.Event)
+ svcs.Image = services.NewImageService(db, svcs.Docker, svcs.ContainerRegistry, svcs.ImageUpdate, svcs.Vulnerability, svcs.Event)
svcs.Project = services.NewProjectService(db, svcs.Settings, svcs.Event, svcs.Image, svcs.Docker)
svcs.Environment = services.NewEnvironmentService(db, httpClient, svcs.Docker, svcs.Event, svcs.Settings)
svcs.Container = services.NewContainerService(db, svcs.Event, svcs.Docker, svcs.Image, svcs.Settings)
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.go
index 090444e6b..4b07d846d 100644
--- a/backend/internal/common/errors.go
+++ b/backend/internal/common/errors.go
@@ -1294,3 +1294,25 @@ type GitOpsSyncMappingError struct {
func (e *GitOpsSyncMappingError) Error() string {
return "Failed to map GitOps sync"
}
+
+type VulnerabilityScanError struct {
+ Err error
+}
+
+func (e *VulnerabilityScanError) Error() string {
+ return fmt.Sprintf("Failed to scan image for vulnerabilities: %v", e.Err)
+}
+
+type VulnerabilityScanNotFoundError struct{}
+
+func (e *VulnerabilityScanNotFoundError) Error() string {
+ return "Vulnerability scan not found"
+}
+
+type VulnerabilityScanRetrievalError struct {
+ Err error
+}
+
+func (e *VulnerabilityScanRetrievalError) Error() string {
+ return fmt.Sprintf("Failed to retrieve vulnerability scan: %v", e.Err)
+}
diff --git a/backend/internal/huma/handlers/settings.go b/backend/internal/huma/handlers/settings.go
index 0f26051a1..5815f1d2f 100644
--- a/backend/internal/huma/handlers/settings.go
+++ b/backend/internal/huma/handlers/settings.go
@@ -288,10 +288,15 @@ func (h *SettingsHandler) UpdateSettings(ctx context.Context, input *UpdateSetti
return nil, err
}
- // Validate projects directory if provided
+ // Validate projects directory if provided and changed from current value.
+ // Skip validation when the value matches the current (possibly env-overridden) setting
+ // so that saving unrelated settings doesn't fail due to env-provided directory formats.
if input.Body.ProjectsDirectory != nil && *input.Body.ProjectsDirectory != "" {
- if err := validateProjectsDirectoryValue(*input.Body.ProjectsDirectory); err != nil {
- return nil, huma.Error400BadRequest(err.Error())
+ currentDir := h.settingsService.GetSettingsConfig().ProjectsDirectory.Value
+ if *input.Body.ProjectsDirectory != currentDir {
+ if err := validateProjectsDirectoryValue(*input.Body.ProjectsDirectory); err != nil {
+ return nil, huma.Error400BadRequest(err.Error())
+ }
}
}
diff --git a/backend/internal/huma/handlers/vulnerabilities.go b/backend/internal/huma/handlers/vulnerabilities.go
new file mode 100644
index 000000000..0f8acbbe6
--- /dev/null
+++ b/backend/internal/huma/handlers/vulnerabilities.go
@@ -0,0 +1,559 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/types/base"
+ "github.com/getarcaneapp/arcane/types/vulnerability"
+)
+
+// VulnerabilityHandler provides Huma-based vulnerability scanning endpoints.
+type VulnerabilityHandler struct {
+ vulnerabilityService *services.VulnerabilityService
+}
+
+// --- Huma Input/Output Types ---
+
+type ScanImageInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ImageID string `path:"imageId" doc:"Image ID to scan"`
+}
+
+type ScanImageOutput struct {
+ Body base.ApiResponse[vulnerability.ScanResult]
+}
+
+type GetScanResultInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ImageID string `path:"imageId" doc:"Image ID"`
+}
+
+type GetScanResultOutput struct {
+ Body base.ApiResponse[vulnerability.ScanResult]
+}
+
+type GetScanSummaryInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ImageID string `path:"imageId" doc:"Image ID"`
+}
+
+type GetScanSummaryOutput struct {
+ Body base.ApiResponse[vulnerability.ScanSummary]
+}
+
+type ListImageVulnerabilitiesInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ImageID string `path:"imageId" doc:"Image ID"`
+ Search string `query:"search" doc:"Search query"`
+ Sort string `query:"sort" doc:"Sort field"`
+ Order string `query:"order" doc:"Sort order"`
+ Start int `query:"start" doc:"Start offset"`
+ Limit int `query:"limit" doc:"Limit"`
+ Page int `query:"page" doc:"Page number"`
+ Severity string `query:"severity" doc:"Comma-separated severity filter"`
+}
+
+type ListImageVulnerabilitiesOutput struct {
+ Body base.Paginated[vulnerability.Vulnerability]
+}
+
+type GetEnvironmentSummaryInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type GetEnvironmentSummaryOutput struct {
+ Body base.ApiResponse[vulnerability.EnvironmentVulnerabilitySummary]
+}
+
+type ListAllVulnerabilitiesInput 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"`
+ Start int `query:"start" doc:"Start offset"`
+ Limit int `query:"limit" doc:"Limit"`
+ Page int `query:"page" doc:"Page number"`
+ Severity string `query:"severity" doc:"Comma-separated severity filter"`
+ ImageName string `query:"imageName" doc:"Filter by image/repo name (substring)"`
+}
+
+type ListAllVulnerabilitiesOutput struct {
+ Body base.Paginated[vulnerability.VulnerabilityWithImage]
+}
+
+type GetScannerStatusInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type ScannerStatus struct {
+ // Available indicates if the vulnerability scanner (Trivy) is available
+ Available bool `json:"available"`
+
+ // Version is the version of the scanner if available
+ Version string `json:"version,omitempty"`
+}
+
+type GetScannerStatusOutput struct {
+ Body base.ApiResponse[ScannerStatus]
+}
+
+// RegisterVulnerability registers vulnerability scanning routes using Huma.
+func RegisterVulnerability(api huma.API, vulnerabilityService *services.VulnerabilityService) {
+ h := &VulnerabilityHandler{
+ vulnerabilityService: vulnerabilityService,
+ }
+
+ huma.Register(api, huma.Operation{
+ OperationID: "scan-image-vulnerabilities",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/images/{imageId}/vulnerabilities/scan",
+ Summary: "Scan image for vulnerabilities",
+ Description: "Initiates a vulnerability scan for the specified image using Trivy",
+ Tags: []string{"Vulnerabilities"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ScanImage)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-image-vulnerabilities",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/images/{imageId}/vulnerabilities",
+ Summary: "Get vulnerability scan result",
+ Description: "Retrieves the most recent vulnerability scan result for an image",
+ Tags: []string{"Vulnerabilities"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetScanResult)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-image-vulnerability-summary",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/images/{imageId}/vulnerabilities/summary",
+ Summary: "Get vulnerability scan summary",
+ Description: "Retrieves just the summary of vulnerabilities for an image (for list views)",
+ Tags: []string{"Vulnerabilities"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetScanSummary)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "list-image-vulnerabilities",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/images/{imageId}/vulnerabilities/list",
+ Summary: "List image vulnerabilities",
+ Description: "Retrieves paginated vulnerabilities for an image",
+ Tags: []string{"Vulnerabilities"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ListImageVulnerabilities)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-vulnerability-scanner-status",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/vulnerabilities/scanner-status",
+ Summary: "Get vulnerability scanner status",
+ Description: "Check if the vulnerability scanner (Trivy) is available and get its version",
+ Tags: []string{"Vulnerabilities"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetScannerStatus)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-environment-vulnerability-summary",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/vulnerabilities/summary",
+ Summary: "Get environment vulnerability summary",
+ Description: "Retrieves aggregated vulnerability counts across all images in the environment",
+ Tags: []string{"Vulnerabilities"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetEnvironmentSummary)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "list-environment-vulnerabilities",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/vulnerabilities/all",
+ Summary: "List environment vulnerabilities",
+ Description: "Retrieves paginated vulnerabilities across all scanned images in the environment",
+ Tags: []string{"Vulnerabilities"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ListAllVulnerabilities)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "ignore-vulnerability",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/vulnerabilities/ignore",
+ Summary: "Ignore a vulnerability",
+ Description: "Creates an ignore record for a specific vulnerability",
+ Tags: []string{"Vulnerabilities"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.IgnoreVulnerability)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "unignore-vulnerability",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/vulnerabilities/ignore/{ignoreId}",
+ Summary: "Unignore a vulnerability",
+ Description: "Removes an ignore record for a vulnerability",
+ Tags: []string{"Vulnerabilities"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.UnignoreVulnerability)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "list-ignored-vulnerabilities",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/vulnerabilities/ignored",
+ Summary: "List ignored vulnerabilities",
+ Description: "Retrieves a list of all ignored vulnerabilities for the environment",
+ Tags: []string{"Vulnerabilities"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ListIgnoredVulnerabilities)
+}
+
+// ScanImage initiates a vulnerability scan for an image.
+func (h *VulnerabilityHandler) ScanImage(ctx context.Context, input *ScanImageInput) (*ScanImageOutput, error) {
+ if h.vulnerabilityService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ result, err := h.vulnerabilityService.ScanImage(ctx, input.EnvironmentID, input.ImageID, *user)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.VulnerabilityScanError{Err: err}).Error())
+ }
+
+ return &ScanImageOutput{
+ Body: base.ApiResponse[vulnerability.ScanResult]{
+ Success: true,
+ Data: *result,
+ },
+ }, nil
+}
+
+// GetScanResult retrieves the vulnerability scan result for an image.
+func (h *VulnerabilityHandler) GetScanResult(ctx context.Context, input *GetScanResultInput) (*GetScanResultOutput, error) {
+ if h.vulnerabilityService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ result, err := h.vulnerabilityService.GetScanResult(ctx, input.ImageID)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())
+ }
+
+ if result == nil {
+ return nil, huma.Error404NotFound((&common.VulnerabilityScanNotFoundError{}).Error())
+ }
+
+ return &GetScanResultOutput{
+ Body: base.ApiResponse[vulnerability.ScanResult]{
+ Success: true,
+ Data: *result,
+ },
+ }, nil
+}
+
+// GetScanSummary retrieves just the vulnerability summary for an image.
+func (h *VulnerabilityHandler) GetScanSummary(ctx context.Context, input *GetScanSummaryInput) (*GetScanSummaryOutput, error) {
+ if h.vulnerabilityService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ summary, err := h.vulnerabilityService.GetScanSummary(ctx, input.ImageID)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())
+ }
+
+ if summary == nil {
+ return nil, huma.Error404NotFound((&common.VulnerabilityScanNotFoundError{}).Error())
+ }
+
+ return &GetScanSummaryOutput{
+ Body: base.ApiResponse[vulnerability.ScanSummary]{
+ Success: true,
+ Data: *summary,
+ },
+ }, nil
+}
+
+// ListImageVulnerabilities returns a paginated list of vulnerabilities for an image.
+func (h *VulnerabilityHandler) ListImageVulnerabilities(ctx context.Context, input *ListImageVulnerabilitiesInput) (*ListImageVulnerabilitiesOutput, error) {
+ if h.vulnerabilityService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ params := buildPaginationParams(input.Page, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ if params.Limit == 0 {
+ params.Limit = 20
+ }
+ if input.Severity != "" {
+ params.Filters["severity"] = input.Severity
+ }
+
+ items, paginationResp, err := h.vulnerabilityService.ListVulnerabilities(ctx, input.ImageID, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())
+ }
+
+ if items == nil {
+ items = []vulnerability.Vulnerability{}
+ }
+
+ return &ListImageVulnerabilitiesOutput{
+ Body: base.Paginated[vulnerability.Vulnerability]{
+ Success: true,
+ Data: items,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+// GetEnvironmentSummary returns aggregated vulnerability info for the current environment.
+func (h *VulnerabilityHandler) GetEnvironmentSummary(ctx context.Context, input *GetEnvironmentSummaryInput) (*GetEnvironmentSummaryOutput, error) {
+ if h.vulnerabilityService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ summary, err := h.vulnerabilityService.GetEnvironmentSummary(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())
+ }
+
+ if summary == nil {
+ summary = &vulnerability.EnvironmentVulnerabilitySummary{}
+ }
+
+ return &GetEnvironmentSummaryOutput{
+ Body: base.ApiResponse[vulnerability.EnvironmentVulnerabilitySummary]{
+ Success: true,
+ Data: *summary,
+ },
+ }, nil
+}
+
+// ListAllVulnerabilities returns a paginated list of vulnerabilities across all images.
+func (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, input *ListAllVulnerabilitiesInput) (*ListAllVulnerabilitiesOutput, error) {
+ if h.vulnerabilityService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ params := buildPaginationParams(input.Page, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ if params.Limit == 0 {
+ params.Limit = 20
+ }
+ if input.Severity != "" {
+ params.Filters["severity"] = input.Severity
+ }
+ if input.ImageName != "" {
+ params.Filters["imageName"] = input.ImageName
+ }
+
+ items, paginationResp, err := h.vulnerabilityService.ListAllVulnerabilities(ctx, input.EnvironmentID, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())
+ }
+
+ if items == nil {
+ items = []vulnerability.VulnerabilityWithImage{}
+ }
+
+ return &ListAllVulnerabilitiesOutput{
+ Body: base.Paginated[vulnerability.VulnerabilityWithImage]{
+ Success: true,
+ Data: items,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+// GetScannerStatus checks if the vulnerability scanner is available.
+func (h *VulnerabilityHandler) GetScannerStatus(ctx context.Context, input *GetScannerStatusInput) (*GetScannerStatusOutput, error) {
+ if h.vulnerabilityService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ version := h.vulnerabilityService.GetTrivyVersion(ctx)
+ available := version != ""
+
+ return &GetScannerStatusOutput{
+ Body: base.ApiResponse[ScannerStatus]{
+ Success: true,
+ Data: ScannerStatus{
+ Available: available,
+ Version: version,
+ },
+ },
+ }, nil
+}
+
+type IgnoreVulnerabilityInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body vulnerability.IgnorePayload
+}
+
+type IgnoreVulnerabilityOutput struct {
+ Body base.ApiResponse[vulnerability.IgnoredVulnerability]
+}
+
+// IgnoreVulnerability creates an ignore record for a vulnerability.
+func (h *VulnerabilityHandler) IgnoreVulnerability(ctx context.Context, input *IgnoreVulnerabilityInput) (*IgnoreVulnerabilityOutput, error) {
+ if h.vulnerabilityService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ payload := &input.Body
+ payload.CreatedBy = user.ID
+
+ ignore, err := h.vulnerabilityService.IgnoreVulnerability(ctx, input.EnvironmentID, payload)
+ if err != nil {
+ if err.Error() == "vulnerability is already ignored" {
+ return nil, huma.Error409Conflict(err.Error())
+ }
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+
+ return &IgnoreVulnerabilityOutput{
+ Body: base.ApiResponse[vulnerability.IgnoredVulnerability]{
+ Success: true,
+ Data: vulnerability.IgnoredVulnerability{
+ ID: ignore.ID,
+ EnvironmentID: ignore.EnvironmentID,
+ ImageID: ignore.ImageID,
+ VulnerabilityID: ignore.VulnerabilityID,
+ PkgName: ignore.PkgName,
+ InstalledVersion: ignore.InstalledVersion,
+ Reason: ignore.Reason,
+ CreatedBy: ignore.CreatedBy,
+ CreatedAt: ignore.CreatedAt,
+ },
+ },
+ }, nil
+}
+
+type UnignoreVulnerabilityInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ IgnoreID string `path:"ignoreId" doc:"Ignore record ID"`
+}
+
+type UnignoreVulnerabilityOutput struct {
+ Body base.ApiResponse[struct{}]
+}
+
+// UnignoreVulnerability removes an ignore record for a vulnerability.
+func (h *VulnerabilityHandler) UnignoreVulnerability(ctx context.Context, input *UnignoreVulnerabilityInput) (*UnignoreVulnerabilityOutput, error) {
+ if h.vulnerabilityService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if err := h.vulnerabilityService.UnignoreVulnerability(ctx, input.EnvironmentID, input.IgnoreID); err != nil {
+ if err.Error() == "ignore record not found" {
+ return nil, huma.Error404NotFound(err.Error())
+ }
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+
+ return &UnignoreVulnerabilityOutput{
+ Body: base.ApiResponse[struct{}]{
+ Success: true,
+ },
+ }, nil
+}
+
+type ListIgnoredVulnerabilitiesInput 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"`
+ Start int `query:"start" doc:"Start offset"`
+ Limit int `query:"limit" doc:"Limit"`
+ Page int `query:"page" doc:"Page number"`
+}
+
+type ListIgnoredVulnerabilitiesOutput struct {
+ Body base.Paginated[vulnerability.IgnoredVulnerability]
+}
+
+// ListIgnoredVulnerabilities returns a list of ignored vulnerabilities.
+func (h *VulnerabilityHandler) ListIgnoredVulnerabilities(ctx context.Context, input *ListIgnoredVulnerabilitiesInput) (*ListIgnoredVulnerabilitiesOutput, error) {
+ if h.vulnerabilityService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ params := buildPaginationParams(input.Page, input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ if params.Limit == 0 {
+ params.Limit = 20
+ }
+
+ items, paginationResp, err := h.vulnerabilityService.ListIgnoredVulnerabilities(ctx, input.EnvironmentID, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+
+ if items == nil {
+ items = []vulnerability.IgnoredVulnerability{}
+ }
+
+ return &ListIgnoredVulnerabilitiesOutput{
+ Body: base.Paginated[vulnerability.IgnoredVulnerability]{
+ Success: true,
+ Data: items,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/huma.go b/backend/internal/huma/huma.go
index 1edc1a7bb..afb600fcf 100644
--- a/backend/internal/huma/huma.go
+++ b/backend/internal/huma/huma.go
@@ -143,6 +143,7 @@ type Services struct {
SystemUpgrade *services.SystemUpgradeService
GitRepository *services.GitRepositoryService
GitOpsSync *services.GitOpsSyncService
+ Vulnerability *services.VulnerabilityService
Config *config.Config
}
@@ -301,6 +302,7 @@ func registerHandlers(api huma.API, svc *Services) {
var systemUpgradeSvc *services.SystemUpgradeService
var gitRepositorySvc *services.GitRepositoryService
var gitOpsSyncSvc *services.GitOpsSyncService
+ var vulnerabilitySvc *services.VulnerabilityService
var cfg *config.Config
if svc != nil {
@@ -333,6 +335,7 @@ func registerHandlers(api huma.API, svc *Services) {
systemUpgradeSvc = svc.SystemUpgrade
gitRepositorySvc = svc.GitRepository
gitOpsSyncSvc = svc.GitOpsSync
+ vulnerabilitySvc = svc.Vulnerability
cfg = svc.Config
}
handlers.RegisterHealth(api)
@@ -361,4 +364,5 @@ func registerHandlers(api huma.API, svc *Services) {
handlers.RegisterSystem(api, dockerSvc, systemSvc, systemUpgradeSvc, cfg)
handlers.RegisterGitRepositories(api, gitRepositorySvc)
handlers.RegisterGitOpsSyncs(api, gitOpsSyncSvc)
+ handlers.RegisterVulnerability(api, vulnerabilitySvc)
}
diff --git a/backend/internal/models/event.go b/backend/internal/models/event.go
index a57574757..9ecf6cb25 100644
--- a/backend/internal/models/event.go
+++ b/backend/internal/models/event.go
@@ -18,11 +18,12 @@ const (
EventTypeContainerUpdate EventType = "container.update"
EventTypeContainerError EventType = "container.error"
- EventTypeImagePull EventType = "image.pull"
- EventTypeImageLoad EventType = "image.load"
- EventTypeImageDelete EventType = "image.delete"
- EventTypeImageScan EventType = "image.scan"
- EventTypeImageError EventType = "image.error"
+ EventTypeImagePull EventType = "image.pull"
+ EventTypeImageLoad EventType = "image.load"
+ EventTypeImageDelete EventType = "image.delete"
+ EventTypeImageScan EventType = "image.scan"
+ EventTypeImageError EventType = "image.error"
+ EventTypeImageVulnerabilityScan EventType = "image.vulnerability_scan"
EventTypeProjectDeploy EventType = "project.deploy"
EventTypeProjectDelete EventType = "project.delete"
diff --git a/backend/internal/models/notification.go b/backend/internal/models/notification.go
index 4be50061f..868703f45 100644
--- a/backend/internal/models/notification.go
+++ b/backend/internal/models/notification.go
@@ -38,8 +38,9 @@ func IsValidNotificationProvider(provider NotificationProvider) bool {
type NotificationEventType string
const (
- NotificationEventImageUpdate NotificationEventType = "image_update"
- NotificationEventContainerUpdate NotificationEventType = "container_update"
+ NotificationEventImageUpdate NotificationEventType = "image_update"
+ NotificationEventContainerUpdate NotificationEventType = "container_update"
+ NotificationEventVulnerabilityFound NotificationEventType = "vulnerability_found"
)
type EmailTLSMode string
diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.go
index 42f5c45ed..03223c5e3 100644
--- a/backend/internal/models/settings.go
+++ b/backend/internal/models/settings.go
@@ -75,6 +75,11 @@ type Settings struct {
AuthLocalEnabled SettingVariable `key:"authLocalEnabled,public" meta:"label=Local Authentication;type=boolean;keywords=local,auth,authentication,username,password,login,credentials;category=security;description=Enable local username/password authentication" catmeta:"id=security;title=Security;icon=shield;url=/settings/security;description=Manage authentication and security settings"`
AuthSessionTimeout SettingVariable `key:"authSessionTimeout" meta:"label=Session Timeout;type=number;keywords=session,timeout,expire,duration,lifetime,minutes,logout;category=security;description=How long user sessions remain active"`
AuthPasswordPolicy SettingVariable `key:"authPasswordPolicy" meta:"label=Password Policy;type=select;keywords=password,policy,strength,complexity,requirements,security,rules;category=security;description=Set password strength requirements"`
+ VulnerabilityScanEnabled SettingVariable `key:"vulnerabilityScanEnabled" meta:"label=Scheduled Vulnerability Scan;type=boolean;keywords=vulnerability,scan,security,trivy,schedule,automatic,cve;category=security;description=Enable scheduled vulnerability scanning of all Docker images"`
+ VulnerabilityScanInterval SettingVariable `key:"vulnerabilityScanInterval" meta:"label=Vulnerability Scan Interval;type=cron;keywords=vulnerability,scan,interval,schedule,frequency,trivy,cve;category=security;description=How often to run scheduled vulnerability scans (cron expression)"`
+ TrivyImage SettingVariable `key:"trivyImage,envOverride" meta:"label=Trivy Image;type=text;keywords=trivy,scanner,vulnerability,security,image;category=security;description=Override the Trivy image used for vulnerability scans"`
+ TrivyConfig SettingVariable `key:"trivyConfig" meta:"label=Trivy Config (YAML);type=textarea;keywords=trivy,config,yaml,configuration,scanner,settings;category=security;description=Trivy configuration file content in YAML format"`
+ TrivyIgnore SettingVariable `key:"trivyIgnore" meta:"label=.trivyignore;type=textarea;keywords=trivy,ignore,ignorefile,vulnerabilities,exceptions,exclusions;category=security;description=Trivy ignore file content - one vulnerability ID per line"`
AuthOidcConfig SettingVariable `key:"authOidcConfig,sensitive,deprecated" meta:"label=OIDC Config;type=text;keywords=oidc,config,client,id,issuer,secret,oauth;category=security;description=OIDC provider configuration (deprecated - use individual fields)"`
OidcEnabled SettingVariable `key:"oidcEnabled,public,envOverride" meta:"label=OIDC Authentication;type=boolean;keywords=oidc,openid,connect,sso,oauth,external,provider,federation;category=security;description=Enable OpenID Connect (OIDC) authentication"`
OidcClientId SettingVariable `key:"oidcClientId,public,envOverride" meta:"label=OIDC Client ID;type=text;keywords=oidc,client,id,oauth,openid;category=security;description=OIDC provider client ID"`
diff --git a/backend/internal/models/vulnerability_ignore.go b/backend/internal/models/vulnerability_ignore.go
new file mode 100644
index 000000000..59f43297c
--- /dev/null
+++ b/backend/internal/models/vulnerability_ignore.go
@@ -0,0 +1,59 @@
+package models
+
+import (
+ "time"
+
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+// VulnerabilityIgnore stores ignored vulnerability records
+type VulnerabilityIgnore struct {
+ // ID is the unique identifier for this ignore record
+ ID string `json:"id" gorm:"primaryKey;type:text"`
+
+ // EnvironmentID is the environment where this ignore applies
+ EnvironmentID string `json:"environmentId" gorm:"column:environment_id;index"`
+
+ // ImageID is the Docker image ID
+ ImageID string `json:"imageId" gorm:"column:image_id;index"`
+
+ // VulnerabilityID is the CVE or vulnerability identifier (e.g., CVE-2023-1234)
+ VulnerabilityID string `json:"vulnerabilityId" gorm:"column:vulnerability_id;index"`
+
+ // PkgName is the package name containing the vulnerability
+ PkgName string `json:"pkgName" gorm:"column:pkg_name"`
+
+ // InstalledVersion is the version of the package with the vulnerability
+ InstalledVersion string `json:"installedVersion" gorm:"column:installed_version"`
+
+ // Reason is an optional reason for ignoring this vulnerability
+ Reason *string `json:"reason,omitempty" gorm:"column:reason"`
+
+ // CreatedBy is the user ID who created this ignore record
+ CreatedBy string `json:"createdBy" gorm:"column:created_by"`
+
+ // CreatedAt is when this ignore record was created
+ CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`
+}
+
+func (v *VulnerabilityIgnore) TableName() string {
+ return "vulnerability_ignores"
+}
+
+// BeforeCreate sets the ID and CreatedAt before inserting
+func (v *VulnerabilityIgnore) BeforeCreate(db *gorm.DB) error {
+ if v.ID == "" {
+ v.ID = uuid.New().String()
+ }
+ if v.CreatedAt.IsZero() {
+ v.CreatedAt = time.Now()
+ }
+ return nil
+}
+
+// VulnerabilityIgnoreCompositeKey generates a composite key for deduplication
+// This helps prevent duplicate ignore records for the same vulnerability
+func (v *VulnerabilityIgnore) CompositeKey() string {
+ return v.EnvironmentID + ":" + v.ImageID + ":" + v.VulnerabilityID + ":" + v.PkgName + ":" + v.InstalledVersion
+}
diff --git a/backend/internal/models/vulnerability_scan.go b/backend/internal/models/vulnerability_scan.go
new file mode 100644
index 000000000..2f9bbb3bd
--- /dev/null
+++ b/backend/internal/models/vulnerability_scan.go
@@ -0,0 +1,94 @@
+package models
+
+import (
+ "time"
+)
+
+// VulnerabilityScanRecord stores vulnerability scan results for images
+type VulnerabilityScanRecord struct {
+ // ImageID is the Docker image ID (primary key)
+ ID string `json:"id" gorm:"primaryKey;type:text"`
+
+ // ImageName is the image name with tag (e.g., nginx:latest)
+ ImageName string `json:"imageName" gorm:"column:image_name"`
+
+ // Status is the status of the scan (pending, scanning, completed, failed)
+ Status string `json:"status" gorm:"column:status"`
+
+ // ScanTime is the timestamp when the scan was performed
+ ScanTime time.Time `json:"scanTime" gorm:"column:scan_time"`
+
+ // Duration is the duration of the scan in milliseconds
+ Duration int64 `json:"duration" gorm:"column:duration"`
+
+ // Total vulnerability counts by severity
+ CriticalCount int `json:"criticalCount" gorm:"column:critical_count"`
+ HighCount int `json:"highCount" gorm:"column:high_count"`
+ MediumCount int `json:"mediumCount" gorm:"column:medium_count"`
+ LowCount int `json:"lowCount" gorm:"column:low_count"`
+ UnknownCount int `json:"unknownCount" gorm:"column:unknown_count"`
+ TotalCount int `json:"totalCount" gorm:"column:total_count"`
+
+ // Vulnerabilities stores the JSON encoded vulnerabilities list
+ Vulnerabilities StringSlice `json:"vulnerabilities" gorm:"column:vulnerabilities;type:text"`
+
+ // Error contains the error message if the scan failed
+ Error *string `json:"error,omitempty" gorm:"column:error"`
+
+ // ScannerVersion is the version of the scanner used
+ ScannerVersion string `json:"scannerVersion" gorm:"column:scanner_version"`
+
+ BaseModel
+}
+
+func (v *VulnerabilityScanRecord) TableName() string {
+ return "vulnerability_scans"
+}
+
+// Scan status constants
+const (
+ ScanStatusPending = "pending"
+ ScanStatusScanning = "scanning"
+ ScanStatusCompleted = "completed"
+ ScanStatusFailed = "failed"
+)
+
+// IsCompleted returns true if the scan has completed
+func (v *VulnerabilityScanRecord) IsCompleted() bool {
+ return v.Status == ScanStatusCompleted
+}
+
+// IsFailed returns true if the scan has failed
+func (v *VulnerabilityScanRecord) IsFailed() bool {
+ return v.Status == ScanStatusFailed
+}
+
+// IsScanning returns true if the scan is in progress
+func (v *VulnerabilityScanRecord) IsScanning() bool {
+ return v.Status == ScanStatusScanning
+}
+
+// GetTotalVulnerabilities returns the total count of vulnerabilities
+func (v *VulnerabilityScanRecord) GetTotalVulnerabilities() int {
+ return v.TotalCount
+}
+
+// GetHighestSeverity returns the highest severity level found
+func (v *VulnerabilityScanRecord) GetHighestSeverity() string {
+ if v.CriticalCount > 0 {
+ return "CRITICAL"
+ }
+ if v.HighCount > 0 {
+ return "HIGH"
+ }
+ if v.MediumCount > 0 {
+ return "MEDIUM"
+ }
+ if v.LowCount > 0 {
+ return "LOW"
+ }
+ if v.UnknownCount > 0 {
+ return "UNKNOWN"
+ }
+ return "NONE"
+}
diff --git a/backend/internal/services/apprise_service.go b/backend/internal/services/apprise_service.go
index 0c09e26a4..166b8a675 100644
--- a/backend/internal/services/apprise_service.go
+++ b/backend/internal/services/apprise_service.go
@@ -106,6 +106,8 @@ func (s *AppriseService) SendNotification(ctx context.Context, title, body, form
if settings.ContainerUpdateTag != "" {
tags = []string{settings.ContainerUpdateTag}
}
+ case models.NotificationEventVulnerabilityFound:
+ // No dedicated tag in AppriseSettings; notification is sent without a tag
}
payload := AppriseNotificationPayload{
diff --git a/backend/internal/services/image_service.go b/backend/internal/services/image_service.go
index 6f9d758e8..6b5b848ae 100644
--- a/backend/internal/services/image_service.go
+++ b/backend/internal/services/image_service.go
@@ -8,11 +8,10 @@ import (
"errors"
"fmt"
"io"
+ "log/slog"
"net/http"
"strings"
- "log/slog"
-
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/image"
@@ -22,26 +21,29 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
"github.com/getarcaneapp/arcane/types/containerregistry"
imagetypes "github.com/getarcaneapp/arcane/types/image"
+ "github.com/getarcaneapp/arcane/types/vulnerability"
ref "go.podman.io/image/v5/docker/reference"
"golang.org/x/sync/errgroup"
"gorm.io/gorm"
)
type ImageService struct {
- db *database.DB
- dockerService *DockerClientService
- imageUpdateService *ImageUpdateService
- registryService *ContainerRegistryService
- eventService *EventService
+ db *database.DB
+ dockerService *DockerClientService
+ imageUpdateService *ImageUpdateService
+ registryService *ContainerRegistryService
+ vulnerabilityService *VulnerabilityService
+ eventService *EventService
}
-func NewImageService(db *database.DB, dockerService *DockerClientService, registryService *ContainerRegistryService, imageUpdateService *ImageUpdateService, eventService *EventService) *ImageService {
+func NewImageService(db *database.DB, dockerService *DockerClientService, registryService *ContainerRegistryService, imageUpdateService *ImageUpdateService, vulnerabilityService *VulnerabilityService, eventService *EventService) *ImageService {
return &ImageService{
- db: db,
- dockerService: dockerService,
- registryService: registryService,
- imageUpdateService: imageUpdateService,
- eventService: eventService,
+ db: db,
+ dockerService: dockerService,
+ registryService: registryService,
+ imageUpdateService: imageUpdateService,
+ vulnerabilityService: vulnerabilityService,
+ eventService: eventService,
}
}
@@ -93,6 +95,13 @@ func (s *ImageService) RemoveImage(ctx context.Context, id string, force bool, u
}
}
+ // Clean up vulnerability scan records for the deleted image
+ if s.vulnerabilityService != nil {
+ if err := s.vulnerabilityService.DeleteScanResult(ctx, id); err != nil {
+ slog.WarnContext(ctx, "failed to delete vulnerability scan record", "id", id, "error", err)
+ }
+ }
+
metadata := models.JSON{
"action": "delete",
"imageId": id,
@@ -385,6 +394,15 @@ func (s *ImageService) PruneImages(ctx context.Context, dangling bool) (*image.P
}); err != nil {
slog.WarnContext(ctx, "failed to clean up image update records after prune", "error", err)
}
+
+ // Clean up vulnerability scan records for pruned images
+ if s.vulnerabilityService != nil {
+ for _, imgID := range idsToDelete {
+ if err := s.vulnerabilityService.DeleteScanResult(ctx, imgID); err != nil {
+ slog.WarnContext(ctx, "failed to delete vulnerability scan record after prune", "id", imgID, "error", err)
+ }
+ }
+ }
}
}
@@ -428,9 +446,10 @@ func (s *ImageService) ListImagesPaginated(ctx context.Context, params paginatio
}
var (
- dockerImages []image.Summary
- containers []container.Summary
- updateRecords []models.ImageUpdateRecord
+ dockerImages []image.Summary
+ containers []container.Summary
+ updateRecords []models.ImageUpdateRecord
+ vulnerabilityMap map[string]*vulnerability.ScanSummary
)
g, groupCtx := errgroup.WithContext(ctx)
@@ -467,10 +486,22 @@ func (s *ImageService) ListImagesPaginated(ctx context.Context, params paginatio
return nil, pagination.Response{}, err
}
+ if s.vulnerabilityService != nil {
+ imageIDs := make([]string, 0, len(dockerImages))
+ for _, img := range dockerImages {
+ imageIDs = append(imageIDs, img.ID)
+ }
+ var err error
+ vulnerabilityMap, err = s.vulnerabilityService.GetScanSummariesByImageIDs(ctx, imageIDs)
+ if err != nil {
+ return nil, pagination.Response{}, err
+ }
+ }
+
inUseMap := buildInUseMap(containers)
updateMap := buildUpdateMap(updateRecords)
- items := mapDockerImagesToDTOs(dockerImages, inUseMap, updateMap)
+ items := mapDockerImagesToDTOs(dockerImages, inUseMap, updateMap, vulnerabilityMap)
config := s.getImagePaginationConfig()
@@ -597,7 +628,7 @@ func buildUpdateInfo(updateRecord *models.ImageUpdateRecord) *imagetypes.UpdateI
}
}
-func mapDockerImagesToDTOs(dockerImages []image.Summary, inUseMap map[string]bool, updateMap map[string]*models.ImageUpdateRecord) []imagetypes.Summary {
+func mapDockerImagesToDTOs(dockerImages []image.Summary, inUseMap map[string]bool, updateMap map[string]*models.ImageUpdateRecord, vulnerabilityMap map[string]*vulnerability.ScanSummary) []imagetypes.Summary {
items := make([]imagetypes.Summary, 0, len(dockerImages))
for _, di := range dockerImages {
repo, tag := determineRepoAndTag(di)
@@ -619,6 +650,12 @@ func mapDockerImagesToDTOs(dockerImages []image.Summary, inUseMap map[string]boo
imageDto.UpdateInfo = buildUpdateInfo(updateRecord)
}
+ if vulnerabilityMap != nil {
+ if summary, exists := vulnerabilityMap[di.ID]; exists {
+ imageDto.VulnerabilityScan = summary
+ }
+ }
+
items = append(items, imageDto)
}
return items
diff --git a/backend/internal/services/job_service.go b/backend/internal/services/job_service.go
index dc3e93feb..32d098502 100644
--- a/backend/internal/services/job_service.go
+++ b/backend/internal/services/job_service.go
@@ -55,6 +55,7 @@ func (s *JobService) GetJobSchedules(ctx context.Context) jobschedule.Config {
PollingInterval: s.settings.GetStringSetting(ctx, "pollingInterval", "0 */15 * * * *"),
ScheduledPruneInterval: s.settings.GetStringSetting(ctx, "scheduledPruneInterval", "0 0 0 * * *"),
GitopsSyncInterval: s.settings.GetStringSetting(ctx, "gitopsSyncInterval", "0 */5 * * * *"),
+ VulnerabilityScanInterval: s.settings.GetStringSetting(ctx, "vulnerabilityScanInterval", "0 0 0 * * *"),
}
}
@@ -80,6 +81,7 @@ func (s *JobService) UpdateJobSchedules(ctx context.Context, updates jobschedule
{key: "pollingInterval", current: current.PollingInterval, update: updates.PollingInterval},
{key: "scheduledPruneInterval", current: current.ScheduledPruneInterval, update: updates.ScheduledPruneInterval},
{key: "gitopsSyncInterval", current: current.GitopsSyncInterval, update: updates.GitopsSyncInterval},
+ {key: "vulnerabilityScanInterval", current: current.VulnerabilityScanInterval, update: updates.VulnerabilityScanInterval},
}
// Validate inputs (cron expressions)
@@ -219,6 +221,7 @@ func (s *JobService) getJobScheduleInternal(ctx context.Context, meta meta.JobMe
"pollingInterval": "0 */15 * * * *",
"scheduledPruneInterval": "0 0 0 * * *",
"gitopsSyncInterval": "0 */5 * * * *",
+ "vulnerabilityScanInterval": "0 0 0 * * *",
}
defaultSchedule := defaultSchedules[meta.SettingsKey]
diff --git a/backend/internal/services/notification_service.go b/backend/internal/services/notification_service.go
index 7d24e09e9..d9db51517 100644
--- a/backend/internal/services/notification_service.go
+++ b/backend/internal/services/notification_service.go
@@ -25,6 +25,18 @@ import (
const logoURLPath = "/api/app-images/logo-email"
+// VulnerabilityNotificationPayload is the data sent to all providers for vulnerability_found events.
+// Only vulnerabilities with a fixed version should trigger this notification.
+type VulnerabilityNotificationPayload struct {
+ CVEID string // e.g. CVE-2024-1234
+ CVELink string // e.g. https://nvd.nist.gov/vuln/detail/CVE-2024-1234
+ Severity string // CRITICAL, HIGH, MEDIUM, LOW, UNKNOWN
+ ImageName string // e.g. nginx:latest
+ FixedVersion string
+ PkgName string // optional
+ InstalledVersion string // optional
+}
+
type NotificationService struct {
db *database.DB
config *config.Config
@@ -259,6 +271,71 @@ func (s *NotificationService) SendContainerUpdateNotification(ctx context.Contex
return nil
}
+// SendVulnerabilityNotification notifies all enabled providers that have vulnerability_found event enabled.
+// Call this for each vulnerability that has a fixed version (so users can upgrade).
+func (s *NotificationService) SendVulnerabilityNotification(ctx context.Context, payload VulnerabilityNotificationPayload) error {
+ settings, err := s.GetAllSettings(ctx)
+ if err != nil {
+ return fmt.Errorf("failed to get notification settings: %w", err)
+ }
+
+ var errors []string
+ for _, setting := range settings {
+ if !setting.Enabled {
+ continue
+ }
+ if !s.isEventEnabled(setting.Config, models.NotificationEventVulnerabilityFound) {
+ continue
+ }
+
+ var sendErr error
+ switch setting.Provider {
+ case models.NotificationProviderDiscord:
+ sendErr = s.sendDiscordVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderEmail:
+ sendErr = s.sendEmailVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderTelegram:
+ sendErr = s.sendTelegramVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderSignal:
+ sendErr = s.sendSignalVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderSlack:
+ sendErr = s.sendSlackVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderNtfy:
+ sendErr = s.sendNtfyVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderPushover:
+ sendErr = s.sendPushoverVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderGotify:
+ sendErr = s.sendGotifyVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderGeneric:
+ sendErr = s.sendGenericVulnerabilityNotification(ctx, payload, setting.Config)
+ default:
+ slog.WarnContext(ctx, "Unknown notification provider", "provider", setting.Provider)
+ continue
+ }
+
+ status := "success"
+ var errMsg *string
+ if sendErr != nil {
+ status = "failed"
+ msg := sendErr.Error()
+ errMsg = &msg
+ errors = append(errors, fmt.Sprintf("%s: %s", setting.Provider, msg))
+ }
+
+ s.logNotification(ctx, setting.Provider, payload.ImageName, status, errMsg, models.JSON{
+ "cveId": payload.CVEID,
+ "severity": payload.Severity,
+ "fixedVersion": payload.FixedVersion,
+ "eventType": string(models.NotificationEventVulnerabilityFound),
+ })
+ }
+
+ if len(errors) > 0 {
+ return fmt.Errorf("notification errors: %s", strings.Join(errors, "; "))
+ }
+ return nil
+}
+
func (s *NotificationService) sendDiscordNotification(ctx context.Context, imageRef string, updateInfo *imageupdate.Response, config models.JSON) error {
var discordConfig models.DiscordConfig
configBytes, err := json.Marshal(config)
@@ -660,6 +737,41 @@ func (s *NotificationService) TestNotification(ctx context.Context, provider mod
return fmt.Errorf("please save your %s settings before testing", provider)
}
+ // Test vulnerability notification (all providers)
+ if testType == "vulnerability-found" {
+ payload := VulnerabilityNotificationPayload{
+ CVEID: "CVE-2024-1234",
+ CVELink: "https://nvd.nist.gov/vuln/detail/CVE-2024-1234",
+ Severity: "HIGH",
+ ImageName: "nginx:latest",
+ FixedVersion: "1.25.1-1",
+ PkgName: "libssl3",
+ InstalledVersion: "3.0.0-1",
+ }
+ switch provider {
+ case models.NotificationProviderDiscord:
+ return s.sendDiscordVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderEmail:
+ return s.sendEmailVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderTelegram:
+ return s.sendTelegramVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderSignal:
+ return s.sendSignalVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderSlack:
+ return s.sendSlackVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderNtfy:
+ return s.sendNtfyVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderPushover:
+ return s.sendPushoverVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderGotify:
+ return s.sendGotifyVulnerabilityNotification(ctx, payload, setting.Config)
+ case models.NotificationProviderGeneric:
+ return s.sendGenericVulnerabilityNotification(ctx, payload, setting.Config)
+ default:
+ return fmt.Errorf("unknown provider: %s", provider)
+ }
+ }
+
testUpdate := &imageupdate.Response{
HasUpdate: true,
UpdateType: "digest",
@@ -1807,6 +1919,381 @@ func (s *NotificationService) sendGenericContainerUpdateNotification(ctx context
return nil
}
+func (s *NotificationService) renderVulnerabilityEmailTemplate(payload VulnerabilityNotificationPayload) (string, string, error) {
+ appURL := s.config.GetAppURL()
+ logoURL := appURL + logoURLPath
+ data := map[string]interface{}{
+ "LogoURL": logoURL,
+ "AppURL": appURL,
+ "CVEID": payload.CVEID,
+ "CVELink": payload.CVELink,
+ "Severity": payload.Severity,
+ "ImageName": payload.ImageName,
+ "FixedVersion": payload.FixedVersion,
+ "PkgName": payload.PkgName,
+ "InstalledVersion": payload.InstalledVersion,
+ }
+
+ htmlContent, err := resources.FS.ReadFile("email-templates/vulnerability-found_html.tmpl")
+ if err != nil {
+ return "", "", fmt.Errorf("failed to read HTML template: %w", err)
+ }
+ htmlTmpl, err := template.New("html").Parse(string(htmlContent))
+ if err != nil {
+ return "", "", fmt.Errorf("failed to parse HTML template: %w", err)
+ }
+ var htmlBuf bytes.Buffer
+ if err := htmlTmpl.ExecuteTemplate(&htmlBuf, "root", data); err != nil {
+ return "", "", fmt.Errorf("failed to execute HTML template: %w", err)
+ }
+
+ textContent, err := resources.FS.ReadFile("email-templates/vulnerability-found_text.tmpl")
+ if err != nil {
+ return "", "", fmt.Errorf("failed to read text template: %w", err)
+ }
+ textTmpl, err := template.New("text").Parse(string(textContent))
+ if err != nil {
+ return "", "", fmt.Errorf("failed to parse text template: %w", err)
+ }
+ var textBuf bytes.Buffer
+ if err := textTmpl.ExecuteTemplate(&textBuf, "root", data); err != nil {
+ return "", "", fmt.Errorf("failed to execute text template: %w", err)
+ }
+ return htmlBuf.String(), textBuf.String(), nil
+}
+
+func (s *NotificationService) sendEmailVulnerabilityNotification(ctx context.Context, payload VulnerabilityNotificationPayload, config models.JSON) error {
+ var emailConfig models.EmailConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal email config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &emailConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal email config: %w", err)
+ }
+ if emailConfig.SMTPHost == "" || emailConfig.SMTPPort == 0 {
+ return fmt.Errorf("SMTP host or port not configured")
+ }
+ if len(emailConfig.ToAddresses) == 0 {
+ return fmt.Errorf("no recipient email addresses configured")
+ }
+ if _, err := mail.ParseAddress(emailConfig.FromAddress); err != nil {
+ return fmt.Errorf("invalid from address: %w", err)
+ }
+ for _, addr := range emailConfig.ToAddresses {
+ if _, err := mail.ParseAddress(addr); err != nil {
+ return fmt.Errorf("invalid to address %s: %w", addr, err)
+ }
+ }
+ if emailConfig.SMTPPassword != "" {
+ if decrypted, err := crypto.Decrypt(emailConfig.SMTPPassword); err == nil {
+ emailConfig.SMTPPassword = decrypted
+ } else {
+ slog.Warn("Failed to decrypt email SMTP password, using raw value (may be unencrypted legacy value)", "error", err)
+ }
+ }
+ htmlBody, _, err := s.renderVulnerabilityEmailTemplate(payload)
+ if err != nil {
+ return fmt.Errorf("failed to render email template: %w", err)
+ }
+ subject := fmt.Sprintf("Vulnerability %s (fix available): %s", payload.CVEID, notifications.SanitizeForEmail(payload.ImageName))
+ if err := notifications.SendEmail(ctx, emailConfig, subject, htmlBody); err != nil {
+ return fmt.Errorf("failed to send email: %w", err)
+ }
+ return nil
+}
+
+func (s *NotificationService) sendDiscordVulnerabilityNotification(ctx context.Context, payload VulnerabilityNotificationPayload, config models.JSON) error {
+ var discordConfig models.DiscordConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Discord config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &discordConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Discord config: %w", err)
+ }
+ if discordConfig.WebhookID == "" || discordConfig.Token == "" {
+ return fmt.Errorf("discord webhook ID or token not configured")
+ }
+ if discordConfig.Token != "" {
+ if decrypted, err := crypto.Decrypt(discordConfig.Token); err == nil {
+ discordConfig.Token = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Discord token, using raw value (may be unencrypted legacy value)", "error", err)
+ }
+ }
+ message := fmt.Sprintf("⚠️ **Vulnerability Found (Fix Available)**\n\n"+
+ "**CVE:** %s\n"+
+ "**Severity:** %s\n"+
+ "**Image:** %s\n"+
+ "**Fixed version:** %s\n",
+ payload.CVEID, payload.Severity, payload.ImageName, payload.FixedVersion)
+ if payload.CVELink != "" {
+ message += fmt.Sprintf("**Link:** %s\n", payload.CVELink)
+ }
+ if payload.PkgName != "" {
+ message += fmt.Sprintf("**Package:** %s\n", payload.PkgName)
+ }
+ if payload.InstalledVersion != "" {
+ message += fmt.Sprintf("**Installed version:** %s\n", payload.InstalledVersion)
+ }
+ if err := notifications.SendDiscord(ctx, discordConfig, message); err != nil {
+ return fmt.Errorf("failed to send Discord notification: %w", err)
+ }
+ return nil
+}
+
+func (s *NotificationService) sendTelegramVulnerabilityNotification(ctx context.Context, payload VulnerabilityNotificationPayload, config models.JSON) error {
+ var telegramConfig models.TelegramConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Telegram config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &telegramConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Telegram config: %w", err)
+ }
+ if telegramConfig.BotToken == "" {
+ return fmt.Errorf("telegram bot token not configured")
+ }
+ if len(telegramConfig.ChatIDs) == 0 {
+ return fmt.Errorf("no telegram chat IDs configured")
+ }
+ if telegramConfig.BotToken != "" {
+ if decrypted, err := crypto.Decrypt(telegramConfig.BotToken); err == nil {
+ telegramConfig.BotToken = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Telegram bot token, using raw value (may be unencrypted legacy value)", "error", err)
+ }
+ }
+ message := fmt.Sprintf("⚠️ <b>Vulnerability Found (Fix Available)</b>\n\n"+
+ "<b>CVE:</b> %s\n"+
+ "<b>Severity:</b> %s\n"+
+ "<b>Image:</b> %s\n"+
+ "<b>Fixed version:</b> %s\n",
+ payload.CVEID, payload.Severity, payload.ImageName, payload.FixedVersion)
+ if payload.CVELink != "" {
+ message += fmt.Sprintf("<b>Link:</b> %s\n", payload.CVELink)
+ }
+ if payload.PkgName != "" {
+ message += fmt.Sprintf("<b>Package:</b> %s\n", payload.PkgName)
+ }
+ if payload.InstalledVersion != "" {
+ message += fmt.Sprintf("<b>Installed version:</b> <code>%s</code>\n", payload.InstalledVersion)
+ }
+ if telegramConfig.ParseMode == "" {
+ telegramConfig.ParseMode = "HTML"
+ }
+ if err := notifications.SendTelegram(ctx, telegramConfig, message); err != nil {
+ return fmt.Errorf("failed to send Telegram notification: %w", err)
+ }
+ return nil
+}
+
+func (s *NotificationService) sendSignalVulnerabilityNotification(ctx context.Context, payload VulnerabilityNotificationPayload, config models.JSON) error {
+ var signalConfig models.SignalConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Signal config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &signalConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Signal config: %w", err)
+ }
+ if signalConfig.Host == "" || signalConfig.Port == 0 || signalConfig.Source == "" || len(signalConfig.Recipients) == 0 {
+ return fmt.Errorf("signal not fully configured")
+ }
+ if signalConfig.Password != "" {
+ if decrypted, err := crypto.Decrypt(signalConfig.Password); err == nil {
+ signalConfig.Password = decrypted
+ }
+ }
+ if signalConfig.Token != "" {
+ if decrypted, err := crypto.Decrypt(signalConfig.Token); err == nil {
+ signalConfig.Token = decrypted
+ }
+ }
+ message := fmt.Sprintf("⚠️ Vulnerability Found (Fix Available)\n\nCVE: %s\nSeverity: %s\nImage: %s\nFixed version: %s\n",
+ payload.CVEID, payload.Severity, payload.ImageName, payload.FixedVersion)
+ if payload.CVELink != "" {
+ message += fmt.Sprintf("Link: %s\n", payload.CVELink)
+ }
+ if payload.PkgName != "" {
+ message += fmt.Sprintf("Package: %s\n", payload.PkgName)
+ }
+ if payload.InstalledVersion != "" {
+ message += fmt.Sprintf("Installed version: %s\n", payload.InstalledVersion)
+ }
+ if err := notifications.SendSignal(ctx, signalConfig, message); err != nil {
+ return fmt.Errorf("failed to send Signal notification: %w", err)
+ }
+ return nil
+}
+
+func (s *NotificationService) sendSlackVulnerabilityNotification(ctx context.Context, payload VulnerabilityNotificationPayload, config models.JSON) error {
+ var slackConfig models.SlackConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Slack config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &slackConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Slack config: %w", err)
+ }
+ if slackConfig.Token == "" {
+ return fmt.Errorf("slack token not configured")
+ }
+ if slackConfig.Token != "" {
+ if decrypted, err := crypto.Decrypt(slackConfig.Token); err == nil {
+ slackConfig.Token = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Slack token, using raw value (may be unencrypted legacy value)", "error", err)
+ }
+ }
+ message := fmt.Sprintf("⚠️ *Vulnerability Found (Fix Available)*\n\n"+
+ "*CVE:* %s\n*Severity:* %s\n*Image:* %s\n*Fixed version:* %s\n",
+ payload.CVEID, payload.Severity, payload.ImageName, payload.FixedVersion)
+ if payload.CVELink != "" {
+ message += fmt.Sprintf("*Link:* %s\n", payload.CVELink)
+ }
+ if payload.PkgName != "" {
+ message += fmt.Sprintf("*Package:* %s\n", payload.PkgName)
+ }
+ if payload.InstalledVersion != "" {
+ message += fmt.Sprintf("*Installed version:* `%s`\n", payload.InstalledVersion)
+ }
+ if err := notifications.SendSlack(ctx, slackConfig, message); err != nil {
+ return fmt.Errorf("failed to send Slack notification: %w", err)
+ }
+ return nil
+}
+
+func (s *NotificationService) sendNtfyVulnerabilityNotification(ctx context.Context, payload VulnerabilityNotificationPayload, config models.JSON) error {
+ var ntfyConfig models.NtfyConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Ntfy config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &ntfyConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Ntfy config: %w", err)
+ }
+ if ntfyConfig.Topic == "" {
+ return fmt.Errorf("ntfy topic is required")
+ }
+ if ntfyConfig.Password != "" {
+ if decrypted, err := crypto.Decrypt(ntfyConfig.Password); err == nil {
+ ntfyConfig.Password = decrypted
+ }
+ }
+ message := fmt.Sprintf("⚠️ Vulnerability Found (Fix Available)\n\nCVE: %s\nSeverity: %s\nImage: %s\nFixed version: %s\n",
+ payload.CVEID, payload.Severity, payload.ImageName, payload.FixedVersion)
+ if payload.CVELink != "" {
+ message += fmt.Sprintf("Link: %s\n", payload.CVELink)
+ }
+ if payload.PkgName != "" {
+ message += fmt.Sprintf("Package: %s\n", payload.PkgName)
+ }
+ if payload.InstalledVersion != "" {
+ message += fmt.Sprintf("Installed version: %s\n", payload.InstalledVersion)
+ }
+ if err := notifications.SendNtfy(ctx, ntfyConfig, message); err != nil {
+ return fmt.Errorf("failed to send Ntfy notification: %w", err)
+ }
+ return nil
+}
+
+func (s *NotificationService) sendPushoverVulnerabilityNotification(ctx context.Context, payload VulnerabilityNotificationPayload, config models.JSON) error {
+ var pushoverConfig models.PushoverConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Pushover config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &pushoverConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Pushover config: %w", err)
+ }
+ if pushoverConfig.Token == "" || pushoverConfig.User == "" {
+ return fmt.Errorf("pushover token or user not configured")
+ }
+ if pushoverConfig.Token != "" {
+ if decrypted, err := crypto.Decrypt(pushoverConfig.Token); err == nil {
+ pushoverConfig.Token = decrypted
+ }
+ }
+ message := fmt.Sprintf("⚠️ Vulnerability Found (Fix Available)\n\nCVE: %s\nSeverity: %s\nImage: %s\nFixed version: %s\n",
+ payload.CVEID, payload.Severity, payload.ImageName, payload.FixedVersion)
+ if payload.CVELink != "" {
+ message += fmt.Sprintf("Link: %s\n", payload.CVELink)
+ }
+ if payload.PkgName != "" {
+ message += fmt.Sprintf("Package: %s\n", payload.PkgName)
+ }
+ if payload.InstalledVersion != "" {
+ message += fmt.Sprintf("Installed version: %s\n", payload.InstalledVersion)
+ }
+ if err := notifications.SendPushover(ctx, pushoverConfig, message); err != nil {
+ return fmt.Errorf("failed to send Pushover notification: %w", err)
+ }
+ return nil
+}
+
+func (s *NotificationService) sendGotifyVulnerabilityNotification(ctx context.Context, payload VulnerabilityNotificationPayload, config models.JSON) error {
+ var gotifyConfig models.GotifyConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Gotify config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &gotifyConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Gotify config: %w", err)
+ }
+ if gotifyConfig.Token != "" {
+ if decrypted, err := crypto.Decrypt(gotifyConfig.Token); err == nil {
+ gotifyConfig.Token = decrypted
+ }
+ }
+ message := fmt.Sprintf("⚠️ Vulnerability Found (Fix Available)\n\nCVE: %s\nSeverity: %s\nImage: %s\nFixed version: %s\n",
+ payload.CVEID, payload.Severity, payload.ImageName, payload.FixedVersion)
+ if payload.CVELink != "" {
+ message += fmt.Sprintf("Link: %s\n", payload.CVELink)
+ }
+ if payload.PkgName != "" {
+ message += fmt.Sprintf("Package: %s\n", payload.PkgName)
+ }
+ if payload.InstalledVersion != "" {
+ message += fmt.Sprintf("Installed version: %s\n", payload.InstalledVersion)
+ }
+ if err := notifications.SendGotify(ctx, gotifyConfig, message); err != nil {
+ return fmt.Errorf("failed to send Gotify notification: %w", err)
+ }
+ return nil
+}
+
+func (s *NotificationService) sendGenericVulnerabilityNotification(ctx context.Context, payload VulnerabilityNotificationPayload, config models.JSON) error {
+ var genericConfig models.GenericConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Generic config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &genericConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Generic config: %w", err)
+ }
+ if genericConfig.WebhookURL == "" {
+ return fmt.Errorf("webhook URL not configured")
+ }
+ message := fmt.Sprintf("Vulnerability Found (Fix Available)\n\nCVE: %s\nSeverity: %s\nImage: %s\nFixed version: %s\n",
+ payload.CVEID, payload.Severity, payload.ImageName, payload.FixedVersion)
+ if payload.CVELink != "" {
+ message += fmt.Sprintf("Link: %s\n", payload.CVELink)
+ }
+ if payload.PkgName != "" {
+ message += fmt.Sprintf("Package: %s\n", payload.PkgName)
+ }
+ if payload.InstalledVersion != "" {
+ message += fmt.Sprintf("Installed version: %s\n", payload.InstalledVersion)
+ }
+ title := fmt.Sprintf("Vulnerability %s: %s", payload.CVEID, payload.ImageName)
+ if err := notifications.SendGenericWithTitle(ctx, genericConfig, title, message); err != nil {
+ return fmt.Errorf("failed to send Generic webhook notification: %w", err)
+ }
+ return nil
+}
+
func (s *NotificationService) sendBatchGenericNotification(ctx context.Context, updates map[string]*imageupdate.Response, config models.JSON) error {
var genericConfig models.GenericConfig
configBytes, err := json.Marshal(config)
diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.go
index fc72f9bb8..800354369 100644
--- a/backend/internal/services/settings_service.go
+++ b/backend/internal/services/settings_service.go
@@ -33,11 +33,12 @@ type SettingsService struct {
db *database.DB
config atomic.Pointer[models.Settings]
- OnImagePollingSettingsChanged func(ctx context.Context)
- OnAutoUpdateSettingsChanged func(ctx context.Context)
- OnProjectsDirectoryChanged func(ctx context.Context)
- OnScheduledPruneSettingsChanged func(ctx context.Context)
- OnTimeoutSettingsChanged func(ctx context.Context, timeoutSettings map[string]string)
+ OnImagePollingSettingsChanged func(ctx context.Context)
+ OnAutoUpdateSettingsChanged func(ctx context.Context)
+ OnProjectsDirectoryChanged func(ctx context.Context)
+ OnScheduledPruneSettingsChanged func(ctx context.Context)
+ OnVulnerabilityScanSettingsChanged func(ctx context.Context)
+ OnTimeoutSettingsChanged func(ctx context.Context, timeoutSettings map[string]string)
}
func NewSettingsService(ctx context.Context, db *database.DB) (*SettingsService, error) {
@@ -108,6 +109,7 @@ func (s *SettingsService) getDefaultSettings() *models.Settings {
AuthLocalEnabled: models.SettingVariable{Value: "true"},
AuthSessionTimeout: models.SettingVariable{Value: "1440"},
AuthPasswordPolicy: models.SettingVariable{Value: "strong"},
+ TrivyImage: models.SettingVariable{Value: "ghcr.io/aquasecurity/trivy:latest"},
// AuthOidcConfig DEPRECATED will be removed in a future release
AuthOidcConfig: models.SettingVariable{Value: "{}"},
OidcEnabled: models.SettingVariable{Value: "false"},
@@ -431,7 +433,7 @@ func (s *SettingsService) UpdateSettings(ctx context.Context, updates settings.U
return nil, fmt.Errorf("failed to load current settings: %w", err)
}
- valuesToUpdate, changedPolling, changedAutoUpdate, changedScheduledPrune, changedTimeouts, err := s.prepareUpdateValues(updates, cfg, defaultCfg)
+ valuesToUpdate, changedPolling, changedAutoUpdate, changedScheduledPrune, changedVulnerabilityScan, changedTimeouts, err := s.prepareUpdateValues(updates, cfg, defaultCfg)
if err != nil {
return nil, err
}
@@ -462,6 +464,9 @@ func (s *SettingsService) UpdateSettings(ctx context.Context, updates settings.U
if changedScheduledPrune && s.OnScheduledPruneSettingsChanged != nil {
s.OnScheduledPruneSettingsChanged(ctx)
}
+ if changedVulnerabilityScan && s.OnVulnerabilityScanSettingsChanged != nil {
+ s.OnVulnerabilityScanSettingsChanged(ctx)
+ }
if slices.ContainsFunc(valuesToUpdate, func(sv models.SettingVariable) bool { return sv.Key == "projectsDirectory" }) && s.OnProjectsDirectoryChanged != nil {
s.OnProjectsDirectoryChanged(ctx)
}
@@ -482,7 +487,7 @@ var timeoutSettingKeys = []string{
"proxyRequestTimeout",
}
-func (s *SettingsService) prepareUpdateValues(updates settings.Update, cfg, defaultCfg *models.Settings) ([]models.SettingVariable, bool, bool, bool, map[string]string, error) {
+func (s *SettingsService) prepareUpdateValues(updates settings.Update, cfg, defaultCfg *models.Settings) ([]models.SettingVariable, bool, bool, bool, bool, map[string]string, error) {
rt := reflect.TypeOf(updates)
rv := reflect.ValueOf(updates)
valuesToUpdate := make([]models.SettingVariable, 0)
@@ -490,6 +495,7 @@ func (s *SettingsService) prepareUpdateValues(updates settings.Update, cfg, defa
changedPolling := false
changedAutoUpdate := false
changedScheduledPrune := false
+ changedVulnerabilityScan := false
changedTimeouts := make(map[string]string)
for i := 0; i < rt.NumField(); i++ {
@@ -507,10 +513,10 @@ func (s *SettingsService) prepareUpdateValues(updates settings.Update, cfg, defa
}
// Validate cron settings
- cronFields := []string{"scheduledPruneInterval", "autoUpdateInterval", "pollingInterval", "environmentHealthInterval", "eventCleanupInterval", "analyticsHeartbeatInterval"}
+ cronFields := []string{"scheduledPruneInterval", "autoUpdateInterval", "pollingInterval", "environmentHealthInterval", "eventCleanupInterval", "analyticsHeartbeatInterval", "vulnerabilityScanInterval"}
if slices.Contains(cronFields, key) && value != "" {
if _, err := cron.NewParser(cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow).Parse(value); err != nil {
- return nil, false, false, false, nil, fmt.Errorf("invalid cron expression for %s: %w", key, err)
+ return nil, false, false, false, false, nil, fmt.Errorf("invalid cron expression for %s: %w", key, err)
}
}
@@ -529,7 +535,7 @@ func (s *SettingsService) prepareUpdateValues(updates settings.Update, cfg, defa
if errors.Is(err, models.SettingSensitiveForbiddenError{}) {
continue
} else if err != nil {
- return nil, false, false, false, nil, fmt.Errorf("failed to update in-memory config for key '%s': %w", key, err)
+ return nil, false, false, false, false, nil, fmt.Errorf("failed to update in-memory config for key '%s': %w", key, err)
}
valuesToUpdate = append(valuesToUpdate, models.SettingVariable{
@@ -544,6 +550,8 @@ func (s *SettingsService) prepareUpdateValues(updates settings.Update, cfg, defa
changedAutoUpdate = true
case "scheduledPruneEnabled", "scheduledPruneInterval", "scheduledPruneContainers", "scheduledPruneImages", "scheduledPruneVolumes", "scheduledPruneNetworks", "scheduledPruneBuildCache":
changedScheduledPrune = true
+ case "vulnerabilityScanEnabled", "vulnerabilityScanInterval":
+ changedVulnerabilityScan = true
}
// Track timeout setting changes
@@ -552,7 +560,7 @@ func (s *SettingsService) prepareUpdateValues(updates settings.Update, cfg, defa
}
}
- return valuesToUpdate, changedPolling, changedAutoUpdate, changedScheduledPrune, changedTimeouts, nil
+ return valuesToUpdate, changedPolling, changedAutoUpdate, changedScheduledPrune, changedVulnerabilityScan, changedTimeouts, nil
}
func (s *SettingsService) persistSettings(ctx context.Context, values []models.SettingVariable) error {
diff --git a/backend/internal/services/vulnerability_service.go b/backend/internal/services/vulnerability_service.go
new file mode 100644
index 000000000..29c67ba17
--- /dev/null
+++ b/backend/internal/services/vulnerability_service.go
@@ -0,0 +1,1772 @@
+package services
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "strings"
+ "sync"
+ "time"
+
+ containertypes "github.com/docker/docker/api/types/container"
+ imagetypes "github.com/docker/docker/api/types/image"
+ mounttypes "github.com/docker/docker/api/types/mount"
+ volumetypes "github.com/docker/docker/api/types/volume"
+ "github.com/docker/docker/client"
+ "github.com/docker/docker/pkg/stdcopy"
+ "github.com/getarcaneapp/arcane/backend/internal/database"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/timeouts"
+ "github.com/getarcaneapp/arcane/backend/pkg/libarcane"
+ "github.com/getarcaneapp/arcane/types/vulnerability"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+const (
+ DefaultTrivyImage = "ghcr.io/aquasecurity/trivy:latest"
+ trivyCacheVolumeName = "arcane-trivy-cache"
+ trivyCacheMountTarget = "/root/.cache"
+ scanStaleTimeout = 30 * time.Minute
+ trivyMaxCPUNano = int64(1_000_000_000) // 1 CPU core
+ trivyMaxMemoryBytes = int64(512 * 1024 * 1024)
+)
+
+// VulnerabilityService handles vulnerability scanning of container images
+type VulnerabilityService struct {
+ db *database.DB
+ dockerService *DockerClientService
+ eventService *EventService
+ settingsService *SettingsService
+ notificationService *NotificationService
+ // scanLocks provides per-image locking to allow concurrent scans of different images
+ // while preventing duplicate scans of the same image
+ scanLocks sync.Map // map[string]*sync.Mutex
+}
+
+// getImageLock returns a mutex for the given image ID, creating one if needed
+func (s *VulnerabilityService) getImageLock(imageID string) *sync.Mutex {
+ lock, _ := s.scanLocks.LoadOrStore(imageID, &sync.Mutex{})
+ return lock.(*sync.Mutex)
+}
+
+// NewVulnerabilityService creates a new VulnerabilityService instance
+func NewVulnerabilityService(db *database.DB, dockerService *DockerClientService, eventService *EventService, settingsService *SettingsService, notificationService *NotificationService) *VulnerabilityService {
+ return &VulnerabilityService{
+ db: db,
+ dockerService: dockerService,
+ eventService: eventService,
+ settingsService: settingsService,
+ notificationService: notificationService,
+ }
+}
+
+// ScanImage scans an image for vulnerabilities using Trivy
+func (s *VulnerabilityService) ScanImage(ctx context.Context, envID string, imageID string, user models.User) (*vulnerability.ScanResult, error) {
+ scanCtx := context.WithoutCancel(ctx)
+
+ // Get Docker client to inspect the image
+ dockerClient, err := s.dockerService.GetClient()
+ if err != nil {
+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)
+ }
+
+ // Inspect the image to get details
+ imageInspect, err := dockerClient.ImageInspect(scanCtx, imageID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to inspect image: %w", err)
+ }
+
+ // Determine image name to scan
+ imageName := imageID
+ if len(imageInspect.RepoTags) > 0 {
+ imageName = imageInspect.RepoTags[0]
+ } else if len(imageInspect.RepoDigests) > 0 {
+ imageName = imageInspect.RepoDigests[0]
+ }
+
+ // Create pending scan record
+ pendingResult := &vulnerability.ScanResult{
+ ImageID: imageID,
+ ImageName: imageName,
+ ScanTime: time.Now(),
+ Status: vulnerability.ScanStatusScanning,
+ }
+ if saveErr := s.saveScanResult(scanCtx, pendingResult); saveErr != nil {
+ slog.WarnContext(scanCtx, "failed to save pending scan result", "error", saveErr)
+ }
+
+ go func(bgCtx context.Context, scanEnvID, imgID, imgName string, scanUser models.User) {
+ s.scanImageInBackgroundInternal(bgCtx, scanEnvID, imgID, imgName, scanUser)
+ }(scanCtx, envID, imageID, imageName, user)
+
+ return pendingResult, nil
+}
+
+func (s *VulnerabilityService) markStaleScanIfNeeded(ctx context.Context, record *models.VulnerabilityScanRecord) bool {
+ if record == nil {
+ return false
+ }
+ if record.Status != models.ScanStatusScanning && record.Status != models.ScanStatusPending {
+ return false
+ }
+ if time.Since(record.ScanTime) <= scanStaleTimeout {
+ return false
+ }
+
+ errMsg := "Scan timed out or was interrupted. Please retry."
+ record.Status = models.ScanStatusFailed
+ record.Error = &errMsg
+ record.Duration = time.Since(record.ScanTime).Milliseconds()
+
+ if s.db == nil {
+ return true
+ }
+
+ if err := s.db.WithContext(ctx).
+ Model(&models.VulnerabilityScanRecord{}).
+ Where("id = ?", record.ID).
+ Updates(map[string]any{
+ "status": record.Status,
+ "error": errMsg,
+ "duration": record.Duration,
+ }).Error; err != nil {
+ slog.WarnContext(ctx, "failed to mark stale scan as failed", "error", err, "scan_id", record.ID)
+ return false
+ }
+
+ return true
+}
+
+func (s *VulnerabilityService) scanImageInBackgroundInternal(ctx context.Context, envID string, imageID, imageName string, user models.User) {
+ trivyImage, err := s.ensureTrivyImageInternal(ctx)
+ if err != nil {
+ result := &vulnerability.ScanResult{
+ ImageID: imageID,
+ ImageName: imageName,
+ ScanTime: time.Now(),
+ Status: vulnerability.ScanStatusFailed,
+ Error: fmt.Sprintf("Trivy scanner is not available: %s", err.Error()),
+ }
+ if saveErr := s.saveScanResult(ctx, result); saveErr != nil {
+ slog.WarnContext(ctx, "failed to save scan result", "error", saveErr)
+ }
+ return
+ }
+
+ startTime := time.Now()
+ result, err := s.runTrivyScan(ctx, trivyImage, imageName, imageID)
+ duration := time.Since(startTime).Milliseconds()
+
+ if err != nil {
+ failedResult := &vulnerability.ScanResult{
+ ImageID: imageID,
+ ImageName: imageName,
+ ScanTime: time.Now(),
+ Status: vulnerability.ScanStatusFailed,
+ Error: err.Error(),
+ Duration: duration,
+ }
+ if saveErr := s.saveScanResult(ctx, failedResult); saveErr != nil {
+ slog.WarnContext(ctx, "failed to save failed scan result", "error", saveErr)
+ }
+ s.logScanEvent(ctx, envID, imageID, imageName, user, false, err.Error())
+ return
+ }
+
+ result.Duration = duration
+ s.ensureSummary(result)
+ if saveErr := s.saveScanResult(ctx, result); saveErr != nil {
+ slog.WarnContext(ctx, "failed to save scan result", "error", saveErr)
+ }
+
+ s.notifyVulnerabilitiesWithFix(ctx, result)
+ s.logScanEvent(ctx, envID, imageID, imageName, user, true, "")
+}
+
+// GetScanResult retrieves the most recent scan result for an image
+func (s *VulnerabilityService) GetScanResult(ctx context.Context, imageID string) (*vulnerability.ScanResult, error) {
+ if s.db == nil {
+ return nil, nil
+ }
+
+ var record models.VulnerabilityScanRecord
+ err := s.db.WithContext(ctx).Where("id = ?", imageID).First(&record).Error
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("failed to get scan result: %w", err)
+ }
+
+ s.markStaleScanIfNeeded(ctx, &record)
+
+ return s.convertRecordToResult(&record)
+}
+
+// GetScanSummary retrieves just the summary for an image (for list views)
+func (s *VulnerabilityService) GetScanSummary(ctx context.Context, imageID string) (*vulnerability.ScanSummary, error) {
+ if s.db == nil {
+ return nil, nil
+ }
+
+ var record models.VulnerabilityScanRecord
+ err := s.db.WithContext(ctx).
+ Select("id", "scan_time", "status", "critical_count", "high_count", "medium_count", "low_count", "unknown_count", "total_count", "error").
+ Where("id = ?", imageID).
+ First(&record).Error
+
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("failed to get scan summary: %w", err)
+ }
+
+ s.markStaleScanIfNeeded(ctx, &record)
+
+ var errPtr *string
+ if record.Error != nil {
+ errPtr = record.Error
+ }
+
+ return &vulnerability.ScanSummary{
+ ImageID: record.ID,
+ ScanTime: record.ScanTime,
+ Status: vulnerability.ScanStatus(record.Status),
+ Summary: &vulnerability.SeveritySummary{
+ Critical: record.CriticalCount,
+ High: record.HighCount,
+ Medium: record.MediumCount,
+ Low: record.LowCount,
+ Unknown: record.UnknownCount,
+ Total: record.TotalCount,
+ },
+ Error: stringPtrValueOrEmptyInternal(errPtr),
+ }, nil
+}
+
+// ListVulnerabilities returns a paginated, filtered list of vulnerabilities for an image.
+func (s *VulnerabilityService) ListVulnerabilities(ctx context.Context, imageID string, params pagination.QueryParams) ([]vulnerability.Vulnerability, pagination.Response, error) {
+ result, err := s.GetScanResult(ctx, imageID)
+ if err != nil {
+ return nil, pagination.Response{}, fmt.Errorf("failed to get scan result: %w", err)
+ }
+ if result == nil {
+ limit := params.Limit
+ if limit <= 0 {
+ limit = 20
+ }
+ return []vulnerability.Vulnerability{}, pagination.Response{
+ TotalPages: 1,
+ TotalItems: 0,
+ CurrentPage: 1,
+ ItemsPerPage: limit,
+ GrandTotalItems: 0,
+ }, nil
+ }
+
+ config := pagination.Config[vulnerability.Vulnerability]{
+ SearchAccessors: []pagination.SearchAccessor[vulnerability.Vulnerability]{
+ func(item vulnerability.Vulnerability) (string, error) { return item.VulnerabilityID, nil },
+ func(item vulnerability.Vulnerability) (string, error) { return item.PkgName, nil },
+ func(item vulnerability.Vulnerability) (string, error) { return item.InstalledVersion, nil },
+ func(item vulnerability.Vulnerability) (string, error) { return item.FixedVersion, nil },
+ func(item vulnerability.Vulnerability) (string, error) { return item.Title, nil },
+ },
+ SortBindings: []pagination.SortBinding[vulnerability.Vulnerability]{
+ {
+ Key: "vulnerabilityId",
+ Fn: func(a, b vulnerability.Vulnerability) int {
+ return strings.Compare(a.VulnerabilityID, b.VulnerabilityID)
+ },
+ },
+ {
+ Key: "pkgName",
+ Fn: func(a, b vulnerability.Vulnerability) int { return strings.Compare(a.PkgName, b.PkgName) },
+ },
+ {
+ Key: "severity",
+ Fn: func(a, b vulnerability.Vulnerability) int {
+ return severityRankInternal(a.Severity) - severityRankInternal(b.Severity)
+ },
+ },
+ {
+ Key: "installedVersion",
+ Fn: func(a, b vulnerability.Vulnerability) int {
+ return strings.Compare(a.InstalledVersion, b.InstalledVersion)
+ },
+ },
+ {
+ Key: "fixedVersion",
+ Fn: func(a, b vulnerability.Vulnerability) int { return strings.Compare(a.FixedVersion, b.FixedVersion) },
+ },
+ },
+ FilterAccessors: []pagination.FilterAccessor[vulnerability.Vulnerability]{
+ {
+ Key: "severity",
+ Fn: func(item vulnerability.Vulnerability, value string) bool {
+ return strings.EqualFold(string(item.Severity), value)
+ },
+ },
+ },
+ }
+
+ filtered := pagination.SearchOrderAndPaginate(result.Vulnerabilities, params, config)
+ response := pagination.BuildResponseFromFilterResult(filtered, params)
+
+ return filtered.Items, response, nil
+}
+
+// GetEnvironmentSummary returns aggregated vulnerability counts across all images.
+func (s *VulnerabilityService) GetEnvironmentSummary(ctx context.Context) (*vulnerability.EnvironmentVulnerabilitySummary, error) {
+ if s.db != nil && s.dockerService != nil {
+ if deleted, err := s.CleanupOrphanedScanRecords(ctx); err != nil {
+ slog.WarnContext(ctx, "failed to cleanup orphaned vulnerability scan records", "error", err)
+ } else if deleted > 0 {
+ slog.DebugContext(ctx, "cleaned up orphaned vulnerability scan records", "deleted", deleted)
+ }
+ }
+
+ summary := &vulnerability.EnvironmentVulnerabilitySummary{
+ Summary: &vulnerability.SeveritySummary{},
+ }
+
+ if s.dockerService != nil {
+ _, _, _, total, err := s.dockerService.GetAllImages(ctx)
+ if err != nil {
+ slog.WarnContext(ctx, "failed to list images for vulnerability summary", "error", err)
+ } else {
+ summary.TotalImages = total
+ }
+ }
+
+ if s.db == nil {
+ return summary, nil
+ }
+
+ type aggregate struct {
+ Critical int `gorm:"column:critical"`
+ High int `gorm:"column:high"`
+ Medium int `gorm:"column:medium"`
+ Low int `gorm:"column:low"`
+ Unknown int `gorm:"column:unknown"`
+ Total int `gorm:"column:total"`
+ Scanned int `gorm:"column:scanned"`
+ }
+
+ var agg aggregate
+ err := s.db.WithContext(ctx).
+ Model(&models.VulnerabilityScanRecord{}).
+ Select(
+ "COALESCE(SUM(critical_count), 0) AS critical",
+ "COALESCE(SUM(high_count), 0) AS high",
+ "COALESCE(SUM(medium_count), 0) AS medium",
+ "COALESCE(SUM(low_count), 0) AS low",
+ "COALESCE(SUM(unknown_count), 0) AS unknown",
+ "COALESCE(SUM(total_count), 0) AS total",
+ "COUNT(*) AS scanned",
+ ).
+ Where("status = ?", models.ScanStatusCompleted).
+ Scan(&agg).Error
+ if err != nil {
+ return nil, fmt.Errorf("failed to aggregate vulnerability summary: %w", err)
+ }
+
+ summary.ScannedImages = agg.Scanned
+ summary.Summary = &vulnerability.SeveritySummary{
+ Critical: agg.Critical,
+ High: agg.High,
+ Medium: agg.Medium,
+ Low: agg.Low,
+ Unknown: agg.Unknown,
+ Total: agg.Total,
+ }
+
+ return summary, nil
+}
+
+// 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.db == nil {
+ return []vulnerability.VulnerabilityWithImage{}, pagination.Response{
+ TotalPages: 1,
+ TotalItems: 0,
+ CurrentPage: 1,
+ ItemsPerPage: params.Limit,
+ GrandTotalItems: 0,
+ }, nil
+ }
+
+ var records []models.VulnerabilityScanRecord
+ if err := s.db.WithContext(ctx).
+ Select("id", "image_name", "vulnerabilities", "status", "total_count").
+ Where("status = ?", models.ScanStatusCompleted).
+ Where("total_count > 0").
+ Find(&records).Error; err != nil {
+ return nil, pagination.Response{}, fmt.Errorf("failed to list vulnerability scans: %w", err)
+ }
+
+ items := make([]vulnerability.VulnerabilityWithImage, 0)
+ for _, record := range records {
+ if len(record.Vulnerabilities) == 0 || record.Vulnerabilities[0] == "" {
+ continue
+ }
+
+ var vulns []vulnerability.Vulnerability
+ if err := json.Unmarshal([]byte(record.Vulnerabilities[0]), &vulns); err != nil {
+ slog.WarnContext(ctx, "failed to unmarshal vulnerabilities", "error", err, "image_id", record.ID)
+ continue
+ }
+
+ for _, vuln := range vulns {
+ items = append(items, vulnerability.VulnerabilityWithImage{
+ Vulnerability: vuln,
+ ImageID: record.ID,
+ ImageName: record.ImageName,
+ })
+ }
+ }
+
+ // Filter out ignored vulnerabilities
+ items, err := s.filterIgnoredVulnerabilities(ctx, envID, items)
+ if err != nil {
+ slog.WarnContext(ctx, "failed to filter ignored vulnerabilities", "error", err)
+ }
+
+ config := pagination.Config[vulnerability.VulnerabilityWithImage]{
+ SearchAccessors: []pagination.SearchAccessor[vulnerability.VulnerabilityWithImage]{
+ func(item vulnerability.VulnerabilityWithImage) (string, error) { return item.VulnerabilityID, nil },
+ func(item vulnerability.VulnerabilityWithImage) (string, error) { return item.PkgName, nil },
+ func(item vulnerability.VulnerabilityWithImage) (string, error) { return item.InstalledVersion, nil },
+ func(item vulnerability.VulnerabilityWithImage) (string, error) { return item.FixedVersion, nil },
+ func(item vulnerability.VulnerabilityWithImage) (string, error) { return item.Title, nil },
+ func(item vulnerability.VulnerabilityWithImage) (string, error) { return item.ImageName, nil },
+ func(item vulnerability.VulnerabilityWithImage) (string, error) { return item.ImageID, nil },
+ },
+ SortBindings: []pagination.SortBinding[vulnerability.VulnerabilityWithImage]{
+ {
+ Key: "vulnerabilityId",
+ Fn: func(a, b vulnerability.VulnerabilityWithImage) int {
+ return strings.Compare(a.VulnerabilityID, b.VulnerabilityID)
+ },
+ },
+ {
+ Key: "pkgName",
+ Fn: func(a, b vulnerability.VulnerabilityWithImage) int { return strings.Compare(a.PkgName, b.PkgName) },
+ },
+ {
+ Key: "severity",
+ Fn: func(a, b vulnerability.VulnerabilityWithImage) int {
+ return severityRankInternal(a.Severity) - severityRankInternal(b.Severity)
+ },
+ },
+ {
+ Key: "installedVersion",
+ Fn: func(a, b vulnerability.VulnerabilityWithImage) int {
+ return strings.Compare(a.InstalledVersion, b.InstalledVersion)
+ },
+ },
+ {
+ Key: "fixedVersion",
+ Fn: func(a, b vulnerability.VulnerabilityWithImage) int {
+ return strings.Compare(a.FixedVersion, b.FixedVersion)
+ },
+ },
+ {
+ Key: "imageName",
+ Fn: func(a, b vulnerability.VulnerabilityWithImage) int { return strings.Compare(a.ImageName, b.ImageName) },
+ },
+ },
+ FilterAccessors: []pagination.FilterAccessor[vulnerability.VulnerabilityWithImage]{
+ {
+ Key: "severity",
+ Fn: func(item vulnerability.VulnerabilityWithImage, value string) bool {
+ return strings.EqualFold(string(item.Severity), value)
+ },
+ },
+ {
+ Key: "imageName",
+ Fn: func(item vulnerability.VulnerabilityWithImage, value string) bool {
+ itemLower := strings.ToLower(item.ImageName)
+ for _, part := range strings.Split(value, ",") {
+ if part = strings.TrimSpace(part); part != "" && strings.Contains(itemLower, strings.ToLower(part)) {
+ return true
+ }
+ }
+ return false
+ },
+ },
+ },
+ }
+
+ filtered := pagination.SearchOrderAndPaginate(items, params, config)
+ response := pagination.BuildResponseFromFilterResult(filtered, params)
+
+ return filtered.Items, response, nil
+}
+
+func severityRankInternal(severity vulnerability.Severity) int {
+ switch severity {
+ case vulnerability.SeverityCritical:
+ return 4
+ case vulnerability.SeverityHigh:
+ return 3
+ case vulnerability.SeverityMedium:
+ return 2
+ case vulnerability.SeverityLow:
+ return 1
+ case vulnerability.SeverityUnknown:
+ return 0
+ default:
+ return 0
+ }
+}
+
+// GetScanSummariesByImageIDs retrieves scan summaries for multiple images
+func (s *VulnerabilityService) GetScanSummariesByImageIDs(ctx context.Context, imageIDs []string) (map[string]*vulnerability.ScanSummary, error) {
+ if s.db == nil || len(imageIDs) == 0 {
+ return make(map[string]*vulnerability.ScanSummary), nil
+ }
+
+ var records []models.VulnerabilityScanRecord
+ err := s.db.WithContext(ctx).
+ Select("id", "scan_time", "status", "critical_count", "high_count", "medium_count", "low_count", "unknown_count", "total_count", "error").
+ Where("id IN ?", imageIDs).
+ Find(&records).Error
+
+ if err != nil {
+ return nil, fmt.Errorf("failed to get scan summaries: %w", err)
+ }
+
+ result := make(map[string]*vulnerability.ScanSummary, len(records))
+ for _, record := range records {
+ s.markStaleScanIfNeeded(ctx, &record)
+ var errStr string
+ if record.Error != nil {
+ errStr = *record.Error
+ }
+
+ result[record.ID] = &vulnerability.ScanSummary{
+ ImageID: record.ID,
+ ScanTime: record.ScanTime,
+ Status: vulnerability.ScanStatus(record.Status),
+ Summary: &vulnerability.SeveritySummary{
+ Critical: record.CriticalCount,
+ High: record.HighCount,
+ Medium: record.MediumCount,
+ Low: record.LowCount,
+ Unknown: record.UnknownCount,
+ Total: record.TotalCount,
+ },
+ Error: errStr,
+ }
+ }
+
+ return result, nil
+}
+
+// ScanAllImages scans all Docker images for vulnerabilities. It is intended
+// for use by the scheduled vulnerability scan job. A single long-running Trivy
+// container is created and reused for every image via docker exec, which avoids
+// the overhead of creating/destroying a container per scan. The caller-supplied
+// user is recorded in the event log.
+func (s *VulnerabilityService) ScanAllImages(ctx context.Context, envID string, user models.User) (scanned, failed int, err error) {
+ dockerClient, err := s.dockerService.GetClient()
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to connect to Docker: %w", err)
+ }
+
+ images, err := dockerClient.ImageList(ctx, imagetypes.ListOptions{})
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to list images: %w", err)
+ }
+
+ trivyImage, err := s.ensureTrivyImageInternal(ctx)
+ if err != nil {
+ return 0, 0, fmt.Errorf("trivy scanner not available: %w", err)
+ }
+
+ cacheVolume, err := s.ensureTrivyCacheVolumeInternal(ctx)
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to ensure trivy cache volume: %w", err)
+ }
+
+ // Create a single long-running Trivy container for the entire batch.
+ containerID, err := s.createBatchTrivyContainer(ctx, trivyImage, cacheVolume)
+ if err != nil {
+ return 0, 0, fmt.Errorf("failed to create batch trivy container: %w", err)
+ }
+ defer func() {
+ cleanupCtx := context.WithoutCancel(ctx)
+ if rmErr := dockerClient.ContainerRemove(cleanupCtx, containerID, containertypes.RemoveOptions{Force: true}); rmErr != nil {
+ slog.WarnContext(cleanupCtx, "failed to remove batch trivy container", "containerId", containerID, "error", rmErr)
+ }
+ }()
+
+ scannerVersion := s.GetTrivyVersion(ctx)
+
+ for _, img := range images {
+ if ctx.Err() != nil {
+ return scanned, failed, ctx.Err()
+ }
+
+ imageID := img.ID
+ imageName := imageID
+ if len(img.RepoTags) > 0 {
+ imageName = img.RepoTags[0]
+ } else if len(img.RepoDigests) > 0 {
+ imageName = img.RepoDigests[0]
+ }
+
+ // Skip intermediate / dangling images with no name
+ if imageName == "<none>:<none>" || imageName == imageID {
+ continue
+ }
+
+ slog.InfoContext(ctx, "scheduled vulnerability scan: scanning image", "image", imageName, "imageId", imageID)
+
+ startTime := time.Now()
+ result, scanErr := s.execTrivyScanInContainer(ctx, containerID, imageName, imageID, scannerVersion)
+ duration := time.Since(startTime).Milliseconds()
+
+ if scanErr != nil {
+ failed++
+ failedResult := &vulnerability.ScanResult{
+ ImageID: imageID,
+ ImageName: imageName,
+ ScanTime: time.Now(),
+ Status: vulnerability.ScanStatusFailed,
+ Error: scanErr.Error(),
+ Duration: duration,
+ }
+ if saveErr := s.saveScanResult(ctx, failedResult); saveErr != nil {
+ slog.WarnContext(ctx, "failed to save failed scan result", "error", saveErr)
+ }
+ s.logScheduledScanEvent(ctx, envID, imageID, imageName, user, false, scanErr.Error())
+ continue
+ }
+
+ scanned++
+ result.Duration = duration
+ s.ensureSummary(result)
+ if saveErr := s.saveScanResult(ctx, result); saveErr != nil {
+ slog.WarnContext(ctx, "failed to save scan result", "error", saveErr)
+ }
+ s.notifyVulnerabilitiesWithFix(ctx, result)
+ s.logScheduledScanEvent(ctx, envID, imageID, imageName, user, true, "")
+ }
+
+ return scanned, failed, nil
+}
+
+// createBatchTrivyContainer creates a long-running Trivy container that stays
+// alive so we can exec individual scan commands into it. This avoids the
+// overhead of creating/starting/removing a container for every image.
+func (s *VulnerabilityService) createBatchTrivyContainer(ctx context.Context, trivyImage, cacheVolume string) (string, error) {
+ dockerClient, err := s.dockerService.GetClient()
+ if err != nil {
+ return "", fmt.Errorf("failed to connect to Docker: %w", err)
+ }
+
+ config := &containertypes.Config{
+ Image: trivyImage,
+ Entrypoint: []string{"sh", "-c", "trap 'exit 0' TERM; while :; do sleep 1; done"},
+ Labels: map[string]string{
+ libarcane.InternalContainerLabel: "true",
+ },
+ }
+
+ hostConfig := &containertypes.HostConfig{
+ Mounts: []mounttypes.Mount{
+ {
+ Type: mounttypes.TypeBind,
+ Source: "/var/run/docker.sock",
+ Target: "/var/run/docker.sock",
+ },
+ {
+ Type: mounttypes.TypeVolume,
+ Source: cacheVolume,
+ Target: trivyCacheMountTarget,
+ },
+ },
+ Resources: containertypes.Resources{
+ NanoCPUs: trivyMaxCPUNano,
+ Memory: trivyMaxMemoryBytes,
+ MemorySwap: trivyMaxMemoryBytes,
+ },
+ }
+
+ resp, err := dockerClient.ContainerCreate(ctx, config, hostConfig, nil, nil, "")
+ if err != nil {
+ return "", fmt.Errorf("failed to create container: %w", err)
+ }
+
+ if err := dockerClient.ContainerStart(ctx, resp.ID, containertypes.StartOptions{}); err != nil {
+ _ = dockerClient.ContainerRemove(ctx, resp.ID, containertypes.RemoveOptions{Force: true})
+ return "", fmt.Errorf("failed to start container: %w", err)
+ }
+
+ return resp.ID, nil
+}
+
+// execTrivyScanInContainer runs a trivy scan for a single image inside an
+// already-running container via docker exec.
+func (s *VulnerabilityService) execTrivyScanInContainer(ctx context.Context, containerID, imageName, imageID, scannerVersion string) (*vulnerability.ScanResult, error) {
+ dockerClient, err := s.dockerService.GetClient()
+ if err != nil {
+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)
+ }
+
+ execCfg := containertypes.ExecOptions{
+ Cmd: []string{"trivy", "image", "--format", "json", "--quiet", imageName},
+ AttachStdout: true,
+ AttachStderr: true,
+ }
+
+ execResp, err := dockerClient.ContainerExecCreate(ctx, containerID, execCfg)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create exec: %w", err)
+ }
+
+ attachResp, err := dockerClient.ContainerExecAttach(ctx, execResp.ID, containertypes.ExecAttachOptions{})
+ if err != nil {
+ return nil, fmt.Errorf("failed to attach to exec: %w", err)
+ }
+ defer attachResp.Close()
+
+ var stdout, stderr bytes.Buffer
+ if _, err := stdcopy.StdCopy(&stdout, &stderr, attachResp.Reader); err != nil {
+ return nil, fmt.Errorf("failed to read exec output: %w", err)
+ }
+
+ // Check exit code
+ execInspect, err := dockerClient.ContainerExecInspect(ctx, execResp.ID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to inspect exec: %w", err)
+ }
+
+ if execInspect.ExitCode != 0 {
+ errMsg := strings.TrimSpace(stderr.String())
+ if errMsg == "" {
+ errMsg = strings.TrimSpace(stdout.String())
+ }
+ if errMsg == "" {
+ errMsg = fmt.Sprintf("exit status %d", execInspect.ExitCode)
+ }
+ return nil, fmt.Errorf("trivy scan failed: %s", errMsg)
+ }
+
+ output := bytes.TrimSpace(stdout.Bytes())
+ if len(output) == 0 {
+ errMsg := strings.TrimSpace(stderr.String())
+ if errMsg == "" {
+ errMsg = "trivy scan produced no output"
+ }
+ return nil, fmt.Errorf("trivy scan failed: %s", errMsg)
+ }
+
+ var trivyReport vulnerability.TrivyReport
+ if err := json.Unmarshal(output, &trivyReport); err != nil {
+ return nil, fmt.Errorf("failed to parse trivy output: %w", err)
+ }
+
+ result := vulnerability.ConvertTrivyReportToScanResult(&trivyReport, imageID, time.Now(), 0)
+ result.ScannerVersion = scannerVersion
+
+ return result, nil
+}
+
+// DeleteScanResult deletes the scan result for an image
+func (s *VulnerabilityService) DeleteScanResult(ctx context.Context, imageID string) error {
+ if s.db == nil {
+ return nil
+ }
+
+ return s.db.WithContext(ctx).Where("id = ?", imageID).Delete(&models.VulnerabilityScanRecord{}).Error
+}
+
+// CleanupOrphanedScanRecords removes vulnerability scan records for images that
+// no longer exist in Docker. This keeps "images scanned" counts in sync (e.g.
+// avoids "5/3" when images were deleted after being scanned). Safe to call
+// even when no images exist; returns the number of records deleted.
+func (s *VulnerabilityService) CleanupOrphanedScanRecords(ctx context.Context) (deleted int64, err error) {
+ if s.db == nil {
+ return 0, nil
+ }
+
+ dockerClient, err := s.dockerService.GetClient()
+ if err != nil {
+ return 0, fmt.Errorf("failed to connect to Docker: %w", err)
+ }
+
+ images, err := dockerClient.ImageList(ctx, imagetypes.ListOptions{})
+ if err != nil {
+ return 0, fmt.Errorf("failed to list images: %w", err)
+ }
+
+ currentIDs := make(map[string]struct{}, len(images))
+ for _, img := range images {
+ currentIDs[img.ID] = struct{}{}
+ }
+
+ // Build list for NOT IN. If no images, we delete all scan records.
+ var ids []string
+ if len(currentIDs) > 0 {
+ ids = make([]string, 0, len(currentIDs))
+ for id := range currentIDs {
+ ids = append(ids, id)
+ }
+ }
+
+ var result *gorm.DB
+ if len(ids) == 0 {
+ result = s.db.WithContext(ctx).Where("1 = 1").Delete(&models.VulnerabilityScanRecord{})
+ } else {
+ result = s.db.WithContext(ctx).Where("id NOT IN ?", ids).Delete(&models.VulnerabilityScanRecord{})
+ }
+ if result.Error != nil {
+ return 0, result.Error
+ }
+
+ return result.RowsAffected, nil
+}
+
+// GetTrivyVersion returns the Trivy version from the Trivy container image
+func (s *VulnerabilityService) GetTrivyVersion(ctx context.Context) string {
+ dockerClient, err := s.dockerService.GetClient()
+ if err != nil {
+ return ""
+ }
+
+ trivyImage, err := s.ensureTrivyImageInternal(ctx)
+ if err != nil {
+ return ""
+ }
+
+ config := &containertypes.Config{
+ Image: trivyImage,
+ Cmd: []string{"--version"},
+ Labels: map[string]string{
+ libarcane.InternalContainerLabel: "true",
+ },
+ }
+
+ hostConfig := &containertypes.HostConfig{
+ AutoRemove: true,
+ }
+
+ resp, err := dockerClient.ContainerCreate(ctx, config, hostConfig, nil, nil, "")
+ if err != nil {
+ return ""
+ }
+
+ if err := dockerClient.ContainerStart(ctx, resp.ID, containertypes.StartOptions{}); err != nil {
+ _ = dockerClient.ContainerRemove(ctx, resp.ID, containertypes.RemoveOptions{Force: true})
+ return ""
+ }
+
+ logs, err := dockerClient.ContainerLogs(ctx, resp.ID, containertypes.LogsOptions{
+ ShowStdout: true,
+ ShowStderr: true,
+ Follow: true,
+ })
+ if err != nil {
+ _ = dockerClient.ContainerRemove(ctx, resp.ID, containertypes.RemoveOptions{Force: true})
+ return ""
+ }
+ defer logs.Close()
+
+ var stdout bytes.Buffer
+ logDone := make(chan error, 1)
+ go func() {
+ _, err := stdcopy.StdCopy(&stdout, io.Discard, logs)
+ logDone <- err
+ }()
+
+ statusCh, errCh := dockerClient.ContainerWait(ctx, resp.ID, containertypes.WaitConditionNotRunning)
+ var waitResp containertypes.WaitResponse
+ select {
+ case err := <-errCh:
+ if err != nil {
+ return ""
+ }
+ case waitResp = <-statusCh:
+ }
+
+ logs.Close()
+ if err := <-logDone; err != nil && !errors.Is(err, io.EOF) {
+ return ""
+ }
+
+ if waitResp.StatusCode != 0 {
+ return ""
+ }
+
+ return parseTrivyVersion(stdout.String())
+}
+
+func parseTrivyVersion(output string) string {
+ output = strings.TrimSpace(output)
+ if output == "" {
+ return ""
+ }
+ lines := strings.Split(output, "\n")
+ for _, line := range lines {
+ if strings.HasPrefix(line, "Version:") {
+ return strings.TrimSpace(strings.TrimPrefix(line, "Version:"))
+ }
+ }
+ return strings.TrimSpace(output)
+}
+
+func (s *VulnerabilityService) getTrivyImageRef() string {
+ if s.settingsService == nil {
+ return DefaultTrivyImage
+ }
+
+ cfg := s.settingsService.GetSettingsConfig()
+ if cfg == nil {
+ return DefaultTrivyImage
+ }
+
+ override := strings.TrimSpace(cfg.TrivyImage.Value)
+ if override == "" {
+ return DefaultTrivyImage
+ }
+
+ return override
+}
+
+func (s *VulnerabilityService) ensureTrivyImageInternal(ctx context.Context) (string, error) {
+ dockerClient, err := s.dockerService.GetClient()
+ if err != nil {
+ return "", fmt.Errorf("failed to connect to Docker: %w", err)
+ }
+
+ trivyImage := s.getTrivyImageRef()
+ if _, err := dockerClient.ImageInspect(ctx, trivyImage); err == nil {
+ return trivyImage, nil
+ }
+
+ pullTimeoutSeconds := 0
+ if s.settingsService != nil && s.settingsService.GetSettingsConfig() != nil {
+ pullTimeoutSeconds = s.settingsService.GetSettingsConfig().DockerImagePullTimeout.AsInt()
+ }
+
+ pullCtx, pullCancel := timeouts.WithTimeout(ctx, pullTimeoutSeconds, timeouts.DefaultDockerImagePull)
+ defer pullCancel()
+
+ pullReader, err := dockerClient.ImagePull(pullCtx, trivyImage, imagetypes.PullOptions{})
+ if err != nil {
+ if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {
+ return "", fmt.Errorf("trivy image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", trivyImage)
+ }
+ return "", fmt.Errorf("pull trivy image %s: %w", trivyImage, err)
+ }
+ _, _ = io.Copy(io.Discard, pullReader)
+ _ = pullReader.Close()
+
+ return trivyImage, nil
+}
+
+func (s *VulnerabilityService) ensureTrivyCacheVolumeInternal(ctx context.Context) (string, error) {
+ dockerClient, err := s.dockerService.GetClient()
+ if err != nil {
+ return "", err
+ }
+
+ if _, err := dockerClient.VolumeInspect(ctx, trivyCacheVolumeName); err == nil {
+ return trivyCacheVolumeName, nil
+ }
+
+ _, err = dockerClient.VolumeCreate(ctx, volumetypes.CreateOptions{
+ Name: trivyCacheVolumeName,
+ Labels: map[string]string{
+ libarcane.InternalContainerLabel: "true",
+ },
+ })
+ if err != nil {
+ return "", fmt.Errorf("failed to create trivy cache volume: %w", err)
+ }
+
+ return trivyCacheVolumeName, nil
+}
+
+// runTrivyScan executes Trivy scan on an image
+func (s *VulnerabilityService) getTrivyConfigFiles(ctx context.Context) (configContent, ignoreContent string, err error) {
+ if s.settingsService == nil {
+ return "", "", nil
+ }
+
+ cfg := s.settingsService.GetSettingsConfig()
+ if cfg == nil {
+ return "", "", nil
+ }
+
+ return cfg.TrivyConfig.Value, cfg.TrivyIgnore.Value, nil
+}
+
+func (s *VulnerabilityService) createTrivyConfigTempFile(ctx context.Context, content string) (string, bool) {
+ configFile, err := os.CreateTemp("", "trivy-config-*.yaml")
+ if err != nil {
+ slog.WarnContext(ctx, "failed to create trivy config temp file", "error", err)
+ return "", false
+ }
+ if _, err := configFile.WriteString(content); err != nil {
+ slog.WarnContext(ctx, "failed to write trivy config", "error", err)
+ configFile.Close()
+ _ = os.Remove(configFile.Name())
+ return "", false
+ }
+ _ = configFile.Close()
+ return configFile.Name(), true
+}
+
+func (s *VulnerabilityService) createTrivyIgnoreTempFile(ctx context.Context, content string) (string, bool) {
+ ignoreFile, err := os.CreateTemp("", "trivy-ignore-*")
+ if err != nil {
+ slog.WarnContext(ctx, "failed to create trivy ignore temp file", "error", err)
+ return "", false
+ }
+ if _, err := ignoreFile.WriteString(content); err != nil {
+ slog.WarnContext(ctx, "failed to write trivy ignore", "error", err)
+ ignoreFile.Close()
+ _ = os.Remove(ignoreFile.Name())
+ return "", false
+ }
+ _ = ignoreFile.Close()
+ return ignoreFile.Name(), true
+}
+
+func cleanupTempFiles(ctx context.Context, tempFiles []string) {
+ for _, f := range tempFiles {
+ if err := os.Remove(f); err != nil {
+ slog.WarnContext(ctx, "failed to remove trivy temp file", "path", f, "error", err)
+ }
+ }
+}
+
+func (s *VulnerabilityService) buildTrivyCommandArgs(
+ ctx context.Context,
+ imageName string,
+ configContent string,
+ ignoreContent string,
+) ([]string, []string) {
+ cmdArgs := []string{"image", "--format", "json", "--quiet"}
+ var tempFiles []string
+
+ if strings.TrimSpace(configContent) != "" {
+ if tempFile, ok := s.createTrivyConfigTempFile(ctx, configContent); ok {
+ tempFiles = append(tempFiles, tempFile)
+ cmdArgs = append(cmdArgs, "--config", "/tmp/trivy-config.yaml")
+ }
+ }
+
+ if strings.TrimSpace(ignoreContent) != "" {
+ if tempFile, ok := s.createTrivyIgnoreTempFile(ctx, ignoreContent); ok {
+ tempFiles = append(tempFiles, tempFile)
+ cmdArgs = append(cmdArgs, "--ignorefile", "/tmp/trivy-ignore")
+ }
+ }
+
+ cmdArgs = append(cmdArgs, imageName)
+
+ return cmdArgs, tempFiles
+}
+
+func buildTrivyContainerConfig(trivyImage string, cmdArgs []string) *containertypes.Config {
+ return &containertypes.Config{
+ Image: trivyImage,
+ Cmd: cmdArgs,
+ Labels: map[string]string{
+ libarcane.InternalContainerLabel: "true",
+ },
+ }
+}
+
+func buildTrivyHostConfig(cacheVolume string, tempFiles []string) *containertypes.HostConfig {
+ hostConfig := &containertypes.HostConfig{
+ AutoRemove: true,
+ Mounts: []mounttypes.Mount{
+ {
+ Type: mounttypes.TypeBind,
+ Source: "/var/run/docker.sock",
+ Target: "/var/run/docker.sock",
+ },
+ {
+ Type: mounttypes.TypeVolume,
+ Source: cacheVolume,
+ Target: trivyCacheMountTarget,
+ },
+ },
+ Resources: containertypes.Resources{
+ NanoCPUs: trivyMaxCPUNano,
+ Memory: trivyMaxMemoryBytes,
+ MemorySwap: trivyMaxMemoryBytes,
+ },
+ }
+
+ addTrivyTempFileMounts(hostConfig, tempFiles)
+ return hostConfig
+}
+
+func addTrivyTempFileMounts(hostConfig *containertypes.HostConfig, tempFiles []string) {
+ for _, tempFile := range tempFiles {
+ switch {
+ case strings.Contains(tempFile, "trivy-config"):
+ hostConfig.Mounts = append(hostConfig.Mounts, mounttypes.Mount{
+ Type: mounttypes.TypeBind,
+ Source: tempFile,
+ Target: "/tmp/trivy-config.yaml",
+ ReadOnly: true,
+ })
+ case strings.Contains(tempFile, "trivy-ignore"):
+ hostConfig.Mounts = append(hostConfig.Mounts, mounttypes.Mount{
+ Type: mounttypes.TypeBind,
+ Source: tempFile,
+ Target: "/tmp/trivy-ignore",
+ ReadOnly: true,
+ })
+ }
+ }
+}
+
+func (s *VulnerabilityService) runTrivyContainer(
+ ctx context.Context,
+ dockerClient *client.Client,
+ config *containertypes.Config,
+ hostConfig *containertypes.HostConfig,
+) ([]byte, []byte, int64, int64, error) {
+ resp, err := dockerClient.ContainerCreate(ctx, config, hostConfig, nil, nil, "")
+ if err != nil {
+ return nil, nil, 0, 0, fmt.Errorf("failed to create trivy container: %w", err)
+ }
+
+ if err := dockerClient.ContainerStart(ctx, resp.ID, containertypes.StartOptions{}); err != nil {
+ _ = dockerClient.ContainerRemove(ctx, resp.ID, containertypes.RemoveOptions{Force: true})
+ return nil, nil, 0, 0, fmt.Errorf("failed to start trivy container: %w", err)
+ }
+
+ logs, err := dockerClient.ContainerLogs(ctx, resp.ID, containertypes.LogsOptions{
+ ShowStdout: true,
+ ShowStderr: true,
+ Follow: true,
+ })
+ if err != nil {
+ _ = dockerClient.ContainerRemove(ctx, resp.ID, containertypes.RemoveOptions{Force: true})
+ return nil, nil, 0, 0, fmt.Errorf("failed to stream trivy logs: %w", err)
+ }
+ defer logs.Close()
+
+ var stdout, stderr bytes.Buffer
+ logDone := make(chan error, 1)
+ go func() {
+ _, err := stdcopy.StdCopy(&stdout, &stderr, logs)
+ logDone <- err
+ }()
+
+ startTime := time.Now()
+ statusCode, err := s.waitForTrivyContainer(ctx, dockerClient, resp.ID)
+ if err != nil {
+ return nil, nil, 0, 0, err
+ }
+
+ logs.Close()
+ if err := <-logDone; err != nil && !errors.Is(err, io.EOF) {
+ return nil, nil, 0, 0, fmt.Errorf("failed to read trivy logs: %w", err)
+ }
+
+ duration := time.Since(startTime).Milliseconds()
+ return stdout.Bytes(), stderr.Bytes(), duration, statusCode, nil
+}
+
+func (s *VulnerabilityService) waitForTrivyContainer(
+ ctx context.Context,
+ dockerClient *client.Client,
+ containerID string,
+) (int64, error) {
+ statusCh, errCh := dockerClient.ContainerWait(ctx, containerID, containertypes.WaitConditionNotRunning)
+ select {
+ case err := <-errCh:
+ if err != nil {
+ if ctx.Err() != nil {
+ cleanupCtx, cleanupCancel := timeouts.WithTimeout(ctx, 0, timeouts.DefaultDockerAPI)
+ defer cleanupCancel()
+ _ = dockerClient.ContainerRemove(cleanupCtx, containerID, containertypes.RemoveOptions{Force: true})
+ return 0, fmt.Errorf("scan cancelled: %w", ctx.Err())
+ }
+ return 0, fmt.Errorf("trivy container wait failed: %w", err)
+ }
+ return 0, nil
+ case waitResp := <-statusCh:
+ return waitResp.StatusCode, nil
+ }
+}
+
+func (s *VulnerabilityService) runTrivyScan(ctx context.Context, trivyImage string, imageName string, imageID string) (*vulnerability.ScanResult, error) {
+ // Use per-image locking to allow concurrent scans of different images
+ lock := s.getImageLock(imageID)
+ lock.Lock()
+ defer lock.Unlock()
+
+ dockerClient, err := s.dockerService.GetClient()
+ if err != nil {
+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)
+ }
+
+ cacheVolume, err := s.ensureTrivyCacheVolumeInternal(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ // Get Trivy config files if they exist
+ configContent, ignoreContent, err := s.getTrivyConfigFiles(ctx)
+ if err != nil {
+ slog.WarnContext(ctx, "failed to get trivy config files", "error", err)
+ }
+
+ cmdArgs, tempFiles := s.buildTrivyCommandArgs(ctx, imageName, configContent, ignoreContent)
+ defer cleanupTempFiles(ctx, tempFiles)
+
+ config := buildTrivyContainerConfig(trivyImage, cmdArgs)
+ hostConfig := buildTrivyHostConfig(cacheVolume, tempFiles)
+
+ stdout, stderr, duration, statusCode, err := s.runTrivyContainer(ctx, dockerClient, config, hostConfig)
+ if err != nil {
+ return nil, err
+ }
+
+ if statusCode != 0 {
+ errMsg := strings.TrimSpace(string(stderr))
+ if errMsg == "" {
+ errMsg = strings.TrimSpace(string(stdout))
+ }
+ if errMsg == "" {
+ errMsg = fmt.Sprintf("exit status %d", statusCode)
+ }
+ return nil, fmt.Errorf("trivy scan failed: %s", errMsg)
+ }
+
+ output := bytes.TrimSpace(stdout)
+ if len(output) == 0 {
+ errMsg := strings.TrimSpace(string(stderr))
+ if errMsg == "" {
+ errMsg = "trivy scan produced no output"
+ }
+ return nil, fmt.Errorf("trivy scan failed: %s", errMsg)
+ }
+
+ // Parse Trivy JSON output
+ var trivyReport vulnerability.TrivyReport
+ if err := json.Unmarshal(output, &trivyReport); err != nil {
+ return nil, fmt.Errorf("failed to parse trivy output: %w", err)
+ }
+
+ // Convert Trivy report to our ScanResult format
+ result := vulnerability.ConvertTrivyReportToScanResult(&trivyReport, imageID, time.Now(), duration)
+ result.ScannerVersion = s.GetTrivyVersion(ctx)
+
+ return result, nil
+}
+
+// saveScanResult saves the scan result to the database
+func (s *VulnerabilityService) saveScanResult(ctx context.Context, result *vulnerability.ScanResult) error {
+ if s.db == nil {
+ return nil
+ }
+
+ s.ensureSummary(result)
+
+ // Convert vulnerabilities to JSON
+ var vulnJSON models.StringSlice
+ if len(result.Vulnerabilities) > 0 {
+ vulnBytes, err := json.Marshal(result.Vulnerabilities)
+ if err != nil {
+ return fmt.Errorf("failed to marshal vulnerabilities: %w", err)
+ }
+ vulnJSON = models.StringSlice{string(vulnBytes)}
+ }
+
+ var errPtr *string
+ if result.Error != "" {
+ errPtr = &result.Error
+ }
+
+ var summary *vulnerability.SeveritySummary
+ if result.Summary != nil {
+ summary = result.Summary
+ } else {
+ summary = &vulnerability.SeveritySummary{}
+ }
+
+ record := models.VulnerabilityScanRecord{
+ ID: result.ImageID,
+ ImageName: result.ImageName,
+ Status: string(result.Status),
+ ScanTime: result.ScanTime,
+ Duration: result.Duration,
+ CriticalCount: summary.Critical,
+ HighCount: summary.High,
+ MediumCount: summary.Medium,
+ LowCount: summary.Low,
+ UnknownCount: summary.Unknown,
+ TotalCount: summary.Total,
+ Vulnerabilities: vulnJSON,
+ Error: errPtr,
+ ScannerVersion: result.ScannerVersion,
+ }
+
+ // Upsert the record
+ return s.db.WithContext(ctx).Clauses(clause.OnConflict{
+ Columns: []clause.Column{{Name: "id"}},
+ UpdateAll: true,
+ }).Create(&record).Error
+}
+
+const nvdBaseURL = "https://nvd.nist.gov/vuln/detail/"
+
+func cveLink(vulnerabilityID string) string {
+ if vulnerabilityID == "" {
+ return ""
+ }
+ if strings.HasPrefix(strings.ToUpper(vulnerabilityID), "CVE-") {
+ return nvdBaseURL + vulnerabilityID
+ }
+ return ""
+}
+
+// notifyVulnerabilitiesWithFix sends a notification for each vulnerability that has a fixed version.
+// It is called after a successful scan save. Notifications are sent asynchronously; errors are logged.
+// Notifications are suppressed for ignored vulnerabilities across all environments.
+func (s *VulnerabilityService) notifyVulnerabilitiesWithFix(ctx context.Context, result *vulnerability.ScanResult) {
+ if s.notificationService == nil || result == nil {
+ return
+ }
+ if result.Status != vulnerability.ScanStatusCompleted || len(result.Vulnerabilities) == 0 {
+ return
+ }
+
+ vulnerabilities := result.Vulnerabilities
+ filtered, err := s.filterIgnoredVulnerabilitiesForImage(ctx, result.ImageID, vulnerabilities)
+ if err != nil {
+ slog.WarnContext(ctx, "failed to filter ignored vulnerabilities for notifications", "error", err)
+ } else {
+ vulnerabilities = filtered
+ }
+
+ for i := range vulnerabilities {
+ v := &vulnerabilities[i]
+ if v.FixedVersion == "" {
+ continue
+ }
+ payload := VulnerabilityNotificationPayload{
+ CVEID: v.VulnerabilityID,
+ CVELink: cveLink(v.VulnerabilityID),
+ Severity: string(v.Severity),
+ ImageName: result.ImageName,
+ FixedVersion: v.FixedVersion,
+ PkgName: v.PkgName,
+ InstalledVersion: v.InstalledVersion,
+ }
+ if err := s.notificationService.SendVulnerabilityNotification(ctx, payload); err != nil {
+ slog.WarnContext(ctx, "failed to send vulnerability notification", "cve", v.VulnerabilityID, "image", result.ImageName, "error", err)
+ }
+ }
+}
+
+func (s *VulnerabilityService) filterIgnoredVulnerabilitiesForImage(
+ ctx context.Context,
+ imageID string,
+ vulns []vulnerability.Vulnerability,
+) ([]vulnerability.Vulnerability, error) {
+ if s.db == nil || len(vulns) == 0 || imageID == "" {
+ return vulns, nil
+ }
+
+ var ignores []models.VulnerabilityIgnore
+ if err := s.db.WithContext(ctx).Where("image_id = ?", imageID).Find(&ignores).Error; err != nil {
+ return nil, err
+ }
+ if len(ignores) == 0 {
+ return vulns, nil
+ }
+
+ ignoredKeys := make(map[string]struct{}, len(ignores))
+ for _, ignore := range ignores {
+ key := fmt.Sprintf("%s:%s:%s:%s", ignore.ImageID, ignore.VulnerabilityID, ignore.PkgName, ignore.InstalledVersion)
+ ignoredKeys[key] = struct{}{}
+ }
+
+ filtered := make([]vulnerability.Vulnerability, 0, len(vulns))
+ for _, vuln := range vulns {
+ key := fmt.Sprintf("%s:%s:%s:%s", imageID, vuln.VulnerabilityID, vuln.PkgName, vuln.InstalledVersion)
+ if _, isIgnored := ignoredKeys[key]; isIgnored {
+ continue
+ }
+ filtered = append(filtered, vuln)
+ }
+
+ return filtered, nil
+}
+
+// convertRecordToResult converts a database record to a ScanResult
+func (s *VulnerabilityService) convertRecordToResult(record *models.VulnerabilityScanRecord) (*vulnerability.ScanResult, error) {
+ result := &vulnerability.ScanResult{
+ ImageID: record.ID,
+ ImageName: record.ImageName,
+ ScanTime: record.ScanTime,
+ Status: vulnerability.ScanStatus(record.Status),
+ Duration: record.Duration,
+ Summary: &vulnerability.SeveritySummary{
+ Critical: record.CriticalCount,
+ High: record.HighCount,
+ Medium: record.MediumCount,
+ Low: record.LowCount,
+ Unknown: record.UnknownCount,
+ Total: record.TotalCount,
+ },
+ ScannerVersion: record.ScannerVersion,
+ }
+
+ if record.Error != nil {
+ result.Error = *record.Error
+ }
+
+ // Parse vulnerabilities from JSON
+ if len(record.Vulnerabilities) > 0 && record.Vulnerabilities[0] != "" {
+ var vulns []vulnerability.Vulnerability
+ if err := json.Unmarshal([]byte(record.Vulnerabilities[0]), &vulns); err != nil {
+ slog.Warn("failed to unmarshal vulnerabilities", "error", err)
+ } else {
+ result.Vulnerabilities = vulns
+ }
+ }
+
+ s.ensureSummary(result)
+
+ return result, nil
+}
+
+func (s *VulnerabilityService) ensureSummary(result *vulnerability.ScanResult) {
+ if result == nil {
+ return
+ }
+
+ if len(result.Vulnerabilities) == 0 {
+ if result.Summary == nil {
+ result.Summary = &vulnerability.SeveritySummary{}
+ }
+ return
+ }
+
+ if result.Summary != nil && result.Summary.Total > 0 {
+ return
+ }
+
+ result.Summary = buildSeveritySummaryFromVulnerabilitiesInternal(result.Vulnerabilities)
+}
+
+func buildSeveritySummaryFromVulnerabilitiesInternal(vulns []vulnerability.Vulnerability) *vulnerability.SeveritySummary {
+ summary := &vulnerability.SeveritySummary{}
+ for _, vuln := range vulns {
+ switch vuln.Severity {
+ case vulnerability.SeverityCritical:
+ summary.Critical++
+ case vulnerability.SeverityHigh:
+ summary.High++
+ case vulnerability.SeverityMedium:
+ summary.Medium++
+ case vulnerability.SeverityLow:
+ summary.Low++
+ case vulnerability.SeverityUnknown:
+ summary.Unknown++
+ default:
+ summary.Unknown++
+ }
+ summary.Total++
+ }
+ return summary
+}
+
+// logScanEvent logs a vulnerability scan event
+func (s *VulnerabilityService) logScanEvent(ctx context.Context, envID string, imageID, imageName string, user models.User, success bool, errMsg string) {
+ metadata := models.JSON{
+ "action": "vulnerability_scan",
+ "imageId": imageID,
+ "imageName": imageName,
+ "success": success,
+ }
+ if errMsg != "" {
+ metadata["error"] = errMsg
+ }
+
+ environmentID := envID
+ if environmentID == "" {
+ environmentID = "0"
+ }
+
+ eventType := models.EventTypeImageScan
+ if err := s.eventService.LogImageEvent(ctx, eventType, imageID, imageName, user.ID, user.Username, environmentID, metadata); err != nil {
+ slog.WarnContext(ctx, "failed to log vulnerability scan event", "error", err)
+ }
+}
+
+// logScheduledScanEvent logs a vulnerability scan event using the dedicated scheduled scan event type.
+func (s *VulnerabilityService) logScheduledScanEvent(ctx context.Context, envID string, imageID, imageName string, user models.User, success bool, errMsg string) {
+ metadata := models.JSON{
+ "action": "scheduled_vulnerability_scan",
+ "imageId": imageID,
+ "imageName": imageName,
+ "success": success,
+ }
+ if errMsg != "" {
+ metadata["error"] = errMsg
+ }
+
+ environmentID := envID
+ if environmentID == "" {
+ environmentID = "0"
+ }
+
+ if err := s.eventService.LogImageEvent(ctx, models.EventTypeImageVulnerabilityScan, imageID, imageName, user.ID, user.Username, environmentID, metadata); err != nil {
+ slog.WarnContext(ctx, "failed to log scheduled vulnerability scan event", "error", err)
+ }
+}
+
+// stringPtrValueOrEmptyInternal returns the string value from a pointer or empty string if nil
+func stringPtrValueOrEmptyInternal(p *string) string {
+ if p == nil {
+ return ""
+ }
+ return *p
+}
+
+// IgnoreVulnerability creates a new ignore record for a vulnerability
+func (s *VulnerabilityService) IgnoreVulnerability(ctx context.Context, envID string, payload *vulnerability.IgnorePayload) (*models.VulnerabilityIgnore, error) {
+ if s.db == nil {
+ return nil, errors.New("database not available")
+ }
+
+ // Check if already ignored (composite key check)
+ var existing models.VulnerabilityIgnore
+ err := s.db.WithContext(ctx).Where(
+ "environment_id = ? AND image_id = ? AND vulnerability_id = ? AND pkg_name = ? AND installed_version = ?",
+ envID, payload.ImageID, payload.VulnerabilityID, payload.PkgName, payload.InstalledVersion,
+ ).First(&existing).Error
+
+ if err == nil {
+ return nil, errors.New("vulnerability is already ignored")
+ }
+
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, fmt.Errorf("failed to check existing ignore: %w", err)
+ }
+
+ ignore := &models.VulnerabilityIgnore{
+ EnvironmentID: envID,
+ ImageID: payload.ImageID,
+ VulnerabilityID: payload.VulnerabilityID,
+ PkgName: payload.PkgName,
+ InstalledVersion: payload.InstalledVersion,
+ Reason: payload.Reason,
+ CreatedBy: payload.CreatedBy,
+ }
+
+ if err := s.db.WithContext(ctx).Create(ignore).Error; err != nil {
+ return nil, fmt.Errorf("failed to create ignore record: %w", err)
+ }
+
+ slog.InfoContext(ctx, "vulnerability ignored",
+ "vulnerability_id", payload.VulnerabilityID,
+ "image_id", payload.ImageID,
+ "pkg_name", payload.PkgName,
+ )
+
+ return ignore, nil
+}
+
+// UnignoreVulnerability removes an ignore record
+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(&models.VulnerabilityIgnore{})
+ if result.Error != nil {
+ return fmt.Errorf("failed to delete ignore record: %w", result.Error)
+ }
+
+ if result.RowsAffected == 0 {
+ return errors.New("ignore record not found")
+ }
+
+ slog.InfoContext(ctx, "vulnerability unignored", "ignore_id", ignoreID)
+ return nil
+}
+
+func applyIgnoredVulnerabilitiesSort(query *gorm.DB, sort string) *gorm.DB {
+ if sort == "" {
+ return query.Order("created_at DESC")
+ }
+
+ for _, part := range strings.Split(sort, ",") {
+ part = strings.TrimSpace(part)
+ if part == "" {
+ continue
+ }
+
+ desc := false
+ switch {
+ case strings.HasPrefix(part, "-"):
+ desc = true
+ part = strings.TrimPrefix(part, "-")
+ case strings.HasPrefix(part, "+"):
+ part = strings.TrimPrefix(part, "+")
+ }
+
+ query = applyIgnoredVulnerabilitiesSortPart(query, part, desc)
+ }
+
+ return query
+}
+
+func applyIgnoredVulnerabilitiesSortPart(query *gorm.DB, part string, desc bool) *gorm.DB {
+ direction := "ASC"
+ if desc {
+ direction = "DESC"
+ }
+
+ switch part {
+ case "createdAt":
+ return query.Order("created_at " + direction)
+ case "vulnerabilityId":
+ return query.Order("vulnerability_id " + direction)
+ default:
+ return query.Order("created_at DESC")
+ }
+}
+
+func mapIgnoredVulnerabilities(ignores []models.VulnerabilityIgnore) []vulnerability.IgnoredVulnerability {
+ result := make([]vulnerability.IgnoredVulnerability, len(ignores))
+ for i, ignore := range ignores {
+ result[i] = vulnerability.IgnoredVulnerability{
+ ID: ignore.ID,
+ EnvironmentID: ignore.EnvironmentID,
+ ImageID: ignore.ImageID,
+ VulnerabilityID: ignore.VulnerabilityID,
+ PkgName: ignore.PkgName,
+ InstalledVersion: ignore.InstalledVersion,
+ Reason: ignore.Reason,
+ CreatedBy: ignore.CreatedBy,
+ CreatedAt: ignore.CreatedAt,
+ }
+ }
+ return result
+}
+
+func buildIgnoredVulnerabilitiesResponse(total int64, params pagination.QueryParams, ignores []models.VulnerabilityIgnore) pagination.Response {
+ filtered := pagination.FilterResult[models.VulnerabilityIgnore]{
+ Items: ignores,
+ TotalCount: total,
+ TotalAvailable: total,
+ }
+ return pagination.BuildResponseFromFilterResult(filtered, params)
+}
+
+// ListIgnoredVulnerabilities returns a list of ignored vulnerabilities for an environment
+func (s *VulnerabilityService) ListIgnoredVulnerabilities(ctx context.Context, envID string, params pagination.QueryParams) ([]vulnerability.IgnoredVulnerability, pagination.Response, error) {
+ if params.Limit == 0 {
+ params.Limit = 20
+ }
+
+ if s.db == nil {
+ return []vulnerability.IgnoredVulnerability{}, pagination.Response{
+ TotalPages: 1,
+ TotalItems: 0,
+ CurrentPage: 1,
+ ItemsPerPage: params.Limit,
+ GrandTotalItems: 0,
+ }, nil
+ }
+
+ var ignores []models.VulnerabilityIgnore
+ query := s.db.WithContext(ctx).Where("environment_id = ?", envID)
+ query = applyIgnoredVulnerabilitiesSort(query, params.Sort)
+
+ // Count total
+ var total int64
+ if err := query.Model(&models.VulnerabilityIgnore{}).Count(&total).Error; err != nil {
+ return nil, pagination.Response{}, fmt.Errorf("failed to count ignored vulnerabilities: %w", err)
+ }
+
+ // Apply pagination
+ offset := params.Start
+ if err := query.Offset(offset).Limit(params.Limit).Find(&ignores).Error; err != nil {
+ return nil, pagination.Response{}, fmt.Errorf("failed to list ignored vulnerabilities: %w", err)
+ }
+
+ result := mapIgnoredVulnerabilities(ignores)
+ response := buildIgnoredVulnerabilitiesResponse(total, params, ignores)
+
+ return result, response, nil
+}
+
+// GetIgnoreRecordsForImage retrieves all ignore records for a specific image
+func (s *VulnerabilityService) GetIgnoreRecordsForImage(ctx context.Context, envID string, imageID string) ([]models.VulnerabilityIgnore, error) {
+ if s.db == nil {
+ return nil, nil
+ }
+
+ var ignores []models.VulnerabilityIgnore
+ if err := s.db.WithContext(ctx).Where("environment_id = ? AND image_id = ?", envID, imageID).Find(&ignores).Error; err != nil {
+ return nil, fmt.Errorf("failed to get ignore records: %w", err)
+ }
+
+ return ignores, nil
+}
+
+// filterIgnoredVulnerabilities removes ignored vulnerabilities from the list
+func (s *VulnerabilityService) filterIgnoredVulnerabilities(ctx context.Context, envID string, vulns []vulnerability.VulnerabilityWithImage) ([]vulnerability.VulnerabilityWithImage, error) {
+ if s.db == nil || len(vulns) == 0 {
+ return vulns, nil
+ }
+
+ // Get all ignore records for this environment
+ var ignores []models.VulnerabilityIgnore
+ if err := s.db.WithContext(ctx).Where("environment_id = ?", envID).Find(&ignores).Error; err != nil {
+ return nil, fmt.Errorf("failed to get ignore records: %w", err)
+ }
+
+ if len(ignores) == 0 {
+ return vulns, nil
+ }
+
+ // Build a set of ignored vulnerability keys
+ ignoredKeys := make(map[string]struct{}, len(ignores))
+ for _, ignore := range ignores {
+ key := fmt.Sprintf("%s:%s:%s:%s", ignore.ImageID, ignore.VulnerabilityID, ignore.PkgName, ignore.InstalledVersion)
+ ignoredKeys[key] = struct{}{}
+ }
+
+ // Filter out ignored vulnerabilities
+ filtered := make([]vulnerability.VulnerabilityWithImage, 0, len(vulns))
+ for _, vuln := range vulns {
+ key := fmt.Sprintf("%s:%s:%s:%s", vuln.ImageID, vuln.VulnerabilityID, vuln.PkgName, vuln.InstalledVersion)
+ if _, isIgnored := ignoredKeys[key]; !isIgnored {
+ filtered = append(filtered, vuln)
+ }
+ }
+
+ return filtered, nil
+}
diff --git a/backend/pkg/scheduler/vulnerability_scan_job.go b/backend/pkg/scheduler/vulnerability_scan_job.go
new file mode 100644
index 000000000..6d33d9c62
--- /dev/null
+++ b/backend/pkg/scheduler/vulnerability_scan_job.go
@@ -0,0 +1,100 @@
+package scheduler
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "strconv"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/types"
+ "github.com/robfig/cron/v3"
+)
+
+const VulnerabilityScanJobName = "vulnerability-scan"
+
+// systemUser is used as the actor for scheduled vulnerability scans.
+var vulnerabilityScanSystemUser = models.User{
+ Username: "System",
+}
+
+// VulnerabilityScanJob periodically scans all Docker images for vulnerabilities
+// using Trivy. It is opt-in via the "vulnerabilityScanEnabled" setting.
+type VulnerabilityScanJob struct {
+ vulnerabilityService *services.VulnerabilityService
+ settingsService *services.SettingsService
+}
+
+// NewVulnerabilityScanJob creates a new VulnerabilityScanJob.
+func NewVulnerabilityScanJob(vulnerabilityService *services.VulnerabilityService, settingsService *services.SettingsService) *VulnerabilityScanJob {
+ return &VulnerabilityScanJob{
+ vulnerabilityService: vulnerabilityService,
+ settingsService: settingsService,
+ }
+}
+
+func (j *VulnerabilityScanJob) Name() string {
+ return VulnerabilityScanJobName
+}
+
+// Schedule returns the cron expression for the job. Defaults to daily at midnight.
+func (j *VulnerabilityScanJob) Schedule(ctx context.Context) string {
+ schedule := j.settingsService.GetStringSetting(ctx, "vulnerabilityScanInterval", "0 0 0 * * *")
+ if schedule == "" {
+ schedule = "0 0 0 * * *"
+ }
+
+ // Handle legacy straight int if it somehow didn't get migrated
+ if i, err := strconv.Atoi(schedule); err == nil {
+ if i <= 0 {
+ i = 1440
+ }
+ switch {
+ case i%1440 == 0:
+ schedule = fmt.Sprintf("0 0 0 */%d * *", i/1440)
+ case i%60 == 0:
+ schedule = fmt.Sprintf("0 0 */%d * * *", i/60)
+ default:
+ schedule = fmt.Sprintf("0 */%d * * * *", i)
+ }
+ }
+
+ parser := cron.NewParser(cron.Second | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)
+ if _, err := parser.Parse(schedule); err != nil {
+ slog.WarnContext(ctx, "Invalid cron expression for vulnerability-scan, using default", "invalid_schedule", schedule, "error", err)
+ return "0 0 0 * * *"
+ }
+
+ return schedule
+}
+
+func (j *VulnerabilityScanJob) Run(ctx context.Context) {
+ enabled := j.settingsService.GetBoolSetting(ctx, "vulnerabilityScanEnabled", false)
+ if !enabled {
+ slog.DebugContext(ctx, "scheduled vulnerability scan disabled; skipping run")
+ return
+ }
+
+ slog.InfoContext(ctx, "scheduled vulnerability scan started")
+
+ // Remove scan records for images that no longer exist (fixes e.g. "5/3 images scanned").
+ deleted, err := j.vulnerabilityService.CleanupOrphanedScanRecords(ctx)
+ if err != nil {
+ slog.WarnContext(ctx, "orphaned vulnerability scan cleanup failed", "error", err)
+ }
+ if deleted > 0 {
+ slog.InfoContext(ctx, "cleaned up orphaned vulnerability scan records", "deleted", deleted)
+ }
+
+ scanned, failed, err := j.vulnerabilityService.ScanAllImages(ctx, types.LOCAL_DOCKER_ENVIRONMENT_ID, vulnerabilityScanSystemUser)
+ if err != nil {
+ slog.ErrorContext(ctx, "scheduled vulnerability scan failed", "error", err)
+ return
+ }
+
+ slog.InfoContext(ctx, "scheduled vulnerability scan completed",
+ "scanned", scanned,
+ "failed", failed,
+ )
+}
diff --git a/backend/resources/email-templates/vulnerability-found_html.tmpl b/backend/resources/email-templates/vulnerability-found_html.tmpl
new file mode 100644
index 000000000..427f7a769
--- /dev/null
+++ b/backend/resources/email-templates/vulnerability-found_html.tmpl
@@ -0,0 +1,9 @@
+{{define "root"}}<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html dir="ltr" lang="en"><head><link rel="preload" as="image" href="{{.LogoURL}}"/><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/><meta name="x-apple-disable-message-reformatting"/></head><body style="background-color:#0f172a"><!--$--><!--html--><!--head--><!--body--><table border="0" width="100%" cellPadding="0" cellSpacing="0" role="presentation" align="center"><tbody><tr><td style="padding:40px 20px;background-color:#0f172a;font-family:-apple-system, BlinkMacSystemFont, &#x27;Segoe UI&#x27;, Roboto, &#x27;Helvetica Neue&#x27;, Arial, sans-serif"><table align="center" width="100%" border="0" cellPadding="0" cellSpacing="0" role="presentation" style="max-width:37.5em;width:600px;margin:0 auto"><tbody><tr style="width:100%"><td>
+<table align="center" width="100%" border="0" cellPadding="0" cellSpacing="0" role="presentation" style="text-align:center;margin-bottom:32px"><tbody><tr><td><img alt="Arcane" height="auto" src="{{.LogoURL}}" style="display:inline-block;outline:none;border:none;text-decoration:none;width:180px;height:auto" width="180"/></td></tr></tbody></table><div style="background-color:rgba(30, 41, 59, 0.6);backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px);border:1px solid rgba(148, 163, 184, 0.1);padding:32px;border-radius:16px;box-shadow:0 8px 32px 0 rgba(0, 0, 0, 0.37)"><table align="center" width="100%" border="0" cellPadding="0" cellSpacing="0" role="presentation"><tbody style="width:100%"><tr style="width:100%"><td data-id="__react-email-column"><h1 style="font-size:24px;font-weight:bold;margin:0;color:#f1f5f9">Vulnerability Found (Fix Available)</h1></td><td align="right" data-id="__react-email-column"></td></tr></tbody></table>
+<table align="center" width="100%" border="0" cellPadding="0" cellSpacing="0" role="presentation" style="margin-top:24px"><tbody><tr><td><p style="font-size:16px;line-height:24px;color:#cbd5e1;margin:0 0 16px 0;margin-top:0;margin-right:0;margin-bottom:16px;margin-left:0">A vulnerability with an available fix was detected in one of your container images. Update to the fixed version to resolve the issue.</p></td></tr></tbody></table><table align="center" width="100%" border="0" cellPadding="0" cellSpacing="0" role="presentation" style="margin-top:20px;background-color:rgba(15, 23, 42, 0.5);border:1px solid rgba(148, 163, 184, 0.1);padding:20px;border-radius:12px"><tbody><tr><td><table align="center" width="100%" border="0" cellPadding="0" cellSpacing="0" role="presentation" style="margin-bottom:0"><tbody style="width:100%"><tr style="width:100%"><td data-id="__react-email-column" style="width:140px;vertical-align:top;padding-right:12px">
+<p style="font-size:14px;line-height:24px;font-weight:600;color:#94a3b8;margin:8px 0;margin-top:8px;margin-right:0;margin-bottom:8px;margin-left:0">CVE:</p></td><td data-id="__react-email-column"><a href="{{.CVELink}}" style="color:#a78bfa;text-decoration-line:none;text-decoration:none" target="_blank">{{.CVEID}}</a></td></tr></tbody></table><hr style="width:100%;border:none;border-top:1px solid #eaeaea;border-color:rgba(148, 163, 184, 0.2);margin:4px 0"/><table align="center" width="100%" border="0" cellPadding="0" cellSpacing="0" role="presentation" style="margin-bottom:0"><tbody style="width:100%"><tr style="width:100%"><td data-id="__react-email-column" style="width:140px;vertical-align:top;padding-right:12px"><p style="font-size:14px;line-height:24px;font-weight:600;color:#94a3b8;margin:8px 0;margin-top:8px;margin-right:0;margin-bottom:8px;margin-left:0">Severity:</p></td><td data-id="__react-email-column">
+<p style="font-size:14px;line-height:24px;color:#94a3b8;margin:8px 0;word-break:break-word;font-weight:600;margin-top:8px;margin-right:0;margin-bottom:8px;margin-left:0">{{.Severity}}</p></td></tr></tbody></table><hr style="width:100%;border:none;border-top:1px solid #eaeaea;border-color:rgba(148, 163, 184, 0.2);margin:4px 0"/><table align="center" width="100%" border="0" cellPadding="0" cellSpacing="0" role="presentation" style="margin-bottom:0"><tbody style="width:100%"><tr style="width:100%"><td data-id="__react-email-column" style="width:140px;vertical-align:top;padding-right:12px"><p style="font-size:14px;line-height:24px;font-weight:600;color:#94a3b8;margin:8px 0;margin-top:8px;margin-right:0;margin-bottom:8px;margin-left:0">Image:</p></td><td data-id="__react-email-column"><p style="font-size:14px;line-height:24px;color:#e2e8f0;margin:8px 0;word-break:break-word;margin-top:8px;margin-right:0;margin-bottom:8px;margin-left:0">{{.ImageName}}</p></td></tr></tbody></table>
+<hr style="width:100%;border:none;border-top:1px solid #eaeaea;border-color:rgba(148, 163, 184, 0.2);margin:4px 0"/><table align="center" width="100%" border="0" cellPadding="0" cellSpacing="0" role="presentation" style="margin-bottom:0"><tbody style="width:100%"><tr style="width:100%"><td data-id="__react-email-column" style="width:140px;vertical-align:top;padding-right:12px"><p style="font-size:14px;line-height:24px;font-weight:600;color:#94a3b8;margin:8px 0;margin-top:8px;margin-right:0;margin-bottom:8px;margin-left:0">Fixed version:</p></td><td data-id="__react-email-column"><p style="font-size:14px;line-height:24px;font-weight:600;color:#34d399;margin:8px 0;word-break:break-word;margin-top:8px;margin-right:0;margin-bottom:8px;margin-left:0">{{.FixedVersion}}</p></td></tr></tbody></table><hr style="width:100%;border:none;border-top:1px solid #eaeaea;border-color:rgba(148, 163, 184, 0.2);margin:4px 0"/>
+<table align="center" width="100%" border="0" cellPadding="0" cellSpacing="0" role="presentation" style="margin-bottom:0"><tbody style="width:100%"><tr style="width:100%"><td data-id="__react-email-column" style="width:140px;vertical-align:top;padding-right:12px"><p style="font-size:14px;line-height:24px;font-weight:600;color:#94a3b8;margin:8px 0;margin-top:8px;margin-right:0;margin-bottom:8px;margin-left:0">Package:</p></td><td data-id="__react-email-column"><p style="font-size:14px;line-height:24px;color:#e2e8f0;margin:8px 0;word-break:break-word;margin-top:8px;margin-right:0;margin-bottom:8px;margin-left:0">{{.PkgName}}</p></td></tr></tbody></table><hr style="width:100%;border:none;border-top:1px solid #eaeaea;border-color:rgba(148, 163, 184, 0.2);margin:4px 0"/><table align="center" width="100%" border="0" cellPadding="0" cellSpacing="0" role="presentation" style="margin-bottom:0"><tbody style="width:100%"><tr style="width:100%">
+<td data-id="__react-email-column" style="width:140px;vertical-align:top;padding-right:12px"><p style="font-size:14px;line-height:24px;font-weight:600;color:#94a3b8;margin:8px 0;margin-top:8px;margin-right:0;margin-bottom:8px;margin-left:0">Installed version:</p></td><td data-id="__react-email-column"><p style="font-size:14px;line-height:24px;color:#e2e8f0;margin:8px 0;word-break:break-word;margin-top:8px;margin-right:0;margin-bottom:8px;margin-left:0">{{.InstalledVersion}}</p></td></tr></tbody></table></td></tr></tbody></table><table align="center" width="100%" border="0" cellPadding="0" cellSpacing="0" role="presentation" style="margin-top:24px"><tbody><tr><td><p style="font-size:13px;line-height:20px;color:#94a3b8;margin:0;margin-top:0;margin-bottom:0;margin-left:0;margin-right:0">This is an automated notification from Arcane. View the Security page in your dashboard for full scan results and to re-scan after updating.</p></td></tr></tbody></table></div>
+<table align="center" width="100%" border="0" cellPadding="0" cellSpacing="0" role="presentation" style="text-align:center;margin-top:32px;padding-top:24px"><tbody><tr><td><p style="font-size:14px;line-height:20px;margin:0;margin-top:0;margin-bottom:0;margin-left:0;margin-right:0"><a href="{{.AppURL}}" style="color:#a78bfa;text-decoration-line:none;text-decoration:none;font-weight:500" target="_blank">Open Arcane Dashboard →</a></p></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table><!--/$--></body></html>{{end}}
\ No newline at end of file
diff --git a/backend/resources/email-templates/vulnerability-found_text.tmpl b/backend/resources/email-templates/vulnerability-found_text.tmpl
new file mode 100644
index 000000000..a15cc488a
--- /dev/null
+++ b/backend/resources/email-templates/vulnerability-found_text.tmpl
@@ -0,0 +1,43 @@
+{{define "root"}}VULNERABILITY FOUND (FIX AVAILABLE)
+
+A vulnerability with an available fix was detected in one of your container im
+ages. Update to the fixed version to resolve the issue.
+
+CVE:
+
+{{.CVEID}} {{.CVELink}}
+
+----------------------------------------
+
+Severity:
+
+{{.Severity}}
+
+----------------------------------------
+
+Image:
+
+{{.ImageName}}
+
+----------------------------------------
+
+Fixed version:
+
+{{.FixedVersion}}
+
+----------------------------------------
+
+Package:
+
+{{.PkgName}}
+
+----------------------------------------
+
+Installed version:
+
+{{.InstalledVersion}}
+
+This is an automated notification from Arcane. View the Security page in your
+dashboard for full scan results and to re-scan after updating.
+
+Open Arcane Dashboard → {{.AppURL}}{{end}}
\ No newline at end of file
diff --git a/backend/resources/migrations/postgres/033_add_vulnerability_scans.down.sql b/backend/resources/migrations/postgres/033_add_vulnerability_scans.down.sql
new file mode 100644
index 000000000..a943e6999
--- /dev/null
+++ b/backend/resources/migrations/postgres/033_add_vulnerability_scans.down.sql
@@ -0,0 +1,2 @@
+-- Remove vulnerability_scans table
+DROP TABLE IF EXISTS vulnerability_scans;
diff --git a/backend/resources/migrations/postgres/033_add_vulnerability_scans.up.sql b/backend/resources/migrations/postgres/033_add_vulnerability_scans.up.sql
new file mode 100644
index 000000000..54bdb5ead
--- /dev/null
+++ b/backend/resources/migrations/postgres/033_add_vulnerability_scans.up.sql
@@ -0,0 +1,23 @@
+-- Add vulnerability_scans table for storing vulnerability scan results
+CREATE TABLE IF NOT EXISTS vulnerability_scans (
+ id TEXT PRIMARY KEY,
+ image_name TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'pending',
+ scan_time TIMESTAMP NOT NULL,
+ duration BIGINT NOT NULL DEFAULT 0,
+ critical_count INTEGER NOT NULL DEFAULT 0,
+ high_count INTEGER NOT NULL DEFAULT 0,
+ medium_count INTEGER NOT NULL DEFAULT 0,
+ low_count INTEGER NOT NULL DEFAULT 0,
+ unknown_count INTEGER NOT NULL DEFAULT 0,
+ total_count INTEGER NOT NULL DEFAULT 0,
+ vulnerabilities TEXT,
+ error TEXT,
+ scanner_version TEXT,
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP
+);
+
+-- Create indexes for efficient querying
+CREATE INDEX IF NOT EXISTS idx_vulnerability_scans_status ON vulnerability_scans(status);
+CREATE INDEX IF NOT EXISTS idx_vulnerability_scans_scan_time ON vulnerability_scans(scan_time);
diff --git a/backend/resources/migrations/postgres/034_add_vulnerability_ignores.down.sql b/backend/resources/migrations/postgres/034_add_vulnerability_ignores.down.sql
new file mode 100644
index 000000000..bf0cb0176
--- /dev/null
+++ b/backend/resources/migrations/postgres/034_add_vulnerability_ignores.down.sql
@@ -0,0 +1,2 @@
+-- Drop vulnerability_ignores table
+DROP TABLE IF EXISTS vulnerability_ignores;
diff --git a/backend/resources/migrations/postgres/034_add_vulnerability_ignores.up.sql b/backend/resources/migrations/postgres/034_add_vulnerability_ignores.up.sql
new file mode 100644
index 000000000..6ea2eeaec
--- /dev/null
+++ b/backend/resources/migrations/postgres/034_add_vulnerability_ignores.up.sql
@@ -0,0 +1,18 @@
+-- Add vulnerability_ignores table for storing ignored vulnerability records
+CREATE TABLE IF NOT EXISTS vulnerability_ignores (
+ id TEXT PRIMARY KEY,
+ environment_id TEXT NOT NULL,
+ image_id TEXT NOT NULL,
+ vulnerability_id TEXT NOT NULL,
+ pkg_name TEXT NOT NULL,
+ installed_version TEXT NOT NULL,
+ reason TEXT,
+ created_by TEXT NOT NULL,
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
+);
+
+-- Create indexes for efficient querying
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_env ON vulnerability_ignores(environment_id);
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_image ON vulnerability_ignores(image_id);
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_vuln ON vulnerability_ignores(vulnerability_id);
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_composite ON vulnerability_ignores(environment_id, image_id, vulnerability_id, pkg_name, installed_version);
diff --git a/backend/resources/migrations/sqlite/033_add_vulnerability_scans.down.sql b/backend/resources/migrations/sqlite/033_add_vulnerability_scans.down.sql
new file mode 100644
index 000000000..a943e6999
--- /dev/null
+++ b/backend/resources/migrations/sqlite/033_add_vulnerability_scans.down.sql
@@ -0,0 +1,2 @@
+-- Remove vulnerability_scans table
+DROP TABLE IF EXISTS vulnerability_scans;
diff --git a/backend/resources/migrations/sqlite/033_add_vulnerability_scans.up.sql b/backend/resources/migrations/sqlite/033_add_vulnerability_scans.up.sql
new file mode 100644
index 000000000..0aa9a0489
--- /dev/null
+++ b/backend/resources/migrations/sqlite/033_add_vulnerability_scans.up.sql
@@ -0,0 +1,23 @@
+-- Add vulnerability_scans table for storing vulnerability scan results
+CREATE TABLE IF NOT EXISTS vulnerability_scans (
+ id TEXT PRIMARY KEY,
+ image_name TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'pending',
+ scan_time DATETIME NOT NULL,
+ duration INTEGER NOT NULL DEFAULT 0,
+ critical_count INTEGER NOT NULL DEFAULT 0,
+ high_count INTEGER NOT NULL DEFAULT 0,
+ medium_count INTEGER NOT NULL DEFAULT 0,
+ low_count INTEGER NOT NULL DEFAULT 0,
+ unknown_count INTEGER NOT NULL DEFAULT 0,
+ total_count INTEGER NOT NULL DEFAULT 0,
+ vulnerabilities TEXT,
+ error TEXT,
+ scanner_version TEXT,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME
+);
+
+-- Create indexes for efficient querying
+CREATE INDEX IF NOT EXISTS idx_vulnerability_scans_status ON vulnerability_scans(status);
+CREATE INDEX IF NOT EXISTS idx_vulnerability_scans_scan_time ON vulnerability_scans(scan_time);
diff --git a/backend/resources/migrations/sqlite/034_add_vulnerability_ignores.down.sql b/backend/resources/migrations/sqlite/034_add_vulnerability_ignores.down.sql
new file mode 100644
index 000000000..bf0cb0176
--- /dev/null
+++ b/backend/resources/migrations/sqlite/034_add_vulnerability_ignores.down.sql
@@ -0,0 +1,2 @@
+-- Drop vulnerability_ignores table
+DROP TABLE IF EXISTS vulnerability_ignores;
diff --git a/backend/resources/migrations/sqlite/034_add_vulnerability_ignores.up.sql b/backend/resources/migrations/sqlite/034_add_vulnerability_ignores.up.sql
new file mode 100644
index 000000000..08aac3e06
--- /dev/null
+++ b/backend/resources/migrations/sqlite/034_add_vulnerability_ignores.up.sql
@@ -0,0 +1,18 @@
+-- Add vulnerability_ignores table for storing ignored vulnerability records
+CREATE TABLE IF NOT EXISTS vulnerability_ignores (
+ id TEXT PRIMARY KEY,
+ environment_id TEXT NOT NULL,
+ image_id TEXT NOT NULL,
+ vulnerability_id TEXT NOT NULL,
+ pkg_name TEXT NOT NULL,
+ installed_version TEXT NOT NULL,
+ reason TEXT,
+ created_by TEXT NOT NULL,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
+);
+
+-- Create indexes for efficient querying
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_env ON vulnerability_ignores(environment_id);
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_image ON vulnerability_ignores(image_id);
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_vuln ON vulnerability_ignores(vulnerability_id);
+CREATE INDEX IF NOT EXISTS idx_vulnerability_ignores_composite ON vulnerability_ignores(environment_id, image_id, vulnerability_id, pkg_name, installed_version);
diff --git a/cli/go.sum b/cli/go.sum
index 96ae4b732..033931218 100644
--- a/cli/go.sum
+++ b/cli/go.sum
@@ -29,6 +29,7 @@ github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEX
github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhIGpJy4=
github.com/clipperhouse/uax29/v2 v2.3.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
github.com/compose-spec/compose-go/v2 v2.10.1 h1:mFbXobojGRFIVi1UknrvaDAZ+PkJfyjqkA1yseh+vAU=
+github.com/compose-spec/compose-go/v2 v2.10.1/go.mod h1:Ohac1SzhO/4fXXrzWIztIVB6ckmKBv1Nt5Z5mGVESUg=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
@@ -46,6 +47,7 @@ github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/
github.com/getarcaneapp/arcane/types v0.0.0-20260110011808-8759100aa57c h1:WF99RwEYf1ADwD91nzALE2iaT8NfdF0olUuwQQqwa3s=
github.com/getarcaneapp/arcane/types v0.0.0-20260110011808-8759100aa57c/go.mod h1:LSJ0lfbq0wCjczpaV2d/xfxslwoHCsPQ3JebWo+8uaE=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
+github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
diff --git a/email-templates/emails/vulnerability-found.tsx b/email-templates/emails/vulnerability-found.tsx
new file mode 100644
index 000000000..3b3f12731
--- /dev/null
+++ b/email-templates/emails/vulnerability-found.tsx
@@ -0,0 +1,225 @@
+import { Column, Hr, Link, Row, Section, Text } from '@react-email/components';
+import { BaseTemplate } from '../components/base-template';
+import CardHeader from '../components/card-header';
+import { sharedPreviewProps, sharedTemplateProps } from '../props';
+
+interface VulnerabilityFoundEmailProps {
+ logoURL: string;
+ appURL: string;
+ cveId: string;
+ cveLink: string;
+ severity: string;
+ imageName: string;
+ fixedVersion: string;
+ pkgName?: string;
+ installedVersion?: string;
+}
+
+export const VulnerabilityFoundEmail = ({
+ logoURL,
+ appURL,
+ cveId,
+ cveLink,
+ severity,
+ imageName,
+ fixedVersion,
+ pkgName,
+ installedVersion,
+}: VulnerabilityFoundEmailProps) => {
+ const severityColor =
+ severity === 'CRITICAL'
+ ? '#ef4444'
+ : severity === 'HIGH'
+ ? '#f97316'
+ : severity === 'MEDIUM'
+ ? '#eab308'
+ : severity === 'LOW'
+ ? '#22c55e'
+ : '#94a3b8';
+
+ return (
+ <BaseTemplate logoURL={logoURL} appURL={appURL}>
+ <CardHeader title="Vulnerability Found (Fix Available)" />
+
+ <Section style={{ marginTop: '24px' }}>
+ <Text style={mainTextStyle}>
+ A vulnerability with an available fix was detected in one of your container images. Update to the fixed
+ version to resolve the issue.
+ </Text>
+ </Section>
+
+ <Section style={infoSectionStyle}>
+ <Row style={infoRowStyle}>
+ <Column style={labelColumnStyle}>
+ <Text style={labelStyle}>CVE:</Text>
+ </Column>
+ <Column>
+ {cveLink ? (
+ <Link href={cveLink} style={linkStyle}>
+ {cveId}
+ </Link>
+ ) : (
+ <Text style={valueStyle}>{cveId}</Text>
+ )}
+ </Column>
+ </Row>
+
+ <Hr style={dividerStyle} />
+
+ <Row style={infoRowStyle}>
+ <Column style={labelColumnStyle}>
+ <Text style={labelStyle}>Severity:</Text>
+ </Column>
+ <Column>
+ <Text style={{ ...valueStyle, color: severityColor, fontWeight: 600 }}>{severity}</Text>
+ </Column>
+ </Row>
+
+ <Hr style={dividerStyle} />
+
+ <Row style={infoRowStyle}>
+ <Column style={labelColumnStyle}>
+ <Text style={labelStyle}>Image:</Text>
+ </Column>
+ <Column>
+ <Text style={valueStyle}>{imageName}</Text>
+ </Column>
+ </Row>
+
+ <Hr style={dividerStyle} />
+
+ <Row style={infoRowStyle}>
+ <Column style={labelColumnStyle}>
+ <Text style={labelStyle}>Fixed version:</Text>
+ </Column>
+ <Column>
+ <Text style={fixedVersionStyle}>{fixedVersion}</Text>
+ </Column>
+ </Row>
+
+ {pkgName && (
+ <>
+ <Hr style={dividerStyle} />
+ <Row style={infoRowStyle}>
+ <Column style={labelColumnStyle}>
+ <Text style={labelStyle}>Package:</Text>
+ </Column>
+ <Column>
+ <Text style={valueStyle}>{pkgName}</Text>
+ </Column>
+ </Row>
+ </>
+ )}
+
+ {installedVersion && (
+ <>
+ <Hr style={dividerStyle} />
+ <Row style={infoRowStyle}>
+ <Column style={labelColumnStyle}>
+ <Text style={labelStyle}>Installed version:</Text>
+ </Column>
+ <Column>
+ <Text style={valueStyle}>{installedVersion}</Text>
+ </Column>
+ </Row>
+ </>
+ )}
+ </Section>
+
+ <Section style={{ marginTop: '24px' }}>
+ <Text style={footerStyle}>
+ This is an automated notification from Arcane. View the Security page in your dashboard for full scan results
+ and to re-scan after updating.
+ </Text>
+ </Section>
+ </BaseTemplate>
+ );
+};
+
+export default VulnerabilityFoundEmail;
+
+const mainTextStyle = {
+ fontSize: '16px',
+ lineHeight: '24px',
+ color: '#cbd5e1',
+ margin: '0 0 16px 0',
+};
+
+const infoSectionStyle = {
+ marginTop: '20px',
+ backgroundColor: 'rgba(15, 23, 42, 0.5)',
+ border: '1px solid rgba(148, 163, 184, 0.1)',
+ padding: '20px',
+ borderRadius: '12px',
+};
+
+const infoRowStyle = {
+ marginBottom: '0',
+};
+
+const labelColumnStyle = {
+ width: '140px',
+ verticalAlign: 'top' as const,
+ paddingRight: '12px',
+};
+
+const labelStyle = {
+ fontSize: '14px',
+ fontWeight: '600' as const,
+ color: '#94a3b8',
+ margin: '8px 0',
+};
+
+const valueStyle = {
+ fontSize: '14px',
+ color: '#e2e8f0',
+ margin: '8px 0',
+ wordBreak: 'break-word' as const,
+};
+
+const fixedVersionStyle = {
+ fontSize: '14px',
+ fontWeight: '600' as const,
+ color: '#34d399',
+ margin: '8px 0',
+ wordBreak: 'break-word' as const,
+};
+
+const linkStyle = {
+ color: '#a78bfa',
+ textDecoration: 'none',
+};
+
+const dividerStyle = {
+ borderColor: 'rgba(148, 163, 184, 0.2)',
+ margin: '4px 0',
+};
+
+const footerStyle = {
+ fontSize: '13px',
+ lineHeight: '20px',
+ color: '#94a3b8',
+ margin: '0',
+};
+
+VulnerabilityFoundEmail.TemplateProps = {
+ ...sharedTemplateProps,
+ cveId: '{{.CVEID}}',
+ cveLink: '{{.CVELink}}',
+ severity: '{{.Severity}}',
+ imageName: '{{.ImageName}}',
+ fixedVersion: '{{.FixedVersion}}',
+ pkgName: '{{.PkgName}}',
+ installedVersion: '{{.InstalledVersion}}',
+};
+
+VulnerabilityFoundEmail.PreviewProps = {
+ ...sharedPreviewProps,
+ cveId: 'CVE-2024-1234',
+ cveLink: 'https://nvd.nist.gov/vuln/detail/CVE-2024-1234',
+ severity: 'HIGH',
+ imageName: 'nginx:latest',
+ fixedVersion: '1.25.1-1',
+ pkgName: 'libssl3',
+ installedVersion: '3.0.0-1',
+};
diff --git a/frontend/.husky/pre-commit b/frontend/.husky/pre-commit
deleted file mode 100644
index 2cbd23ff0..000000000
--- a/frontend/.husky/pre-commit
+++ /dev/null
@@ -1,2 +0,0 @@
-pnpm -C frontend lint-staged
-echo "lint-staged complete"
\ No newline at end of file
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 97213bab2..c11f019b7 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -128,6 +128,9 @@
"common_search": "Search…",
"common_usage": "Usage",
"common_reset": "Reset",
+ "common_previous": "Previous",
+ "common_next": "Next",
+ "pagination_showing": "Showing {from} to {to} of {total}",
"common_unsaved_changes": "Unsaved changes",
"common_all_changes_saved": "All changes saved",
"common_remove_selected_count": "Remove Selected ({count})",
@@ -564,7 +567,6 @@
"images_has_updates": "Has Updates",
"images_no_updates": "No Updates",
"images_tags_description": "Repository tags associated with this image",
- "images_env_vars_description": "Environment variables defined in this image",
"images_pull_description": "Enter the image reference you want to pull from a registry.",
"images_image_name_label": "Image Name *",
"images_image_name_placeholder": "nginx, redis, ubuntu, etc.",
@@ -593,6 +595,51 @@
"images_remove_success_many": "{count} images removed successfully",
"images_remove_failed_one": "Failed to remove image",
"images_remove_failed_many": "Failed to remove {count} images",
+ "_comment_vulnerabilities": "=== VULNERABILITIES ===",
+ "vuln_title": "Vulnerabilities",
+ "vuln_scan": "Scan",
+ "vuln_rescan": "Re-scan",
+ "vuln_scan_image": "Scan for Vulnerabilities",
+ "vuln_scanning": "Scanning…",
+ "vuln_scan_started": "Vulnerability scan started",
+ "vuln_scan_completed": "Vulnerability scan completed",
+ "vuln_scan_failed": "Vulnerability scan failed",
+ "vuln_no_scan": "Not scanned",
+ "vuln_no_vulnerabilities": "No vulnerabilities found",
+ "vuln_scanner_not_available": "Scanner not available",
+ "vuln_scanner_not_installed": "Trivy scanner is not installed. Please install Trivy to enable vulnerability scanning.",
+ "vuln_severity_critical": "Critical",
+ "vuln_severity_high": "High",
+ "vuln_severity_medium": "Medium",
+ "vuln_severity_low": "Low",
+ "vuln_severity_unknown": "Unknown",
+ "vuln_count_critical": "{count} Critical",
+ "vuln_count_high": "{count} High",
+ "vuln_count_medium": "{count} Medium",
+ "vuln_count_low": "{count} Low",
+ "vuln_count_unknown": "{count} Unknown",
+ "vuln_count_total": "{count} Total",
+ "vuln_summary": "Vulnerability Summary",
+ "vuln_details": "Vulnerability Details",
+ "vuln_package": "Package",
+ "vuln_installed_version": "Installed Version",
+ "vuln_fixed_version": "Fixed Version",
+ "vuln_no_fix": "No fix available",
+ "vuln_references": "References",
+ "vuln_cvss_score": "CVSS Score",
+ "vuln_published": "Published",
+ "vuln_last_modified": "Last Modified",
+ "vuln_scan_time": "Last Scan",
+ "vuln_scan_duration": "Scan Duration",
+ "vuln_scanner_version": "Scanner Version",
+ "vuln_status_pending": "Pending",
+ "vuln_status_scanning": "Scanning",
+ "vuln_status_completed": "Completed",
+ "vuln_status_failed": "Failed",
+ "vuln_clean": "Clean",
+ "vuln_click_to_scan": "Click scan to check for vulnerabilities",
+ "vuln_showing_first": "Showing first {count} of {total} vulnerabilities",
+ "vuln_filter_image_placeholder": "Filter by image or repo…",
"_comment_volumes": "=== VOLUMES ===",
"volumes_title": "Volumes",
"volumes_subtitle": "Manage your Docker volumes",
@@ -885,6 +932,9 @@
"general_settings_saved": "Settings Updated Successfully",
"_comment_settings_security": "=== SETTINGS - SECURITY ===",
"security_title": "Security",
+ "security_subtitle": "Aggregated vulnerability findings across all images in this environment.",
+ "security_images_scanned": "Images Scanned",
+ "security_total_vulnerabilities": "Total Vulnerabilities",
"security_description": "Configure authentication methods, session timeouts, and other security-related options.",
"security_authentication_heading": "Authentication",
"security_local_auth_label": "Local Authentication",
@@ -913,6 +963,10 @@
"security_password_policy_basic_tooltip": "Minimum 8 characters.",
"security_password_policy_standard_tooltip": "10+ chars with upper, lower, and a number.",
"security_password_policy_strong_tooltip": "12+ chars with upper, lower, number, and symbol.",
+ "security_vulnerability_scanning_heading": "Vulnerability Scanning",
+ "security_trivy_image_label": "Trivy Image",
+ "security_trivy_image_description": "Container image used for vulnerability scans.",
+ "security_trivy_image_note": "Note: This must be a Trivy image (for example, ghcr.io/aquasecurity/trivy:latest).",
"security_enable_one_provider": "Enable at least one authentication provider.",
"security_enable_one_provider_error": "At least one authentication provider must be enabled.",
"security_form_validation_error": "Please check the form for errors.",
@@ -920,6 +974,21 @@
"security_settings_saved": "Settings saved successfully.",
"security_local_enabled_info": "Local Authentication enabled to ensure at least one provider is active.",
"security_settings_save_failed": "Failed to save security settings",
+ "security_scan_all": "Scan all images",
+ "security_scanning": "Scanning",
+ "security_no_images_to_scan": "No images available to scan",
+ "security_scan_all_success": "Started scanning {count} images. Results will appear as scans complete.",
+ "security_scan_all_failed": "Failed to start scan for {count} images",
+ "security_scan_all_partial": "Started {succeeded} scans; {failed} failed to start",
+ "security_scan_all_error": "Error starting scan all operation",
+ "vuln_ignore": "Ignore vulnerability",
+ "vuln_ignore_success": "Ignored {cve}",
+ "vuln_ignore_failed": "Failed to ignore vulnerability",
+ "vuln_unignore": "Unignore",
+ "vuln_unignore_success": "Vulnerability unignored",
+ "vuln_unignore_failed": "Failed to unignore vulnerability",
+ "vuln_ignored_title": "Ignored Vulnerabilities",
+ "vuln_ignored_empty": "No ignored vulnerabilities",
"_comment_settings_jobs": "=== SETTINGS - JOBS ===",
"jobs_title": "Job Schedules",
"jobs_description": "Configure how often Arcane background jobs run. Changes apply immediately.",
@@ -928,6 +997,7 @@
"jobs_telemetry_heading": "Telemetry",
"jobs_updates_heading": "Updates",
"jobs_sync_heading": "Sync",
+ "jobs_security_heading": "Security",
"jobs_moved_title": "Job schedules moved",
"jobs_moved_description": "Job schedules are now managed per environment. Select an environment to edit schedules and run jobs.",
"jobs_moved_cta": "Go to Environments",
@@ -1599,12 +1669,16 @@
"notifications_event_image_update_description": "Notify when a new image version is available",
"notifications_event_container_update_label": "Container Updated",
"notifications_event_container_update_description": "Notify when a container is actually updated/restarted",
+ "notifications_event_vulnerability_found_label": "Vulnerability Found (Fix Available)",
+ "notifications_event_vulnerability_found_description": "Notify when a scan finds a vulnerability that has a fixed version (CVE link, severity, image, fixed version)",
"notifications_email_tls_mode_label": "TLS Mode",
"notifications_email_tls_mode_placeholder": "Select TLS mode",
"notifications_email_tls_mode_description": "StartTLS (default) upgrades from plain connection. SSL/TLS uses encryption from start. None uses no encryption.",
"notifications_email_test_simple": "Simple Test Email",
"notifications_email_test_image_update": "Image Update Email",
"notifications_email_test_batch_image_update": "Batch Image Updates Email",
+ "notifications_email_test_vulnerability_found": "Vulnerability Found Email",
+ "notifications_test_vulnerability_notification": "Test Vulnerability Notification",
"notifications_apprise_title": "Apprise Integration",
"notifications_apprise_description": "Configure Apprise API for unified notifications across multiple services",
"notifications_apprise_enabled_label": "Enable Apprise",
diff --git a/frontend/package.json b/frontend/package.json
index e620b8ed7..0f83d7bc5 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -7,10 +7,10 @@
"dev": "vite dev --port 3000 --host",
"build": "vite build",
"preview": "vite preview --port 3000",
- "prepare": "cd .. && husky frontend/.husky",
"lint-staged": "lint-staged",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"format": "prettier --write ./src",
+ "format:check": "prettier --check ./src",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"knip": "knip",
"i18n:unused": "i18n-unused display-unused",
@@ -50,11 +50,9 @@
"bytes": "^3.1.2",
"clsx": "^2.1.1",
"formsnap": "^2.0.1",
- "husky": "^9.1.7",
"i18n-unused": "^0.19.0",
"isomorphic-dompurify": "^2.35.0",
"knip": "^5.82.1",
- "lint-staged": "^16.2.7",
"mode-watcher": "^1.1.0",
"paneforge": "^1.0.2",
"runed": "^0.37.0",
@@ -73,10 +71,5 @@
"vite": "^7.3.1",
"vite-plugin-devtools-json": "^1.0.0",
"zod": "^4.3.6"
- },
- "lint-staged": {
- "*": [
- "sh -c 'cd .. && just format all'"
- ]
}
}
diff --git a/frontend/src/lib/components/arcane-table/arcane-table-filter.svelte b/frontend/src/lib/components/arcane-table/arcane-table-filter.svelte
index 49d90f277..f14e284dc 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table-filter.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table-filter.svelte
@@ -22,6 +22,7 @@
label: string;
value: string | boolean;
icon?: Component;
+ dotClass?: string;
}[];
showCheckboxes?: boolean;
} = $props();
@@ -88,7 +89,9 @@
<CheckIcon class="text-foreground size-6" />
</div>
{/if}
- {#if option.icon}
+ {#if option.dotClass}
+ <span class="{option.dotClass} h-2 w-2 shrink-0 rounded-full" aria-hidden="true"></span>
+ {:else if option.icon}
{@const Icon = option.icon}
<Icon class="text-muted-foreground shrink-0" />
{/if}
diff --git a/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte b/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
index 775b978b1..b965f6f2b 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table-toolbar.svelte
@@ -2,7 +2,14 @@
import type { Table } from '@tanstack/table-core';
import { DataTableFacetedFilter, DataTableViewOptions } from './index.js';
import { Input } from '$lib/components/ui/input/index.js';
- import { imageUpdateFilters, usageFilters, severityFilters, templateTypeFilters, projectStatusFilters } from './data.js';
+ import {
+ imageUpdateFilters,
+ usageFilters,
+ severityFilters,
+ vulnerabilitySeverityFilters,
+ templateTypeFilters,
+ projectStatusFilters
+ } from './data.js';
import { debounced } from '$lib/utils/utils.js';
import { ArcaneButton } from '$lib/components/arcane-button';
import { m } from '$lib/paraglide/messages';
@@ -21,7 +28,8 @@
onToggleMobileField,
customViewOptions,
customToolbarActions,
- class: className
+ class: className,
+ imageNameFilterOptions = []
}: {
table: Table<TData>;
selectedIds?: string[];
@@ -32,6 +40,7 @@
customViewOptions?: Snippet;
customToolbarActions?: Snippet;
class?: string;
+ imageNameFilterOptions?: string[];
} = $props();
const isFiltered = $derived(table.getState().columnFilters.length > 0 || !!table.getState().globalFilter);
@@ -42,6 +51,12 @@
const severityColumn = $derived(
table.getAllColumns().some((col) => col.id === 'severity') ? table.getColumn('severity') : undefined
);
+ const vulnSeverityColumn = $derived(
+ table.getAllColumns().some((col) => col.id === 'vulnSeverity') ? table.getColumn('vulnSeverity') : undefined
+ );
+ const imageNameColumn = $derived(
+ table.getAllColumns().some((col) => col.id === 'imageName') ? table.getColumn('imageName') : undefined
+ );
const statusColumn = $derived(table.getAllColumns().some((col) => col.id === 'status') ? table.getColumn('status') : undefined);
const serviceCountColumn = $derived(
table.getAllColumns().some((col) => col.id === 'serviceCount') ? table.getColumn('serviceCount') : undefined
@@ -49,15 +64,18 @@
const typeColumn = $derived(table.getAllColumns().some((col) => col.id === 'type') ? table.getColumn('type') : undefined);
const debouncedSetGlobal = debounced((v: string) => table.setGlobalFilter(v), 300);
+ const imageNameFilterOptionsFormatted = $derived(imageNameFilterOptions.map((name) => ({ label: name, value: name })));
const hasSelection = $derived(!selectionDisabled && (selectedIds?.length ?? 0) > 0);
const hasBulkActions = $derived(bulkActions && bulkActions.length > 0);
// Check if any filter columns exist
const hasFilterColumns = $derived(
- !!(typeColumn && !severityColumn) ||
+ !!(typeColumn && !severityColumn && !vulnSeverityColumn) ||
!!usageColumn ||
!!updatesColumn ||
!!severityColumn ||
+ !!vulnSeverityColumn ||
+ !!(imageNameColumn && imageNameFilterOptions.length > 0) ||
!!(statusColumn && serviceCountColumn)
);
const activeFilterCount = $derived(table.getState().columnFilters.length);
@@ -81,7 +99,7 @@
{#if hasFilterColumns}
<div class="hidden items-center gap-1.5 md:flex">
- {#if typeColumn && !severityColumn}
+ {#if typeColumn && !severityColumn && !vulnSeverityColumn}
<DataTableFacetedFilter column={typeColumn} title={m.common_type()} options={templateTypeFilters} />
{/if}
{#if usageColumn}
@@ -90,9 +108,18 @@
{#if updatesColumn}
<DataTableFacetedFilter column={updatesColumn} title={m.images_updates()} options={imageUpdateFilters} />
{/if}
- {#if severityColumn}
+ {#if vulnSeverityColumn}
+ <DataTableFacetedFilter
+ column={vulnSeverityColumn}
+ title={m.events_col_severity()}
+ options={vulnerabilitySeverityFilters}
+ />
+ {:else if severityColumn}
<DataTableFacetedFilter column={severityColumn} title={m.events_col_severity()} options={severityFilters} />
{/if}
+ {#if imageNameColumn && imageNameFilterOptionsFormatted.length > 0}
+ <DataTableFacetedFilter column={imageNameColumn} title={m.common_image()} options={imageNameFilterOptionsFormatted} />
+ {/if}
{#if statusColumn && serviceCountColumn}
<DataTableFacetedFilter column={statusColumn} title={m.common_status()} options={projectStatusFilters} />
{/if}
@@ -116,7 +143,7 @@
</Popover.Trigger>
<Popover.Content align="end" class="w-56 p-2">
<div class="flex flex-col gap-1.5">
- {#if typeColumn && !severityColumn}
+ {#if typeColumn && !severityColumn && !vulnSeverityColumn}
<DataTableFacetedFilter column={typeColumn} title={m.common_type()} options={templateTypeFilters} />
{/if}
{#if usageColumn}
@@ -125,9 +152,22 @@
{#if updatesColumn}
<DataTableFacetedFilter column={updatesColumn} title={m.images_updates()} options={imageUpdateFilters} />
{/if}
- {#if severityColumn}
+ {#if vulnSeverityColumn}
+ <DataTableFacetedFilter
+ column={vulnSeverityColumn}
+ title={m.events_col_severity()}
+ options={vulnerabilitySeverityFilters}
+ />
+ {:else if severityColumn}
<DataTableFacetedFilter column={severityColumn} title={m.events_col_severity()} options={severityFilters} />
{/if}
+ {#if imageNameColumn && imageNameFilterOptionsFormatted.length > 0}
+ <DataTableFacetedFilter
+ column={imageNameColumn}
+ title={m.common_image()}
+ options={imageNameFilterOptionsFormatted}
+ />
+ {/if}
{#if statusColumn && serviceCountColumn}
<DataTableFacetedFilter column={statusColumn} title={m.common_status()} options={projectStatusFilters} />
{/if}
diff --git a/frontend/src/lib/components/arcane-table/arcane-table.svelte b/frontend/src/lib/components/arcane-table/arcane-table.svelte
index 487f43feb..c17ce71be 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table.svelte
@@ -64,7 +64,8 @@
groupBy,
groupIcon,
groupCollapsedState = $bindable<Record<string, boolean>>({}),
- onGroupToggle
+ onGroupToggle,
+ imageNameFilterOptions
}: {
items: Paginated<TData>;
requestOptions: SearchPaginationSortRequest;
@@ -100,6 +101,7 @@
groupIcon?: (groupName: string) => Component;
groupCollapsedState?: Record<string, boolean>;
onGroupToggle?: (groupName: string) => void;
+ imageNameFilterOptions?: string[];
} = $props();
// Default page size constant
@@ -625,6 +627,7 @@
{onToggleMobileField}
{customViewOptions}
{customToolbarActions}
+ {imageNameFilterOptions}
/>
</div>
{/if}
@@ -680,6 +683,7 @@
{onToggleMobileField}
{customViewOptions}
{customToolbarActions}
+ {imageNameFilterOptions}
/>
</div>
{/if}
diff --git a/frontend/src/lib/components/arcane-table/data.ts b/frontend/src/lib/components/arcane-table/data.ts
index 335ff9ca5..28df504ba 100644
--- a/frontend/src/lib/components/arcane-table/data.ts
+++ b/frontend/src/lib/components/arcane-table/data.ts
@@ -12,6 +12,13 @@ import {
StopIcon
} from '$lib/icons';
+export interface FilterOption {
+ value: string | boolean;
+ label: string;
+ icon?: any;
+ dotClass?: string;
+}
+
export const usageFilters = [
{
value: true,
@@ -71,6 +78,34 @@ export const severityFilters = [
}
];
+export const vulnerabilitySeverityFilters = [
+ {
+ value: 'CRITICAL',
+ label: m.vuln_severity_critical(),
+ dotClass: 'bg-red-500'
+ },
+ {
+ value: 'HIGH',
+ label: m.vuln_severity_high(),
+ dotClass: 'bg-orange-500'
+ },
+ {
+ value: 'MEDIUM',
+ label: m.vuln_severity_medium(),
+ dotClass: 'bg-amber-500'
+ },
+ {
+ value: 'LOW',
+ label: m.vuln_severity_low(),
+ dotClass: 'bg-emerald-500'
+ },
+ {
+ value: 'UNKNOWN',
+ label: m.vuln_severity_unknown(),
+ dotClass: 'bg-slate-400'
+ }
+];
+
export const templateTypeFilters = [
{
value: 'false',
diff --git a/frontend/src/lib/components/arcane-table/index.ts b/frontend/src/lib/components/arcane-table/index.ts
index 2cd391a1d..cf08093ec 100644
--- a/frontend/src/lib/components/arcane-table/index.ts
+++ b/frontend/src/lib/components/arcane-table/index.ts
@@ -3,4 +3,4 @@ export { default as DataTableViewOptions } from './arcane-table-view-options.sve
export { default as DataTableFacetedFilter } from './arcane-table-filter.svelte';
export type { ColumnSpec, FieldSpec, MobileFieldVisibility, BulkAction } from './arcane-table.types.svelte';
export { default as UniversalMobileCard } from './cards/universal-mobile-card.svelte';
-export { usageFilters, imageUpdateFilters, severityFilters } from './data.js';
+export { usageFilters, imageUpdateFilters, severityFilters, vulnerabilitySeverityFilters } from './data.js';
diff --git a/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte b/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte
index 3d6534663..c24d17929 100644
--- a/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte
+++ b/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte
@@ -158,7 +158,7 @@
{m.sidebar_management()}
</h4>
<div class="space-y-2">
- {#each navigationItems.managementItems as item}
+ {#each navigationItems.managementItems as item (item.url)}
{@const IconComponent = item.icon}
<a
href={item.url}
@@ -184,7 +184,33 @@
{m.sidebar_resources()}
</h4>
<div class="space-y-2">
- {#each navigationItems.resourceItems as item}
+ {#each navigationItems.resourceItems as item (item.url)}
+ {@const IconComponent = item.icon}
+ <a
+ href={item.url}
+ onclick={handleItemClick}
+ class={cn(
+ 'flex items-center gap-3 rounded-2xl px-4 py-3 text-sm font-medium transition-all duration-200 ease-out',
+ 'focus-visible:ring-muted-foreground/50 hover:scale-[1.01] focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:ring-offset-transparent',
+ isActiveItem(item)
+ ? 'bg-muted text-foreground hover:bg-muted/70 shadow-sm'
+ : 'text-foreground hover:bg-muted/50'
+ )}
+ aria-current={isActiveItem(item) ? 'page' : undefined}
+ >
+ <IconComponent size={20} />
+ <span>{item.title}</span>
+ </a>
+ {/each}
+ </div>
+ </section>
+
+ <section>
+ <h4 class="text-muted-foreground/70 mb-4 px-3 text-[11px] font-bold tracking-widest uppercase">
+ {m.security_title()}
+ </h4>
+ <div class="space-y-2">
+ {#each navigationItems.securityItems as item (item.url)}
{@const IconComponent = item.icon}
<a
href={item.url}
@@ -212,7 +238,7 @@
{m.sidebar_administration()}
</h4>
<div class="space-y-2">
- {#each navigationItems.settingsItems as item}
+ {#each navigationItems.settingsItems as item (item.url)}
{#if item.items}
{@const IconComponent = item.icon}
<div class="space-y-2">
@@ -230,7 +256,7 @@
<span>{item.title}</span>
</a>
<div class="ml-6 space-y-1">
- {#each item.items as subItem}
+ {#each item.items as subItem (subItem.url)}
{@const SubIconComponent = subItem.icon}
<a
href={subItem.url}
diff --git a/frontend/src/lib/components/sidebar/sidebar.svelte b/frontend/src/lib/components/sidebar/sidebar.svelte
index cf78ca4aa..eb4af80fb 100644
--- a/frontend/src/lib/components/sidebar/sidebar.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar.svelte
@@ -97,6 +97,7 @@
<Sidebar.Content class={!isCollapsed ? '-mt-2' : ''}>
<SidebarItemGroup label={m.sidebar_management()} items={managementItems} />
<SidebarItemGroup label={m.sidebar_resources()} items={navigationItems.resourceItems} />
+ <SidebarItemGroup label={m.security_title()} items={navigationItems.securityItems} />
{#if isAdmin}
<SidebarItemGroup label={m.sidebar_administration()} items={desktopSettingsItems} />
{/if}
diff --git a/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte b/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
new file mode 100644
index 000000000..d363be956
--- /dev/null
+++ b/frontend/src/lib/components/vulnerability/vulnerability-scan-item.svelte
@@ -0,0 +1,294 @@
+<script lang="ts">
+ import * as ArcaneTooltip from '$lib/components/arcane-tooltip';
+ import { Spinner } from '$lib/components/ui/spinner/index.js';
+ import { ArcaneButton } from '$lib/components/arcane-button';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { toast } from 'svelte-sonner';
+ import { onDestroy } from 'svelte';
+ import type { VulnerabilityScanSummary } from '$lib/types/vulnerability.type';
+ import { m } from '$lib/paraglide/messages';
+ import { vulnerabilityService } from '$lib/services/vulnerability-service';
+ import { startVulnerabilityScanPolling } from '$lib/utils/vulnerability-scan.util';
+ import { ShieldCheckIcon, ShieldAlertIcon, ScanIcon, ShieldXIcon } from '$lib/icons';
+
+ interface Props {
+ scanSummary?: VulnerabilityScanSummary;
+ imageId: string;
+ onScanned?: (data: VulnerabilityScanSummary) => void;
+ }
+
+ let { scanSummary = $bindable(), imageId, onScanned }: Props = $props();
+
+ let isScanning = $state(false);
+ let isOpen = $state(false);
+ let stopPolling: (() => void) | null = $state(null);
+
+ const hasError = $derived(scanSummary?.status === 'failed' || !!scanSummary?.error);
+ const isCompleted = $derived(scanSummary?.status === 'completed');
+ const hasCritical = $derived((scanSummary?.summary?.critical ?? 0) > 0);
+ const hasHigh = $derived((scanSummary?.summary?.high ?? 0) > 0);
+ const hasMedium = $derived((scanSummary?.summary?.medium ?? 0) > 0);
+ const hasLow = $derived((scanSummary?.summary?.low ?? 0) > 0);
+ const hasAnyVuln = $derived((scanSummary?.summary?.total ?? 0) > 0);
+ const totalCount = $derived(scanSummary?.summary?.total ?? 0);
+
+ const statusLabel = $derived.by(() => {
+ if (!scanSummary) return m.vuln_no_scan();
+ if (scanSummary.status === 'failed') return m.common_error();
+ if (scanSummary.status === 'scanning') return m.vuln_scanning();
+ if (scanSummary.summary?.total === 0) return m.vuln_clean();
+ if ((scanSummary.summary?.critical ?? 0) > 0) return m.vuln_severity_critical();
+ if ((scanSummary.summary?.high ?? 0) > 0) return m.vuln_severity_high();
+ if ((scanSummary.summary?.medium ?? 0) > 0) return m.vuln_severity_medium();
+ if ((scanSummary.summary?.low ?? 0) > 0) return m.vuln_severity_low();
+ return m.vuln_severity_unknown();
+ });
+
+ const statusVariant = $derived.by(() => {
+ if (hasError) return 'red';
+ if (!isCompleted) return 'gray';
+ if (totalCount === 0) return 'emerald';
+ if (totalCount < 10) return 'amber';
+ if (totalCount < 50) return 'orange';
+ return 'red';
+ });
+
+ const statusBadgeText = $derived.by(() => {
+ if (!isCompleted) return statusLabel;
+ return `${statusLabel} · ${totalCount}`;
+ });
+
+ const triggerDotClass = $derived.by(() => {
+ if (hasError) return 'bg-red-500';
+ if (!isCompleted) return 'bg-muted-foreground/50';
+ if (totalCount === 0) return 'bg-emerald-500';
+ if (hasCritical) return 'bg-red-500';
+ if (hasHigh) return 'bg-orange-500';
+ if (hasMedium) return 'bg-amber-500';
+ if ((scanSummary?.summary?.low ?? 0) > 0) return 'bg-yellow-500';
+ return 'bg-gray-400';
+ });
+
+ const severitySegments = $derived.by(() => {
+ const summary = scanSummary?.summary;
+ if (!summary) return [] as Array<{ key: string; pct: number; barClass: string }>;
+ const total = Math.max(summary.total, 1);
+ return [
+ { key: 'critical', pct: (summary.critical / total) * 100, barClass: 'bg-red-500' },
+ { key: 'high', pct: (summary.high / total) * 100, barClass: 'bg-orange-500' },
+ { key: 'medium', pct: (summary.medium / total) * 100, barClass: 'bg-amber-500' },
+ { key: 'low', pct: (summary.low / total) * 100, barClass: 'bg-yellow-500' },
+ { key: 'unknown', pct: (summary.unknown / total) * 100, barClass: 'bg-gray-400' }
+ ].filter((segment) => segment.pct > 0);
+ });
+
+ async function startScan() {
+ if (isScanning) return;
+
+ isScanning = true;
+ try {
+ const result = await vulnerabilityService.scanImage(imageId);
+ if (result) {
+ const summary: VulnerabilityScanSummary = {
+ imageId: result.imageId,
+ scanTime: result.scanTime,
+ status: result.status,
+ summary: result.summary,
+ error: result.error
+ };
+ scanSummary = summary;
+ onScanned?.(summary);
+ if (result.status === 'completed') {
+ toast.success(m.vuln_scan_completed());
+ } else if (result.status === 'failed') {
+ toast.error(result.error || m.vuln_scan_failed());
+ } else {
+ beginPolling(true);
+ }
+ }
+ } catch (error) {
+ console.error('Error scanning image:', error);
+ toast.error(m.vuln_scan_failed());
+ } finally {
+ isScanning = false;
+ }
+ }
+
+ function stopScanPolling() {
+ if (stopPolling) {
+ stopPolling();
+ stopPolling = null;
+ }
+ }
+
+ function beginPolling(showToast: boolean) {
+ if (stopPolling) return;
+ const cancel = startVulnerabilityScanPolling(imageId, (id) => vulnerabilityService.getScanSummary(id), {
+ onUpdate: (summary) => {
+ scanSummary = summary;
+ onScanned?.(summary);
+ },
+ onComplete: (summary) => {
+ scanSummary = summary;
+ onScanned?.(summary);
+ stopScanPolling();
+ if (showToast) {
+ if (summary.status === 'completed') {
+ toast.success(m.vuln_scan_completed());
+ } else {
+ toast.error(summary.error || m.vuln_scan_failed());
+ }
+ }
+ },
+ onError: () => {}
+ });
+
+ stopPolling = cancel;
+ }
+
+ $effect(() => {
+ const scanning = scanSummary?.status === 'scanning' || scanSummary?.status === 'pending';
+ if (scanning) {
+ beginPolling(false);
+ } else {
+ stopScanPolling();
+ }
+ });
+
+ onDestroy(() => {
+ stopScanPolling();
+ });
+</script>
+
+{#snippet severityBadge(count: number, label: string, colorClass: string)}
+ {#if count > 0}
+ <div class="flex items-center justify-between text-xs">
+ <span class={colorClass}>{label}</span>
+ <span class="font-mono font-medium {colorClass}">{count}</span>
+ </div>
+ {/if}
+{/snippet}
+
+{#snippet tooltipContent()}
+ <div class="max-w-[240px] space-y-3 p-3">
+ {#if hasError}
+ <div class="flex items-center gap-2 text-red-500">
+ <ShieldXIcon class="size-4" />
+ <span class="text-sm font-medium">{m.vuln_scan_failed()}</span>
+ </div>
+ {#if scanSummary?.error}
+ <p class="text-muted-foreground text-xs">{scanSummary.error}</p>
+ {/if}
+ {:else if scanSummary?.status === 'scanning' || isScanning}
+ <div class="flex items-center gap-2 text-blue-500">
+ <Spinner class="size-4" />
+ <span class="text-sm font-medium">{m.vuln_scanning()}</span>
+ </div>
+ {:else if isCompleted && scanSummary?.summary}
+ <div class="space-y-2">
+ <div class="flex items-center gap-2">
+ {#if hasCritical}
+ <ShieldAlertIcon class="size-4 text-red-500" />
+ {:else if hasHigh}
+ <ShieldAlertIcon class="size-4 text-orange-500" />
+ {:else if hasMedium}
+ <ShieldAlertIcon class="size-4 text-amber-500" />
+ {:else if hasAnyVuln}
+ <ShieldAlertIcon class="size-4 text-yellow-500" />
+ {:else}
+ <ShieldCheckIcon class="size-4 text-emerald-500" />
+ {/if}
+ <div>
+ <p class="text-sm font-medium">{statusLabel}</p>
+ <p class="text-muted-foreground text-xs">{m.vuln_summary()}</p>
+ </div>
+ </div>
+ <div class="bg-muted/40 rounded-md p-2">
+ <div class="flex items-center justify-between text-xs">
+ <span class="text-muted-foreground">{m.common_total()}</span>
+ <span class="font-mono">{totalCount}</span>
+ </div>
+ <div class="bg-muted/70 mt-2 flex h-2 overflow-hidden rounded-full">
+ {#each severitySegments as segment (segment.key)}
+ <div class={segment.barClass} style={`width: ${segment.pct}%`}></div>
+ {/each}
+ </div>
+ </div>
+ <div class="space-y-1.5">
+ {@render severityBadge(scanSummary.summary.critical, m.vuln_severity_critical(), 'text-red-500')}
+ {@render severityBadge(scanSummary.summary.high, m.vuln_severity_high(), 'text-orange-500')}
+ {@render severityBadge(scanSummary.summary.medium, m.vuln_severity_medium(), 'text-amber-500')}
+ {@render severityBadge(scanSummary.summary.low, m.vuln_severity_low(), 'text-yellow-600')}
+ {@render severityBadge(scanSummary.summary.unknown, m.vuln_severity_unknown(), 'text-gray-500')}
+ </div>
+ {#if !hasAnyVuln}
+ <p class="text-xs text-emerald-500">{m.vuln_no_vulnerabilities()}</p>
+ {/if}
+ </div>
+ {:else}
+ <div class="text-muted-foreground flex items-center gap-2">
+ <ScanIcon class="size-4" />
+ <span class="text-sm font-medium">{m.vuln_no_scan()}</span>
+ </div>
+ <p class="text-muted-foreground text-xs">
+ {m.vuln_click_to_scan()}
+ </p>
+ {/if}
+
+ {#if !isScanning && scanSummary?.status !== 'scanning'}
+ <button
+ onclick={startScan}
+ disabled={isScanning}
+ class="bg-secondary text-secondary-foreground hover:bg-secondary/80 w-full rounded-md px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50"
+ >
+ {isScanning
+ ? m.vuln_scanning()
+ : scanSummary?.status === 'completed' || scanSummary?.status === 'failed'
+ ? m.vuln_rescan()
+ : m.vuln_scan()}
+ </button>
+ {/if}
+ </div>
+{/snippet}
+
+<ArcaneTooltip.Root bind:open={isOpen} interactive>
+ <ArcaneTooltip.Trigger>
+ <div class="flex w-16 flex-col items-center gap-1">
+ {#if isScanning || scanSummary?.status === 'scanning'}
+ <div class="flex items-center justify-center gap-1.5 text-xs text-blue-500">
+ <Spinner class="size-3 shrink-0" />
+ <span class="truncate">{m.vuln_scanning()}</span>
+ </div>
+ {:else if hasError}
+ <div class="flex items-center justify-center gap-1.5 text-xs text-red-500">
+ <ShieldXIcon class="size-3 shrink-0" />
+ <span class="truncate">{m.vuln_scan_failed()}</span>
+ </div>
+ {:else if isCompleted}
+ <div
+ class="border-border/50 bg-muted/20 flex w-full min-w-0 items-center justify-center gap-1.5 rounded-md border px-2 py-1"
+ >
+ <span class="{triggerDotClass} size-2 shrink-0 rounded-full" aria-hidden="true"></span>
+ <span class="text-foreground text-xs font-medium tabular-nums">{totalCount}</span>
+ </div>
+ {:else}
+ <div class="flex justify-center">
+ <ArcaneButton
+ action="base"
+ tone="ghost"
+ size="icon"
+ icon={ScanIcon}
+ showLabel={false}
+ customLabel={m.vuln_scan()}
+ onclick={startScan}
+ disabled={isScanning}
+ class="size-7"
+ />
+ </div>
+ {/if}
+ </div>
+ </ArcaneTooltip.Trigger>
+ <ArcaneTooltip.Content side="right">
+ {@render tooltipContent()}
+ </ArcaneTooltip.Content>
+</ArcaneTooltip.Root>
diff --git a/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte b/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte
new file mode 100644
index 000000000..03b6a1128
--- /dev/null
+++ b/frontend/src/lib/components/vulnerability/vulnerability-scan-panel.svelte
@@ -0,0 +1,513 @@
+<script lang="ts">
+ import * as Card from '$lib/components/ui/card';
+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';
+ import UniversalMobileCard from '$lib/components/arcane-table/cards/universal-mobile-card.svelte';
+ import { ArcaneButton } from '$lib/components/arcane-button';
+ import { Spinner } from '$lib/components/ui/spinner';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { m } from '$lib/paraglide/messages';
+ import { vulnerabilityService } from '$lib/services/vulnerability-service.js';
+ import type { ColumnSpec } from '$lib/components/arcane-table/arcane-table.types.svelte';
+ import type { VulnerabilityScanResult, Vulnerability as VulnType, SeveritySummary } from '$lib/types/vulnerability.type';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import { ShieldCheckIcon, ShieldAlertIcon, ShieldXIcon, ScanIcon, CodeIcon, CheckIcon } from '$lib/icons';
+
+ interface Props {
+ scan?: VulnerabilityScanResult | null;
+ isScanning?: boolean;
+ onScan?: () => void;
+ }
+
+ let { scan, isScanning = false, onScan }: Props = $props();
+
+ const DEFAULT_PAGE_SIZE = 20;
+
+ type VulnerabilityRow = VulnType & { id: string };
+
+ function buildSeveritySummary(vulns: VulnType[]): SeveritySummary {
+ const summary: SeveritySummary = {
+ critical: 0,
+ high: 0,
+ medium: 0,
+ low: 0,
+ unknown: 0,
+ total: 0
+ };
+
+ for (const vuln of vulns) {
+ switch (vuln.severity) {
+ case 'CRITICAL':
+ summary.critical++;
+ break;
+ case 'HIGH':
+ summary.high++;
+ break;
+ case 'MEDIUM':
+ summary.medium++;
+ break;
+ case 'LOW':
+ summary.low++;
+ break;
+ default:
+ summary.unknown++;
+ }
+ summary.total++;
+ }
+
+ return summary;
+ }
+
+ const resolvedSummary = $derived.by(() => {
+ if (scan?.summary) return scan.summary;
+ if (scan?.vulnerabilities?.length) {
+ return buildSeveritySummary(scan.vulnerabilities);
+ }
+ return undefined;
+ });
+
+ let vulnerabilityRequestOptions = $state<SearchPaginationSortRequest>({
+ pagination: { page: 1, limit: DEFAULT_PAGE_SIZE },
+ sort: { column: 'vulnSeverity', direction: 'desc' }
+ });
+
+ let vulnerabilityItems = $state<Paginated<VulnerabilityRow>>({
+ data: [],
+ pagination: {
+ totalPages: 1,
+ totalItems: 0,
+ currentPage: 1,
+ itemsPerPage: DEFAULT_PAGE_SIZE,
+ grandTotalItems: 0
+ }
+ });
+
+ const columns = $derived([
+ { accessorKey: 'vulnerabilityId', title: 'CVE', cell: CveCell },
+ { accessorKey: 'pkgName', title: m.vuln_package(), cell: PackageCell },
+ { id: 'vulnSeverity', accessorKey: 'severity', title: m.events_col_severity(), sortable: true, cell: SeverityCell },
+ { accessorKey: 'installedVersion', title: m.vuln_installed_version(), cell: InstalledCell },
+ { accessorKey: 'fixedVersion', title: m.vuln_fixed_version(), cell: FixedCell }
+ ] satisfies ColumnSpec<VulnerabilityRow>[]);
+
+ const mobileFields = [
+ { id: 'vulnerabilityId', label: 'CVE', defaultVisible: true },
+ { id: 'pkgName', label: m.vuln_package(), defaultVisible: true },
+ { id: 'vulnSeverity', label: m.events_col_severity(), defaultVisible: true },
+ { id: 'installedVersion', label: m.vuln_installed_version(), defaultVisible: false },
+ { id: 'fixedVersion', label: m.vuln_fixed_version(), defaultVisible: false }
+ ];
+
+ const severityBars = $derived.by(() => {
+ if (!resolvedSummary)
+ return [] as Array<{
+ key: string;
+ label: string;
+ count: number;
+ pct: number;
+ barClass: string;
+ textClass: string;
+ }>;
+ const total = Math.max(resolvedSummary.total, 1);
+ return [
+ {
+ key: 'critical',
+ label: m.vuln_severity_critical(),
+ count: resolvedSummary.critical,
+ pct: (resolvedSummary.critical / total) * 100,
+ barClass: 'bg-red-500',
+ textClass: 'text-red-500'
+ },
+ {
+ key: 'high',
+ label: m.vuln_severity_high(),
+ count: resolvedSummary.high,
+ pct: (resolvedSummary.high / total) * 100,
+ barClass: 'bg-orange-500',
+ textClass: 'text-orange-500'
+ },
+ {
+ key: 'medium',
+ label: m.vuln_severity_medium(),
+ count: resolvedSummary.medium,
+ pct: (resolvedSummary.medium / total) * 100,
+ barClass: 'bg-amber-500',
+ textClass: 'text-amber-500'
+ },
+ {
+ key: 'low',
+ label: m.vuln_severity_low(),
+ count: resolvedSummary.low,
+ pct: (resolvedSummary.low / total) * 100,
+ barClass: 'bg-yellow-500',
+ textClass: 'text-yellow-600'
+ },
+ {
+ key: 'unknown',
+ label: m.vuln_severity_unknown(),
+ count: resolvedSummary.unknown,
+ pct: (resolvedSummary.unknown / total) * 100,
+ barClass: 'bg-gray-400',
+ textClass: 'text-gray-500'
+ }
+ ].filter((bar) => bar.count > 0);
+ });
+
+ const scanStatusLabel = $derived.by(() => {
+ if (!resolvedSummary) return m.common_unknown();
+ if (resolvedSummary.total === 0) return m.vuln_clean();
+ if (resolvedSummary.critical > 0) return m.vuln_severity_critical();
+ if (resolvedSummary.high > 0) return m.vuln_severity_high();
+ if (resolvedSummary.medium > 0) return m.vuln_severity_medium();
+ if (resolvedSummary.low > 0) return m.vuln_severity_low();
+ return m.vuln_severity_unknown();
+ });
+
+ const scanStatusTone = $derived.by(() => {
+ if (!resolvedSummary) return 'bg-muted text-muted-foreground';
+ if (resolvedSummary.total === 0) return 'bg-emerald-500/15 text-emerald-500 ring-emerald-500/30';
+ if (resolvedSummary.critical > 0) return 'bg-red-500/15 text-red-500 ring-red-500/30';
+ if (resolvedSummary.high > 0) return 'bg-orange-500/15 text-orange-500 ring-orange-500/30';
+ if (resolvedSummary.medium > 0) return 'bg-amber-500/15 text-amber-500 ring-amber-500/30';
+ if (resolvedSummary.low > 0) return 'bg-yellow-500/15 text-yellow-600 ring-yellow-500/30';
+ return 'bg-gray-500/15 text-gray-500 ring-gray-500/30';
+ });
+
+ const scanDurationLabel = $derived.by(() => {
+ const durationMs = scan?.duration ?? 0;
+ if (!durationMs) return m.common_na();
+ if (durationMs < 1000) return `${durationMs} ms`;
+ return `${(durationMs / 1000).toFixed(1)} s`;
+ });
+
+ const headerIcon = $derived.by(() => {
+ const isClean = scan?.status === 'completed' && (resolvedSummary?.total ?? 0) === 0;
+ return isClean ? ShieldCheckIcon : ShieldAlertIcon;
+ });
+
+ const isWorking = $derived.by(() => isScanning || scan?.status === 'scanning');
+ const hasError = $derived.by(() => scan?.status === 'failed' || !!scan?.error);
+
+ function getSeverityLabel(severity: string): string {
+ switch (severity) {
+ case 'CRITICAL':
+ return m.vuln_severity_critical();
+ case 'HIGH':
+ return m.vuln_severity_high();
+ case 'MEDIUM':
+ return m.vuln_severity_medium();
+ case 'LOW':
+ return m.vuln_severity_low();
+ default:
+ return m.vuln_severity_unknown();
+ }
+ }
+
+ function getSeverityBadgeVariant(severity: string): 'red' | 'orange' | 'amber' | 'green' | 'gray' {
+ switch (severity) {
+ case 'CRITICAL':
+ return 'red';
+ case 'HIGH':
+ return 'orange';
+ case 'MEDIUM':
+ return 'amber';
+ case 'LOW':
+ return 'green';
+ default:
+ return 'gray';
+ }
+ }
+
+ function getSeverityIconVariant(severity: string): 'red' | 'orange' | 'amber' | 'emerald' | 'gray' {
+ switch (severity) {
+ case 'CRITICAL':
+ return 'red';
+ case 'HIGH':
+ return 'orange';
+ case 'MEDIUM':
+ return 'amber';
+ case 'LOW':
+ return 'emerald';
+ default:
+ return 'gray';
+ }
+ }
+
+ function getVulnerabilityKey(vuln: VulnType, index: number): string {
+ return [vuln.vulnerabilityId, vuln.pkgName, vuln.installedVersion ?? '', vuln.fixedVersion ?? '', String(index)].join('-');
+ }
+
+ async function refreshVulnerabilityTable(options: SearchPaginationSortRequest) {
+ if (!scan?.imageId) {
+ const empty: Paginated<VulnerabilityRow> = {
+ data: [],
+ pagination: {
+ totalPages: 1,
+ totalItems: 0,
+ currentPage: 1,
+ itemsPerPage: DEFAULT_PAGE_SIZE,
+ grandTotalItems: 0
+ }
+ };
+ vulnerabilityItems = empty;
+ return empty;
+ }
+
+ const mergedFilters = { ...(options.filters ?? {}) };
+ if (mergedFilters.vulnSeverity) {
+ mergedFilters.severity = mergedFilters.vulnSeverity;
+ delete mergedFilters.vulnSeverity;
+ }
+
+ const sort = options.sort?.column === 'vulnSeverity' ? { ...options.sort, column: 'severity' } : options.sort;
+
+ const request: SearchPaginationSortRequest = {
+ ...options,
+ sort,
+ filters: Object.keys(mergedFilters).length ? mergedFilters : undefined
+ };
+
+ const response = await vulnerabilityService.getImageVulnerabilities(scan.imageId, request);
+ const page = request.pagination?.page ?? 1;
+ const limit = request.pagination?.limit ?? DEFAULT_PAGE_SIZE;
+ const offset = (page - 1) * limit;
+ const mapped: Paginated<VulnerabilityRow> = {
+ ...response,
+ data: (response.data ?? []).map((item, index) => ({
+ ...item,
+ id: getVulnerabilityKey(item, offset + index)
+ }))
+ };
+ vulnerabilityItems = mapped;
+ return mapped;
+ }
+
+ let lastScanKey = '';
+ $effect(() => {
+ const scanKey = scan ? `${scan.imageId}:${scan.scanTime}` : '';
+ const totalVulns = resolvedSummary?.total ?? 0;
+ if (!scan?.imageId || scan?.status !== 'completed' || totalVulns === 0) {
+ lastScanKey = scanKey;
+ return;
+ }
+ if (scanKey && scanKey !== lastScanKey) {
+ lastScanKey = scanKey;
+ void refreshVulnerabilityTable(vulnerabilityRequestOptions);
+ }
+ });
+</script>
+
+{#snippet CveCell({ item }: { item: VulnerabilityRow })}
+ <a
+ href="https://nvd.nist.gov/vuln/detail/{item.vulnerabilityId}"
+ target="_blank"
+ rel="noopener noreferrer"
+ class="font-mono text-xs text-blue-600 hover:underline dark:text-blue-400"
+ >
+ {item.vulnerabilityId}
+ </a>
+{/snippet}
+
+{#snippet PackageCell({ item }: { item: VulnerabilityRow })}
+ <span class="font-mono text-xs">{item.pkgName}</span>
+{/snippet}
+
+{#snippet SeverityCell({ item }: { item: VulnerabilityRow })}
+ {#if item.severity === 'CRITICAL'}
+ <StatusBadge text={m.vuln_severity_critical()} variant="red" size="sm" />
+ {:else if item.severity === 'HIGH'}
+ <StatusBadge text={m.vuln_severity_high()} variant="orange" size="sm" />
+ {:else if item.severity === 'MEDIUM'}
+ <StatusBadge text={m.vuln_severity_medium()} variant="amber" size="sm" />
+ {:else if item.severity === 'LOW'}
+ <StatusBadge text={m.vuln_severity_low()} variant="lime" size="sm" />
+ {:else}
+ <StatusBadge text={m.vuln_severity_unknown()} variant="gray" size="sm" />
+ {/if}
+{/snippet}
+
+{#snippet InstalledCell({ item }: { item: VulnerabilityRow })}
+ <span class="font-mono text-xs">{item.installedVersion}</span>
+{/snippet}
+
+{#snippet FixedCell({ item }: { item: VulnerabilityRow })}
+ <span class="font-mono text-xs">{item.fixedVersion || m.vuln_no_fix()}</span>
+{/snippet}
+
+{#snippet VulnerabilityMobileCard({
+ row,
+ item,
+ mobileFieldVisibility
+}: {
+ row: any;
+ item: VulnerabilityRow;
+ mobileFieldVisibility: Record<string, boolean>;
+})}
+ <UniversalMobileCard
+ {item}
+ icon={(item) => ({
+ component: ShieldAlertIcon,
+ variant: getSeverityIconVariant(item.severity)
+ })}
+ title={(item) => item.vulnerabilityId}
+ subtitle={(item) => ((mobileFieldVisibility.pkgName ?? true) ? item.pkgName : null)}
+ badges={[
+ (item) =>
+ (mobileFieldVisibility.vulnSeverity ?? true)
+ ? { variant: getSeverityBadgeVariant(item.severity), text: getSeverityLabel(item.severity) }
+ : null
+ ]}
+ fields={[
+ {
+ label: m.vuln_installed_version(),
+ getValue: (item) => item.installedVersion,
+ type: 'mono',
+ icon: CodeIcon,
+ iconVariant: 'blue',
+ show: mobileFieldVisibility.installedVersion ?? true
+ },
+ {
+ label: m.vuln_fixed_version(),
+ getValue: (item) => item.fixedVersion || m.vuln_no_fix(),
+ type: 'mono',
+ icon: CheckIcon,
+ iconVariant: item.fixedVersion ? 'emerald' : 'gray',
+ show: mobileFieldVisibility.fixedVersion ?? true
+ }
+ ]}
+ />
+{/snippet}
+
+<Card.Root>
+ <Card.Header icon={headerIcon}>
+ <div class="flex flex-col space-y-1.5">
+ <Card.Title>{m.vuln_title()}</Card.Title>
+ <Card.Description>
+ {#if scan?.status === 'completed'}
+ {m.vuln_scan_time()}: {scan ? new Date(scan.scanTime).toLocaleString() : m.common_na()}
+ {:else if isWorking}
+ {m.vuln_scanning()}
+ {:else}
+ {m.vuln_no_scan()}
+ {/if}
+ </Card.Description>
+ </div>
+ </Card.Header>
+ <Card.Content class="p-4">
+ {#if isWorking}
+ <div class="flex items-center justify-center py-8">
+ <Spinner class="size-8" />
+ <span class="text-muted-foreground ml-3">{m.vuln_scanning()}</span>
+ </div>
+ {:else if scan?.status === 'completed' && resolvedSummary}
+ {@const summary = resolvedSummary}
+ {#if summary.total === 0}
+ <div class="rounded-2xl border border-emerald-500/20 bg-emerald-500/5 p-6 shadow-sm">
+ <div class="flex items-center gap-4">
+ <div class="rounded-full bg-emerald-500/15 p-3">
+ <ShieldCheckIcon class="size-6 text-emerald-500" />
+ </div>
+ <div class="space-y-1">
+ <p class="text-xs font-semibold tracking-wide text-emerald-400 uppercase">{m.vuln_summary()}</p>
+ <p class="text-lg font-semibold text-emerald-200">{m.vuln_clean()}</p>
+ <p class="text-sm text-emerald-300/80">{m.vuln_no_vulnerabilities()}</p>
+ </div>
+ </div>
+ <div class="text-muted-foreground mt-4 flex flex-wrap gap-2 text-xs">
+ <span class="bg-muted/50 rounded-full px-2 py-1">{scanDurationLabel}</span>
+ {#if scan?.scannerVersion}
+ <span class="bg-muted/50 rounded-full px-2 py-1">Trivy {scan.scannerVersion}</span>
+ {/if}
+ </div>
+ </div>
+ {:else}
+ <div class="grid gap-4 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)]">
+ <div class="border-border/60 bg-muted/30 rounded-2xl border p-5 shadow-sm">
+ <div class="flex items-center justify-between">
+ <p class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">{m.vuln_summary()}</p>
+ <span class={`inline-flex items-center rounded-full px-2.5 py-1 text-xs font-semibold ring-1 ${scanStatusTone}`}>
+ {scanStatusLabel}
+ </span>
+ </div>
+ <div class="mt-5 flex items-end gap-4">
+ <div class="text-5xl leading-none font-semibold tracking-tight">{summary.total}</div>
+ <div class="text-muted-foreground space-y-1 text-xs">
+ <div class="tracking-wide uppercase">{m.common_total()}</div>
+ <div>{m.vuln_details()}</div>
+ </div>
+ </div>
+ <div class="mt-5 space-y-2">
+ {#each severityBars as bar (bar.key)}
+ <div class="flex items-center gap-3 text-xs">
+ <span class="text-muted-foreground w-24">{bar.label}</span>
+ <div class="bg-muted/60 relative h-2 flex-1 overflow-hidden rounded-full">
+ <div class={`h-full ${bar.barClass}`} style={`width: ${bar.pct}%`}></div>
+ </div>
+ <span class={`w-8 text-right font-mono ${bar.textClass}`}>{bar.count}</span>
+ </div>
+ {/each}
+ </div>
+ <div class="text-muted-foreground mt-4 flex flex-wrap gap-2 text-xs">
+ <span class="bg-muted/50 rounded-full px-2 py-1">{scanDurationLabel}</span>
+ {#if scan?.scannerVersion}
+ <span class="bg-muted/50 rounded-full px-2 py-1">Trivy {scan.scannerVersion}</span>
+ {/if}
+ </div>
+ </div>
+
+ <div class="grid gap-3 sm:grid-cols-2">
+ {#each severityBars as bar (bar.key)}
+ <div class="border-border/60 bg-muted/30 rounded-xl border p-4 shadow-sm">
+ <div class="flex items-center justify-between">
+ <span class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">{bar.label}</span>
+ </div>
+ <div class={`mt-2 text-3xl font-semibold ${bar.textClass}`}>{bar.count}</div>
+ <div class="bg-muted/60 mt-3 h-1.5 rounded-full">
+ <div class={`h-full ${bar.barClass}`} style={`width: ${bar.pct}%`}></div>
+ </div>
+ </div>
+ {/each}
+ </div>
+ </div>
+ {/if}
+
+ {#if resolvedSummary && resolvedSummary.total > 0}
+ <div class="mt-6 space-y-2">
+ <h4 class="text-muted-foreground text-sm font-semibold">{m.vuln_details()}</h4>
+ <div class="border-border/60 rounded-xl border">
+ <ArcaneTable
+ items={vulnerabilityItems}
+ bind:requestOptions={vulnerabilityRequestOptions}
+ onRefresh={refreshVulnerabilityTable}
+ {columns}
+ mobileCard={VulnerabilityMobileCard}
+ {mobileFields}
+ selectionDisabled
+ unstyled
+ />
+ </div>
+ </div>
+ {/if}
+ {:else if hasError}
+ <div class="flex items-center gap-3 rounded-lg bg-red-50 p-4 dark:bg-red-950/20">
+ <ShieldXIcon class="size-8 text-red-500" />
+ <div>
+ <p class="font-medium text-red-800 dark:text-red-200">{m.vuln_scan_failed()}</p>
+ <p class="text-sm text-red-600 dark:text-red-400">{scan?.error || m.vuln_scanner_not_installed()}</p>
+ </div>
+ </div>
+ {:else}
+ <div class="flex flex-col items-center justify-center py-8 text-center">
+ <ScanIcon class="text-muted-foreground/50 mb-4 size-12" />
+ <p class="text-muted-foreground mb-2">{m.vuln_no_scan()}</p>
+ <ArcaneButton action="base" onclick={onScan} disabled={!onScan || isScanning}>
+ {#if isScanning}
+ <Spinner class="mr-2 size-4" />
+ {:else}
+ <ScanIcon class="mr-2 size-4" />
+ {/if}
+ {m.vuln_scan_image()}
+ </ArcaneButton>
+ </div>
+ {/if}
+ </Card.Content>
+</Card.Root>
diff --git a/frontend/src/lib/config/navigation-config.ts b/frontend/src/lib/config/navigation-config.ts
index fe61da668..eee178702 100644
--- a/frontend/src/lib/config/navigation-config.ts
+++ b/frontend/src/lib/config/navigation-config.ts
@@ -15,7 +15,8 @@ import {
VolumesIcon,
EventsIcon,
SettingsIcon,
- GitBranchIcon
+ GitBranchIcon,
+ ShieldAlertIcon
} from '$lib/icons';
import { m } from '$lib/paraglide/messages';
import type { ShortcutKey } from '$lib/utils/keyboard-shortcut.utils';
@@ -41,6 +42,7 @@ export const navigationItems: Record<string, NavigationItem[]> = {
{ title: m.networks_title(), url: '/networks', icon: NetworksIcon, shortcut: ['mod', '7'] },
{ title: m.volumes_title(), url: '/volumes', icon: VolumesIcon, shortcut: ['mod', '8'] }
],
+ securityItems: [{ title: m.vuln_title(), url: '/security', icon: ShieldAlertIcon, shortcut: ['mod', 's'] }],
settingsItems: [
{
title: m.events_title(),
@@ -95,6 +97,10 @@ export function getAvailableMobileNavItems(): NavigationItem[] {
flatItems.push(...navigationItems.resourceItems);
}
+ if (navigationItems.securityItems) {
+ flatItems.push(...navigationItems.securityItems);
+ }
+
if (navigationItems.settingsItems) {
const settingsTopLevel = navigationItems.settingsItems.filter((item) => !item.items);
flatItems.push(...settingsTopLevel);
diff --git a/frontend/src/lib/icons/index.ts b/frontend/src/lib/icons/index.ts
index bfbd343db..30f7ec4a0 100644
--- a/frontend/src/lib/icons/index.ts
+++ b/frontend/src/lib/icons/index.ts
@@ -109,3 +109,8 @@ export { default as JobsIcon } from 'virtual:icons/solar/alarm-linear';
export { default as UploadIcon } from 'virtual:icons/solar/upload-minimalistic-linear';
export { default as RedeployIcon } from 'virtual:icons/solar/refresh-circle-linear';
export { default as EdgeConnectionIcon } from 'virtual:icons/solar/cloud-upload-linear';
+export { default as ShieldCheckIcon } from 'virtual:icons/solar/shield-check-linear';
+export { default as ShieldAlertIcon } from 'virtual:icons/solar/shield-warning-linear';
+export { default as ShieldXIcon } from 'virtual:icons/solar/shield-cross-linear';
+export { default as ScanIcon } from 'virtual:icons/solar/magnifer-linear';
+export { default as AlertTriangleIcon } from 'virtual:icons/solar/danger-triangle-linear';
diff --git a/frontend/src/lib/services/vulnerability-service.ts b/frontend/src/lib/services/vulnerability-service.ts
new file mode 100644
index 000000000..c8573d5d5
--- /dev/null
+++ b/frontend/src/lib/services/vulnerability-service.ts
@@ -0,0 +1,104 @@
+import BaseAPIService from './api-service';
+import { environmentStore } from '$lib/stores/environment.store.svelte';
+import type {
+ VulnerabilityScanResult,
+ VulnerabilityScanSummary,
+ ScannerStatus,
+ Vulnerability,
+ VulnerabilityWithImage,
+ EnvironmentVulnerabilitySummary,
+ IgnoredVulnerability,
+ IgnoreVulnerabilityPayload
+} from '$lib/types/vulnerability.type';
+import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import { transformPaginationParams } from '$lib/utils/params.util';
+
+export class VulnerabilityService extends BaseAPIService {
+ /**
+ * Scan an image for vulnerabilities
+ */
+ async scanImage(imageId: string): Promise<VulnerabilityScanResult> {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/images/${imageId}/vulnerabilities/scan`));
+ }
+
+ /**
+ * Get the full vulnerability scan result for an image
+ */
+ async getScanResult(imageId: string): Promise<VulnerabilityScanResult> {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/images/${imageId}/vulnerabilities`));
+ }
+
+ /**
+ * Get a paginated list of vulnerabilities for an image
+ */
+ async getImageVulnerabilities(imageId: string, options?: SearchPaginationSortRequest): Promise<Paginated<Vulnerability>> {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ const params = transformPaginationParams(options);
+ const res = await this.api.get(`/environments/${envId}/images/${imageId}/vulnerabilities/list`, { params });
+ return res.data;
+ }
+
+ /**
+ * Get just the vulnerability summary for an image (for list views)
+ */
+ async getScanSummary(imageId: string): Promise<VulnerabilityScanSummary> {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/images/${imageId}/vulnerabilities/summary`));
+ }
+
+ /**
+ * Get the scanner status (whether Trivy is available)
+ */
+ async getScannerStatus(): Promise<ScannerStatus> {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/vulnerabilities/scanner-status`));
+ }
+
+ /**
+ * Get aggregated vulnerability summary for the current environment
+ */
+ async getEnvironmentSummary(): Promise<EnvironmentVulnerabilitySummary> {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.get(`/environments/${envId}/vulnerabilities/summary`));
+ }
+
+ /**
+ * Get a paginated list of vulnerabilities across all images
+ */
+ async getAllVulnerabilities(options?: SearchPaginationSortRequest): Promise<Paginated<VulnerabilityWithImage>> {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ const params = transformPaginationParams(options);
+ const res = await this.api.get(`/environments/${envId}/vulnerabilities/all`, { params });
+ return res.data;
+ }
+
+ /**
+ * Ignore a vulnerability
+ */
+ async ignoreVulnerability(payload: IgnoreVulnerabilityPayload): Promise<IgnoredVulnerability> {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ return this.handleResponse(this.api.post(`/environments/${envId}/vulnerabilities/ignore`, payload));
+ }
+
+ /**
+ * Unignore a vulnerability
+ */
+ async unignoreVulnerability(ignoreId: string): Promise<void> {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ await this.handleResponse(this.api.delete(`/environments/${envId}/vulnerabilities/ignore/${ignoreId}`));
+ }
+
+ /**
+ * Get a list of ignored vulnerabilities
+ */
+ async getIgnoredVulnerabilities(options?: SearchPaginationSortRequest): Promise<Paginated<IgnoredVulnerability>> {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ const params = transformPaginationParams(options);
+ const res = await this.api.get(`/environments/${envId}/vulnerabilities/ignored`, { params });
+ return res.data;
+ }
+}
+
+export const vulnerabilityService = new VulnerabilityService();
diff --git a/frontend/src/lib/types/image.type.ts b/frontend/src/lib/types/image.type.ts
index cc7d4d66e..2ac8f93aa 100644
--- a/frontend/src/lib/types/image.type.ts
+++ b/frontend/src/lib/types/image.type.ts
@@ -1,3 +1,5 @@
+import type { VulnerabilityScanSummary } from './vulnerability.type';
+
export interface ImageUpdateInfoDto {
hasUpdate: boolean;
updateType: string;
@@ -33,6 +35,7 @@ export interface ImageSummaryDto {
repo: string;
tag: string;
updateInfo?: ImageUpdateInfoDto;
+ vulnerabilityScan?: VulnerabilityScanSummary;
}
export interface ImageDetailSummaryDto {
diff --git a/frontend/src/lib/types/job-schedule.type.ts b/frontend/src/lib/types/job-schedule.type.ts
index 02b9697d5..42c713078 100644
--- a/frontend/src/lib/types/job-schedule.type.ts
+++ b/frontend/src/lib/types/job-schedule.type.ts
@@ -6,6 +6,7 @@ export type JobSchedules = {
pollingInterval: string;
scheduledPruneInterval: string;
gitopsSyncInterval: string;
+ vulnerabilityScanInterval: string;
};
export type JobSchedulesUpdate = Partial<JobSchedules>;
diff --git a/frontend/src/lib/types/notification-providers.ts b/frontend/src/lib/types/notification-providers.ts
index 892f94052..cd7bd5b47 100644
--- a/frontend/src/lib/types/notification-providers.ts
+++ b/frontend/src/lib/types/notification-providers.ts
@@ -19,6 +19,7 @@ export interface BaseProviderFormValues {
enabled: boolean;
eventImageUpdate: boolean;
eventContainerUpdate: boolean;
+ eventVulnerabilityFound: boolean;
}
// Provider-specific form value types
@@ -161,7 +162,8 @@ export function discordSettingsToFormValues(settings?: NotificationSettings): Di
username: (cfg?.username as string) || 'Arcane',
avatarUrl: (cfg?.avatarUrl as string) || '',
eventImageUpdate: events?.image_update ?? true,
- eventContainerUpdate: events?.container_update ?? true
+ eventContainerUpdate: events?.container_update ?? true,
+ eventVulnerabilityFound: events?.vulnerability_found ?? true
};
}
@@ -178,7 +180,8 @@ export function emailSettingsToFormValues(settings?: NotificationSettings): Emai
toAddresses: Array.isArray(cfg?.toAddresses) ? (cfg.toAddresses as string[]).join(', ') : '',
tlsMode: ((cfg?.tlsMode as string) || 'starttls') as EmailTLSMode,
eventImageUpdate: events?.image_update ?? true,
- eventContainerUpdate: events?.container_update ?? true
+ eventContainerUpdate: events?.container_update ?? true,
+ eventVulnerabilityFound: events?.vulnerability_found ?? true
};
}
@@ -193,7 +196,8 @@ export function telegramSettingsToFormValues(settings?: NotificationSettings): T
notification: (cfg?.notification as boolean) ?? true,
title: (cfg?.title as string) || '',
eventImageUpdate: events?.image_update ?? true,
- eventContainerUpdate: events?.container_update ?? true
+ eventContainerUpdate: events?.container_update ?? true,
+ eventVulnerabilityFound: events?.vulnerability_found ?? true
};
}
@@ -211,7 +215,8 @@ export function signalSettingsToFormValues(settings?: NotificationSettings): Sig
recipients: Array.isArray(cfg?.recipients) ? (cfg.recipients as string[]).join(', ') : '',
disableTls: (cfg?.disableTls as boolean) ?? false,
eventImageUpdate: events?.image_update ?? true,
- eventContainerUpdate: events?.container_update ?? true
+ eventContainerUpdate: events?.container_update ?? true,
+ eventVulnerabilityFound: events?.vulnerability_found ?? true
};
}
@@ -228,7 +233,8 @@ export function slackSettingsToFormValues(settings?: NotificationSettings): Slac
channel: (cfg?.channel as string) || '',
threadTs: (cfg?.threadTs as string) || '',
eventImageUpdate: events?.image_update ?? true,
- eventContainerUpdate: events?.container_update ?? true
+ eventContainerUpdate: events?.container_update ?? true,
+ eventVulnerabilityFound: events?.vulnerability_found ?? true
};
}
@@ -253,7 +259,8 @@ export function discordFormValuesToSettings(values: DiscordFormValues): Notifica
avatarUrl: values.avatarUrl,
events: {
image_update: values.eventImageUpdate,
- container_update: values.eventContainerUpdate
+ container_update: values.eventContainerUpdate,
+ vulnerability_found: values.eventVulnerabilityFound
}
}
};
@@ -276,7 +283,8 @@ export function emailFormValuesToSettings(values: EmailFormValues): Notification
tlsMode: values.tlsMode,
events: {
image_update: values.eventImageUpdate,
- container_update: values.eventContainerUpdate
+ container_update: values.eventContainerUpdate,
+ vulnerability_found: values.eventVulnerabilityFound
}
}
};
@@ -297,7 +305,8 @@ export function telegramFormValuesToSettings(values: TelegramFormValues): Notifi
title: values.title,
events: {
image_update: values.eventImageUpdate,
- container_update: values.eventContainerUpdate
+ container_update: values.eventContainerUpdate,
+ vulnerability_found: values.eventVulnerabilityFound
}
}
};
@@ -321,7 +330,8 @@ export function signalFormValuesToSettings(values: SignalFormValues): Notificati
disableTls: values.disableTls,
events: {
image_update: values.eventImageUpdate,
- container_update: values.eventContainerUpdate
+ container_update: values.eventContainerUpdate,
+ vulnerability_found: values.eventVulnerabilityFound
}
}
};
@@ -341,7 +351,8 @@ export function slackFormValuesToSettings(values: SlackFormValues): Notification
threadTs: values.threadTs,
events: {
image_update: values.eventImageUpdate,
- container_update: values.eventContainerUpdate
+ container_update: values.eventContainerUpdate,
+ vulnerability_found: values.eventVulnerabilityFound
}
}
};
@@ -364,7 +375,8 @@ export function ntfySettingsToFormValues(settings?: NotificationSettings): NtfyF
firebase: (cfg?.firebase as boolean) ?? true,
disableTlsVerification: (cfg?.disableTlsVerification as boolean) ?? false,
eventImageUpdate: events?.image_update ?? true,
- eventContainerUpdate: events?.container_update ?? true
+ eventContainerUpdate: events?.container_update ?? true,
+ eventVulnerabilityFound: events?.vulnerability_found ?? true
};
}
@@ -379,7 +391,8 @@ export function pushoverSettingsToFormValues(settings?: NotificationSettings): P
priority: Number(cfg?.priority ?? 0),
title: (cfg?.title as string) || '',
eventImageUpdate: events?.image_update ?? true,
- eventContainerUpdate: events?.container_update ?? true
+ eventContainerUpdate: events?.container_update ?? true,
+ eventVulnerabilityFound: events?.vulnerability_found ?? true
};
}
@@ -396,7 +409,8 @@ export function gotifySettingsToFormValues(settings?: NotificationSettings): Got
title: (cfg?.title as string) || '',
disableTls: (cfg?.disableTls as boolean) ?? false,
eventImageUpdate: events?.image_update ?? true,
- eventContainerUpdate: events?.container_update ?? true
+ eventContainerUpdate: events?.container_update ?? true,
+ eventVulnerabilityFound: events?.vulnerability_found ?? true
};
}
@@ -419,7 +433,8 @@ export function genericSettingsToFormValues(settings?: NotificationSettings): Ge
messageKey: (cfg?.messageKey as string) || 'message',
customHeaders: customHeadersStr,
eventImageUpdate: events?.image_update ?? true,
- eventContainerUpdate: events?.container_update ?? true
+ eventContainerUpdate: events?.container_update ?? true,
+ eventVulnerabilityFound: events?.vulnerability_found ?? true
};
}
@@ -444,7 +459,8 @@ export function ntfyFormValuesToSettings(values: NtfyFormValues): NotificationSe
disableTlsVerification: values.disableTlsVerification,
events: {
image_update: values.eventImageUpdate,
- container_update: values.eventContainerUpdate
+ container_update: values.eventContainerUpdate,
+ vulnerability_found: values.eventVulnerabilityFound
}
}
};
@@ -465,7 +481,8 @@ export function pushoverFormValuesToSettings(values: PushoverFormValues): Notifi
title: values.title,
events: {
image_update: values.eventImageUpdate,
- container_update: values.eventContainerUpdate
+ container_update: values.eventContainerUpdate,
+ vulnerability_found: values.eventVulnerabilityFound
}
}
};
@@ -485,7 +502,8 @@ export function gotifyFormValuesToSettings(values: GotifyFormValues): Notificati
disableTls: values.disableTls,
events: {
image_update: values.eventImageUpdate,
- container_update: values.eventContainerUpdate
+ container_update: values.eventContainerUpdate,
+ vulnerability_found: values.eventVulnerabilityFound
}
}
};
@@ -519,7 +537,8 @@ export function genericFormValuesToSettings(values: GenericFormValues): Notifica
customHeaders: customHeaders,
events: {
image_update: values.eventImageUpdate,
- container_update: values.eventContainerUpdate
+ container_update: values.eventContainerUpdate,
+ vulnerability_found: values.eventVulnerabilityFound
}
}
};
diff --git a/frontend/src/lib/types/settings.type.ts b/frontend/src/lib/types/settings.type.ts
index 7499cb1c1..a56b78367 100644
--- a/frontend/src/lib/types/settings.type.ts
+++ b/frontend/src/lib/types/settings.type.ts
@@ -16,6 +16,8 @@ export type Settings = {
scheduledPruneVolumes?: boolean;
scheduledPruneNetworks?: boolean;
scheduledPruneBuildCache?: boolean;
+ vulnerabilityScanEnabled?: boolean;
+ vulnerabilityScanInterval?: number;
maxImageUploadSize: number;
baseServerUrl: string;
enableGravatar: boolean;
@@ -29,6 +31,7 @@ export type Settings = {
authLocalEnabled: boolean;
authSessionTimeout: number;
authPasswordPolicy: 'basic' | 'standard' | 'strong';
+ trivyImage: string;
oidcEnabled: boolean;
oidcClientId: string;
oidcClientSecret?: string;
diff --git a/frontend/src/lib/types/vulnerability.type.ts b/frontend/src/lib/types/vulnerability.type.ts
new file mode 100644
index 000000000..7ec9b6894
--- /dev/null
+++ b/frontend/src/lib/types/vulnerability.type.ts
@@ -0,0 +1,89 @@
+// Vulnerability types for frontend
+export type VulnerabilitySeverity = 'UNKNOWN' | 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
+export type VulnerabilityScanStatus = 'pending' | 'scanning' | 'completed' | 'failed';
+
+export interface CVSSInfo {
+ v2Score?: number;
+ v3Score?: number;
+ v2Vector?: string;
+ v3Vector?: string;
+}
+
+export interface Vulnerability {
+ vulnerabilityId: string;
+ pkgName: string;
+ installedVersion: string;
+ fixedVersion?: string;
+ severity: VulnerabilitySeverity;
+ title?: string;
+ description?: string;
+ references?: string[];
+ cvss?: CVSSInfo;
+ publishedDate?: string;
+ lastModifiedDate?: string;
+}
+
+export interface VulnerabilityWithImage extends Vulnerability {
+ imageId: string;
+ imageName: string;
+}
+
+export interface SeveritySummary {
+ critical: number;
+ high: number;
+ medium: number;
+ low: number;
+ unknown: number;
+ total: number;
+}
+
+export interface EnvironmentVulnerabilitySummary {
+ totalImages: number;
+ scannedImages: number;
+ summary?: SeveritySummary;
+}
+
+export interface VulnerabilityScanResult {
+ imageId: string;
+ imageName: string;
+ scanTime: string;
+ status: VulnerabilityScanStatus;
+ summary?: SeveritySummary;
+ vulnerabilities?: Vulnerability[];
+ error?: string;
+ duration?: number;
+ scannerVersion?: string;
+}
+
+export interface VulnerabilityScanSummary {
+ imageId: string;
+ scanTime: string;
+ status: VulnerabilityScanStatus;
+ summary?: SeveritySummary;
+ error?: string;
+}
+
+export interface ScannerStatus {
+ available: boolean;
+ version?: string;
+}
+
+export interface IgnoreVulnerabilityPayload {
+ imageId: string;
+ vulnerabilityId: string;
+ pkgName: string;
+ installedVersion: string;
+ reason?: string;
+}
+
+export interface IgnoredVulnerability {
+ id: string;
+ environmentId: string;
+ imageId: string;
+ vulnerabilityId: string;
+ pkgName: string;
+ installedVersion: string;
+ reason?: string;
+ createdBy: string;
+ createdAt: string;
+}
diff --git a/frontend/src/lib/utils/vulnerability-scan.util.ts b/frontend/src/lib/utils/vulnerability-scan.util.ts
new file mode 100644
index 000000000..26042cb04
--- /dev/null
+++ b/frontend/src/lib/utils/vulnerability-scan.util.ts
@@ -0,0 +1,95 @@
+import type { VulnerabilityScanSummary } from '$lib/types/vulnerability.type';
+
+export type VulnerabilityScanPollOptions = {
+ intervalMs?: number;
+ maxAttempts?: number;
+ onUpdate?: (summary: VulnerabilityScanSummary) => void;
+ onComplete?: (summary: VulnerabilityScanSummary) => void;
+ onError?: (error: unknown) => void;
+};
+
+export type VulnerabilityScanTracker = {
+ cancel: () => void;
+ promise: Promise<VulnerabilityScanSummary>;
+};
+
+export function startVulnerabilityScanPolling(
+ imageId: string,
+ fetchSummary: (imageId: string) => Promise<VulnerabilityScanSummary>,
+ options: VulnerabilityScanPollOptions = {}
+): () => void {
+ const { intervalMs = 2000, maxAttempts = 0, onUpdate, onComplete, onError } = options;
+ let attempts = 0;
+ let cancelled = false;
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
+
+ const schedule = () => {
+ if (cancelled) return;
+ timeoutId = setTimeout(run, intervalMs);
+ };
+
+ const run = async () => {
+ if (cancelled) return;
+ attempts += 1;
+ try {
+ const summary = await fetchSummary(imageId);
+ onUpdate?.(summary);
+
+ const isScanning = summary?.status === 'scanning' || summary?.status === 'pending';
+ if (!isScanning) {
+ onComplete?.(summary);
+ return;
+ }
+ } catch (error) {
+ onError?.(error);
+ }
+
+ if (maxAttempts > 0 && attempts >= maxAttempts) {
+ onError?.(new Error('Scan polling exceeded max attempts.'));
+ return;
+ }
+
+ schedule();
+ };
+
+ void run();
+
+ return () => {
+ cancelled = true;
+ if (timeoutId) {
+ clearTimeout(timeoutId);
+ }
+ };
+}
+
+export function startVulnerabilityScanTracking(
+ imageId: string,
+ fetchSummary: (imageId: string) => Promise<VulnerabilityScanSummary>,
+ options: VulnerabilityScanPollOptions = {}
+): VulnerabilityScanTracker {
+ let resolvePromise: (summary: VulnerabilityScanSummary) => void;
+ let rejectPromise: (error: unknown) => void;
+
+ const promise = new Promise<VulnerabilityScanSummary>((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+
+ const cancel = startVulnerabilityScanPolling(imageId, fetchSummary, {
+ ...options,
+ onComplete: (summary) => {
+ options.onComplete?.(summary);
+ if (summary.status === 'completed') {
+ resolvePromise(summary);
+ } else {
+ rejectPromise(summary);
+ }
+ },
+ onError: (error) => {
+ options.onError?.(error);
+ rejectPromise(error);
+ }
+ });
+
+ return { cancel, promise };
+}
diff --git a/frontend/src/routes/(app)/environments/[id]/+page.svelte b/frontend/src/routes/(app)/environments/[id]/+page.svelte
index aedddecf8..0991172b7 100644
--- a/frontend/src/routes/(app)/environments/[id]/+page.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/+page.svelte
@@ -147,7 +147,8 @@
scheduledPruneImages: z.boolean(),
scheduledPruneVolumes: z.boolean(),
scheduledPruneNetworks: z.boolean(),
- scheduledPruneBuildCache: z.boolean()
+ scheduledPruneBuildCache: z.boolean(),
+ vulnerabilityScanEnabled: z.boolean()
});
// Build current settings object from environment and settings data
@@ -169,7 +170,8 @@
scheduledPruneImages: settings?.scheduledPruneImages ?? true,
scheduledPruneVolumes: settings?.scheduledPruneVolumes ?? false,
scheduledPruneNetworks: settings?.scheduledPruneNetworks ?? true,
- scheduledPruneBuildCache: settings?.scheduledPruneBuildCache ?? false
+ scheduledPruneBuildCache: settings?.scheduledPruneBuildCache ?? false,
+ vulnerabilityScanEnabled: settings?.vulnerabilityScanEnabled ?? false
});
// Custom save handler for environment-specific settings
@@ -198,7 +200,8 @@
scheduledPruneImages: formData.scheduledPruneImages,
scheduledPruneVolumes: formData.scheduledPruneVolumes,
scheduledPruneNetworks: formData.scheduledPruneNetworks,
- scheduledPruneBuildCache: formData.scheduledPruneBuildCache
+ scheduledPruneBuildCache: formData.scheduledPruneBuildCache,
+ vulnerabilityScanEnabled: formData.vulnerabilityScanEnabled
});
}
diff --git a/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte b/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte
index 03c25b6cf..44376a04c 100644
--- a/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/components/JobsTab.svelte
@@ -30,6 +30,8 @@
return `${envBase}?tab=gitops`;
case 'scheduledPruneEnabled':
return undefined;
+ case 'vulnerabilityScanEnabled':
+ return undefined;
default:
return prereq.settingsUrl;
}
@@ -72,6 +74,7 @@
const categories = [
{ id: 'monitoring', label: m.jobs_monitoring_heading() },
{ id: 'maintenance', label: m.jobs_maintenance_heading() },
+ { id: 'security', label: m.jobs_security_heading() },
{ id: 'updates', label: m.jobs_updates_heading() },
{ id: 'sync', label: m.jobs_sync_heading() },
{ id: 'telemetry', label: m.jobs_telemetry_heading() }
@@ -98,6 +101,8 @@
return $formInputs.autoUpdate.value;
case 'image-polling':
return $formInputs.pollingEnabled.value;
+ case 'vulnerability-scan':
+ return $formInputs.vulnerabilityScanEnabled.value;
default:
return undefined;
}
@@ -148,6 +153,8 @@
<Switch bind:checked={$formInputs.autoUpdate.value} disabled={!$formInputs.pollingEnabled.value} />
{:else if job.id === 'scheduled-prune'}
<Switch bind:checked={$formInputs.scheduledPruneEnabled.value} />
+ {:else if job.id === 'vulnerability-scan'}
+ <Switch bind:checked={$formInputs.vulnerabilityScanEnabled.value} />
{/if}
{/snippet}
diff --git a/frontend/src/routes/(app)/images/[imageId]/+page.svelte b/frontend/src/routes/(app)/images/[imageId]/+page.svelte
index 89acc5c2d..aceecc562 100644
--- a/frontend/src/routes/(app)/images/[imageId]/+page.svelte
+++ b/frontend/src/routes/(app)/images/[imageId]/+page.svelte
@@ -8,11 +8,15 @@
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import { toast } from 'svelte-sonner';
+ import { onDestroy } from 'svelte';
import { ArcaneButton } from '$lib/components/arcane-button';
import { m } from '$lib/paraglide/messages';
import { imageService } from '$lib/services/image-service.js';
+ import { vulnerabilityService } from '$lib/services/vulnerability-service.js';
+ import { startVulnerabilityScanPolling } from '$lib/utils/vulnerability-scan.util';
import { ResourceDetailLayout, type DetailAction } from '$lib/layouts';
- import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import VulnerabilityScanPanel from '$lib/components/vulnerability/vulnerability-scan-panel.svelte';
+ import type { VulnerabilityScanResult } from '$lib/types/vulnerability.type';
import { VolumesIcon, ClockIcon, TagIcon, LayersIcon, CpuIcon, InfoIcon, SettingsIcon, HashIcon } from '$lib/icons';
let { data } = $props();
@@ -21,12 +25,111 @@
let isLoading = $state({
pulling: false,
removing: false,
- refreshing: false
+ refreshing: false,
+ scanning: false
});
- const shortId = $derived(() => image?.id?.split(':')[1]?.substring(0, 12) || m.common_na());
+ let vulnerabilityScan = $state<VulnerabilityScanResult | null>(null);
+ let hasLoadedVulnerabilities = $state(false);
+ let stopScanPolling: (() => void) | null = $state(null);
- const createdDate = $derived(() => {
+ // Load vulnerability scan data when image changes
+ $effect(() => {
+ if (image?.id && !hasLoadedVulnerabilities) {
+ loadVulnerabilityScan();
+ }
+ });
+
+ async function loadVulnerabilityScan() {
+ if (!image?.id) return;
+ try {
+ const result = await vulnerabilityService.getScanResult(image.id);
+ vulnerabilityScan = result;
+ } catch {
+ // No scan data found, that's okay
+ vulnerabilityScan = null;
+ }
+ hasLoadedVulnerabilities = true;
+ }
+
+ async function handleScanImage() {
+ if (!image?.id || isLoading.scanning) return;
+ isLoading.scanning = true;
+ try {
+ const result = await vulnerabilityService.scanImage(image.id);
+ vulnerabilityScan = result;
+ if (result.status === 'completed') {
+ toast.success(m.vuln_scan_completed());
+ } else if (result.status === 'failed') {
+ toast.error(result.error || m.vuln_scan_failed());
+ } else {
+ beginScanPolling(true);
+ }
+ } catch (error) {
+ console.error('Failed to scan image:', error);
+ toast.error(m.vuln_scan_failed());
+ } finally {
+ isLoading.scanning = false;
+ }
+ }
+
+ function stopPolling() {
+ if (stopScanPolling) {
+ stopScanPolling();
+ stopScanPolling = null;
+ }
+ }
+
+ function beginScanPolling(showToast: boolean) {
+ if (!image?.id || stopScanPolling) return;
+ const cancel = startVulnerabilityScanPolling(image.id, (id) => vulnerabilityService.getScanSummary(id), {
+ onUpdate: (summary) => {
+ vulnerabilityScan = {
+ ...(vulnerabilityScan ?? {}),
+ imageId: summary.imageId,
+ scanTime: summary.scanTime,
+ status: summary.status,
+ summary: summary.summary,
+ error: summary.error
+ } as VulnerabilityScanResult;
+ },
+ onComplete: async (summary) => {
+ stopPolling();
+ try {
+ vulnerabilityScan = await vulnerabilityService.getScanResult(summary.imageId);
+ } catch (error) {
+ console.error('Failed to load scan result:', error);
+ }
+ if (showToast) {
+ if (summary.status === 'completed') {
+ toast.success(m.vuln_scan_completed());
+ } else {
+ toast.error(summary.error || m.vuln_scan_failed());
+ }
+ }
+ },
+ onError: () => {}
+ });
+
+ stopScanPolling = cancel;
+ }
+
+ $effect(() => {
+ const scanning = vulnerabilityScan?.status === 'scanning' || vulnerabilityScan?.status === 'pending';
+ if (scanning) {
+ beginScanPolling(false);
+ } else {
+ stopPolling();
+ }
+ });
+
+ onDestroy(() => {
+ stopPolling();
+ });
+
+ const shortId = $derived.by(() => image?.id?.split(':')[1]?.substring(0, 12) || m.common_na());
+
+ const createdDate = $derived.by(() => {
if (!image?.created) return m.common_na();
try {
const date = new Date(image.created);
@@ -37,9 +140,13 @@
}
});
- const imageSize = $derived(() => bytes.format(image?.size || 0) || '0 B');
- const architecture = $derived(() => image?.architecture || m.common_na());
- const osName = $derived(() => image?.os || m.common_na());
+ const imageSize = $derived.by(() => bytes.format(image?.size || 0) || '0 B');
+ const architecture = $derived.by(() => image?.architecture || m.common_na());
+ const osName = $derived.by(() => image?.os || m.common_na());
+ const repoTags = $derived.by(() => image?.repoTags ?? []);
+ const envVars = $derived.by(() => image?.config?.env ?? []);
+ const hasTags = $derived.by(() => repoTags.length > 0);
+ const hasEnv = $derived.by(() => envVars.length > 0);
async function handleImageRemove(id: string) {
openConfirmDialog({
@@ -64,6 +171,14 @@
}
const actions: DetailAction[] = $derived([
+ {
+ id: 'scan',
+ action: 'base',
+ label: m.vuln_scan(),
+ loading: isLoading.scanning,
+ disabled: isLoading.scanning,
+ onclick: handleScanImage
+ },
{
id: 'remove',
action: 'remove',
@@ -78,22 +193,28 @@
<ResourceDetailLayout
backUrl="/images"
backLabel={m.images_title()}
- title={image?.repoTags?.[0] || shortId()}
- subtitle={shortId()}
+ title={image?.repoTags?.[0] || shortId}
+ subtitle={shortId}
{actions}
>
- {#snippet badges()}
- {#if image?.architecture}
- <StatusBadge variant="blue" text={image.architecture} />
- {/if}
- {#if image?.os}
- <StatusBadge variant="purple" text={image.os} />
- {/if}
- <StatusBadge variant="gray" text={imageSize()} />
- {/snippet}
-
{#if image}
<div class="space-y-6">
+ {#if hasTags}
+ <div class="border-border/60 bg-muted/30 rounded-xl border px-4 py-3">
+ <div class="flex flex-wrap items-center gap-2">
+ <span class="text-muted-foreground inline-flex items-center gap-2 text-xs font-semibold tracking-wide uppercase">
+ <TagIcon class="size-4" />
+ {m.common_tags()}
+ </span>
+ {#each repoTags as tag (tag)}
+ <Badge variant="secondary" class="cursor-pointer text-xs select-all" title="Click to select">
+ {tag}
+ </Badge>
+ {/each}
+ </div>
+ </div>
+ {/if}
+
<Card.Root>
<Card.Header icon={InfoIcon}>
<div class="flex flex-col space-y-1.5">
@@ -101,180 +222,138 @@
<Card.Description>{m.common_details_description({ resource: m.resource_image() })}</Card.Description>
</div>
</Card.Header>
- <Card.Content class="p-4">
- <div class="grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-6">
- <div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-gray-500/10 p-2">
- <HashIcon class="size-5 text-gray-500" />
- </div>
- <div class="min-w-0 flex-1">
- <p class="text-muted-foreground text-sm font-medium">{m.common_id()}</p>
- <p
- class="mt-1 cursor-pointer font-mono text-xs font-semibold break-all select-all sm:text-sm"
- title="Click to select"
- >
- {image?.id || m.common_na()}
- </p>
+ <Card.Content class="p-5">
+ <div class="grid gap-3 sm:grid-cols-2">
+ <div class="border-border/60 bg-muted/30 rounded-2xl border p-4 sm:col-span-2">
+ <div class="text-muted-foreground flex items-center gap-2 text-xs font-semibold tracking-wide uppercase">
+ <HashIcon class="text-muted-foreground size-4" />
+ {m.common_id()}
</div>
+ <p
+ class="mt-2 cursor-pointer font-mono text-xs font-semibold break-all select-all sm:text-sm"
+ title="Click to select"
+ >
+ {image?.id || m.common_na()}
+ </p>
</div>
- <div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-blue-500/10 p-2">
- <VolumesIcon class="size-5 text-blue-500" />
- </div>
- <div class="min-w-0 flex-1">
- <p class="text-muted-foreground text-sm font-medium">{m.common_size()}</p>
- <p class="mt-1 cursor-pointer text-sm font-semibold select-all sm:text-base" title="Click to select">
- {imageSize()}
- </p>
+ <div class="border-border/60 bg-muted/30 rounded-xl border p-3">
+ <div class="text-muted-foreground flex items-center gap-2 text-xs font-semibold">
+ <VolumesIcon class="size-4 text-blue-500" />
+ {m.common_size()}
</div>
+ <p class="mt-2 cursor-pointer text-sm font-semibold select-all" title="Click to select">{imageSize}</p>
</div>
- <div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-green-500/10 p-2">
- <ClockIcon class="size-5 text-green-500" />
- </div>
- <div class="min-w-0 flex-1">
- <p class="text-muted-foreground text-sm font-medium">{m.common_created()}</p>
- <p class="mt-1 cursor-pointer text-sm font-semibold select-all sm:text-base" title="Click to select">
- {createdDate()}
- </p>
+ <div class="border-border/60 bg-muted/30 rounded-xl border p-3">
+ <div class="text-muted-foreground flex items-center gap-2 text-xs font-semibold">
+ <ClockIcon class="size-4 text-green-500" />
+ {m.common_created()}
</div>
+ <p class="mt-2 cursor-pointer text-sm font-semibold select-all" title="Click to select">{createdDate}</p>
</div>
- <div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-orange-500/10 p-2">
- <CpuIcon class="size-5 text-orange-500" />
- </div>
- <div class="min-w-0 flex-1">
- <p class="text-muted-foreground text-sm font-medium">{m.common_architecture()}</p>
- <p class="mt-1 cursor-pointer text-sm font-semibold select-all sm:text-base" title="Click to select">
- {architecture()}
- </p>
+ <div class="border-border/60 bg-muted/30 rounded-xl border p-3">
+ <div class="text-muted-foreground flex items-center gap-2 text-xs font-semibold">
+ <CpuIcon class="size-4 text-orange-500" />
+ {m.common_architecture()}
</div>
+ <p class="mt-2 cursor-pointer text-sm font-semibold select-all" title="Click to select">{architecture}</p>
</div>
- <div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-indigo-500/10 p-2">
- <LayersIcon class="size-5 text-indigo-500" />
- </div>
- <div class="min-w-0 flex-1">
- <p class="text-muted-foreground text-sm font-medium">{m.images_os()}</p>
- <p class="mt-1 cursor-pointer text-sm font-semibold select-all sm:text-base" title="Click to select">
- {osName()}
- </p>
+ <div class="border-border/60 bg-muted/30 rounded-xl border p-3">
+ <div class="text-muted-foreground flex items-center gap-2 text-xs font-semibold">
+ <LayersIcon class="size-4 text-indigo-500" />
+ {m.images_os()}
</div>
+ <p class="mt-2 cursor-pointer text-sm font-semibold select-all" title="Click to select">{osName}</p>
</div>
{#if image?.dockerVersion}
- <div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-purple-500/10 p-2">
- <InfoIcon class="size-5 text-purple-500" />
- </div>
- <div class="min-w-0 flex-1">
- <p class="text-muted-foreground text-sm font-medium">{m.common_docker_version()}</p>
- <p class="mt-1 cursor-pointer text-sm font-semibold select-all sm:text-base" title="Click to select">
- {image.dockerVersion}
- </p>
+ <div class="border-border/60 bg-muted/30 rounded-xl border p-3">
+ <div class="text-muted-foreground flex items-center gap-2 text-xs font-semibold">
+ <InfoIcon class="size-4 text-purple-500" />
+ {m.common_docker_version()}
</div>
+ <p class="mt-2 cursor-pointer text-sm font-semibold select-all" title="Click to select">
+ {image.dockerVersion}
+ </p>
</div>
{/if}
{#if image?.author}
- <div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-pink-500/10 p-2">
- <InfoIcon class="size-5 text-pink-500" />
- </div>
- <div class="min-w-0 flex-1">
- <p class="text-muted-foreground text-sm font-medium">{m.common_author()}</p>
- <p class="mt-1 cursor-pointer text-sm font-semibold break-all select-all sm:text-base" title="Click to select">
- {image.author}
- </p>
+ <div class="border-border/60 bg-muted/30 rounded-xl border p-3">
+ <div class="text-muted-foreground flex items-center gap-2 text-xs font-semibold">
+ <InfoIcon class="size-4 text-pink-500" />
+ {m.common_author()}
</div>
+ <p class="mt-2 cursor-pointer text-sm font-semibold break-all select-all" title="Click to select">
+ {image.author}
+ </p>
</div>
{/if}
{#if image.config?.workingDir}
- <div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-amber-500/10 p-2">
- <InfoIcon class="size-5 text-amber-500" />
- </div>
- <div class="min-w-0 flex-1">
- <p class="text-muted-foreground text-sm font-medium">{m.common_working_dir()}</p>
- <p
- class="mt-1 cursor-pointer font-mono text-xs font-semibold break-all select-all sm:text-sm"
- title="Click to select"
- >
- {image.config.workingDir}
- </p>
+ <div class="border-border/60 bg-muted/30 rounded-xl border p-3 sm:col-span-2">
+ <div class="text-muted-foreground flex items-center gap-2 text-xs font-semibold">
+ <InfoIcon class="size-4 text-amber-500" />
+ {m.common_working_dir()}
</div>
+ <p
+ class="mt-2 cursor-pointer font-mono text-xs font-semibold break-all select-all sm:text-sm"
+ title="Click to select"
+ >
+ {image.config.workingDir}
+ </p>
</div>
{/if}
</div>
- </Card.Content>
- </Card.Root>
- {#if image.repoTags && image.repoTags.length > 0}
- <Card.Root>
- <Card.Header icon={TagIcon}>
- <div class="flex flex-col space-y-1.5">
- <Card.Title>{m.common_tags()}</Card.Title>
- <Card.Description>{m.images_tags_description()}</Card.Description>
- </div>
- </Card.Header>
- <Card.Content class="p-4">
- <div class="flex flex-wrap gap-2">
- {#each image.repoTags as tag (tag)}
- <Badge variant="secondary" class="cursor-pointer text-sm select-all" title="Click to select">{tag}</Badge>
- {/each}
- </div>
- </Card.Content>
- </Card.Root>
- {/if}
-
- {#if image.config?.env && image.config.env.length > 0}
- <Card.Root>
- <Card.Header icon={SettingsIcon}>
- <div class="flex flex-col space-y-1.5">
- <Card.Title>{m.common_environment_variables()}</Card.Title>
- <Card.Description>{m.images_env_vars_description()}</Card.Description>
- </div>
- </Card.Header>
- <Card.Content class="p-4">
- <div class="grid grid-cols-1 gap-3 lg:grid-cols-2 2xl:grid-cols-3">
- {#each image.config.env as env (env)}
- {#if env.includes('=')}
- {@const [key, ...valueParts] = env.split('=')}
- {@const value = valueParts.join('=')}
- <Card.Root variant="subtle">
- <Card.Content class="flex flex-col gap-2 p-4">
- <div class="text-muted-foreground text-xs font-semibold tracking-wide break-all uppercase">{key}</div>
+ {#if hasEnv}
+ <div class="border-border/60 bg-muted/30 mt-4 rounded-2xl border p-4">
+ <div class="flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <div class="text-muted-foreground flex items-center gap-2 text-xs font-semibold tracking-wide uppercase">
+ <SettingsIcon class="size-4" />
+ {m.common_environment_variables()}
+ </div>
+ </div>
+ </div>
+ <div class="mt-4 grid grid-cols-1 gap-2 sm:grid-cols-2">
+ {#each envVars as env (env)}
+ {#if env.includes('=')}
+ {@const [key, ...valueParts] = env.split('=')}
+ {@const value = valueParts.join('=')}
+ <div class="border-border/50 bg-muted/20 rounded-lg border px-3 py-2">
+ <div class="text-muted-foreground text-[11px] font-semibold tracking-wide break-all uppercase">
+ {key}
+ </div>
<div
- class="text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all"
+ class="text-foreground mt-1 cursor-pointer font-mono text-xs font-medium break-all select-all"
title="Click to select"
>
{value}
</div>
- </Card.Content>
- </Card.Root>
- {:else}
- <Card.Root variant="subtle">
- <Card.Content class="flex flex-col gap-2 p-4">
- <div class="text-muted-foreground text-xs font-semibold tracking-wide uppercase">ENV_VAR</div>
+ </div>
+ {:else}
+ <div class="border-border/50 bg-muted/20 rounded-lg border px-3 py-2">
+ <div class="text-muted-foreground text-[11px] font-semibold tracking-wide uppercase">ENV_VAR</div>
<div
- class="text-foreground cursor-pointer font-mono text-sm font-medium break-all select-all"
+ class="text-foreground mt-1 cursor-pointer font-mono text-xs font-medium break-all select-all"
title="Click to select"
>
{env}
</div>
- </Card.Content>
- </Card.Root>
- {/if}
- {/each}
+ </div>
+ {/if}
+ {/each}
+ </div>
</div>
- </Card.Content>
- </Card.Root>
- {/if}
+ {/if}
+ </Card.Content>
+ </Card.Root>
+
+ <VulnerabilityScanPanel scan={vulnerabilityScan} isScanning={isLoading.scanning} onScan={handleScanImage} />
</div>
{:else}
<div class="py-12 text-center">
diff --git a/frontend/src/routes/(app)/images/image-table.svelte b/frontend/src/routes/(app)/images/image-table.svelte
index f0eb7c5de..3e1efe726 100644
--- a/frontend/src/routes/(app)/images/image-table.svelte
+++ b/frontend/src/routes/(app)/images/image-table.svelte
@@ -4,6 +4,7 @@
import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
import { Spinner } from '$lib/components/ui/spinner/index.js';
import { goto } from '$app/navigation';
+ import { onDestroy } from 'svelte';
import { toast } from 'svelte-sonner';
import bytes from 'bytes';
import { openConfirmDialog } from '$lib/components/confirm-dialog';
@@ -12,14 +13,18 @@
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import ImageUpdateItem from '$lib/components/image-update-item.svelte';
+ import VulnerabilityScanItem from '$lib/components/vulnerability/vulnerability-scan-item.svelte';
import UniversalMobileCard from '$lib/components/arcane-table/cards/universal-mobile-card.svelte';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
import type { ImageSummaryDto, ImageUpdateInfoDto } from '$lib/types/image.type';
+ import type { VulnerabilityScanSummary } from '$lib/types/vulnerability.type';
import { format } from 'date-fns';
import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '$lib/components/arcane-table';
import { m } from '$lib/paraglide/messages';
import { imageService } from '$lib/services/image-service';
- import { DownloadIcon, TrashIcon, InspectIcon, ImagesIcon, VolumesIcon, ClockIcon, EllipsisIcon } from '$lib/icons';
+ import { vulnerabilityService } from '$lib/services/vulnerability-service';
+ import { startVulnerabilityScanPolling } from '$lib/utils/vulnerability-scan.util';
+ import { DownloadIcon, TrashIcon, InspectIcon, ImagesIcon, VolumesIcon, ClockIcon, EllipsisIcon, ScanIcon } from '$lib/icons';
let {
images = $bindable(),
@@ -39,6 +44,9 @@
});
let isPullingInline = $state<Record<string, boolean>>({});
+ let isScanningInline = $state<Record<string, boolean>>({});
+
+ const scanPollers = new Map<string, () => void>();
async function handleDeleteSelected(ids: string[]) {
if (!ids || ids.length === 0) return;
@@ -134,6 +142,40 @@
isPullingInline[imageId] = false;
}
+ async function handleInlineVulnerabilityScan(imageId: string) {
+ isScanningInline[imageId] = true;
+
+ const result = await tryCatch(vulnerabilityService.scanImage(imageId));
+ handleApiResultWithCallbacks({
+ result,
+ message: m.vuln_scan_failed(),
+ setLoadingState: () => {},
+ onSuccess: async (data) => {
+ const summary: VulnerabilityScanSummary = {
+ imageId: data.imageId,
+ scanTime: data.scanTime,
+ status: data.status,
+ summary: data.summary,
+ error: data.error
+ };
+ await handleVulnerabilityScanChanged(imageId, summary);
+
+ if (data.status === 'completed') {
+ toast.success(m.vuln_scan_completed());
+ return;
+ }
+ if (data.status === 'failed') {
+ toast.error(data.error || m.vuln_scan_failed());
+ return;
+ }
+
+ startScanPolling(imageId, true);
+ }
+ });
+
+ isScanningInline[imageId] = false;
+ }
+
async function handleUpdateInfoChanged(imageId: string, newUpdateInfo: ImageUpdateInfoDto) {
const imageIndex = images.data.findIndex((img) => img.id === imageId);
if (imageIndex !== -1) {
@@ -143,6 +185,64 @@
await onImageUpdated?.();
}
+ async function handleVulnerabilityScanChanged(imageId: string, newScanSummary: VulnerabilityScanSummary) {
+ const imageIndex = images.data.findIndex((img) => img.id === imageId);
+ if (imageIndex !== -1) {
+ images.data[imageIndex].vulnerabilityScan = newScanSummary;
+ images = { ...images, data: [...images.data] };
+ }
+ if (newScanSummary.status === 'completed' || newScanSummary.status === 'failed') {
+ await onImageUpdated?.();
+ }
+ }
+
+ function stopScanPolling(imageId: string) {
+ const cancel = scanPollers.get(imageId);
+ if (cancel) {
+ cancel();
+ scanPollers.delete(imageId);
+ }
+ }
+
+ function startScanPolling(imageId: string, showToast: boolean) {
+ if (scanPollers.has(imageId)) return;
+
+ const cancel = startVulnerabilityScanPolling(imageId, (id) => vulnerabilityService.getScanSummary(id), {
+ onUpdate: (summary) => {
+ void handleVulnerabilityScanChanged(imageId, summary);
+ },
+ onComplete: (summary) => {
+ void handleVulnerabilityScanChanged(imageId, summary);
+ stopScanPolling(imageId);
+ if (showToast) {
+ if (summary.status === 'completed') {
+ toast.success(m.vuln_scan_completed());
+ } else {
+ toast.error(summary.error || m.vuln_scan_failed());
+ }
+ }
+ },
+ onError: () => {}
+ });
+
+ scanPollers.set(imageId, cancel);
+ }
+
+ $effect(() => {
+ for (const item of images.data ?? []) {
+ if (item.vulnerabilityScan?.status === 'scanning' || item.vulnerabilityScan?.status === 'pending') {
+ startScanPolling(item.id, false);
+ }
+ }
+ });
+
+ onDestroy(() => {
+ for (const cancel of scanPollers.values()) {
+ cancel();
+ }
+ scanPollers.clear();
+ });
+
const columns = [
{ accessorKey: 'id', title: m.common_id(), hidden: true },
{ accessorKey: 'repo', title: m.images_repository(), sortable: true, cell: RepoCell },
@@ -162,7 +262,30 @@
return 'unknown';
},
title: m.images_updates(),
- cell: UpdatesCell
+ cell: UpdatesCell,
+ align: 'center',
+ class: 'text-center'
+ },
+ {
+ id: 'vulnerabilities',
+ accessorFn: (row) => {
+ if (!row.vulnerabilityScan) return 'not_scanned';
+ if (row.vulnerabilityScan.status === 'failed') return 'error';
+ if (row.vulnerabilityScan.status === 'completed') {
+ const total = row.vulnerabilityScan.summary?.total ?? 0;
+ const critical = row.vulnerabilityScan.summary?.critical ?? 0;
+ const high = row.vulnerabilityScan.summary?.high ?? 0;
+ if (critical > 0) return 'critical';
+ if (high > 0) return 'high';
+ if (total > 0) return 'has_vulnerabilities';
+ return 'clean';
+ }
+ return 'scanning';
+ },
+ title: m.vuln_title(),
+ cell: VulnerabilitiesCell,
+ align: 'center',
+ class: 'text-center'
},
{ accessorKey: 'size', title: m.common_size(), sortable: true, cell: SizeCell },
{ accessorKey: 'created', title: m.common_created(), sortable: true, cell: CreatedCell }
@@ -173,6 +296,7 @@
{ id: 'repoTags', label: m.common_tags(), defaultVisible: true },
{ id: 'inUse', label: m.common_status(), defaultVisible: true },
{ id: 'updates', label: m.images_updates(), defaultVisible: false },
+ { id: 'vulnerabilities', label: m.vuln_title(), defaultVisible: false },
{ id: 'size', label: m.common_size(), defaultVisible: true },
{ id: 'created', label: m.common_created(), defaultVisible: true }
];
@@ -235,13 +359,25 @@
{/snippet}
{#snippet UpdatesCell({ item }: { item: ImageSummaryDto })}
- <ImageUpdateItem
- updateInfo={item.updateInfo}
- imageId={item.id}
- repo={item.repo}
- tag={item.tag}
- onUpdated={(newInfo) => handleUpdateInfoChanged(item.id, newInfo)}
- />
+ <div class="flex items-center justify-center">
+ <ImageUpdateItem
+ updateInfo={item.updateInfo}
+ imageId={item.id}
+ repo={item.repo}
+ tag={item.tag}
+ onUpdated={(newInfo) => handleUpdateInfoChanged(item.id, newInfo)}
+ />
+ </div>
+{/snippet}
+
+{#snippet VulnerabilitiesCell({ item }: { item: ImageSummaryDto })}
+ <div class="flex items-center justify-center">
+ <VulnerabilityScanItem
+ scanSummary={item.vulnerabilityScan}
+ imageId={item.id}
+ onScanned={(newSummary) => handleVulnerabilityScanChanged(item.id, newSummary)}
+ />
+ </div>
{/snippet}
{#snippet ImageMobileCardSnippet({
@@ -343,6 +479,15 @@
{m.images_pull()}
</DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => handleInlineVulnerabilityScan(item.id)} disabled={isScanningInline[item.id]}>
+ {#if isScanningInline[item.id]}
+ <Spinner class="size-4" />
+ {:else}
+ <ScanIcon class="size-4" />
+ {/if}
+ {m.vuln_scan()}
+ </DropdownMenu.Item>
+
<DropdownMenu.Separator />
<DropdownMenu.Item variant="destructive" onclick={() => deleteImage(item.id)} disabled={isLoading.removing}>
diff --git a/frontend/src/routes/(app)/security/+page.svelte b/frontend/src/routes/(app)/security/+page.svelte
new file mode 100644
index 000000000..533cd5d37
--- /dev/null
+++ b/frontend/src/routes/(app)/security/+page.svelte
@@ -0,0 +1,371 @@
+<script lang="ts">
+ import { ResourcePageLayout, type ActionButton } from '$lib/layouts/index.js';
+ import { m } from '$lib/paraglide/messages';
+ import { vulnerabilityService } from '$lib/services/vulnerability-service';
+ import { imageService } from '$lib/services/image-service';
+ import { parallelRefresh } from '$lib/utils/refresh.util';
+ import { useEnvironmentRefresh } from '$lib/hooks/use-environment-refresh.svelte';
+ import type {
+ EnvironmentVulnerabilitySummary,
+ VulnerabilityWithImage,
+ IgnoredVulnerability
+ } from '$lib/types/vulnerability.type';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import { untrack } from 'svelte';
+ import SecurityVulnerabilityTable from './security-vulnerability-table.svelte';
+ import IgnoredVulnerabilitiesTable from './ignored-vulnerabilities-table.svelte';
+ import { toast } from 'svelte-sonner';
+ import { InspectIcon } from '$lib/icons';
+ import * as Tabs from '$lib/components/ui/tabs/index.js';
+
+ let { data } = $props();
+
+ let summary = $state<EnvironmentVulnerabilitySummary>(untrack(() => data.summary));
+ type VulnerabilityRow = VulnerabilityWithImage & { id: string };
+
+ let vulnerabilities = $state<Paginated<VulnerabilityRow>>(untrack(() => data.vulnerabilities));
+ let requestOptions = $state<SearchPaginationSortRequest>(untrack(() => data.vulnerabilityRequestOptions));
+ let isLoading = $state({ refreshing: false, scanningAll: false });
+ let scanProgress = $state({ current: 0, total: 0 });
+ let activeTab = $state('vulnerabilities');
+ let scanPollTimeout: ReturnType<typeof setTimeout> | null = null;
+
+ // Ignored vulnerabilities state
+ let ignoredVulnerabilities = $state<Paginated<IgnoredVulnerability>>({
+ data: [],
+ pagination: { totalPages: 0, totalItems: 0, currentPage: 1, itemsPerPage: 20 }
+ });
+ let ignoredRequestOptions = $state<SearchPaginationSortRequest>({
+ pagination: { page: 1, limit: 20 }
+ });
+ let isLoadingIgnored = $state(false);
+
+ const summaryCounts = $derived.by(() => ({
+ critical: summary?.summary?.critical ?? 0,
+ high: summary?.summary?.high ?? 0,
+ medium: summary?.summary?.medium ?? 0,
+ low: summary?.summary?.low ?? 0,
+ unknown: summary?.summary?.unknown ?? 0,
+ total: summary?.summary?.total ?? 0
+ }));
+
+ const imagesScannedLabel = $derived.by(() => {
+ const total = summary?.totalImages ?? 0;
+ const scanned = summary?.scannedImages ?? 0;
+ return `${scanned}/${total}`;
+ });
+
+ const severityItems = $derived.by(() => {
+ const items = [
+ { key: 'critical', value: summaryCounts.critical, label: m.vuln_severity_critical(), dotClass: 'bg-red-500' },
+ { key: 'high', value: summaryCounts.high, label: m.vuln_severity_high(), dotClass: 'bg-orange-500' },
+ { key: 'medium', value: summaryCounts.medium, label: m.vuln_severity_medium(), dotClass: 'bg-amber-500' },
+ { key: 'low', value: summaryCounts.low, label: m.vuln_severity_low(), dotClass: 'bg-emerald-500' },
+ { key: 'unknown', value: summaryCounts.unknown, label: m.vuln_severity_unknown(), dotClass: 'bg-slate-400' }
+ ];
+ return items.filter((item) => item.value > 0);
+ });
+
+ function mapVulnerabilityRequest(options: SearchPaginationSortRequest): SearchPaginationSortRequest {
+ const filters = { ...(options.filters ?? {}) };
+ if (filters.vulnSeverity) {
+ filters.severity = filters.vulnSeverity;
+ delete filters.vulnSeverity;
+ }
+
+ const sort = options.sort?.column === 'vulnSeverity' ? { ...options.sort, column: 'severity' } : options.sort;
+
+ return {
+ ...options,
+ sort,
+ filters: Object.keys(filters).length ? filters : undefined
+ };
+ }
+
+ function getVulnerabilityKey(vuln: VulnerabilityWithImage, index: number): string {
+ return [
+ vuln.imageId,
+ vuln.vulnerabilityId,
+ vuln.pkgName,
+ vuln.installedVersion ?? '',
+ vuln.fixedVersion ?? '',
+ String(index)
+ ].join('-');
+ }
+
+ function mapVulnerabilityPage(page: Paginated<VulnerabilityWithImage>, options: SearchPaginationSortRequest) {
+ const pageNumber = options.pagination?.page ?? page.pagination?.currentPage ?? 1;
+ const limit = options.pagination?.limit ?? page.pagination?.itemsPerPage ?? 20;
+ const offset = (pageNumber - 1) * limit;
+ return {
+ ...page,
+ data: (page.data ?? []).map((item, index) => ({
+ ...item,
+ id: getVulnerabilityKey(item, offset + index)
+ }))
+ };
+ }
+
+ async function refreshAll() {
+ const requestForApi = mapVulnerabilityRequest(requestOptions);
+ await parallelRefresh(
+ {
+ summary: {
+ fetch: () => vulnerabilityService.getEnvironmentSummary(),
+ onSuccess: (data) => (summary = data),
+ errorMessage: m.common_refresh_failed({ resource: m.security_title() })
+ },
+ vulnerabilities: {
+ fetch: () => vulnerabilityService.getAllVulnerabilities(requestForApi),
+ onSuccess: (data) => (vulnerabilities = mapVulnerabilityPage(data, requestOptions)),
+ errorMessage: m.common_refresh_failed({ resource: m.vuln_title() })
+ }
+ },
+ (v) => (isLoading.refreshing = v)
+ );
+ }
+
+ function stopScanPolling() {
+ if (scanPollTimeout) {
+ clearTimeout(scanPollTimeout);
+ scanPollTimeout = null;
+ }
+ }
+
+ function startScanPolling(targetTotal: number) {
+ const POLL_INTERVAL_MS = 5000;
+ const MAX_ATTEMPTS = 24;
+ const MAX_IDLE_TICKS = 3;
+ let attempts = 0;
+ let idleTicks = 0;
+ let lastScanned = summary?.scannedImages ?? 0;
+
+ stopScanPolling();
+
+ const tick = async () => {
+ if (attempts >= MAX_ATTEMPTS) {
+ stopScanPolling();
+ return;
+ }
+ attempts++;
+
+ if (isLoading.refreshing) {
+ scanPollTimeout = setTimeout(tick, POLL_INTERVAL_MS);
+ return;
+ }
+
+ await refreshAll();
+
+ const currentScanned = summary?.scannedImages ?? 0;
+ const currentTotal = summary?.totalImages ?? targetTotal;
+
+ if (currentTotal > 0 && currentScanned >= currentTotal) {
+ stopScanPolling();
+ return;
+ }
+
+ if (currentScanned === lastScanned) {
+ idleTicks++;
+ } else {
+ idleTicks = 0;
+ lastScanned = currentScanned;
+ }
+
+ if (idleTicks >= MAX_IDLE_TICKS) {
+ stopScanPolling();
+ return;
+ }
+
+ scanPollTimeout = setTimeout(tick, POLL_INTERVAL_MS);
+ };
+
+ scanPollTimeout = setTimeout(tick, POLL_INTERVAL_MS);
+ }
+
+ async function loadIgnoredVulnerabilities(options?: SearchPaginationSortRequest) {
+ if (isLoadingIgnored) return;
+ isLoadingIgnored = true;
+ try {
+ const request = options ?? ignoredRequestOptions;
+ const response = await vulnerabilityService.getIgnoredVulnerabilities(request);
+ ignoredVulnerabilities = response;
+ if (options) {
+ ignoredRequestOptions = options;
+ }
+ } catch (error) {
+ console.error('Failed to load ignored vulnerabilities:', error);
+ toast.error(m.common_refresh_failed({ resource: m.vuln_ignored_title() }));
+ } finally {
+ isLoadingIgnored = false;
+ }
+ }
+
+ async function handleUnignore(ignoreId: string) {
+ try {
+ await vulnerabilityService.unignoreVulnerability(ignoreId);
+ toast.success(m.vuln_unignore_success());
+ // Refresh both lists
+ await loadIgnoredVulnerabilities();
+ await refreshAll();
+ } catch (error) {
+ console.error('Failed to unignore vulnerability:', error);
+ toast.error(m.vuln_unignore_failed());
+ }
+ }
+
+ function handleTabChange(value: string) {
+ activeTab = value;
+ if (value === 'ignored' && ignoredVulnerabilities.data.length === 0) {
+ loadIgnoredVulnerabilities();
+ }
+ }
+
+ useEnvironmentRefresh(refreshAll);
+
+ $effect(() => () => stopScanPolling());
+
+ async function scanAllImages() {
+ if (isLoading.scanningAll) return;
+
+ isLoading.scanningAll = true;
+ scanProgress = { current: 0, total: 0 };
+
+ try {
+ // Fetch all images with a high limit to get all of them
+ const imagesResponse = await imageService.getImages({ pagination: { page: 1, limit: 1000 } });
+ const images = imagesResponse.data ?? [];
+
+ if (images.length === 0) {
+ toast.info(m.security_no_images_to_scan());
+ isLoading.scanningAll = false;
+ return;
+ }
+
+ scanProgress = { current: 0, total: images.length };
+
+ const BATCH_SIZE = 3;
+ let succeeded = 0;
+ let failed = 0;
+
+ for (let i = 0; i < images.length; i += BATCH_SIZE) {
+ const batch = images.slice(i, i + BATCH_SIZE);
+
+ await Promise.all(
+ batch.map(async (image) => {
+ try {
+ const result = await vulnerabilityService.scanImage(image.id);
+ if (result.status === 'completed' || result.status === 'scanning' || result.status === 'pending') {
+ succeeded++;
+ } else {
+ failed++;
+ }
+ } catch (error) {
+ console.error(`Failed to scan image ${image.id}:`, error);
+ failed++;
+ }
+ scanProgress.current++;
+ })
+ );
+ }
+
+ // Show summary toast (scans run in background; this reflects requests started, not completed)
+ if (failed === 0) {
+ toast.success(m.security_scan_all_success({ count: succeeded }));
+ } else if (succeeded === 0) {
+ toast.error(m.security_scan_all_failed({ count: failed }));
+ } else {
+ toast.warning(m.security_scan_all_partial({ succeeded, failed }));
+ }
+
+ // Refresh the vulnerability data and keep polling for updates as scans complete
+ await refreshAll();
+ startScanPolling(images.length);
+ } catch (error) {
+ console.error('Error during scan all:', error);
+ toast.error(m.security_scan_all_error());
+ } finally {
+ isLoading.scanningAll = false;
+ scanProgress = { current: 0, total: 0 };
+ }
+ }
+
+ const actionButtons: ActionButton[] = $derived([
+ {
+ id: 'scan-all',
+ action: 'base',
+ label: isLoading.scanningAll
+ ? `${m.security_scanning()} (${scanProgress.current}/${scanProgress.total})`
+ : m.security_scan_all(),
+ onclick: scanAllImages,
+ loading: isLoading.scanningAll,
+ disabled: isLoading.scanningAll || isLoading.refreshing,
+ icon: InspectIcon
+ },
+ {
+ id: 'refresh',
+ action: 'restart',
+ label: m.common_refresh(),
+ onclick: refreshAll,
+ loading: isLoading.refreshing,
+ disabled: isLoading.refreshing || isLoading.scanningAll
+ }
+ ]);
+</script>
+
+<ResourcePageLayout title={m.security_title()} subtitle={m.security_subtitle()} {actionButtons}>
+ {#snippet mainContent()}
+ <div class="space-y-6">
+ <!-- Minimal overview: one compact block -->
+ <div class="border-border/40 bg-muted/20 rounded-lg border px-4 py-3">
+ <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div class="text-muted-foreground flex items-baseline gap-4 text-xs">
+ <span
+ >{m.security_images_scanned()}:
+ <span class="text-foreground font-medium tabular-nums">{imagesScannedLabel}</span></span
+ >
+ <span
+ >{m.security_total_vulnerabilities()}:
+ <span class="text-foreground font-medium tabular-nums">{summaryCounts.total}</span></span
+ >
+ </div>
+ {#if severityItems.length > 0}
+ <div class="flex flex-wrap items-center gap-x-4 gap-y-1.5">
+ {#each severityItems as item (item.key)}
+ <div class="flex items-center gap-1.5">
+ <span class="{item.dotClass} h-1.5 w-1.5 shrink-0 rounded-full" aria-hidden="true"></span>
+ <span class="text-muted-foreground text-xs">
+ <span class="text-foreground font-semibold tabular-nums">{item.value}</span>
+ <span class="ml-0.5">{item.label}</span>
+ </span>
+ </div>
+ {/each}
+ </div>
+ {/if}
+ </div>
+ </div>
+
+ <Tabs.Root value={activeTab} onValueChange={handleTabChange}>
+ <Tabs.List class="grid w-full grid-cols-2">
+ <Tabs.Trigger value="vulnerabilities">{m.vuln_title()}</Tabs.Trigger>
+ <Tabs.Trigger value="ignored">{m.vuln_ignored_title()}</Tabs.Trigger>
+ </Tabs.List>
+ <Tabs.Content value="vulnerabilities" class="mt-4">
+ <div class="border-border/60 rounded-xl border">
+ <SecurityVulnerabilityTable bind:vulnerabilities bind:requestOptions />
+ </div>
+ </Tabs.Content>
+ <Tabs.Content value="ignored" class="mt-4">
+ <div class="border-border/60 rounded-xl border">
+ <IgnoredVulnerabilitiesTable
+ {ignoredVulnerabilities}
+ requestOptions={ignoredRequestOptions}
+ isLoading={isLoadingIgnored}
+ onRefresh={loadIgnoredVulnerabilities}
+ onUnignore={handleUnignore}
+ />
+ </div>
+ </Tabs.Content>
+ </Tabs.Root>
+ </div>
+ {/snippet}
+</ResourcePageLayout>
diff --git a/frontend/src/routes/(app)/security/+page.ts b/frontend/src/routes/(app)/security/+page.ts
new file mode 100644
index 000000000..ab528ac46
--- /dev/null
+++ b/frontend/src/routes/(app)/security/+page.ts
@@ -0,0 +1,75 @@
+import { vulnerabilityService } from '$lib/services/vulnerability-service';
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';
+import type { Paginated } from '$lib/types/pagination.type';
+import type { VulnerabilityWithImage } from '$lib/types/vulnerability.type';
+import type { PageLoad } from './$types';
+
+function mapVulnerabilityRequest(options: SearchPaginationSortRequest): SearchPaginationSortRequest {
+ const filters = { ...(options.filters ?? {}) };
+ if (filters.vulnSeverity) {
+ filters.severity = filters.vulnSeverity;
+ delete filters.vulnSeverity;
+ }
+
+ const sort = options.sort?.column === 'vulnSeverity' ? { ...options.sort, column: 'severity' } : options.sort;
+
+ return {
+ ...options,
+ sort,
+ filters: Object.keys(filters).length ? filters : undefined
+ };
+}
+
+function getVulnerabilityKey(vuln: VulnerabilityWithImage, index: number): string {
+ return [
+ vuln.imageId,
+ vuln.vulnerabilityId,
+ vuln.pkgName,
+ vuln.installedVersion ?? '',
+ vuln.fixedVersion ?? '',
+ String(index)
+ ].join('-');
+}
+
+function mapVulnerabilityPage(
+ page: Paginated<VulnerabilityWithImage>,
+ options: SearchPaginationSortRequest
+): Paginated<VulnerabilityWithImage & { id: string }> {
+ const pageNumber = options.pagination?.page ?? page.pagination?.currentPage ?? 1;
+ const limit = options.pagination?.limit ?? page.pagination?.itemsPerPage ?? 20;
+ const offset = (pageNumber - 1) * limit;
+ return {
+ ...page,
+ data: (page.data ?? []).map((item, index) => ({
+ ...item,
+ id: getVulnerabilityKey(item, offset + index)
+ }))
+ };
+}
+
+export const load: PageLoad = async () => {
+ const vulnerabilityRequestOptions = resolveInitialTableRequest('arcane-security-vuln-table', {
+ pagination: {
+ page: 1,
+ limit: 20
+ },
+ sort: {
+ column: 'vulnSeverity',
+ direction: 'desc'
+ }
+ } satisfies SearchPaginationSortRequest);
+
+ const requestForApi = mapVulnerabilityRequest(vulnerabilityRequestOptions);
+
+ const [summary, vulnerabilities] = await Promise.all([
+ vulnerabilityService.getEnvironmentSummary(),
+ vulnerabilityService.getAllVulnerabilities(requestForApi)
+ ]);
+
+ return {
+ summary,
+ vulnerabilities: mapVulnerabilityPage(vulnerabilities, vulnerabilityRequestOptions),
+ vulnerabilityRequestOptions
+ };
+};
diff --git a/frontend/src/routes/(app)/security/ignored-vulnerabilities-table.svelte b/frontend/src/routes/(app)/security/ignored-vulnerabilities-table.svelte
new file mode 100644
index 000000000..27e960f32
--- /dev/null
+++ b/frontend/src/routes/(app)/security/ignored-vulnerabilities-table.svelte
@@ -0,0 +1,136 @@
+<script lang="ts">
+ import { m } from '$lib/paraglide/messages';
+ import type { IgnoredVulnerability } from '$lib/types/vulnerability.type';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import { ShieldAlertIcon, CodeIcon, ImagesIcon, EyeOnIcon } from '$lib/icons';
+ import { ArcaneButton } from '$lib/components/arcane-button';
+
+ let {
+ ignoredVulnerabilities,
+ requestOptions = $bindable(),
+ isLoading,
+ onRefresh,
+ onUnignore
+ }: {
+ ignoredVulnerabilities: Paginated<IgnoredVulnerability>;
+ requestOptions: SearchPaginationSortRequest;
+ isLoading: boolean;
+ onRefresh: (options: SearchPaginationSortRequest) => void;
+ onUnignore: (ignoreId: string) => void;
+ } = $props();
+
+ const DEFAULT_PAGE_SIZE = 20;
+
+ function formatDate(dateString: string): string {
+ const date = new Date(dateString);
+ return date.toLocaleDateString();
+ }
+
+ function handlePageChange(page: number) {
+ const newOptions: SearchPaginationSortRequest = {
+ ...requestOptions,
+ pagination: {
+ page,
+ limit: requestOptions.pagination?.limit ?? DEFAULT_PAGE_SIZE
+ }
+ };
+ onRefresh(newOptions);
+ }
+</script>
+
+<div class="divide-border divide-y">
+ {#if ignoredVulnerabilities.data.length === 0}
+ <div class="text-muted-foreground flex h-32 items-center justify-center">
+ {#if isLoading}
+ <div class="flex items-center gap-2">
+ <div class="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"></div>
+ <span>{m.common_loading()}</span>
+ </div>
+ {:else}
+ {m.vuln_ignored_empty()}
+ {/if}
+ </div>
+ {:else}
+ {#each ignoredVulnerabilities.data as item (item.id)}
+ <div class="hover:bg-muted/50 flex items-center justify-between p-4">
+ <div class="flex-1 space-y-1">
+ <div class="flex items-center gap-2">
+ <ShieldAlertIcon class="text-muted-foreground h-4 w-4" />
+ <a
+ href="https://nvd.nist.gov/vuln/detail/{item.vulnerabilityId}"
+ target="_blank"
+ rel="noopener noreferrer"
+ class="font-mono text-sm font-medium text-blue-600 hover:underline dark:text-blue-400"
+ >
+ {item.vulnerabilityId}
+ </a>
+ </div>
+ <div class="text-muted-foreground flex flex-wrap items-center gap-x-4 gap-y-1 text-xs">
+ <span class="flex items-center gap-1">
+ <CodeIcon class="h-3 w-3" />
+ <span class="font-mono">{item.pkgName}@{item.installedVersion}</span>
+ </span>
+ <span class="flex items-center gap-1">
+ <ImagesIcon class="h-3 w-3" />
+ <span class="max-w-[200px] truncate" title={item.imageId}>
+ {item.imageId.substring(0, 12)}...
+ </span>
+ </span>
+ <span>• {formatDate(item.createdAt)}</span>
+ </div>
+ {#if item.reason}
+ <div class="text-muted-foreground text-xs italic">
+ {item.reason}
+ </div>
+ {/if}
+ </div>
+ <ArcaneButton
+ action="base"
+ size="sm"
+ icon={EyeOnIcon}
+ customLabel={m.vuln_unignore()}
+ onclick={() => onUnignore(item.id)}
+ disabled={isLoading}
+ />
+ </div>
+ {/each}
+
+ {#if ignoredVulnerabilities.pagination.totalPages > 1}
+ <div class="flex items-center justify-between border-t px-4 py-3">
+ <div class="text-muted-foreground text-xs">
+ {m.pagination_showing({
+ from: (ignoredVulnerabilities.pagination.currentPage - 1) * ignoredVulnerabilities.pagination.itemsPerPage + 1,
+ to: Math.min(
+ ignoredVulnerabilities.pagination.currentPage * ignoredVulnerabilities.pagination.itemsPerPage,
+ ignoredVulnerabilities.pagination.totalItems
+ ),
+ total: ignoredVulnerabilities.pagination.totalItems
+ })}
+ </div>
+ <div class="flex items-center gap-2">
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ size="sm"
+ onclick={() => handlePageChange(ignoredVulnerabilities.pagination.currentPage - 1)}
+ disabled={ignoredVulnerabilities.pagination.currentPage <= 1 || isLoading}
+ >
+ {m.common_previous()}
+ </ArcaneButton>
+ <span class="text-muted-foreground text-xs">
+ {ignoredVulnerabilities.pagination.currentPage} / {ignoredVulnerabilities.pagination.totalPages}
+ </span>
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ size="sm"
+ onclick={() => handlePageChange(ignoredVulnerabilities.pagination.currentPage + 1)}
+ disabled={ignoredVulnerabilities.pagination.currentPage >= ignoredVulnerabilities.pagination.totalPages || isLoading}
+ >
+ {m.common_next()}
+ </ArcaneButton>
+ </div>
+ </div>
+ {/if}
+ {/if}
+</div>
diff --git a/frontend/src/routes/(app)/security/security-vulnerability-table.svelte b/frontend/src/routes/(app)/security/security-vulnerability-table.svelte
new file mode 100644
index 000000000..f4011a872
--- /dev/null
+++ b/frontend/src/routes/(app)/security/security-vulnerability-table.svelte
@@ -0,0 +1,276 @@
+<script lang="ts">
+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';
+ import UniversalMobileCard from '$lib/components/arcane-table/cards/universal-mobile-card.svelte';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { vulnerabilityService } from '$lib/services/vulnerability-service';
+ import { m } from '$lib/paraglide/messages';
+ import type { ColumnSpec } from '$lib/components/arcane-table/arcane-table.types.svelte';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import type { VulnerabilityWithImage } from '$lib/types/vulnerability.type';
+ import { ShieldAlertIcon, CodeIcon, CheckIcon, ImagesIcon, EyeOffIcon } from '$lib/icons';
+ import { toast } from 'svelte-sonner';
+ import type { BulkAction } from '$lib/components/arcane-table/arcane-table.types.svelte';
+
+ const DEFAULT_PAGE_SIZE = 20;
+
+ type VulnerabilityRow = VulnerabilityWithImage & { id: string };
+
+ let {
+ vulnerabilities = $bindable(),
+ requestOptions = $bindable()
+ }: {
+ vulnerabilities: Paginated<VulnerabilityRow>;
+ requestOptions: SearchPaginationSortRequest;
+ } = $props();
+
+ function getSeverityLabel(severity: string): string {
+ switch (severity) {
+ case 'CRITICAL':
+ return m.vuln_severity_critical();
+ case 'HIGH':
+ return m.vuln_severity_high();
+ case 'MEDIUM':
+ return m.vuln_severity_medium();
+ case 'LOW':
+ return m.vuln_severity_low();
+ default:
+ return m.vuln_severity_unknown();
+ }
+ }
+
+ function getSeverityBadgeVariant(severity: string): 'red' | 'orange' | 'amber' | 'green' | 'gray' {
+ switch (severity) {
+ case 'CRITICAL':
+ return 'red';
+ case 'HIGH':
+ return 'orange';
+ case 'MEDIUM':
+ return 'amber';
+ case 'LOW':
+ return 'green';
+ default:
+ return 'gray';
+ }
+ }
+
+ function getSeverityIconVariant(severity: string): 'red' | 'orange' | 'amber' | 'emerald' | 'gray' {
+ switch (severity) {
+ case 'CRITICAL':
+ return 'red';
+ case 'HIGH':
+ return 'orange';
+ case 'MEDIUM':
+ return 'amber';
+ case 'LOW':
+ return 'emerald';
+ default:
+ return 'gray';
+ }
+ }
+
+ function getVulnerabilityKey(vuln: VulnerabilityWithImage, index: number): string {
+ return [
+ vuln.imageId,
+ vuln.vulnerabilityId,
+ vuln.pkgName,
+ vuln.installedVersion ?? '',
+ vuln.fixedVersion ?? '',
+ String(index)
+ ].join('-');
+ }
+
+ async function refreshVulnerabilityTable(options: SearchPaginationSortRequest) {
+ const mergedFilters = { ...(options.filters ?? {}) };
+ if (mergedFilters.vulnSeverity) {
+ mergedFilters.severity = mergedFilters.vulnSeverity;
+ delete mergedFilters.vulnSeverity;
+ }
+
+ const sort = options.sort?.column === 'vulnSeverity' ? { ...options.sort, column: 'severity' } : options.sort;
+
+ const request: SearchPaginationSortRequest = {
+ ...options,
+ sort,
+ filters: Object.keys(mergedFilters).length ? mergedFilters : undefined
+ };
+
+ const response = await vulnerabilityService.getAllVulnerabilities(request);
+ const page = request.pagination?.page ?? 1;
+ const limit = request.pagination?.limit ?? DEFAULT_PAGE_SIZE;
+ const offset = (page - 1) * limit;
+ const mapped: Paginated<VulnerabilityRow> = {
+ ...response,
+ data: (response.data ?? []).map((item, index) => ({
+ ...item,
+ id: getVulnerabilityKey(item, offset + index)
+ }))
+ };
+ vulnerabilities = mapped;
+ return mapped;
+ }
+
+ async function handleIgnoreVulnerability(item: VulnerabilityRow) {
+ console.log('Ignoring vulnerability:', {
+ imageId: item.imageId,
+ vulnerabilityId: item.vulnerabilityId,
+ pkgName: item.pkgName,
+ installedVersion: item.installedVersion
+ });
+ try {
+ const payload = {
+ imageId: item.imageId || '',
+ vulnerabilityId: item.vulnerabilityId || '',
+ pkgName: item.pkgName || '',
+ installedVersion: item.installedVersion || ''
+ };
+ console.log('Sending payload:', payload);
+ await vulnerabilityService.ignoreVulnerability(payload);
+ toast.success(m.vuln_ignore_success({ cve: item.vulnerabilityId }));
+ // Refresh the table to remove the ignored vulnerability
+ await refreshVulnerabilityTable(requestOptions);
+ } catch (error) {
+ console.error('Failed to ignore vulnerability:', error);
+ toast.error(m.vuln_ignore_failed());
+ }
+ }
+
+ const columns = $derived([
+ { accessorKey: 'vulnerabilityId', title: 'CVE', cell: CveCell },
+ { accessorKey: 'pkgName', title: m.vuln_package(), cell: PackageCell },
+ { id: 'vulnSeverity', accessorKey: 'severity', title: m.events_col_severity(), sortable: true, cell: SeverityCell },
+ { accessorKey: 'installedVersion', title: m.vuln_installed_version(), cell: InstalledCell },
+ { accessorKey: 'fixedVersion', title: m.vuln_fixed_version(), cell: FixedCell },
+ { accessorKey: 'imageName', title: m.common_image(), sortable: true, cell: ImageCell }
+ ] satisfies ColumnSpec<VulnerabilityRow>[]);
+
+ const uniqueImageNames = $derived(
+ [...new Set((vulnerabilities.data ?? []).map((r) => r.imageName || r.imageId).filter(Boolean) as string[])].sort()
+ );
+
+ const mobileFields = [
+ { id: 'vulnerabilityId', label: 'CVE', defaultVisible: true },
+ { id: 'pkgName', label: m.vuln_package(), defaultVisible: true },
+ { id: 'vulnSeverity', label: m.events_col_severity(), defaultVisible: true },
+ { id: 'imageName', label: m.common_image(), defaultVisible: true },
+ { id: 'installedVersion', label: m.vuln_installed_version(), defaultVisible: false },
+ { id: 'fixedVersion', label: m.vuln_fixed_version(), defaultVisible: false }
+ ];
+</script>
+
+{#snippet CveCell({ item }: { item: VulnerabilityRow })}
+ <a
+ href="https://nvd.nist.gov/vuln/detail/{item.vulnerabilityId}"
+ target="_blank"
+ rel="noopener noreferrer"
+ class="font-mono text-xs text-blue-600 hover:underline dark:text-blue-400"
+ >
+ {item.vulnerabilityId}
+ </a>
+{/snippet}
+
+{#snippet PackageCell({ item }: { item: VulnerabilityRow })}
+ <span class="font-mono text-xs">{item.pkgName}</span>
+{/snippet}
+
+{#snippet SeverityCell({ item }: { item: VulnerabilityRow })}
+ {#if item.severity === 'CRITICAL'}
+ <StatusBadge text={m.vuln_severity_critical()} variant="red" size="sm" />
+ {:else if item.severity === 'HIGH'}
+ <StatusBadge text={m.vuln_severity_high()} variant="orange" size="sm" />
+ {:else if item.severity === 'MEDIUM'}
+ <StatusBadge text={m.vuln_severity_medium()} variant="amber" size="sm" />
+ {:else if item.severity === 'LOW'}
+ <StatusBadge text={m.vuln_severity_low()} variant="lime" size="sm" />
+ {:else}
+ <StatusBadge text={m.vuln_severity_unknown()} variant="gray" size="sm" />
+ {/if}
+{/snippet}
+
+{#snippet InstalledCell({ item }: { item: VulnerabilityRow })}
+ <span class="font-mono text-xs">{item.installedVersion}</span>
+{/snippet}
+
+{#snippet FixedCell({ item }: { item: VulnerabilityRow })}
+ <span class="font-mono text-xs">{item.fixedVersion || m.vuln_no_fix()}</span>
+{/snippet}
+
+{#snippet ImageCell({ item }: { item: VulnerabilityRow })}
+ <a class="truncate text-sm font-medium hover:underline" href="/images/{item.imageId}">
+ {item.imageName || item.imageId}
+ </a>
+{/snippet}
+
+{#snippet VulnerabilityMobileCard({
+ row,
+ item,
+ mobileFieldVisibility
+}: {
+ row: any;
+ item: VulnerabilityRow;
+ mobileFieldVisibility: Record<string, boolean>;
+})}
+ <UniversalMobileCard
+ {item}
+ icon={(item) => ({
+ component: ShieldAlertIcon,
+ variant: getSeverityIconVariant(item.severity)
+ })}
+ title={(item) => item.vulnerabilityId}
+ subtitle={(item) => ((mobileFieldVisibility.pkgName ?? true) ? item.pkgName : null)}
+ badges={[
+ (item) =>
+ (mobileFieldVisibility.vulnSeverity ?? true)
+ ? { variant: getSeverityBadgeVariant(item.severity), text: getSeverityLabel(item.severity) }
+ : null
+ ]}
+ fields={[
+ {
+ label: m.common_image(),
+ getValue: (item) => item.imageName || item.imageId,
+ icon: ImagesIcon,
+ iconVariant: 'gray',
+ show: mobileFieldVisibility.imageName ?? true
+ },
+ {
+ label: m.vuln_installed_version(),
+ getValue: (item) => item.installedVersion,
+ type: 'mono',
+ icon: CodeIcon,
+ iconVariant: 'blue',
+ show: mobileFieldVisibility.installedVersion ?? true
+ },
+ {
+ label: m.vuln_fixed_version(),
+ getValue: (item) => item.fixedVersion || m.vuln_no_fix(),
+ type: 'mono',
+ icon: CheckIcon,
+ iconVariant: item.fixedVersion ? 'emerald' : 'gray',
+ show: mobileFieldVisibility.fixedVersion ?? true
+ }
+ ]}
+ />
+{/snippet}
+
+{#snippet rowActions({ item }: { item: VulnerabilityRow })}
+ <button
+ onclick={() => handleIgnoreVulnerability(item)}
+ class="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs transition-colors"
+ title={m.vuln_ignore()}
+ >
+ <EyeOffIcon class="h-3.5 w-3.5" />
+ <span class="sr-only">{m.vuln_ignore()}</span>
+ </button>
+{/snippet}
+
+<ArcaneTable
+ items={vulnerabilities}
+ bind:requestOptions
+ onRefresh={refreshVulnerabilityTable}
+ {columns}
+ mobileCard={VulnerabilityMobileCard}
+ {mobileFields}
+ persistKey="arcane-security-vuln-table"
+ selectionDisabled
+ imageNameFilterOptions={uniqueImageNames}
+ {rowActions}
+/>
diff --git a/frontend/src/routes/(app)/settings/notifications/+page.svelte b/frontend/src/routes/(app)/settings/notifications/+page.svelte
index 5bd4e5099..657a78fc4 100644
--- a/frontend/src/routes/(app)/settings/notifications/+page.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/+page.svelte
@@ -476,7 +476,7 @@
<Tabs.Root bind:value={providerTab} class="flex min-h-0 w-full min-w-0 flex-col">
<Tabs.List class="scrollbar-hide flex w-full max-w-full justify-start gap-4 overflow-x-auto">
{#each NOTIFICATION_PROVIDER_KEYS as provider (provider)}
- <Tabs.Trigger value={provider} class="flex-shrink-0">
+ <Tabs.Trigger value={provider} class="shrink-0">
{provider.charAt(0).toUpperCase() + provider.slice(1)}
</Tabs.Trigger>
{/each}
@@ -498,7 +498,7 @@
bind:values={discordValues}
disabled={isReadOnly}
{isTesting}
- onTest={() => testNotification('discord')}
+ onTest={(testType) => testNotification('discord', testType)}
/>
</Tabs.Content>
@@ -508,7 +508,7 @@
bind:values={telegramValues}
disabled={isReadOnly}
{isTesting}
- onTest={() => testNotification('telegram')}
+ onTest={(testType) => testNotification('telegram', testType)}
/>
</Tabs.Content>
@@ -518,7 +518,7 @@
bind:values={signalValues}
disabled={isReadOnly}
{isTesting}
- onTest={() => testNotification('signal')}
+ onTest={(testType) => testNotification('signal', testType)}
/>
</Tabs.Content>
@@ -528,7 +528,7 @@
bind:values={slackValues}
disabled={isReadOnly}
{isTesting}
- onTest={() => testNotification('slack')}
+ onTest={(testType) => testNotification('slack', testType)}
/>
</Tabs.Content>
@@ -538,7 +538,7 @@
bind:values={ntfyValues}
disabled={isReadOnly}
{isTesting}
- onTest={() => testNotification('ntfy')}
+ onTest={(testType) => testNotification('ntfy', testType)}
/>
</Tabs.Content>
@@ -548,7 +548,7 @@
bind:values={pushoverValues}
disabled={isReadOnly}
{isTesting}
- onTest={() => testNotification('pushover')}
+ onTest={(testType) => testNotification('pushover', testType)}
/>
</Tabs.Content>
@@ -558,7 +558,7 @@
bind:values={gotifyValues}
disabled={isReadOnly}
{isTesting}
- onTest={() => testNotification('gotify')}
+ onTest={(testType) => testNotification('gotify', testType)}
/>
</Tabs.Content>
@@ -568,7 +568,7 @@
bind:values={genericValues}
disabled={isReadOnly}
{isTesting}
- onTest={() => testNotification('generic')}
+ onTest={(testType) => testNotification('generic', testType)}
/>
</Tabs.Content>
</Tabs.Root>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/DiscordProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/DiscordProviderForm.svelte
index 5cfa9fbb7..2fbef0d48 100644
--- a/frontend/src/routes/(app)/settings/notifications/providers/DiscordProviderForm.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/providers/DiscordProviderForm.svelte
@@ -1,8 +1,9 @@
<script lang="ts">
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
import { m } from '$lib/paraglide/messages';
- import { SendEmailIcon } from '$lib/icons';
+ import { ArrowDownIcon, SendEmailIcon } from '$lib/icons';
import { z } from 'zod/v4';
import type { DiscordFormValues } from '$lib/types/notification-providers';
import ProviderFormWrapper from './ProviderFormWrapper.svelte';
@@ -12,7 +13,7 @@
values: DiscordFormValues;
disabled?: boolean;
isTesting?: boolean;
- onTest?: () => void;
+ onTest?: (testType?: string) => void;
}
let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
@@ -25,7 +26,8 @@
username: z.string(),
avatarUrl: z.string(),
eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean()
+ eventContainerUpdate: z.boolean(),
+ eventVulnerabilityFound: z.boolean()
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
@@ -109,20 +111,36 @@
providerId="discord"
bind:eventImageUpdate={values.eventImageUpdate}
bind:eventContainerUpdate={values.eventContainerUpdate}
+ bind:eventVulnerabilityFound={values.eventVulnerabilityFound}
{disabled}
/>
{#if onTest}
<div class="pt-2">
- <ArcaneButton
- action="base"
- tone="outline"
- onclick={onTest}
- disabled={disabled || isTesting}
- loading={isTesting}
- icon={SendEmailIcon}
- customLabel={m.notifications_test_notification()}
- />
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ >
+ <ArrowDownIcon class="ml-2 size-4" />
+ </ArcaneButton>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="start">
+ <DropdownMenu.Item onclick={() => onTest()}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_notification()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => onTest('vulnerability-found')}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_vulnerability_notification()}
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
</div>
{/if}
</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/EmailProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/EmailProviderForm.svelte
index e8223e2b4..fe7168332 100644
--- a/frontend/src/routes/(app)/settings/notifications/providers/EmailProviderForm.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/providers/EmailProviderForm.svelte
@@ -32,7 +32,8 @@
toAddresses: z.string(),
tlsMode: z.enum(['none', 'starttls', 'ssl']),
eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean()
+ eventContainerUpdate: z.boolean(),
+ eventVulnerabilityFound: z.boolean()
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
@@ -194,6 +195,7 @@
providerId="email"
bind:eventImageUpdate={values.eventImageUpdate}
bind:eventContainerUpdate={values.eventContainerUpdate}
+ bind:eventVulnerabilityFound={values.eventVulnerabilityFound}
{disabled}
/>
@@ -225,6 +227,10 @@
<SendEmailIcon class="size-4" />
{m.notifications_email_test_batch_image_update()}
</DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => onTest('vulnerability-found')}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_email_test_vulnerability_found()}
+ </DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
</div>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/EventSubscriptions.svelte b/frontend/src/routes/(app)/settings/notifications/providers/EventSubscriptions.svelte
index 2185696e1..f50fe7b6c 100644
--- a/frontend/src/routes/(app)/settings/notifications/providers/EventSubscriptions.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/providers/EventSubscriptions.svelte
@@ -7,10 +7,17 @@
providerId: string;
eventImageUpdate: boolean;
eventContainerUpdate: boolean;
+ eventVulnerabilityFound: boolean;
disabled?: boolean;
}
- let { providerId, eventImageUpdate = $bindable(), eventContainerUpdate = $bindable(), disabled = false }: Props = $props();
+ let {
+ providerId,
+ eventImageUpdate = $bindable(),
+ eventContainerUpdate = $bindable(),
+ eventVulnerabilityFound = $bindable(),
+ disabled = false
+ }: Props = $props();
</script>
<div class="space-y-3 pt-2">
@@ -31,5 +38,12 @@
label={m.notifications_event_container_update_label()}
description={m.notifications_event_container_update_description()}
/>
+ <SwitchWithLabel
+ id="{providerId}-event-vulnerability-found"
+ bind:checked={eventVulnerabilityFound}
+ {disabled}
+ label={m.notifications_event_vulnerability_found_label()}
+ description={m.notifications_event_vulnerability_found_description()}
+ />
</div>
</div>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/GenericProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/GenericProviderForm.svelte
index 9707fdde8..85df58cda 100644
--- a/frontend/src/routes/(app)/settings/notifications/providers/GenericProviderForm.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/providers/GenericProviderForm.svelte
@@ -1,8 +1,9 @@
<script lang="ts">
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
import { m } from '$lib/paraglide/messages';
- import { SendEmailIcon } from '$lib/icons';
+ import { ArrowDownIcon, SendEmailIcon } from '$lib/icons';
import { z } from 'zod/v4';
import type { GenericFormValues } from '$lib/types/notification-providers';
import ProviderFormWrapper from './ProviderFormWrapper.svelte';
@@ -12,7 +13,7 @@
values: GenericFormValues;
disabled?: boolean;
isTesting?: boolean;
- onTest?: () => void;
+ onTest?: (testType?: string) => void;
}
let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
@@ -27,7 +28,8 @@
messageKey: z.string(),
customHeaders: z.string(),
eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean()
+ eventContainerUpdate: z.boolean(),
+ eventVulnerabilityFound: z.boolean()
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
@@ -131,20 +133,36 @@
providerId="generic"
bind:eventImageUpdate={values.eventImageUpdate}
bind:eventContainerUpdate={values.eventContainerUpdate}
+ bind:eventVulnerabilityFound={values.eventVulnerabilityFound}
{disabled}
/>
{#if onTest}
<div class="pt-2">
- <ArcaneButton
- action="base"
- tone="outline"
- onclick={onTest}
- disabled={disabled || isTesting}
- loading={isTesting}
- icon={SendEmailIcon}
- customLabel={m.notifications_test_notification()}
- />
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ >
+ <ArrowDownIcon class="ml-2 size-4" />
+ </ArcaneButton>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="start">
+ <DropdownMenu.Item onclick={() => onTest()}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_notification()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => onTest('vulnerability-found')}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_vulnerability_notification()}
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
</div>
{/if}
</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/GotifyProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/GotifyProviderForm.svelte
index 970613696..8d6f7b552 100644
--- a/frontend/src/routes/(app)/settings/notifications/providers/GotifyProviderForm.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/providers/GotifyProviderForm.svelte
@@ -1,11 +1,12 @@
<script lang="ts">
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
import { Label } from '$lib/components/ui/label';
import * as Select from '$lib/components/ui/select/index.js';
import { m } from '$lib/paraglide/messages';
- import { SendEmailIcon } from '$lib/icons';
+ import { ArrowDownIcon, SendEmailIcon } from '$lib/icons';
import { z } from 'zod/v4';
import type { GotifyFormValues } from '$lib/types/notification-providers';
import ProviderFormWrapper from './ProviderFormWrapper.svelte';
@@ -15,7 +16,7 @@
values: GotifyFormValues;
disabled?: boolean;
isTesting?: boolean;
- onTest?: () => void;
+ onTest?: (testType?: string) => void;
}
let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
@@ -49,7 +50,8 @@
title: z.string(),
disableTls: z.boolean(),
eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean()
+ eventContainerUpdate: z.boolean(),
+ eventVulnerabilityFound: z.boolean()
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
@@ -184,20 +186,36 @@
providerId="gotify"
bind:eventImageUpdate={values.eventImageUpdate}
bind:eventContainerUpdate={values.eventContainerUpdate}
+ bind:eventVulnerabilityFound={values.eventVulnerabilityFound}
{disabled}
/>
{#if onTest}
<div class="pt-2">
- <ArcaneButton
- action="base"
- tone="outline"
- onclick={onTest}
- disabled={disabled || isTesting}
- loading={isTesting}
- icon={SendEmailIcon}
- customLabel={m.notifications_test_notification()}
- />
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ >
+ <ArrowDownIcon class="ml-2 size-4" />
+ </ArcaneButton>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="start">
+ <DropdownMenu.Item onclick={() => onTest()}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_notification()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => onTest('vulnerability-found')}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_vulnerability_notification()}
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
</div>
{/if}
</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/NtfyProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/NtfyProviderForm.svelte
index 8f537b480..8485393cd 100644
--- a/frontend/src/routes/(app)/settings/notifications/providers/NtfyProviderForm.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/providers/NtfyProviderForm.svelte
@@ -1,11 +1,12 @@
<script lang="ts">
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
import { Label } from '$lib/components/ui/label';
import Textarea from '$lib/components/ui/textarea/textarea.svelte';
import { m } from '$lib/paraglide/messages';
- import { SendEmailIcon } from '$lib/icons';
+ import { ArrowDownIcon, SendEmailIcon } from '$lib/icons';
import { z } from 'zod/v4';
import type { NtfyFormValues } from '$lib/types/notification-providers';
import ProviderFormWrapper from './ProviderFormWrapper.svelte';
@@ -15,7 +16,7 @@
values: NtfyFormValues;
disabled?: boolean;
isTesting?: boolean;
- onTest?: () => void;
+ onTest?: (testType?: string) => void;
}
let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
@@ -35,7 +36,8 @@
firebase: z.boolean(),
disableTlsVerification: z.boolean(),
eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean()
+ eventContainerUpdate: z.boolean(),
+ eventVulnerabilityFound: z.boolean()
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
@@ -192,20 +194,36 @@
providerId="ntfy"
bind:eventImageUpdate={values.eventImageUpdate}
bind:eventContainerUpdate={values.eventContainerUpdate}
+ bind:eventVulnerabilityFound={values.eventVulnerabilityFound}
{disabled}
/>
{#if onTest}
<div class="pt-2">
- <ArcaneButton
- action="base"
- tone="outline"
- onclick={onTest}
- disabled={disabled || isTesting}
- loading={isTesting}
- icon={SendEmailIcon}
- customLabel={m.notifications_test_notification()}
- />
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ >
+ <ArrowDownIcon class="ml-2 size-4" />
+ </ArcaneButton>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="start">
+ <DropdownMenu.Item onclick={() => onTest()}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_notification()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => onTest('vulnerability-found')}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_vulnerability_notification()}
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
</div>
{/if}
</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/PushoverProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/PushoverProviderForm.svelte
index af919ba3d..c2dbc024c 100644
--- a/frontend/src/routes/(app)/settings/notifications/providers/PushoverProviderForm.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/providers/PushoverProviderForm.svelte
@@ -1,11 +1,12 @@
<script lang="ts">
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
import { Label } from '$lib/components/ui/label';
import Textarea from '$lib/components/ui/textarea/textarea.svelte';
import * as Select from '$lib/components/ui/select/index.js';
import { m } from '$lib/paraglide/messages';
- import { SendEmailIcon } from '$lib/icons';
+ import { ArrowDownIcon, SendEmailIcon } from '$lib/icons';
import { z } from 'zod/v4';
import type { PushoverFormValues } from '$lib/types/notification-providers';
import ProviderFormWrapper from './ProviderFormWrapper.svelte';
@@ -15,7 +16,7 @@
values: PushoverFormValues;
disabled?: boolean;
isTesting?: boolean;
- onTest?: () => void;
+ onTest?: (testType?: string) => void;
}
let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
@@ -39,7 +40,8 @@
priority: z.coerce.number().int().min(-2).max(2),
title: z.string(),
eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean()
+ eventContainerUpdate: z.boolean(),
+ eventVulnerabilityFound: z.boolean()
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
@@ -152,20 +154,36 @@
providerId="pushover"
bind:eventImageUpdate={values.eventImageUpdate}
bind:eventContainerUpdate={values.eventContainerUpdate}
+ bind:eventVulnerabilityFound={values.eventVulnerabilityFound}
{disabled}
/>
{#if onTest}
<div class="pt-2">
- <ArcaneButton
- action="base"
- tone="outline"
- onclick={onTest}
- disabled={disabled || isTesting}
- loading={isTesting}
- icon={SendEmailIcon}
- customLabel={m.notifications_test_notification()}
- />
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ >
+ <ArrowDownIcon class="ml-2 size-4" />
+ </ArcaneButton>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="start">
+ <DropdownMenu.Item onclick={() => onTest()}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_notification()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => onTest('vulnerability-found')}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_vulnerability_notification()}
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
</div>
{/if}
</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/SignalProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/SignalProviderForm.svelte
index bd0a30f71..751e2c2b1 100644
--- a/frontend/src/routes/(app)/settings/notifications/providers/SignalProviderForm.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/providers/SignalProviderForm.svelte
@@ -1,11 +1,12 @@
<script lang="ts">
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
import { Label } from '$lib/components/ui/label';
import Textarea from '$lib/components/ui/textarea/textarea.svelte';
import { m } from '$lib/paraglide/messages';
- import { SendEmailIcon } from '$lib/icons';
+ import { ArrowDownIcon, SendEmailIcon } from '$lib/icons';
import { z } from 'zod/v4';
import type { SignalFormValues } from '$lib/types/notification-providers';
import ProviderFormWrapper from './ProviderFormWrapper.svelte';
@@ -15,7 +16,7 @@
values: SignalFormValues;
disabled?: boolean;
isTesting?: boolean;
- onTest?: () => void;
+ onTest?: (testType?: string) => void;
}
let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
@@ -32,7 +33,8 @@
recipients: z.string(),
disableTls: z.boolean(),
eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean()
+ eventContainerUpdate: z.boolean(),
+ eventVulnerabilityFound: z.boolean()
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
@@ -220,20 +222,36 @@
providerId="signal"
bind:eventImageUpdate={values.eventImageUpdate}
bind:eventContainerUpdate={values.eventContainerUpdate}
+ bind:eventVulnerabilityFound={values.eventVulnerabilityFound}
{disabled}
/>
{#if onTest}
<div class="pt-2">
- <ArcaneButton
- action="base"
- tone="outline"
- onclick={onTest}
- disabled={disabled || isTesting}
- loading={isTesting}
- icon={SendEmailIcon}
- customLabel={m.notifications_test_notification()}
- />
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ >
+ <ArrowDownIcon class="ml-2 size-4" />
+ </ArcaneButton>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="start">
+ <DropdownMenu.Item onclick={() => onTest()}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_notification()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => onTest('vulnerability-found')}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_vulnerability_notification()}
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
</div>
{/if}
</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/SlackProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/SlackProviderForm.svelte
index 89675e8eb..eece4a921 100644
--- a/frontend/src/routes/(app)/settings/notifications/providers/SlackProviderForm.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/providers/SlackProviderForm.svelte
@@ -1,8 +1,9 @@
<script lang="ts">
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
import { m } from '$lib/paraglide/messages';
- import { SendEmailIcon } from '$lib/icons';
+ import { ArrowDownIcon, SendEmailIcon } from '$lib/icons';
import { z } from 'zod/v4';
import type { SlackFormValues } from '$lib/types/notification-providers';
import ProviderFormWrapper from './ProviderFormWrapper.svelte';
@@ -12,7 +13,7 @@
values: SlackFormValues;
disabled?: boolean;
isTesting?: boolean;
- onTest?: () => void;
+ onTest?: (testType?: string) => void;
}
let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
@@ -28,7 +29,8 @@
channel: z.string(),
threadTs: z.string(),
eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean()
+ eventContainerUpdate: z.boolean(),
+ eventVulnerabilityFound: z.boolean()
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
@@ -146,20 +148,36 @@
providerId="slack"
bind:eventImageUpdate={values.eventImageUpdate}
bind:eventContainerUpdate={values.eventContainerUpdate}
+ bind:eventVulnerabilityFound={values.eventVulnerabilityFound}
{disabled}
/>
{#if onTest}
<div class="pt-2">
- <ArcaneButton
- action="base"
- tone="outline"
- onclick={onTest}
- disabled={disabled || isTesting}
- loading={isTesting}
- icon={SendEmailIcon}
- customLabel={m.notifications_test_notification()}
- />
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ >
+ <ArrowDownIcon class="ml-2 size-4" />
+ </ArcaneButton>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="start">
+ <DropdownMenu.Item onclick={() => onTest()}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_notification()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => onTest('vulnerability-found')}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_vulnerability_notification()}
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
</div>
{/if}
</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/TelegramProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/TelegramProviderForm.svelte
index 1be4ba1bb..52f6780a7 100644
--- a/frontend/src/routes/(app)/settings/notifications/providers/TelegramProviderForm.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/providers/TelegramProviderForm.svelte
@@ -1,11 +1,12 @@
<script lang="ts">
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
import { Label } from '$lib/components/ui/label';
import Textarea from '$lib/components/ui/textarea/textarea.svelte';
import { m } from '$lib/paraglide/messages';
- import { SendEmailIcon } from '$lib/icons';
+ import { ArrowDownIcon, SendEmailIcon } from '$lib/icons';
import { z } from 'zod/v4';
import type { TelegramFormValues } from '$lib/types/notification-providers';
import ProviderFormWrapper from './ProviderFormWrapper.svelte';
@@ -15,7 +16,7 @@
values: TelegramFormValues;
disabled?: boolean;
isTesting?: boolean;
- onTest?: () => void;
+ onTest?: (testType?: string) => void;
}
let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
@@ -29,7 +30,8 @@
notification: z.boolean(),
title: z.string(),
eventImageUpdate: z.boolean(),
- eventContainerUpdate: z.boolean()
+ eventContainerUpdate: z.boolean(),
+ eventVulnerabilityFound: z.boolean()
})
.superRefine((d, ctx) => {
if (!d.enabled) return;
@@ -126,20 +128,36 @@
providerId="telegram"
bind:eventImageUpdate={values.eventImageUpdate}
bind:eventContainerUpdate={values.eventContainerUpdate}
+ bind:eventVulnerabilityFound={values.eventVulnerabilityFound}
{disabled}
/>
{#if onTest}
<div class="pt-2">
- <ArcaneButton
- action="base"
- tone="outline"
- onclick={onTest}
- disabled={disabled || isTesting}
- loading={isTesting}
- icon={SendEmailIcon}
- customLabel={m.notifications_test_notification()}
- />
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ >
+ <ArrowDownIcon class="ml-2 size-4" />
+ </ArcaneButton>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="start">
+ <DropdownMenu.Item onclick={() => onTest()}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_notification()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => onTest('vulnerability-found')}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_test_vulnerability_notification()}
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
</div>
{/if}
</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/security/+page.svelte b/frontend/src/routes/(app)/settings/security/+page.svelte
index 81c2e7b97..c0d98c7ec 100644
--- a/frontend/src/routes/(app)/settings/security/+page.svelte
+++ b/frontend/src/routes/(app)/settings/security/+page.svelte
@@ -32,6 +32,7 @@
.min(15, m.security_session_timeout_min())
.max(1440, m.security_session_timeout_max()),
authPasswordPolicy: z.enum(['basic', 'standard', 'strong']),
+ trivyImage: z.string(),
oidcEnabled: z.boolean(),
oidcMergeAccounts: z.boolean(),
oidcSkipTlsVerify: z.boolean(),
@@ -62,6 +63,7 @@
authLocalEnabled: currentSettings.authLocalEnabled,
authSessionTimeout: currentSettings.authSessionTimeout,
authPasswordPolicy: currentSettings.authPasswordPolicy,
+ trivyImage: currentSettings.trivyImage,
oidcEnabled: currentSettings.oidcEnabled,
oidcMergeAccounts: currentSettings.oidcMergeAccounts,
oidcSkipTlsVerify: currentSettings.oidcSkipTlsVerify,
@@ -85,6 +87,7 @@
authLocalEnabled: ($settingsStore || data.settings!).authLocalEnabled,
authSessionTimeout: ($settingsStore || data.settings!).authSessionTimeout,
authPasswordPolicy: ($settingsStore || data.settings!).authPasswordPolicy,
+ trivyImage: ($settingsStore || data.settings!).trivyImage,
oidcEnabled: ($settingsStore || data.settings!).oidcEnabled,
oidcMergeAccounts: ($settingsStore || data.settings!).oidcMergeAccounts,
oidcSkipTlsVerify: ($settingsStore || data.settings!).oidcSkipTlsVerify,
@@ -107,6 +110,7 @@
$formInputs.authLocalEnabled.value !== currentSettings.authLocalEnabled ||
$formInputs.authSessionTimeout.value !== currentSettings.authSessionTimeout ||
$formInputs.authPasswordPolicy.value !== currentSettings.authPasswordPolicy ||
+ $formInputs.trivyImage.value !== currentSettings.trivyImage ||
$formInputs.oidcEnabled.value !== currentSettings.oidcEnabled ||
$formInputs.oidcMergeAccounts.value !== currentSettings.oidcMergeAccounts ||
$formInputs.oidcSkipTlsVerify.value !== currentSettings.oidcSkipTlsVerify ||
@@ -145,6 +149,7 @@
authLocalEnabled: formData.authLocalEnabled,
authSessionTimeout: formData.authSessionTimeout,
authPasswordPolicy: formData.authPasswordPolicy,
+ trivyImage: formData.trivyImage,
oidcEnabled: formData.oidcEnabled,
oidcMergeAccounts: formData.oidcMergeAccounts,
oidcSkipTlsVerify: formData.oidcSkipTlsVerify,
@@ -574,6 +579,31 @@
</div>
</div>
</div>
+
+ <!-- Vulnerability Scanning Section -->
+ <div class="space-y-4">
+ <h3 class="text-lg font-medium">{m.security_vulnerability_scanning_heading()}</h3>
+ <div class="bg-card rounded-lg border shadow-sm">
+ <div class="space-y-6 p-6">
+ <div class="grid gap-4 md:grid-cols-[1fr_1.5fr] md:gap-8">
+ <div>
+ <Label class="text-base">{m.security_trivy_image_label()}</Label>
+ <p class="text-muted-foreground mt-1 text-sm">{m.security_trivy_image_description()}</p>
+ <p class="text-muted-foreground mt-2 text-xs">{m.security_trivy_image_note()}</p>
+ </div>
+ <div class="max-w-xs">
+ <TextInputWithLabel
+ bind:value={$formInputs.trivyImage.value}
+ error={$formInputs.trivyImage.error}
+ label={m.security_trivy_image_label()}
+ placeholder="ghcr.io/aquasecurity/trivy:latest"
+ type="text"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
</fieldset>
{/snippet}
{#snippet additionalContent()}
diff --git a/go.work.sum b/go.work.sum
index 08a5f4ee7..236d3e922 100644
--- a/go.work.sum
+++ b/go.work.sum
@@ -500,6 +500,8 @@ github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6 h1:pnnLy
github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6/go.mod h1:39R/xuhNgVhi+K0/zst4TLrJrVmbm6LVgl4A0+ZFS5M=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
+github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
+github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/sylabs/sif/v2 v2.22.0 h1:Y+xXufp4RdgZe02SR3nWEg7S6q4tPWN237WHYzkDSKA=
diff --git a/package.json b/package.json
index c87c35cd4..28edd715a 100644
--- a/package.json
+++ b/package.json
@@ -11,6 +11,16 @@
"email-templates"
],
"scripts": {
- "preinstall": "npx only-allow pnpm"
+ "preinstall": "npx only-allow pnpm",
+ "prepare": "husky"
+ },
+ "lint-staged": {
+ "*": [
+ "sh -c 'just format all --check'"
+ ]
+ },
+ "devDependencies": {
+ "husky": "^9.1.7",
+ "lint-staged": "^16.2.7"
}
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e60508c54..14281ef2e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -11,10 +11,19 @@ overrides:
cookie: ^0.7.0
next: ^16.1.5
undici: ^6.23.0
+ vite: ^8.0.0-beta.12
+ '@sveltejs/vite-plugin-svelte': ^7.0.0-next.0
importers:
- .: {}
+ .:
+ devDependencies:
+ husky:
+ specifier: ^9.1.7
+ version: 9.1.7
+ lint-staged:
+ specifier: ^16.2.7
+ version: 16.2.7
email-templates:
dependencies:
@@ -57,10 +66,10 @@ importers:
version: 3.21.0
'@sveltejs/adapter-static':
specifier: ^3.0.10
'@sveltejs/kit':
specifier: ^2.49.5
'@tanstack/table-core':
specifier: ^8.21.3
version: 8.21.3
@@ -117,11 +126,11 @@ importers:
specifier: ^0.1.3
version: 0.1.3
'@sveltejs/vite-plugin-svelte':
- specifier: ^6.2.4
+ specifier: ^7.0.0-next.0
'@tailwindcss/vite':
specifier: ^4.1.18
'@types/bytes':
specifier: ^3.1.5
version: 3.1.5
@@ -133,7 +142,7 @@ importers:
version: 25.0.10
bits-ui:
specifier: ^2.15.4
bytes:
specifier: ^3.1.2
version: 3.1.2
@@ -142,10 +151,7 @@ importers:
version: 2.1.1
formsnap:
specifier: ^2.0.1
- husky:
- specifier: ^9.1.7
- version: 9.1.7
i18n-unused:
specifier: ^0.19.0
version: 0.19.0
@@ -155,9 +161,6 @@ importers:
knip:
specifier: ^5.82.1
version: 5.82.1(@types/[email protected])([email protected])
- lint-staged:
- specifier: ^16.2.7
- version: 16.2.7
mode-watcher:
specifier: ^1.1.0
version: 1.1.0([email protected])
@@ -166,7 +169,7 @@ importers:
version: 1.0.2([email protected])
runed:
specifier: ^0.37.0
svelte-check:
specifier: ^4.3.5
@@ -175,10 +178,10 @@ importers:
version: 1.0.7([email protected])
svelte-toolbelt:
specifier: ^0.10.6
sveltekit-superforms:
specifier: ^2.29.1
tailwind-merge:
specifier: ^3.4.0
version: 3.4.0
@@ -204,11 +207,11 @@ importers:
specifier: 1.0.0-next.7
version: 1.0.0-next.7([email protected])
vite:
- specifier: ^7.3.1
+ specifier: ^8.0.0-beta.12
vite-plugin-devtools-json:
specifier: ^1.0.0
zod:
specifier: ^4.3.6
version: 4.3.6
@@ -1175,6 +1178,13 @@ packages:
cpu: [x64]
os: [win32]
+ '@oxc-project/[email protected]':
+ resolution: {integrity: sha512-4vYtWXMnXM6EaweCxbJ6bISAhkNHeN33SihvuX3wrpqaSJA4ZEoW35i9mSvE74+GDf1yTeVE+aEHA+WBpjDk/g==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+
+ '@oxc-project/[email protected]':
+ resolution: {integrity: sha512-m6RebKHIRsax2iCwVpYW2ErQwa4ywHJrE4sCK3/8JK8ZZAWOKXaRJFl/uP51gaVyyXlaS4+chU1nSCdzYf6QqQ==}
+
'@oxc-project/[email protected]':
resolution: {integrity: sha512-LLDEhXB7g1m5J+woRSgfKsFPS3LhR9xRhTeIoEBm5WrkwMxn6eZ0Ld0c0K5eHB57ChZX6I3uSmmLjZ8pcjlRcw==}
@@ -1455,130 +1465,85 @@ packages:
peerDependencies:
react: ^18.0 || ^19.0 || ^19.0.0-rc
- '@rollup/[email protected]':
- resolution: {integrity: sha512-9R0DM/ykwfGIlNu6+2U09ga0WXeZ9MRC2Ter8jnz8415VbuIykVuc6bhdrbORFZANDmTDvq26mJrEVTl8TdnDg==}
- cpu: [arm]
- os: [android]
-
- '@rollup/[email protected]':
- resolution: {integrity: sha512-eFZCb1YUqhTysgW3sj/55du5cG57S7UTNtdMjCW7LwVcj3dTTcowCsC8p7uBdzKsZYa8J7IDE8lhMI+HX1vQvg==}
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-0T1k9FinuBZ/t7rZ8jN6OpUKPnUjNdYHoj/cESWrQ3ZraAJ4OMm6z7QjSfCxqj8mOp9kTKc1zHK3kGz5vMu+nQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [android]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-p3grE2PHcQm2e8PSGZdzIhCKbMCw/xi9XvMPErPhwO17vxtvCN5FEA2mSLgmKlCjHGMQTP6phuQTYWUnKewwGg==}
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-JWWLzvcmc/3pe7qdJqPpuPk91SoE/N+f3PcWx/6ZwuyDVyungAEJPvKm/eEldiDdwTmaEzWfIR+HORxYWrCi1A==}
+ engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [darwin]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-rDUjG25C9qoTm+e02Esi+aqTKSBYwVTaoS1wxcN47/Luqef57Vgp96xNANwt5npq9GDxsH7kXxNkJVEsWEOEaQ==}
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-MTakBxfx3tde5WSmbHxuqlDsIW0EzQym+PJYGF4P6lG2NmKzi128OGynoFUqoD5ryCySEY85dug4v+LWGBElIw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [darwin]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-+JiU7Jbp5cdxekIgdte0jfcu5oqw4GCKr6i3PJTlXTCU5H5Fvtkpbs4XJHRmWNXF+hKmn4v7ogI5OQPaupJgOg==}
- cpu: [arm64]
- os: [freebsd]
-
- '@rollup/[email protected]':
- resolution: {integrity: sha512-V5xC1tOVWtLLmr3YUk2f6EJK4qksksOYiz/TCsFHu/R+woubcLWdC9nZQmwjOAbmExBIVKsm1/wKmEy4z4u4Bw==}
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-jje3oopyOLs7IwfvXoS6Lxnmie5JJO7vW29fdGFu5YGY1EDbVDhD+P9vDihqS5X6fFiqL3ZQZCMBg6jyHkSVww==}
+ engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [freebsd]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-Rn3n+FUk2J5VWx+ywrG/HGPTD9jXNbicRtTM11e/uorplArnXZYsVifnPPqNNP5BsO3roI4n8332ukpY/zN7rQ==}
- cpu: [arm]
- os: [linux]
-
- '@rollup/[email protected]':
- resolution: {integrity: sha512-grPNWydeKtc1aEdrJDWk4opD7nFtQbMmV7769hiAaYyUKCT1faPRm2av8CX1YJsZ4TLAZcg9gTR1KvEzoLjXkg==}
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-A0n8P3hdLAaqzSFrQoA42p23ZKBYQOw+8EH5r15Sa9X1kD9/JXe0YT2gph2QTWvdr0CVK2BOXiK6ENfy6DXOag==}
+ engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-a59mwd1k6x8tXKcUxSyISiquLwB5pX+fJW9TkWU46lCqD/GRDe9uDN31jrMmVP3feI3mhAdvcCClhV8V5MhJFQ==}
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-kWXkoxxarYISBJ4bLNf5vFkEbb4JvccOwxWDxuK9yee8lg5XA7OpvlTptfRuwEvYcOZf+7VS69Uenpmpyo5Bjw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-puS1MEgWX5GsHSoiAsF0TYrpomdvkaXm0CofIMG5uVkP6IBV+ZO9xhC5YEN49nsgYo1DuuMquF9+7EDBVYu4uA==}
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-Z03/wrqau9Bicfgb3Dbs6SYTHliELk2PM2LpG2nFd+cGupTMF5kanLEcj2vuuJLLhptNyS61rtk7SOZ+lPsTUA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-r3Wv40in+lTsULSb6nnoudVbARdOwb2u5fpeoOAZjFLznp6tDU8kd+GTHmJoqZ9lt6/Sys33KdIHUaQihFcu7g==}
- cpu: [loong64]
- os: [linux]
-
- '@rollup/[email protected]':
- resolution: {integrity: sha512-MR8c0+UxAlB22Fq4R+aQSPBayvYa3+9DrwG/i1TKQXFYEaoW3B5b/rkSRIypcZDdWjWnpcvxbNaAJDcSbJU3Lw==}
- cpu: [loong64]
- os: [linux]
-
- '@rollup/[email protected]':
- resolution: {integrity: sha512-3KhoECe1BRlSYpMTeVrD4sh2Pw2xgt4jzNSZIIPLFEsnQn9gAnZagW9+VqDqAHgm1Xc77LzJOo2LdigS5qZ+gw==}
- cpu: [ppc64]
- os: [linux]
-
- '@rollup/[email protected]':
- resolution: {integrity: sha512-ziR1OuZx0vdYZZ30vueNZTg73alF59DicYrPViG0NEgDVN8/Jl87zkAPu4u6VjZST2llgEUjaiNl9JM6HH1Vdw==}
- cpu: [ppc64]
- os: [linux]
-
- '@rollup/[email protected]':
- resolution: {integrity: sha512-uW0Y12ih2XJRERZ4jAfKamTyIHVMPQnTZcQjme2HMVDAHY4amf5u414OqNYC+x+LzRdRcnIG1YodLrrtA8xsxw==}
- cpu: [riscv64]
- os: [linux]
-
- '@rollup/[email protected]':
- resolution: {integrity: sha512-u9yZ0jUkOED1BFrqu3BwMQoixvGHGZ+JhJNkNKY/hyoEgOwlqKb62qu+7UjbPSHYjiVy8kKJHvXKv5coH4wDeg==}
- cpu: [riscv64]
- os: [linux]
-
- '@rollup/[email protected]':
- resolution: {integrity: sha512-/0PenBCmqM4ZUd0190j7J0UsQ/1nsi735iPRakO8iPciE7BQ495Y6msPzaOmvx0/pn+eJVVlZrNrSh4WSYLxNg==}
- cpu: [s390x]
- os: [linux]
-
- '@rollup/[email protected]':
- resolution: {integrity: sha512-a8G4wiQxQG2BAvo+gU6XrReRRqj+pLS2NGXKm8io19goR+K8lw269eTrPkSdDTALwMmJp4th2Uh0D8J9bEV1vg==}
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-iSXXZsQp08CSilff/DCTFZHSVEpEwdicV3W8idHyrByrcsRDVh9sGC3sev6d8BygSGj3vt8GvUKBPCoyMA4tgQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-bD+zjpFrMpP/hqkfEcnjXWHMw5BIghGisOKPj+2NaNDuVT+8Ds4mPf3XcPHuat1tz89WRL+1wbcxKY3WSbiT7w==}
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-qaj+MFudtdCv9xZo9znFvkgoajLdc+vwf0Kz5N44g+LU5XMe+IsACgn3UG7uTRlCCvhMAGXm1XlpEA5bZBrOcw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-eLXw0dOiqE4QmvikfQ6yjgkg/xDM+MdU9YJuP4ySTibXU0oAvnEWXt7UDJmD4UkYialMfOGFPJnIHSe/kdzPxg==}
- cpu: [x64]
- os: [openbsd]
-
- '@rollup/[email protected]':
- resolution: {integrity: sha512-xzm44KgEP11te3S2HCSyYf5zIzWmx3n8HDCc7EE59+lTcswEWNpvMLfd9uJvVX8LCg9QWG67Xt75AuHn4vgsXw==}
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-U662UnMETyjT65gFmG9ma+XziENrs7BBnENi/27swZPYagubfHRirXHG2oMl+pEax2WvO7Kb9gHZmMakpYqBHQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [openharmony]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-yR6Bl3tMC/gBok5cz/Qi0xYnVbIxGx5Fcf/ca0eB6/6JwOY+SRUcJfI0OpeTpPls7f194as62thCt/2BjxYN8g==}
- cpu: [arm64]
- os: [win32]
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-gekrQ3Q2HiC1T5njGyuUJoGpK/l6B/TNXKed3fZXNf9YRTJn3L5MOZsFBn4bN2+UX+8+7hgdlTcEsexX988G4g==}
+ engines: {node: '>=14.0.0'}
+ cpu: [wasm32]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-3fZBidchE0eY0oFZBnekYCfg+5wAB0mbpCBuofh5mZuzIU/4jIVkbESmd2dOsFNS78b53CYv3OAtwqkZZmU5nA==}
- cpu: [ia32]
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-85y5JifyMgs8m5K2XzR/VDsapKbiFiohl7s5lEj7nmNGO0pkTXE7q6TQScei96BNAsoK7JC3pA7ukA8WRHVJpg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
os: [win32]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-xGGY5pXj69IxKb4yv/POoocPy/qmEGhimy/FoTpTSVju3FYXUQQMFCaZZXJVidsmGxRioZAwpThl/4zX41gRKg==}
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-a4VUQZH7LxGbUJ3qJ/TzQG8HxdHvf+jOnqf7B7oFx1TEBm+j2KNL2zr5SQ7wHkNAcaPevF6gf9tQnVBnC4mD+A==}
+ engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [win32]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-SPEpaL6DX4rmcXtnhdrQYgzQ5W2uW3SCJch88lB2zImhJRhIIK44fkUrgIV/Q8yUNfw5oyZ5vkeQsZLhCb06lw==}
- cpu: [x64]
- os: [win32]
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q==}
'@selderee/[email protected]':
resolution: {integrity: sha512-P33hHGdldxGabLFjPPpaTxVolMrzrcegejx+0GxjrIb9Zv48D8yAIA/QTDR2dFl7Uz7urX8aX6+5bCZslr+gWQ==}
@@ -1651,30 +1616,22 @@ packages:
hasBin: true
peerDependencies:
'@opentelemetry/api': ^1.0.0
- '@sveltejs/vite-plugin-svelte': ^3.0.0 || ^4.0.0-next.1 || ^5.0.0 || ^6.0.0-next.0
+ '@sveltejs/vite-plugin-svelte': ^7.0.0-next.0
svelte: ^4.0.0 || ^5.0.0-next.0
typescript: ^5.3.3
- vite: ^5.0.3 || ^6.0.0 || ^7.0.0-beta.0
+ vite: ^8.0.0-beta.12
peerDependenciesMeta:
'@opentelemetry/api':
optional: true
typescript:
optional: true
- '@sveltejs/[email protected]':
- resolution: {integrity: sha512-TZzRTcEtZffICSAoZGkPSl6Etsj2torOVrx6Uw0KpXxrec9Gg6jFWQ60Q3+LmNGfZSxHRCZL7vXVZIWmuV50Ig==}
+ '@sveltejs/[email protected]':
+ resolution: {integrity: sha512-S/QeWT/jtA6scSrDF2nxNKjCqLu0eszZGayJYfqAipYbmt8JM/2dmHVubliikqos8LBeuxRvC14p3GVZMQwoRw==}
engines: {node: ^20.19 || ^22.12 || >=24}
peerDependencies:
- '@sveltejs/vite-plugin-svelte': ^6.0.0-next.0
- svelte: ^5.0.0
- vite: ^6.3.0 || ^7.0.0
-
- '@sveltejs/[email protected]':
- resolution: {integrity: sha512-ou/d51QSdTyN26D7h6dSpusAKaZkAiGM55/AKYi+9AGZw7q85hElbjK3kEyzXHhLSnRISHOYzVge6x0jRZ7DXA==}
- engines: {node: ^20.19 || ^22.12 || >=24}
- peerDependencies:
- svelte: ^5.0.0
- vite: ^6.3.0 || ^7.0.0
+ svelte: ^5.46.4
+ vite: ^8.0.0-beta.12
resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==}
@@ -1770,7 +1727,7 @@ packages:
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-jVA+/UpKL1vRLg6Hkao5jldawNmRo7mQYrZtNHMIVpLfLhDml5nMRUo/8MwoX2vNXvnaXNNMedrMfMugAVX1nA==}
peerDependencies:
- vite: ^5.2.0 || ^6 || ^7
+ vite: ^8.0.0-beta.12
'@tanstack/[email protected]':
resolution: {integrity: sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==}
@@ -2375,7 +2332,6 @@ packages:
resolution: {integrity: sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw==}
engines: {node: 20 || >=22}
- deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
hasBin: true
@@ -2571,70 +2527,140 @@ packages:
cpu: [arm64]
os: [android]
+ resolution: {integrity: sha512-HXJF3x8w9nQ4jbXRiNppBCqeZPIAfUo8zE/kOEGbW5NZvGc/K7nMxbhIr+YlFlHW5mpbg/YFPdbnCh1wAXCKFg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [android]
+
resolution: {integrity: sha512-ylTcDJBN3Hp21TdhRT5zBOIi73P6/W0qwvlFEk22fkdXchtNTOU4Qc37SkzV+EKYxLouZ6M4LG9NfZ1qkhhBWA==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [darwin]
+ resolution: {integrity: sha512-02uTEqf3vIfNMq3h/z2cJfcOXnQ0GRwQrkmPafhueLb2h7mqEidiCzkE4gBMEH65abHRiQvhdcQ+aP0D0g67sg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [darwin]
+
resolution: {integrity: sha512-oBZgKchomuDYxr7ilwLcyms6BCyLn0z8J0+ZZmfpjwg9fRVZIR5/GMXd7r9RH94iDhld3UmSjBM6nXWM2TfZTQ==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [darwin]
+ resolution: {integrity: sha512-1ObhyoCY+tGxtsz1lSx5NXCj3nirk0Y0kB/g8B8DT+sSx4G9djitg9ejFnjb3gJNWo7qXH4DIy2SUHvpoFwfTA==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [darwin]
+
resolution: {integrity: sha512-c2bH6xTrf4BDpK8MoGG4Bd6zAMZDAXS569UxCAGcA7IKbHNMlhGQ89eRmvpIUGfKWNVdbhSbkQaWhEoMGmGslA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [freebsd]
+ resolution: {integrity: sha512-1RINmQKAItO6ISxYgPwszQE1BrsVU5aB45ho6O42mu96UiZBxEXsuQ7cJW4zs4CEodPUioj/QrXW1r9pLUM74A==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [freebsd]
+
resolution: {integrity: sha512-eVdpxh4wYcm0PofJIZVuYuLiqBIakQ9uFZmipf6LF/HRj5Bgm0eb3qL/mr1smyXIS1twwOxNWndd8z0E374hiA==}
engines: {node: '>= 12.0.0'}
cpu: [arm]
os: [linux]
+ resolution: {integrity: sha512-OOCm2//MZJ87CdDK62rZIu+aw9gBv4azMJuA8/KB74wmfS3lnC4yoPHm0uXZ/dvNNHmnZnB8XLAZzObeG0nS1g==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm]
+ os: [linux]
+
resolution: {integrity: sha512-UK65WJAbwIJbiBFXpxrbTNArtfuznvxAJw4Q2ZGlU8kPeDIWEX1dg3rn2veBVUylA2Ezg89ktszWbaQnxD/e3A==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ resolution: {integrity: sha512-WKyLWztD71rTnou4xAD5kQT+982wvca7E6QoLpoawZ1gP9JM0GJj4Tp5jMUh9B3AitHbRZ2/H3W5xQmdEOUlLg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
+
resolution: {integrity: sha512-5Vh9dGeblpTxWHpOx8iauV02popZDsCYMPIgiuw97OJ5uaDsL86cnqSFs5LZkG3ghHoX5isLgWzMs+eD1YzrnA==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
+ resolution: {integrity: sha512-mVZ7Pg2zIbe3XlNbZJdjs86YViQFoJSpc41CbVmKBPiGmC4YrfeOyz65ms2qpAobVd7WQsbW4PdsSJEMymyIMg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
+
resolution: {integrity: sha512-Cfd46gdmj1vQ+lR6VRTTadNHu6ALuw2pKR9lYq4FnhvgBc4zWY1EtZcAc6EffShbb1MFrIPfLDXD6Xprbnni4w==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ resolution: {integrity: sha512-xGlFWRMl+0KvUhgySdIaReQdB4FNudfUTARn7q0hh/V67PVGCs3ADFjw+6++kG1RNd0zdGRlEKa+T13/tQjPMA==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
+
resolution: {integrity: sha512-XJaLUUFXb6/QG2lGIW6aIk6jKdtjtcffUT0NKvIqhSBY3hh9Ch+1LCeH80dR9q9LBjG3ewbDjnumefsLsP6aiA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
+ resolution: {integrity: sha512-eowF8PrKHw9LpoZii5tdZwnBcYDxRw2rRCyvAXLi34iyeYfqCQNA9rmUM0ce62NlPhCvof1+9ivRaTY6pSKDaA==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
+
resolution: {integrity: sha512-FZn+vaj7zLv//D/192WFFVA0RgHawIcHqLX9xuWiQt7P0PtdFEVaxgF9rjM/IRYHQXNnk61/H/gb2Ei+kUQ4xQ==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [win32]
+ resolution: {integrity: sha512-aJReEbSEQzx1uBlQizAOBSjcmr9dCdL3XuC/6HLXAxmtErsj2ICo5yYggg1qOODQMtnjNQv2UHb9NpOuFtYe4w==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [win32]
+
resolution: {integrity: sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [win32]
+ resolution: {integrity: sha512-I9aiFrbd7oYHwlnQDqr1Roz+fTz61oDDJX7n9tYF9FJymH1cIN1DtKw3iYt6b8WZgEjoNwVSncwF4wx/ZedMhw==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [win32]
+
resolution: {integrity: sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ==}
engines: {node: '>= 12.0.0'}
+ resolution: {integrity: sha512-l51N2r93WmGUye3WuFoN5k10zyvrVs0qfKBhyC5ogUQ6Ew6JUSswh78mbSO+IU3nTWsyOArqPCcShdQSadghBQ==}
+ engines: {node: '>= 12.0.0'}
+
resolution: {integrity: sha512-lDIj4RnYmK7/kXMya+qJsmkRFkGolciXjrsZ6PC25GdTfWOAWetR0ZbsNXRAj1EHHImRSalc+whZFg56F5DVow==}
engines: {node: '>=20.17'}
@@ -3075,9 +3101,9 @@ packages:
resolution: {integrity: sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==}
- resolution: {integrity: sha512-wDv/Ht1BNHB4upNbK74s9usvl7hObDnvVzknxqY/E/O3X6rW1U1rV1aENEfJ54eFZDTNo7zv1f5N4edCluH7+A==}
- engines: {node: '>=18.0.0', npm: '>=8.0.0'}
+ resolution: {integrity: sha512-Po/YZECDOqVXjIXrtC5h++a5NLvKAQNrd9ggrIG3sbDfGO5BqTUsrI6l8zdniKRp3r5Tp/2JTrXqx4GIguFCMw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
@@ -3540,17 +3566,18 @@ packages:
resolution: {integrity: sha512-MobvwqX76Vqt/O4AbnNMNWoXWGrKUqZbphCUle/J2KXH82yKQiunOeKnz/nqEPosPsoWWPP9FtNuPBSYpiiwkw==}
peerDependencies:
- vite: ^5.0.0 || ^6.0.0 || ^7.0.0
+ vite: ^8.0.0-beta.12
- resolution: {integrity: sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==}
+ resolution: {integrity: sha512-7s/rfpYOAo7WUHh9irzaGjhhKb12hGv0BpDegAMV5A391wdyvM45WtX6VMV7hvEtZF2j/QtpDpR6ldXI3GgARQ==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
peerDependencies:
'@types/node': ^20.19.0 || >=22.12.0
+ '@vitejs/devtools': ^0.0.0-alpha.24
+ esbuild: ^0.27.0
jiti: '>=1.21.0'
less: ^4.0.0
- lightningcss: ^1.21.0
sass: ^1.70.0
sass-embedded: ^1.70.0
stylus: '>=0.54.8'
@@ -3561,12 +3588,14 @@ packages:
peerDependenciesMeta:
'@types/node':
optional: true
+ '@vitejs/devtools':
+ optional: true
+ esbuild:
+ optional: true
jiti:
optional: true
less:
optional: true
- lightningcss:
- optional: true
sass:
optional: true
sass-embedded:
@@ -3585,7 +3614,7 @@ packages:
resolution: {integrity: sha512-B/Fegf3i8zh0yFbpzZ21amWzHmuNlLlmJT6n7bu5e+pCHUKQIfXSYokrqOBGEMMe9UG2sostKQF9mml/vYaWJQ==}
peerDependencies:
- vite: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0-beta.0
+ vite: ^8.0.0-beta.12
peerDependenciesMeta:
vite:
optional: true
@@ -4330,6 +4359,10 @@ snapshots:
'@oxc-parser/[email protected]':
optional: true
+ '@oxc-project/[email protected]': {}
+
+ '@oxc-project/[email protected]': {}
+
'@oxc-project/[email protected]': {}
'@oxc-resolver/[email protected]':
@@ -4544,80 +4577,48 @@ snapshots:
dependencies:
react: 19.2.4
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
+ '@rolldown/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rolldown/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rolldown/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rolldown/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rolldown/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rolldown/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rolldown/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rolldown/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rolldown/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rolldown/[email protected]':
optional: true
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
+ '@rolldown/[email protected]':
+ dependencies:
+ '@napi-rs/wasm-runtime': 1.1.1
optional: true
- '@rollup/[email protected]':
+ '@rolldown/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rolldown/[email protected]':
optional: true
- '@rollup/[email protected]':
- optional: true
+ '@rolldown/[email protected]': {}
'@selderee/[email protected]':
dependencies:
@@ -4698,15 +4699,15 @@ snapshots:
dependencies:
acorn: 8.15.0
dependencies:
dependencies:
'@standard-schema/spec': 1.1.0
'@sveltejs/acorn-typescript': 1.0.8([email protected])
'@types/cookie': 0.6.0
acorn: 8.15.0
cookie: 0.7.2
@@ -4719,26 +4720,18 @@ snapshots:
set-cookie-parser: 2.7.2
sirv: 3.0.2
svelte: 5.50.0
optionalDependencies:
typescript: 5.9.3
dependencies:
- obug: 2.1.1
- svelte: 5.50.0
-
- dependencies:
deepmerge: 4.3.1
magic-string: 0.30.21
obug: 2.1.1
svelte: 5.50.0
dependencies:
@@ -4809,12 +4802,12 @@ snapshots:
'@tailwindcss/oxide-win32-arm64-msvc': 4.1.18
'@tailwindcss/oxide-win32-x64-msvc': 4.1.18
dependencies:
'@tailwindcss/node': 4.1.18
'@tailwindcss/oxide': 4.1.18
tailwindcss: 4.1.18
'@tanstack/[email protected]': {}
@@ -4988,15 +4981,15 @@ snapshots:
dependencies:
require-from-string: 2.0.2
dependencies:
'@floating-ui/core': 1.7.3
'@floating-ui/dom': 1.7.4
'@internationalized/date': 3.11.0
esm-env: 1.2.2
svelte: 5.50.0
tabbable: 6.4.0
transitivePeerDependencies:
- '@sveltejs/kit'
@@ -5351,6 +5344,7 @@ snapshots:
'@esbuild/win32-arm64': 0.27.2
'@esbuild/win32-ia32': 0.27.2
'@esbuild/win32-x64': 0.27.2
+ optional: true
@@ -5418,11 +5412,11 @@ snapshots:
dependencies:
fd-package-json: 2.0.0
dependencies:
svelte: 5.50.0
svelte-toolbelt: 0.5.0([email protected])
dependencies:
@@ -5691,36 +5685,69 @@ snapshots:
optional: true
+ optional: true
+
optional: true
+ optional: true
+
optional: true
+ optional: true
+
optional: true
+ optional: true
+
optional: true
+ optional: true
+
optional: true
+ optional: true
+
optional: true
+ optional: true
+
optional: true
+ optional: true
+
optional: true
+ optional: true
+
optional: true
+ optional: true
+
optional: true
+ optional: true
+
dependencies:
detect-libc: 2.1.2
@@ -5737,6 +5764,22 @@ snapshots:
lightningcss-win32-arm64-msvc: 1.30.2
lightningcss-win32-x64-msvc: 1.30.2
+ dependencies:
+ detect-libc: 2.1.2
+ optionalDependencies:
+ lightningcss-android-arm64: 1.31.1
+ lightningcss-darwin-arm64: 1.31.1
+ lightningcss-darwin-x64: 1.31.1
+ lightningcss-freebsd-x64: 1.31.1
+ lightningcss-linux-arm-gnueabihf: 1.31.1
+ lightningcss-linux-arm64-gnu: 1.31.1
+ lightningcss-linux-arm64-musl: 1.31.1
+ lightningcss-linux-x64-gnu: 1.31.1
+ lightningcss-linux-x64-musl: 1.31.1
+ lightningcss-win32-arm64-msvc: 1.31.1
+ lightningcss-win32-x64-msvc: 1.31.1
+
dependencies:
commander: 14.0.3
@@ -6173,36 +6216,24 @@ snapshots:
dependencies:
- '@types/estree': 1.0.8
+ '@oxc-project/types': 0.112.0
+ '@rolldown/pluginutils': 1.0.0-rc.3
optionalDependencies:
- '@rollup/rollup-android-arm-eabi': 4.55.1
- '@rollup/rollup-android-arm64': 4.55.1
- '@rollup/rollup-darwin-arm64': 4.55.1
- '@rollup/rollup-darwin-x64': 4.55.1
- '@rollup/rollup-freebsd-arm64': 4.55.1
- '@rollup/rollup-freebsd-x64': 4.55.1
- '@rollup/rollup-linux-arm-gnueabihf': 4.55.1
- '@rollup/rollup-linux-arm-musleabihf': 4.55.1
- '@rollup/rollup-linux-arm64-gnu': 4.55.1
- '@rollup/rollup-linux-arm64-musl': 4.55.1
- '@rollup/rollup-linux-loong64-gnu': 4.55.1
- '@rollup/rollup-linux-loong64-musl': 4.55.1
- '@rollup/rollup-linux-ppc64-gnu': 4.55.1
- '@rollup/rollup-linux-ppc64-musl': 4.55.1
- '@rollup/rollup-linux-riscv64-gnu': 4.55.1
- '@rollup/rollup-linux-riscv64-musl': 4.55.1
- '@rollup/rollup-linux-s390x-gnu': 4.55.1
- '@rollup/rollup-linux-x64-gnu': 4.55.1
- '@rollup/rollup-linux-x64-musl': 4.55.1
- '@rollup/rollup-openbsd-x64': 4.55.1
- '@rollup/rollup-openharmony-arm64': 4.55.1
- '@rollup/rollup-win32-arm64-msvc': 4.55.1
- '@rollup/rollup-win32-ia32-msvc': 4.55.1
- '@rollup/rollup-win32-x64-gnu': 4.55.1
- '@rollup/rollup-win32-x64-msvc': 4.55.1
- fsevents: 2.3.3
+ '@rolldown/binding-android-arm64': 1.0.0-rc.3
+ '@rolldown/binding-darwin-arm64': 1.0.0-rc.3
+ '@rolldown/binding-darwin-x64': 1.0.0-rc.3
+ '@rolldown/binding-freebsd-x64': 1.0.0-rc.3
+ '@rolldown/binding-linux-arm-gnueabihf': 1.0.0-rc.3
+ '@rolldown/binding-linux-arm64-gnu': 1.0.0-rc.3
+ '@rolldown/binding-linux-arm64-musl': 1.0.0-rc.3
+ '@rolldown/binding-linux-x64-gnu': 1.0.0-rc.3
+ '@rolldown/binding-linux-x64-musl': 1.0.0-rc.3
+ '@rolldown/binding-openharmony-arm64': 1.0.0-rc.3
+ '@rolldown/binding-wasm32-wasi': 1.0.0-rc.3
+ '@rolldown/binding-win32-arm64-msvc': 1.0.0-rc.3
+ '@rolldown/binding-win32-x64-msvc': 1.0.0-rc.3
dependencies:
@@ -6228,23 +6259,23 @@ snapshots:
esm-env: 1.2.2
svelte: 5.50.0
dependencies:
dequal: 2.0.3
esm-env: 1.2.2
lz-string: 1.5.0
svelte: 5.50.0
optionalDependencies:
dependencies:
dequal: 2.0.3
esm-env: 1.2.2
lz-string: 1.5.0
svelte: 5.50.0
optionalDependencies:
zod: 4.3.6
@@ -6456,10 +6487,10 @@ snapshots:
runed: 0.28.0([email protected])
svelte: 5.50.0
dependencies:
clsx: 2.1.1
style-to-object: 1.0.11
svelte: 5.50.0
transitivePeerDependencies:
@@ -6503,9 +6534,9 @@ snapshots:
magic-string: 0.30.21
zimmerframe: 1.1.4
dependencies:
devalue: 5.6.2
memoize-weak: 1.0.2
svelte: 5.50.0
@@ -6713,31 +6744,32 @@ snapshots:
'@types/unist': 3.0.3
vfile-message: 4.0.3
dependencies:
uuid: 11.1.0
dependencies:
- esbuild: 0.27.2
+ '@oxc-project/runtime': 0.112.0
fdir: 6.5.0([email protected])
+ lightningcss: 1.31.1
picomatch: 4.0.3
postcss: 8.5.6
- rollup: 4.55.1
+ rolldown: 1.0.0-rc.3
tinyglobby: 0.2.15
optionalDependencies:
'@types/node': 25.0.10
+ esbuild: 0.27.2
fsevents: 2.3.3
jiti: 2.6.1
- lightningcss: 1.30.2
terser: 5.44.0
tsx: 4.21.0
yaml: 2.8.1
optionalDependencies:
dependencies:
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 0553c1e0e..c94d657ab 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -15,3 +15,5 @@ overrides:
cookie: ^0.7.0
next: ^16.1.5
undici: ^6.23.0
+ vite: ^8.0.0-beta.12
+ '@sveltejs/vite-plugin-svelte': ^7.0.0-next.0
diff --git a/tests/spec/settings-notifications.spec.ts b/tests/spec/settings-notifications.spec.ts
index bfb41229b..e35154d05 100644
--- a/tests/spec/settings-notifications.spec.ts
+++ b/tests/spec/settings-notifications.spec.ts
@@ -91,7 +91,8 @@ test.describe('Notification settings', () => {
await page.getByPlaceholder('Enter webhook ID').fill('123456789');
await page.getByPlaceholder('Enter webhook token').fill('abc-def-ghi');
- await page.getByRole('button', { name: 'Test Provider' }).click();
+ await page.locator('[data-dropdown-menu-trigger]').filter({ hasText: 'Test Provider' }).click();
+ await page.getByRole('menuitem', { name: 'Test Provider', exact: true }).click();
const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });
if (await saveAndTestButton.isVisible().catch(() => false)) {
@@ -111,7 +112,8 @@ test.describe('Notification settings', () => {
// Slack OAuth token (xoxb- or xoxp- format)
await page.getByPlaceholder('xoxb-... or xoxp-...').fill('xoxb-123456789012-1234567890123-abcdefghijklmnopqrstuvwx');
- await page.getByRole('button', { name: 'Test Provider' }).click();
+ await page.locator('[data-dropdown-menu-trigger]').filter({ hasText: 'Test Provider' }).click();
+ await page.getByRole('menuitem', { name: 'Test Provider', exact: true }).click();
const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });
if (await saveAndTestButton.isVisible().catch(() => false)) {
@@ -132,7 +134,8 @@ test.describe('Notification settings', () => {
await page.getByPlaceholder('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11').fill('123456:TEST-TOKEN');
await page.getByPlaceholder('@channel, 123456789, @another_channel').fill('123456789');
- await page.getByRole('button', { name: 'Test Provider' }).click();
+ await page.locator('[data-dropdown-menu-trigger]').filter({ hasText: 'Test Provider' }).click();
+ await page.getByRole('menuitem', { name: 'Test Provider', exact: true }).click();
const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });
if (await saveAndTestButton.isVisible().catch(() => false)) {
@@ -151,7 +154,8 @@ test.describe('Notification settings', () => {
await page.getByPlaceholder('https://example.com/webhook').fill('https://example.com/webhook');
- await page.getByRole('button', { name: 'Test Provider' }).click();
+ await page.locator('[data-dropdown-menu-trigger]').filter({ hasText: 'Test Provider' }).click();
+ await page.getByRole('menuitem', { name: 'Test Provider', exact: true }).click();
const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });
if (await saveAndTestButton.isVisible().catch(() => false)) {
@@ -173,7 +177,8 @@ test.describe('Notification settings', () => {
await page.getByRole('textbox', { name: '+' }).fill('+1234567890');
await page.getByRole('textbox', { name: 'Recipients' }).fill('+1987654321');
- await page.getByRole('button', { name: 'Test Provider' }).click();
+ await page.locator('[data-dropdown-menu-trigger]').filter({ hasText: 'Test Provider' }).click();
+ await page.getByRole('menuitem', { name: 'Test Provider', exact: true }).click();
const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });
if (await saveAndTestButton.isVisible().catch(() => false)) {
@@ -193,7 +198,8 @@ test.describe('Notification settings', () => {
await page.getByPlaceholder('ntfy.sh').fill('ntfy.sh');
await page.getByPlaceholder('my-updates').fill('arcane-updates');
- await page.getByRole('button', { name: 'Test Provider' }).click();
+ await page.locator('[data-dropdown-menu-trigger]').filter({ hasText: 'Test Provider' }).click();
+ await page.getByRole('menuitem', { name: 'Test Provider', exact: true }).click();
const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });
if (await saveAndTestButton.isVisible().catch(() => false)) {
diff --git a/types/go.sum b/types/go.sum
index 37cdef6fd..141ab8068 100644
--- a/types/go.sum
+++ b/types/go.sum
@@ -1,4 +1,5 @@
github.com/compose-spec/compose-go/v2 v2.10.1 h1:mFbXobojGRFIVi1UknrvaDAZ+PkJfyjqkA1yseh+vAU=
+github.com/compose-spec/compose-go/v2 v2.10.1/go.mod h1:Ohac1SzhO/4fXXrzWIztIVB6ckmKBv1Nt5Z5mGVESUg=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
@@ -10,6 +11,7 @@ github.com/docker/go-connections v0.6.0/go.mod h1:AahvXYshr6JgfUJGdDCs2b5EZG/vma
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
+github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/mattn/go-shellwords v1.0.12 h1:M2zGm7EW6UQJvDeQxo4T51eKPurbeFbe8WtebGE2xrk=
@@ -23,6 +25,7 @@ github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgr
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
+github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/xhit/go-str2duration/v2 v2.1.0 h1:lxklc02Drh6ynqX+DdPyp5pCKLUQpRT8bp8Ydu2Bstc=
@@ -32,6 +35,7 @@ go.yaml.in/yaml/v4 v4.0.0-rc.3/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfP
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
+golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
diff --git a/types/image/image.go b/types/image/image.go
index b0e9b5035..7ec1a3495 100644
--- a/types/image/image.go
+++ b/types/image/image.go
@@ -7,6 +7,7 @@ import (
"github.com/docker/docker/api/types/image"
containerregistry "github.com/getarcaneapp/arcane/types/containerregistry"
+ "github.com/getarcaneapp/arcane/types/vulnerability"
)
type UpdateInfo struct {
@@ -131,6 +132,11 @@ type Summary struct {
//
// Required: false
UpdateInfo *UpdateInfo `json:"updateInfo,omitempty"`
+
+ // VulnerabilityScan contains the latest vulnerability scan summary for the image.
+ //
+ // Required: false
+ VulnerabilityScan *vulnerability.ScanSummary `json:"vulnerabilityScan,omitempty"`
}
type PruneReport struct {
diff --git a/types/jobschedule/jobschedule.go b/types/jobschedule/jobschedule.go
index 291d30a9d..d9438e20d 100644
--- a/types/jobschedule/jobschedule.go
+++ b/types/jobschedule/jobschedule.go
@@ -14,6 +14,7 @@ type Config struct {
PollingInterval string `json:"pollingInterval"`
ScheduledPruneInterval string `json:"scheduledPruneInterval"`
GitopsSyncInterval string `json:"gitopsSyncInterval"`
+ VulnerabilityScanInterval string `json:"vulnerabilityScanInterval"`
}
// Update is used to update job schedule intervals (in minutes).
@@ -27,6 +28,7 @@ type Update struct {
PollingInterval *string `json:"pollingInterval,omitempty"`
ScheduledPruneInterval *string `json:"scheduledPruneInterval,omitempty"`
GitopsSyncInterval *string `json:"gitopsSyncInterval,omitempty"`
+ VulnerabilityScanInterval *string `json:"vulnerabilityScanInterval,omitempty"`
}
// JobStatus represents the current status and metadata for a background job.
diff --git a/types/meta/job_metadata.go b/types/meta/job_metadata.go
index c4672abeb..30296e456 100644
--- a/types/meta/job_metadata.go
+++ b/types/meta/job_metadata.go
@@ -153,6 +153,24 @@ var jobMetadataRegistry = map[string]JobMetadata{
CanRunManually: false,
Prerequisites: []JobPrerequisiteMetadata{},
},
+ "vulnerability-scan": {
+ ID: "vulnerability-scan",
+ Name: "Vulnerability Scan",
+ Description: "Scans all Docker images for known vulnerabilities using Trivy",
+ Category: "security",
+ SettingsKey: "vulnerabilityScanInterval",
+ EnabledKey: "vulnerabilityScanEnabled",
+ ManagerOnly: false,
+ IsContinuous: false,
+ CanRunManually: true,
+ Prerequisites: []JobPrerequisiteMetadata{
+ {
+ SettingKey: "vulnerabilityScanEnabled",
+ Label: "Scheduled vulnerability scan enabled",
+ SettingsURL: "/settings/security",
+ },
+ },
+ },
}
func GetJobMetadata(jobID string) (JobMetadata, bool) {
diff --git a/types/settings/settings.go b/types/settings/settings.go
index d7672cac0..bdb4d0b9a 100644
--- a/types/settings/settings.go
+++ b/types/settings/settings.go
@@ -112,6 +112,16 @@ type Update struct {
// Required: false
ScheduledPruneBuildCache *string `json:"scheduledPruneBuildCache,omitempty"`
+ // VulnerabilityScanEnabled indicates if scheduled vulnerability scanning is enabled.
+ //
+ // Required: false
+ VulnerabilityScanEnabled *string `json:"vulnerabilityScanEnabled,omitempty"`
+
+ // VulnerabilityScanInterval is the cron expression for scheduled vulnerability scans.
+ //
+ // Required: false
+ VulnerabilityScanInterval *string `json:"vulnerabilityScanInterval,omitempty"`
+
// MaxImageUploadSize is the maximum size for image uploads.
//
// Required: false
@@ -167,6 +177,11 @@ type Update struct {
// Required: false
AuthPasswordPolicy *string `json:"authPasswordPolicy,omitempty"`
+ // TrivyImage overrides the container image used for vulnerability scans.
+ //
+ // Required: false
+ TrivyImage *string `json:"trivyImage,omitempty"`
+
// AuthOidcConfig is deprecated and will be removed in a future release.
//
// Required: false
diff --git a/types/vulnerability/vulnerability.go b/types/vulnerability/vulnerability.go
new file mode 100644
index 000000000..7f89ebcab
--- /dev/null
+++ b/types/vulnerability/vulnerability.go
@@ -0,0 +1,494 @@
+package vulnerability
+
+import (
+ "time"
+)
+
+// Severity represents the severity level of a vulnerability
+type Severity string
+
+const (
+ SeverityUnknown Severity = "UNKNOWN"
+ SeverityLow Severity = "LOW"
+ SeverityMedium Severity = "MEDIUM"
+ SeverityHigh Severity = "HIGH"
+ SeverityCritical Severity = "CRITICAL"
+)
+
+// Vulnerability represents a single vulnerability found in an image
+type Vulnerability struct {
+ // VulnerabilityID is the unique identifier for the vulnerability (e.g., CVE-2021-1234)
+ //
+ // Required: true
+ VulnerabilityID string `json:"vulnerabilityId"`
+
+ // PkgName is the name of the package containing the vulnerability
+ //
+ // Required: true
+ PkgName string `json:"pkgName"`
+
+ // InstalledVersion is the installed version of the vulnerable package
+ //
+ // Required: true
+ InstalledVersion string `json:"installedVersion"`
+
+ // FixedVersion is the version where the vulnerability is fixed (empty if not fixed)
+ //
+ // Required: false
+ FixedVersion string `json:"fixedVersion,omitempty"`
+
+ // Severity is the severity level of the vulnerability
+ //
+ // Required: true
+ Severity Severity `json:"severity"`
+
+ // Title is the title of the vulnerability
+ //
+ // Required: false
+ Title string `json:"title,omitempty"`
+
+ // Description is the description of the vulnerability
+ //
+ // Required: false
+ Description string `json:"description,omitempty"`
+
+ // References is a list of references related to the vulnerability
+ //
+ // Required: false
+ References []string `json:"references,omitempty"`
+
+ // CVSS contains the CVSS score information
+ //
+ // Required: false
+ CVSS *CVSSInfo `json:"cvss,omitempty"`
+
+ // PublishedDate is the date when the vulnerability was published
+ //
+ // Required: false
+ PublishedDate *time.Time `json:"publishedDate,omitempty"`
+
+ // LastModifiedDate is the date when the vulnerability was last modified
+ //
+ // Required: false
+ LastModifiedDate *time.Time `json:"lastModifiedDate,omitempty"`
+}
+
+// VulnerabilityWithImage represents a vulnerability with its source image context
+type VulnerabilityWithImage struct {
+ Vulnerability
+
+ // ImageID is the Docker image ID that contains the vulnerability
+ //
+ // Required: true
+ ImageID string `json:"imageId"`
+
+ // ImageName is the image name with tag (e.g., nginx:latest)
+ //
+ // Required: true
+ ImageName string `json:"imageName"`
+}
+
+// CVSSInfo contains CVSS score information
+type CVSSInfo struct {
+ // V2Score is the CVSS v2 score
+ //
+ // Required: false
+ V2Score float64 `json:"v2Score,omitempty"`
+
+ // V3Score is the CVSS v3 score
+ //
+ // Required: false
+ V3Score float64 `json:"v3Score,omitempty"`
+
+ // V2Vector is the CVSS v2 vector string
+ //
+ // Required: false
+ V2Vector string `json:"v2Vector,omitempty"`
+
+ // V3Vector is the CVSS v3 vector string
+ //
+ // Required: false
+ V3Vector string `json:"v3Vector,omitempty"`
+}
+
+// SeveritySummary contains counts of vulnerabilities by severity
+type SeveritySummary struct {
+ // Critical is the count of critical vulnerabilities
+ //
+ // Required: true
+ Critical int `json:"critical"`
+
+ // High is the count of high severity vulnerabilities
+ //
+ // Required: true
+ High int `json:"high"`
+
+ // Medium is the count of medium severity vulnerabilities
+ //
+ // Required: true
+ Medium int `json:"medium"`
+
+ // Low is the count of low severity vulnerabilities
+ //
+ // Required: true
+ Low int `json:"low"`
+
+ // Unknown is the count of unknown severity vulnerabilities
+ //
+ // Required: true
+ Unknown int `json:"unknown"`
+
+ // Total is the total count of vulnerabilities
+ //
+ // Required: true
+ Total int `json:"total"`
+}
+
+// EnvironmentVulnerabilitySummary contains aggregated vulnerability info for an environment
+type EnvironmentVulnerabilitySummary struct {
+ // TotalImages is the total number of images in the environment
+ //
+ // Required: true
+ TotalImages int `json:"totalImages"`
+
+ // ScannedImages is the number of images with completed scans
+ //
+ // Required: true
+ ScannedImages int `json:"scannedImages"`
+
+ // Summary contains the aggregated severity summary
+ //
+ // Required: false
+ Summary *SeveritySummary `json:"summary,omitempty"`
+}
+
+// ScanResult represents the result of a vulnerability scan
+type ScanResult struct {
+ // ImageID is the Docker image ID that was scanned
+ //
+ // Required: true
+ ImageID string `json:"imageId"`
+
+ // ImageName is the image name with tag (e.g., nginx:latest)
+ //
+ // Required: true
+ ImageName string `json:"imageName"`
+
+ // ScanTime is the timestamp when the scan was performed
+ //
+ // Required: true
+ ScanTime time.Time `json:"scanTime"`
+
+ // Status is the status of the scan (scanning, completed, failed)
+ //
+ // Required: true
+ Status ScanStatus `json:"status"`
+
+ // Summary contains the severity summary of vulnerabilities found
+ //
+ // Required: false
+ Summary *SeveritySummary `json:"summary,omitempty"`
+
+ // Vulnerabilities is the list of vulnerabilities found
+ //
+ // Required: false
+ Vulnerabilities []Vulnerability `json:"vulnerabilities,omitempty"`
+
+ // Error contains the error message if the scan failed
+ //
+ // Required: false
+ Error string `json:"error,omitempty"`
+
+ // Duration is the duration of the scan in milliseconds
+ //
+ // Required: false
+ Duration int64 `json:"duration,omitempty"`
+
+ // ScannerVersion is the version of the scanner used
+ //
+ // Required: false
+ ScannerVersion string `json:"scannerVersion,omitempty"`
+}
+
+// ScanStatus represents the status of a vulnerability scan
+type ScanStatus string
+
+const (
+ ScanStatusPending ScanStatus = "pending"
+ ScanStatusScanning ScanStatus = "scanning"
+ ScanStatusCompleted ScanStatus = "completed"
+ ScanStatusFailed ScanStatus = "failed"
+)
+
+// ScanSummary contains a summary of a vulnerability scan for display in lists
+type ScanSummary struct {
+ // ImageID is the Docker image ID that was scanned
+ //
+ // Required: true
+ ImageID string `json:"imageId"`
+
+ // ScanTime is the timestamp when the scan was performed
+ //
+ // Required: true
+ ScanTime time.Time `json:"scanTime"`
+
+ // Status is the status of the scan
+ //
+ // Required: true
+ Status ScanStatus `json:"status"`
+
+ // Summary contains the severity summary of vulnerabilities found
+ //
+ // Required: false
+ Summary *SeveritySummary `json:"summary,omitempty"`
+
+ // Error contains the error message if the scan failed
+ //
+ // Required: false
+ Error string `json:"error,omitempty"`
+}
+
+// TrivyReport represents the JSON output structure from Trivy scanner
+type TrivyReport struct {
+ SchemaVersion int `json:"SchemaVersion"`
+ ArtifactName string `json:"ArtifactName"`
+ ArtifactType string `json:"ArtifactType"`
+ Metadata TrivyMetadata `json:"Metadata"`
+ Results []TrivyResults `json:"Results"`
+}
+
+// TrivyMetadata contains metadata about the scanned artifact
+type TrivyMetadata struct {
+ OS *TrivyOS `json:"OS,omitempty"`
+ ImageID string `json:"ImageID"`
+ DiffIDs []string `json:"DiffIDs"`
+ RepoTags []string `json:"RepoTags"`
+ RepoDigests []string `json:"RepoDigests"`
+}
+
+// TrivyOS contains OS information
+type TrivyOS struct {
+ Family string `json:"Family"`
+ Name string `json:"Name"`
+}
+
+// TrivyResults contains the results for a specific target
+type TrivyResults struct {
+ Target string `json:"Target"`
+ Class string `json:"Class"`
+ Type string `json:"Type"`
+ Vulnerabilities []TrivyVulnerability `json:"Vulnerabilities"`
+}
+
+// TrivyVulnerability represents a vulnerability in Trivy output
+type TrivyVulnerability struct {
+ VulnerabilityID string `json:"VulnerabilityID"`
+ PkgID string `json:"PkgID"`
+ PkgName string `json:"PkgName"`
+ InstalledVersion string `json:"InstalledVersion"`
+ FixedVersion string `json:"FixedVersion"`
+ Status string `json:"Status"`
+ Layer *TrivyLayer `json:"Layer,omitempty"`
+ SeveritySource string `json:"SeveritySource"`
+ PrimaryURL string `json:"PrimaryURL"`
+ DataSource *TrivyDataSource `json:"DataSource,omitempty"`
+ Title string `json:"Title"`
+ Description string `json:"Description"`
+ Severity string `json:"Severity"`
+ CweIDs []string `json:"CweIDs"`
+ CVSS map[string]TrivyCVSS `json:"CVSS"`
+ References []string `json:"References"`
+ PublishedDate string `json:"PublishedDate"`
+ LastModifiedDate string `json:"LastModifiedDate"`
+}
+
+// TrivyLayer contains information about the layer where the vulnerability was found
+type TrivyLayer struct {
+ Digest string `json:"Digest"`
+ DiffID string `json:"DiffID"`
+}
+
+// TrivyDataSource contains information about the data source
+type TrivyDataSource struct {
+ ID string `json:"ID"`
+ Name string `json:"Name"`
+ URL string `json:"URL"`
+}
+
+// TrivyCVSS contains CVSS score information from Trivy
+type TrivyCVSS struct {
+ V2Vector string `json:"V2Vector"`
+ V3Vector string `json:"V3Vector"`
+ V2Score float64 `json:"V2Score"`
+ V3Score float64 `json:"V3Score"`
+}
+
+// ConvertTrivyReportToScanResult converts a TrivyReport to a ScanResult
+func ConvertTrivyReportToScanResult(report *TrivyReport, imageID string, scanTime time.Time, duration int64) *ScanResult {
+ result := &ScanResult{
+ ImageID: imageID,
+ ImageName: report.ArtifactName,
+ ScanTime: scanTime,
+ Status: ScanStatusCompleted,
+ Duration: duration,
+ Summary: &SeveritySummary{
+ Critical: 0,
+ High: 0,
+ Medium: 0,
+ Low: 0,
+ Unknown: 0,
+ Total: 0,
+ },
+ Vulnerabilities: []Vulnerability{},
+ }
+
+ // Collect all vulnerabilities from all results
+ for _, trivyResult := range report.Results {
+ for _, tv := range trivyResult.Vulnerabilities {
+ vuln := convertTrivyVulnerability(&tv)
+ result.Vulnerabilities = append(result.Vulnerabilities, vuln)
+
+ // Update severity summary
+ switch vuln.Severity {
+ case SeverityCritical:
+ result.Summary.Critical++
+ case SeverityHigh:
+ result.Summary.High++
+ case SeverityMedium:
+ result.Summary.Medium++
+ case SeverityLow:
+ result.Summary.Low++
+ case SeverityUnknown:
+ result.Summary.Unknown++
+ default:
+ result.Summary.Unknown++
+ }
+ result.Summary.Total++
+ }
+ }
+
+ return result
+}
+
+func convertTrivyVulnerability(tv *TrivyVulnerability) Vulnerability {
+ vuln := Vulnerability{
+ VulnerabilityID: tv.VulnerabilityID,
+ PkgName: tv.PkgName,
+ InstalledVersion: tv.InstalledVersion,
+ FixedVersion: tv.FixedVersion,
+ Severity: parseSeverity(tv.Severity),
+ Title: tv.Title,
+ Description: tv.Description,
+ References: tv.References,
+ }
+
+ // Convert CVSS scores
+ if len(tv.CVSS) > 0 {
+ cvss := &CVSSInfo{}
+ for _, cvssData := range tv.CVSS {
+ if cvssData.V3Score > 0 {
+ cvss.V3Score = cvssData.V3Score
+ cvss.V3Vector = cvssData.V3Vector
+ }
+ if cvssData.V2Score > 0 {
+ cvss.V2Score = cvssData.V2Score
+ cvss.V2Vector = cvssData.V2Vector
+ }
+ }
+ if cvss.V2Score > 0 || cvss.V3Score > 0 {
+ vuln.CVSS = cvss
+ }
+ }
+
+ // Parse dates
+ if tv.PublishedDate != "" {
+ if t, err := time.Parse(time.RFC3339, tv.PublishedDate); err == nil {
+ vuln.PublishedDate = &t
+ }
+ }
+ if tv.LastModifiedDate != "" {
+ if t, err := time.Parse(time.RFC3339, tv.LastModifiedDate); err == nil {
+ vuln.LastModifiedDate = &t
+ }
+ }
+
+ return vuln
+}
+
+func parseSeverity(s string) Severity {
+ switch s {
+ case "CRITICAL":
+ return SeverityCritical
+ case "HIGH":
+ return SeverityHigh
+ case "MEDIUM":
+ return SeverityMedium
+ case "LOW":
+ return SeverityLow
+ default:
+ return SeverityUnknown
+ }
+}
+
+// IgnorePayload represents the request to ignore a vulnerability
+type IgnorePayload struct {
+ // ImageID is the Docker image ID
+ //
+ // Required: true
+ ImageID string `json:"imageId" example:"sha256:abc123"`
+
+ // VulnerabilityID is the CVE or vulnerability identifier
+ //
+ // Required: true
+ VulnerabilityID string `json:"vulnerabilityId" example:"CVE-2023-1234"`
+
+ // PkgName is the package name containing the vulnerability
+ //
+ // Required: true
+ PkgName string `json:"pkgName" example:"openssl"`
+
+ // InstalledVersion is the version of the package with the vulnerability
+ //
+ // Required: false
+ InstalledVersion string `json:"installedVersion,omitempty" example:"1.1.1l"`
+
+ // Reason is an optional reason for ignoring this vulnerability
+ //
+ // Required: false
+ Reason *string `json:"reason,omitempty" example:"False positive - not exploitable"`
+
+ // CreatedBy is the user ID who created this ignore record (set by server from auth; do not send from client)
+ //
+ // Required: false
+ CreatedBy string `json:"createdBy,omitempty" example:"user-123"`
+}
+
+// IgnoredVulnerability represents an ignored vulnerability record
+type IgnoredVulnerability struct {
+ // ID is the unique identifier for this ignore record
+ ID string `json:"id"`
+
+ // EnvironmentID is the environment where this ignore applies
+ EnvironmentID string `json:"environmentId"`
+
+ // ImageID is the Docker image ID
+ ImageID string `json:"imageId"`
+
+ // VulnerabilityID is the CVE or vulnerability identifier
+ VulnerabilityID string `json:"vulnerabilityId"`
+
+ // PkgName is the package name containing the vulnerability
+ PkgName string `json:"pkgName"`
+
+ // InstalledVersion is the version of the package with the vulnerability
+ InstalledVersion string `json:"installedVersion"`
+
+ // Reason is an optional reason for ignoring this vulnerability
+ Reason *string `json:"reason,omitempty"`
+
+ // CreatedBy is the user ID who created this ignore record
+ CreatedBy string `json:"createdBy"`
+
+ // CreatedAt is when this ignore record was created
+ CreatedAt time.Time `json:"createdAt"`
+}