Skip to content

Modern Docker Management, Designed for Everyone

10.8 KB
Raw Blame
package ignores

import (
	"context"
	"errors"
	"fmt"
	"log/slog"
	"slices"
	"strings"

	"github.com/getarcaneapp/arcane/types/v2/vulnerability"
	"go.getarcane.app/kit/pkg"
	"gorm.io/gorm"

	"github.com/getarcaneapp/arcane/backend/v2/internal/common"
	"github.com/getarcaneapp/arcane/backend/v2/internal/database"
	"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
	"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil"
)

// Records persists ignore records, whose model the vulnerability domain owns.
type Records struct {
	ForImage func(ctx context.Context, envID, imageID string) ([]vulnerability.IgnoredVulnerability, error)
	// Exists reports whether an ignore record with the identity of ignore exists.
	Exists func(ctx context.Context, ignore *vulnerability.IgnoredVulnerability) (bool, error)
	Get    func(ctx context.Context, envID, ignoreID string) (*vulnerability.IgnoredVulnerability, bool, error)
	// Create inserts ignores inside tx and returns them with their IDs and creation times.
	Create func(tx *gorm.DB, ignores []vulnerability.IgnoredVulnerability, batchSize int) ([]vulnerability.IgnoredVulnerability, error)
	// DeleteIdentity removes every ignore record with the identity of ignore.
	DeleteIdentity func(ctx context.Context, ignore *vulnerability.IgnoredVulnerability) error
	DeleteIDs      func(tx *gorm.DB, envID string, ignoreIDs []string) (int64, error)
	// Page counts the ignore records of envID and lists one ordered page of them.
	Page func(ctx context.Context, envID string, order func(*gorm.DB) *gorm.DB, offset, limit int) ([]vulnerability.IgnoredVulnerability, int64, error)
	// Changed runs after an ignore change commits.
	Changed func()
}

// Service records which vulnerability findings are ignored per environment.
type Service struct {
	db      *database.DB
	records Records
	// activeItemsQuery returns the filtered finding query the vulnerability
	// list uses, so bulk operations match exactly what the list shows.
	activeItemsQuery func(ctx context.Context, db *gorm.DB, envID string, params *pagination.QueryParams) *gorm.DB
}

// ignoreTarget identifies one finding to ignore.
type ignoreTarget struct {
	ImageID          string `gorm:"column:image_id"`
	VulnerabilityID  string `gorm:"column:vulnerability_id"`
	PkgName          string `gorm:"column:pkg_name"`
	InstalledVersion string `gorm:"column:installed_version"`
}

func NewService(db *database.DB, records Records, activeItemsQuery func(ctx context.Context, db *gorm.DB, envID string, params *pagination.QueryParams) *gorm.DB) *Service {
	return &Service{
		db:               db,
		records:          records,
		activeItemsQuery: activeItemsQuery,
	}
}

// FilterForImage drops the findings of imageID that are ignored in envID.
func (s *Service) FilterForImage(
	ctx context.Context,
	envID, imageID string,
	vulns []vulnerability.Vulnerability,
) ([]vulnerability.Vulnerability, error) {
	if len(vulns) == 0 || imageID == "" {
		return vulns, nil
	}

	ignores, err := s.records.ForImage(ctx, envID, imageID)
	if err != nil {
		return nil, err
	}
	if len(ignores) == 0 {
		return vulns, nil
	}

	ignoredKeys := make(map[string]struct{}, len(ignores))
	for _, ignore := range ignores {
		ignoredKeys[ignore.ImageID+":"+ignore.VulnerabilityID+":"+ignore.PkgName+":"+ignore.InstalledVersion] = struct{}{}
	}

	return slices.DeleteFunc(slices.Clone(vulns), func(vulnEntry vulnerability.Vulnerability) bool {
		_, isIgnored := ignoredKeys[imageID+":"+vulnEntry.VulnerabilityID+":"+vulnEntry.PkgName+":"+vulnEntry.InstalledVersion]
		return isIgnored
	}), nil
}

