Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: only patch os level issues with copa
Kyle Mendelle95c55326a59
diff --git a/backend/internal/imagepatch/imagepatch.go b/backend/internal/imagepatch/imagepatch.goindex f8ad975f7..cb73cf13e 100644--- a/backend/internal/imagepatch/imagepatch.go+++ b/backend/internal/imagepatch/imagepatch.go@@ -38,6 +38,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils/logging"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity""github.com/getarcaneapp/arcane/types/v2/imagepatch"+ vulntypes "github.com/getarcaneapp/arcane/types/v2/vulnerability")// ImagePatchService patches image OS packages in place using the Copacetic@@ -227,6 +228,7 @@ func (s *ImagePatchService) patchInBackgroundInternal(ctx context.Context, recorvar vexOutputPath stringif reportPath != "" {copaOpts.Scanner = "trivy"+ copaOpts.PkgTypes = "os"// VEX output is only produced when patching from a report; use it to// count how many packages were actually updated.if vexDir, err := os.MkdirTemp("", "arcane-patch-vex"); err == nil {@@ -248,6 +250,9 @@ func (s *ImagePatchService) patchInBackgroundInternal(ctx context.Context, recordurationMs := time.Since(startTime).Milliseconds()if patchErr != nil {+ if errors.Is(patchErr, copatypes.ErrNoUpdatesFound) {+ patchErr = errors.New("no OS package updates available for this image")+ }s.finishPatchRecordInternal(ctx, record, imagepatch.PatchStatusFailed, patchErr.Error(), nil, durationMs)slog.WarnContext(ctx, "image patch failed","environmentId", record.EnvironmentID,@@ -282,7 +287,7 @@ func (s *ImagePatchService) patchInBackgroundInternal(ctx context.Context, recors.appendPatchActivityInternal(ctx, activityID, 95, "Patched image was created but the expected tag "+record.PatchedRef+" was not found; check the image list")} else if s.vulnerabilityService != nil {s.appendPatchActivityInternal(ctx, activityID, 95, "Re-scanning patched image to verify the patch")- if _, err := s.vulnerabilityService.ScanImage(ctx, record.EnvironmentID, patchedInspect.ID, common.User{Username: "System"}); err != nil {+ if _, err := s.vulnerabilityService.ScanImage(context.WithoutCancel(ctx), record.EnvironmentID, patchedInspect.ID, common.User{Username: "System"}); err != nil {slog.WarnContext(ctx, "failed to start verification scan of patched image", "patchedRef", record.PatchedRef, "error", err)}}@@ -507,7 +512,8 @@ func (s *ImagePatchService) ListPatchTargets(ctx context.Context, envID string,q := s.db.WithContext(ctx).Model(&vulnerability.VulnerabilityScanRecord{}).Where("status = ? AND report_path IS NOT NULL", vulnerability.ScanStatusCompleted).- Where("(fixable_count > 0 OR fixable_count IS NULL OR id IN (?))", patchedImageIDs)+ Where("(fixable_count > 0 OR fixable_count IS NULL OR id IN (?))", patchedImageIDs).+ Where("image_name NOT LIKE 'sha256:%' AND image_name NOT LIKE '%<none>%' AND image_name <> id")if len(excludedNames) > 0 {q = q.Where("image_name NOT IN ?", excludedNames)}@@ -541,7 +547,7 @@ func (s *ImagePatchService) ListPatchTargets(ctx context.Context, envID string,target := imagepatch.PatchTarget{ImageID: scan.ID,ImageRef: scan.ImageName,- FixableCount: fixableVulnerabilityCount(scan),+ FixableCount: fixableVulnerabilityCountInternal(ctx, scan),TotalCount: scan.TotalCount,ScanTime: scan.ScanTime,}@@ -580,36 +586,44 @@ func (s *ImagePatchService) patchedImageScanSummaryInternal(ctx context.Context,var scan vulnerability.VulnerabilityScanRecordif err := s.db.WithContext(ctx).- Where("status = ? AND image_name IN ?", vulnerability.ScanStatusCompleted, names).+ Where("image_name IN ?", names).Order("scan_time DESC").First(&scan).Error; err != nil {return nil}return &imagepatch.PatchScanSummary{- FixableCount: fixableVulnerabilityCount(&scan),+ Status: scan.Status,+ FixableCount: fixableVulnerabilityCountInternal(ctx, &scan),TotalCount: scan.TotalCount,ScanTime: scan.ScanTime,}}-func fixableVulnerabilityCount(scan *vulnerability.VulnerabilityScanRecord) int {+func fixableVulnerabilityCountInternal(ctx context.Context, scan *vulnerability.VulnerabilityScanRecord) int {if scan.FixableCount != nil {return *scan.FixableCount}- // Records written before the fixable_count column existed: parse the blob.- if len(scan.Vulnerabilities) == 0 || scan.Vulnerabilities[0] == "" {+ if scan.ReportPath == nil || strings.TrimSpace(*scan.ReportPath) == "" {return 0}- var vulns []struct {- FixedVersion string `json:"fixedVersion"`+ data, err := acfs.ReadFile(ctx, filepath.Dir(*scan.ReportPath), "/"+filepath.Base(*scan.ReportPath))+ if err != nil {+ return 0}- if err := json.Unmarshal([]byte(scan.Vulnerabilities[0]), &vulns); err != nil {+ var report vulntypes.TrivyReport+ if err := json.Unmarshal(data, &report); err != nil {return 0}count := 0- for _, v := range vulns {- if strings.TrimSpace(v.FixedVersion) != "" {- count+++ for i := range report.Results {+ res := &report.Results[i]+ if res.Class != vulntypes.TrivyClassOSPackages {+ continue+ }+ for j := range res.Vulnerabilities {+ if strings.TrimSpace(res.Vulnerabilities[j].FixedVersion) != "" {+ count+++ }}}return count@@ -624,6 +638,7 @@ func (s *ImagePatchService) PatchFlaggedImages(ctx context.Context, envID stringvar scans []vulnerability.VulnerabilityScanRecordif err := s.db.WithContext(ctx).Where("status = ? AND total_count > 0 AND report_path IS NOT NULL", vulnerability.ScanStatusCompleted).+ Where("image_name NOT LIKE 'sha256:%' AND image_name NOT LIKE '%<none>%' AND image_name <> id").Find(&scans).Error; err != nil {return 0, 0, errors.WrapIf(err, "failed to list vulnerability scans")}@@ -637,7 +652,7 @@ func (s *ImagePatchService) PatchFlaggedImages(ctx context.Context, envID stringscan := &scans[i]// Only patch images whose scan found at least one fixable vulnerability.- if fixableVulnerabilityCount(scan) == 0 {+ if fixableVulnerabilityCountInternal(ctx, scan) == 0 {skipped++continue}diff --git a/backend/internal/imagepatch/imagepatch_test.go b/backend/internal/imagepatch/imagepatch_test.goindex fed872822..974daa231 100644--- a/backend/internal/imagepatch/imagepatch_test.go+++ b/backend/internal/imagepatch/imagepatch_test.go@@ -1,9 +1,20 @@package imagepatchimport (+ "context"+ "fmt""testing"+ "time"+ "github.com/libtnb/sqlite""github.com/stretchr/testify/require"+ "gorm.io/gorm"++ "github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/docker"+ "github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination")func TestResolvePatchedRef(t *testing.T) {@@ -43,3 +54,33 @@ func TestResolvePatchedRef(t *testing.T) {})}}++func TestListPatchTargets_ExcludesUntaggedImages(t *testing.T) {+ ctx := context.Background()+ dsn := fmt.Sprintf("file:image-patch-test-%d?mode=memory&cache=shared", time.Now().UnixNano())+ gdb, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})+ require.NoError(t, err)+ require.NoError(t, gdb.AutoMigrate(&vulnerability.VulnerabilityScanRecord{}, &ImagePatchRecord{}))+ db := &database.DB{DB: gdb}++ svc := &ImagePatchService{+ db: db,+ dockerService: docker.NewDockerClientService(ctx, nil, &config.Config{DockerHost: "unix:///nonexistent-arcane-test.sock"}, nil),+ }++ reportPath := "/data/vulnerability-reports/test.json"+ fixable := 3+ records := []vulnerability.VulnerabilityScanRecord{+ {ID: "sha256:aaa", ImageName: "nginx:latest", Status: vulnerability.ScanStatusCompleted, ScanTime: time.Now(), ReportPath: &reportPath, FixableCount: &fixable},+ {ID: "sha256:bbb", ImageName: "sha256:bbb", Status: vulnerability.ScanStatusCompleted, ScanTime: time.Now(), ReportPath: &reportPath, FixableCount: &fixable},+ {ID: "sha256:ccc", ImageName: "<none>:<none>", Status: vulnerability.ScanStatusCompleted, ScanTime: time.Now(), ReportPath: &reportPath, FixableCount: &fixable},+ }+ for i := range records {+ require.NoError(t, db.Create(&records[i]).Error)+ }++ targets, _, err := svc.ListPatchTargets(ctx, "0", pagination.QueryParams{Limit: 20})+ require.NoError(t, err)+ require.Len(t, targets, 1)+ require.Equal(t, "nginx:latest", targets[0].ImageRef)+}diff --git a/backend/internal/vulnerability/service_test.go b/backend/internal/vulnerability/service_test.goindex 3af44b487..76e06f659 100644--- a/backend/internal/vulnerability/service_test.go+++ b/backend/internal/vulnerability/service_test.go@@ -137,6 +137,30 @@ func setupVulnerabilityScanTestDB(t *testing.T) *database.DB {return &database.DB{DB: db}}+func TestSaveScanResult_FixableCountsOSPackagesOnly(t *testing.T) {+ ctx := context.Background()+ db := setupVulnerabilityScanTestDB(t)+ svc := &VulnerabilityService{db: db}++ result := &vulnerability.ScanResult{+ ImageID: "sha256:img-fixable",+ ImageName: "nginx:latest",+ Status: vulnerability.ScanStatusCompleted,+ ScanTime: time.Now(),+ Vulnerabilities: []vulnerability.Vulnerability{+ {VulnerabilityID: "CVE-1", Class: vulnerability.TrivyClassOSPackages, FixedVersion: "1.2.3"},+ {VulnerabilityID: "CVE-2", Class: vulnerability.TrivyClassOSPackages},+ {VulnerabilityID: "CVE-3", Class: vulnerability.TrivyClassLangPackages, FixedVersion: "2.0.0"},+ },+ }+ require.NoError(t, svc.saveScanResult(ctx, result))++ var record VulnerabilityScanRecord+ require.NoError(t, db.First(&record, "id = ?", "sha256:img-fixable").Error)+ require.NotNil(t, record.FixableCount)+ require.Equal(t, 1, *record.FixableCount)+}+func TestVulnerabilityService_ListVulnerabilities_NoScanReturnsNotFound(t *testing.T) {db := setupVulnerabilityScanTestDB(t)svc := &VulnerabilityService{db: db}diff --git a/backend/internal/vulnerability/vulnerability_store.go b/backend/internal/vulnerability/vulnerability_store.goindex 7726ceb95..cc60186f2 100644--- a/backend/internal/vulnerability/vulnerability_store.go+++ b/backend/internal/vulnerability/vulnerability_store.go@@ -271,7 +271,8 @@ func (s *VulnerabilityService) saveScanResult(ctx context.Context, result *vulnefixable := 0for i := range result.Vulnerabilities {- if strings.TrimSpace(result.Vulnerabilities[i].FixedVersion) != "" {+ v := &result.Vulnerabilities[i]+ if v.Class == vulnerability.TrivyClassOSPackages && strings.TrimSpace(v.FixedVersion) != "" {fixable++}}diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex 2efffe54e..69fcef1d6 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -843,6 +843,7 @@"security_patched_ref": "Patched Tag","security_fixable_after_patch": "{count} fixable","security_verify_scan_pending": "Verifying…",+ "security_verify_failed": "Verify failed","images_patch_started": "Patching image; the result will be tagged {patchedRef}","images_patch_failed": "Failed to patch image","images_details_title": "Image Details",@@ -2091,6 +2092,7 @@"activity_type_container_redeploy": "Container Redeploy","activity_type_container_delete": "Container Delete","activity_type_vulnerability_scan": "Vulnerability Scan",+ "activity_type_image_patch": "Image Patch","activity_type_system_prune": "System Prune","activity_type_resource_action": "Resource Action","activity_unknown_target": "Unknown target",diff --git a/frontend/src/lib/components/activity/activity-completion-toasts.ts b/frontend/src/lib/components/activity/activity-completion-toasts.tsindex e88245bbd..b85491cf7 100644--- a/frontend/src/lib/components/activity/activity-completion-toasts.ts+++ b/frontend/src/lib/components/activity/activity-completion-toasts.ts@@ -36,6 +36,7 @@ const LONG_RUNNING_TYPES = new Set<ActivityType>(['project_redeploy','container_redeploy','vulnerability_scan',+ 'image_patch','auto_update','system_prune']);diff --git a/frontend/src/lib/components/activity/activity-labels.ts b/frontend/src/lib/components/activity/activity-labels.tsindex 7490698c1..bc029fe3c 100644--- a/frontend/src/lib/components/activity/activity-labels.ts+++ b/frontend/src/lib/components/activity/activity-labels.ts@@ -9,6 +9,7 @@ import {RefreshIcon,RestartIcon,ScanIcon,+ ShieldCheckIcon,StartIcon,StopIcon,TrashIcon@@ -54,6 +55,8 @@ export function activityTypeLabel(type: ActivityType): string {return m.activity_type_image_build();case 'image_update_check':return m.activity_type_image_update_check();+ case 'image_patch':+ return m.activity_type_image_patch();case 'project_pull':return m.activity_type_project_pull();case 'project_build':@@ -117,6 +120,8 @@ export function activityTypeIcon(type: ActivityType): IconType {return TrashIcon;case 'vulnerability_scan':return ScanIcon;+ case 'image_patch':+ return ShieldCheckIcon;case 'auto_update':return RefreshIcon;case 'system_prune':diff --git a/frontend/src/lib/types/activity.type.ts b/frontend/src/lib/types/activity.type.tsindex 4f308e54d..6c3fde44c 100644--- a/frontend/src/lib/types/activity.type.ts+++ b/frontend/src/lib/types/activity.type.ts@@ -4,6 +4,7 @@ export type ActivityType =| 'image_pull'| 'image_build'| 'image_update_check'+ | 'image_patch'| 'project_pull'| 'project_build'| 'project_deploy'diff --git a/frontend/src/lib/types/docker.ts b/frontend/src/lib/types/docker.tsindex 1fe40595a..f63afe190 100644--- a/frontend/src/lib/types/docker.ts+++ b/frontend/src/lib/types/docker.ts@@ -610,6 +610,7 @@ export interface ImagePatchRecordDto {}export interface ImagePatchScanSummaryDto {+ status: 'pending' | 'scanning' | 'completed' | 'failed';fixableCount: number;totalCount: number;scanTime: string;diff --git a/frontend/src/routes/(app)/security/+page.svelte b/frontend/src/routes/(app)/security/+page.svelteindex c882d9694..ba77d2010 100644--- a/frontend/src/routes/(app)/security/+page.svelte+++ b/frontend/src/routes/(app)/security/+page.svelte@@ -16,6 +16,7 @@import { TabBar, type TabItem } from '#lib/components/tab-bar';import * as Tabs from '#lib/components/ui/tabs/index.js';import { environmentStore } from '#lib/stores/environment.store.svelte';+ import { activityStore } from '#lib/stores/activity.store.svelte';import { hasPermission } from '#lib/utils/auth';import { mapVulnerabilityPage, mapVulnerabilityRequest } from '#lib/utils/vulnerability';import { useUrlTab } from '#lib/hooks/use-url-tab.svelte';@@ -200,6 +201,21 @@useEnvironmentRefresh(refreshAll);+ let activePatchActivityIds = new Set<string>();+ $effect(() => {+ const active = new Set(+ activityStore.activities+ .filter(+ (a) =>+ (a.type === 'image_patch' || a.type === 'vulnerability_scan') && (a.status === 'queued' || a.status === 'running')+ )+ .map((a) => a.id)+ );+ const finished = [...activePatchActivityIds].some((id) => !active.has(id));+ activePatchActivityIds = active;+ if (finished) void loadPatches();+ });+$effect(() => () => {destroyed = true;stopScanPolling();diff --git a/frontend/src/routes/(app)/security/security-patch-table.svelte b/frontend/src/routes/(app)/security/security-patch-table.svelteindex 32ac4c2fa..ecae30454 100644--- a/frontend/src/routes/(app)/security/security-patch-table.svelte+++ b/frontend/src/routes/(app)/security/security-patch-table.svelte@@ -10,7 +10,7 @@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/shared';- import type { ImagePatchTargetDto, ImagePatchStatus } from '#lib/types/docker';+ import type { ImagePatchTargetDto } from '#lib/types/docker';import { ShieldCheckIcon, ImagesIcon, ClockIcon } from '#lib/icons';import { formatDateTimeShort } from '#lib/utils/formatting';import { environmentStore } from '#lib/stores/environment.store.svelte';@@ -55,17 +55,17 @@}}- function patchStatusLabel(status: ImagePatchStatus) {- switch (status) {- case 'patching':- return m.common_running();- case 'completed':- return m.common_success();- case 'failed':- return m.common_failed();- default:- return m.common_unknown();+ function lastPatchState(item: PatchTargetRow): { label: string; variant: 'green' | 'red' | 'blue' | 'amber' } | null {+ const patch = item.lastPatch;+ if (!patch) return null;+ if (patch.status === 'failed') return { label: m.common_failed(), variant: 'red' };+ if (patch.status !== 'completed') return { label: m.common_running(), variant: 'blue' };+ const scan = item.lastPatchScan;+ if (!scan || scan.status === 'pending' || scan.status === 'scanning') {+ return { label: m.security_verify_scan_pending(), variant: 'blue' };}+ if (scan.status === 'failed') return { label: m.security_verify_failed(), variant: 'amber' };+ return { label: m.common_success(), variant: 'green' };}function lastPatchTooltip(item: PatchTargetRow) {@@ -74,18 +74,10 @@if (patch.status === 'failed' && patch.error) {return patch.error;}- return formatDateTimeShort(patch.createdAt);- }-- function patchStatusVariant(status: ImagePatchStatus): 'green' | 'red' | 'blue' {- switch (status) {- case 'completed':- return 'green';- case 'failed':- return 'red';- default:- return 'blue';+ if (patch.status === 'completed' && item.lastPatchScan?.status === 'completed') {+ return `${m.security_fixable_after_patch({ count: item.lastPatchScan.fixableCount })} · ${formatDateTimeShort(patch.createdAt)}`;}+ return formatDateTimeShort(patch.createdAt);}const columns = $derived([@@ -135,20 +127,10 @@{/snippet}{#snippet LastPatchCell({ item }: { item: PatchTargetRow })}- {#if item.lastPatch}- <div class="flex items-center gap-2" title={lastPatchTooltip(item)}>- <Badge variant={patchStatusVariant(item.lastPatch.status)} size="sm" minWidth="20">- {patchStatusLabel(item.lastPatch.status)}- </Badge>- {#if item.lastPatch.status === 'completed'}- {#if item.lastPatchScan}- <span class="text-xs {item.lastPatchScan.fixableCount === 0 ? 'text-emerald-500' : 'text-amber-500'}">- {m.security_fixable_after_patch({ count: item.lastPatchScan.fixableCount })}- </span>- {:else}- <span class="text-xs text-muted-foreground">{m.security_verify_scan_pending()}</span>- {/if}- {/if}+ {@const state = lastPatchState(item)}+ {#if state}+ <div class="flex items-center" title={lastPatchTooltip(item)}>+ <Badge variant={state.variant} size="sm" minWidth="20">{state.label}</Badge></div>{:else}<span class="text-xs text-muted-foreground">{m.security_not_patched()}</span>@@ -173,10 +155,11 @@: m.security_no_fixable(): null}badges={[- (item) =>- (mobileFieldVisibility['lastPatch'] ?? true) && item.lastPatch- ? { variant: patchStatusVariant(item.lastPatch.status), text: patchStatusLabel(item.lastPatch.status) }- : null+ (item) => {+ if (!(mobileFieldVisibility['lastPatch'] ?? true)) return null;+ const state = lastPatchState(item);+ return state ? { variant: state.variant, text: state.label } : null;+ }]}fields={[{diff --git a/types/imagepatch/imagepatch.go b/types/imagepatch/imagepatch.goindex 2dfc1d61c..6b4fa3a24 100644--- a/types/imagepatch/imagepatch.go+++ b/types/imagepatch/imagepatch.go@@ -40,6 +40,7 @@ type PatchOptions struct {// PatchScanSummary is the scan outcome of a patched image, used to verify a// patch actually removed the fixable vulnerabilities.type PatchScanSummary struct {+ Status string `json:"status"`FixableCount int `json:"fixableCount"`TotalCount int `json:"totalCount"`ScanTime time.Time `json:"scanTime"`diff --git a/types/vulnerability/vulnerability.go b/types/vulnerability/vulnerability.goindex f9a9bcebd..a6470993f 100644--- a/types/vulnerability/vulnerability.go+++ b/types/vulnerability/vulnerability.go@@ -13,6 +13,9 @@ const (SeverityMedium Severity = "MEDIUM"SeverityHigh Severity = "HIGH"SeverityCritical Severity = "CRITICAL"++ TrivyClassOSPackages = "os-pkgs"+ TrivyClassLangPackages = "lang-pkgs")// Vulnerability represents a single vulnerability found in an image@@ -42,6 +45,10 @@ type Vulnerability struct {// Required: trueSeverity Severity `json:"severity"`+ Class string `json:"class,omitempty"`++ Type string `json:"type,omitempty"`+// Title is the title of the vulnerability//// Required: false@@ -409,6 +416,8 @@ func ConvertTrivyReportToScanResult(report *TrivyReport, imageID string, scanTimfor _, trivyResult := range report.Results {for _, tv := range trivyResult.Vulnerabilities {vuln := convertTrivyVulnerability(&tv)+ vuln.Class = trivyResult.Class+ vuln.Type = trivyResult.Typeresult.Vulnerabilities = append(result.Vulnerabilities, vuln)// Update severity summary