// IgnoreVulnerability creates a new ignore record for a vulnerability
func (s *Service) IgnoreVulnerability(ctx context.Context, envID string, payload *vulnerability.IgnorePayload) (*vulnerability.IgnoredVulnerability, error) {
	ignore := vulnerability.IgnoredVulnerability{
		EnvironmentID:    envID,
		ImageID:          payload.ImageID,
		VulnerabilityID:  payload.VulnerabilityID,
		PkgName:          payload.PkgName,
		InstalledVersion: payload.InstalledVersion,
		Reason:           payload.Reason,
		CreatedBy:        payload.CreatedBy,
	}

	// Check if already ignored (composite key check)
	exists, err := s.records.Exists(ctx, &ignore)
	if err != nil {
		return nil, fmt.Errorf("failed to check existing ignore: %w", err)
	}
	if exists {
		return nil, common.Classify(common.ErrConflict, errors.New("vulnerability is already ignored"))
	}

	created, createIgnoreErr := s.records.Create(s.db.WithContext(ctx), []vulnerability.IgnoredVulnerability{ignore}, 1)
	if createIgnoreErr != nil {
		return nil, fmt.Errorf("failed to create ignore record: %w", createIgnoreErr)
	}
	s.records.Changed()

	slog.InfoContext(ctx, "vulnerability ignored",
		"vulnerabilityId", payload.VulnerabilityID,
		"imageId", payload.ImageID,
		"pkgName", payload.PkgName,
	)

	return &created[0], nil
}

// UnignoreVulnerability removes an ignore record together with any duplicates of its identity, so a finding never stays ignored after a restore.
func (s *Service) UnignoreVulnerability(ctx context.Context, envID, ignoreID string) error {
	ignore, found, err := s.records.Get(ctx, envID, ignoreID)
	if err != nil {
		return fmt.Errorf("failed to load ignore record: %w", err)
	}
	if !found {
		return common.Classify(common.ErrNotFound, errors.New("ignore record not found"))
	}

	if deleteErr := s.records.DeleteIdentity(ctx, ignore); deleteErr != nil {
		return fmt.Errorf("failed to delete ignore record: %w", deleteErr)
	}
	s.records.Changed()

	slog.InfoContext(ctx, "vulnerability unignored", "ignoreId", ignoreID)
	return nil
}

// bulkIgnoreBatchSize bounds how many ignore rows one insert or delete statement carries.
const bulkIgnoreBatchSize = 500

// BulkIgnoreVulnerabilities ignores every active finding matching the filters inside one transaction and returns how many ignore records were created.
func (s *Service) BulkIgnoreVulnerabilities(ctx context.Context, envID string, filters *vulnerability.BulkVulnerabilityFilters, createdBy string) (int, error) {
	var ignores []vulnerability.IgnoredVulnerability
	err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
		params := bulkFilterParams(filters, false)
		q := s.activeItemsQuery(ctx, tx, envID, &params)
		var targets []ignoreTarget
		if err := q.Distinct(
			"vulnerability_scan_items.image_id",
			"vulnerability_scan_items.vulnerability_id",
			"vulnerability_scan_items.pkg_name",
			"vulnerability_scan_items.installed_version",
		).Scan(
			&targets,
		).Error; err != nil {
			return fmt.Errorf("failed to resolve vulnerabilities to ignore: %w", err)
		}
		if len(targets) == 0 {
			return nil
		}
		ignores = make([]vulnerability.IgnoredVulnerability, 0, len(targets))
		for _, target := range targets {
			ignores = append(ignores, vulnerability.IgnoredVulnerability{
				EnvironmentID:    envID,
				ImageID:          target.ImageID,
				VulnerabilityID:  target.VulnerabilityID,
				PkgName:          target.PkgName,
				InstalledVersion: target.InstalledVersion,
				CreatedBy:        createdBy,
			})
		}
		if _, err := s.records.Create(tx, ignores, bulkIgnoreBatchSize); err != nil {
			return fmt.Errorf("failed to create ignore records: %w", err)
		}
		return nil
	})
	if err != nil {
		return 0, err
	}
	s.records.Changed()

	slog.InfoContext(ctx, "vulnerabilities ignored in bulk", "environmentId", envID, "affected", len(ignores))
	return len(ignores), nil
}

// BulkUnignoreVulnerabilities removes every ignore record matching the filters inside one transaction and returns how many were removed.
func (s *Service) BulkUnignoreVulnerabilities(ctx context.Context, envID string, filters *vulnerability.BulkVulnerabilityFilters) (int, error) {
	var affected int64
	err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
		params := bulkFilterParams(filters, true)
		q := s.activeItemsQuery(ctx, tx, envID, &params)
		var ignoreIDs []string
		if err := q.Distinct("vulnerability_ignores.id").Pluck("vulnerability_ignores.id", &ignoreIDs).Error; err != nil {
			return fmt.Errorf("failed to resolve ignored vulnerabilities to restore: %w", err)
		}
		for batch := range slices.Chunk(ignoreIDs, bulkIgnoreBatchSize) {
			deleted, err := s.records.DeleteIDs(tx, envID, batch)
			if err != nil {
				return fmt.Errorf("failed to delete ignore records: %w", err)
			}
			affected += deleted
		}
		return nil
	})
	if err != nil {
		return 0, err
	}
	s.records.Changed()

	slog.InfoContext(ctx, "vulnerabilities unignored in bulk", "environmentId", envID, "affected", affected)
	return int(affected), nil
}

// ListIgnoredVulnerabilities returns a list of ignored vulnerabilities for an environment
func (s *Service) ListIgnoredVulnerabilities(ctx context.Context, envID string, params pagination.QueryParams) ([]vulnerability.IgnoredVulnerability, pagination.Response, error) {
	ignores, total, err := s.records.Page(ctx, envID, func(query *gorm.DB) *gorm.DB {
		query = pagination.ApplyLikeSearch(query, strings.ToLower(params.Search),
			"(LOWER(vulnerability_id) LIKE ? OR LOWER(pkg_name) LIKE ? OR LOWER(installed_version) LIKE ? OR "+
				"LOWER(image_id) LIKE ? OR LOWER(COALESCE(reason, '')) LIKE ?)")
		if params.Sort == "" {
			return query.Order("created_at DESC")
		}
		for part := range strings.SplitSeq(params.Sort, ",") {
			part = strings.TrimSpace(part)
			if part == "" {
				continue
			}
			desc := strings.EqualFold(string(params.Order), "desc")
			switch {
			case strings.HasPrefix(part, "-"):
				desc, part = true, strings.TrimPrefix(part, "-")
			case strings.HasPrefix(part, "+"):
				desc, part = false, strings.TrimPrefix(part, "+")
			}
			switch part {
			case "createdAt":
				query = query.Order("created_at " + kit.Ternary(desc, "DESC", "ASC"))
			case "vulnerabilityId":
				query = query.Order("vulnerability_id " + kit.Ternary(desc, "DESC", "ASC"))
			default:
				query = query.Order("created_at DESC")
			}
		}
		return query
	}, params.Start, params.Limit)
	if err != nil {
		return nil, pagination.Response{}, err
	}

	return ignores, pagination.BuildResponse(total, total, params), nil
}

// GetIgnoreRecordsForImage retrieves all ignore records for a specific image
func (s *Service) GetIgnoreRecordsForImage(ctx context.Context, envID, imageID string) ([]vulnerability.IgnoredVulnerability, error) {
	ignores, err := s.records.ForImage(ctx, envID, imageID)
	if err != nil {
		return nil, fmt.Errorf("failed to get ignore records: %w", err)
	}
	return ignores, nil
}

// bulkFilterParams converts bulk filters into the list query params so matching follows the list and export rules.
func bulkFilterParams(filters *vulnerability.BulkVulnerabilityFilters, onlyIgnored bool) pagination.QueryParams {
	values := map[string]string{}
	if filters.Severity != "" {
		values["severity"] = filters.Severity
	}
	if filters.ImageName != "" {
		values["imageName"] = filters.ImageName
	}
	if filters.FixAvailable {
		values["fixAvailable"] = "true"
	}
	if onlyIgnored {
		values["ignored"] = "true"
	}
	return pagination.QueryParams{
		Search:  filters.Search,
		Filters: values,
	}
}