security

package
v0.0.0-...-890248b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 21, 2026 License: AGPL-3.0 Imports: 20 Imported by: 0

Documentation

Overview

Package security provides container security analysis, scoring, and CVE scanning. It analyzes containers for security best practices and vulnerabilities, generating actionable recommendations for remediation.

Package security provides host-level port detection and analysis.

Index

Constants

This section is empty.

Variables

View Source
var DangerousCapabilities = []string{
	"SYS_ADMIN",
	"NET_ADMIN",
	"SYS_PTRACE",
	"SYS_MODULE",
	"DAC_READ_SEARCH",
	"DAC_OVERRIDE",
	"SETUID",
	"SETGID",
	"SYS_RAWIO",
	"SYS_CHROOT",
	"MKNOD",
	"AUDIT_CONTROL",
	"AUDIT_WRITE",
	"BLOCK_SUSPEND",
	"MAC_ADMIN",
	"MAC_OVERRIDE",
	"NET_RAW",
	"SYS_BOOT",
	"SYS_TIME",
	"WAKE_ALARM",
}

DangerousCapabilities lists capabilities that significantly increase risk

View Source
var DangerousPorts = map[uint16]string{
	22:    "SSH",
	23:    "Telnet",
	3306:  "MySQL",
	5432:  "PostgreSQL",
	6379:  "Redis",
	27017: "MongoDB",
	9200:  "Elasticsearch",
	11211: "Memcached",
	2375:  "Docker (unencrypted)",
	2376:  "Docker (TLS)",
	5672:  "RabbitMQ",
	15672: "RabbitMQ Management",
	8500:  "Consul",
	2181:  "ZooKeeper",
	9092:  "Kafka",
}

DangerousPorts is a list of commonly attacked ports

View Source
var SecretPatterns = []string{
	"password",
	"passwd",
	"secret",
	"token",
	"api_key",
	"apikey",
	"api-key",
	"private_key",
	"privatekey",
	"private-key",
	"access_key",
	"accesskey",
	"access-key",
	"secret_key",
	"secretkey",
	"secret-key",
	"auth_token",
	"authtoken",
	"auth-token",
	"bearer",
	"credential",
	"cert",
	"private",
}

SecretPatterns contains patterns that may indicate secrets in environment variables

Functions

func CalculateSimple

func CalculateSimple(issues []Issue) (int, models.SecurityGrade)

CalculateSimple computes just the score and grade without detailed breakdown

func CountIssuesBySeverity

func CountIssuesBySeverity(issues []Issue) map[models.IssueSeverity]int

CountIssuesBySeverity counts issues by severity level

func GetGradeColor

func GetGradeColor(grade models.SecurityGrade) string

GetGradeColor returns the color code for a grade (for UI)

func GetGradeDescription

func GetGradeDescription(grade models.SecurityGrade) string

GetGradeDescription returns a description for a grade

func GetSeverityColor

func GetSeverityColor(severity models.IssueSeverity) string

GetSeverityColor returns the color code for a severity (for UI)

func HasCriticalIssues

func HasCriticalIssues(issues []Issue) bool

HasCriticalIssues returns true if there are any critical severity issues

func HasHighOrAboveIssues

func HasHighOrAboveIssues(issues []Issue) bool

HasHighOrAboveIssues returns true if there are high or critical severity issues

func ValidateScanResult

func ValidateScanResult(result *ScanResult) error

ValidateScanResult validates a scan result

Types

type Analyzer

type Analyzer interface {
	// Name returns the analyzer's unique identifier
	Name() string

	// Description returns a human-readable description
	Description() string

	// Analyze inspects a container and returns any security issues found
	Analyze(ctx context.Context, data *ContainerData) ([]Issue, error)

	// IsEnabled returns whether this analyzer is currently enabled
	IsEnabled() bool

	// SetEnabled enables or disables the analyzer
	SetEnabled(enabled bool)
}

Analyzer defines the interface for security analyzers. Each analyzer checks for a specific category of security issues.

type BaseAnalyzer

type BaseAnalyzer struct {
	// contains filtered or unexported fields
}

BaseAnalyzer provides common functionality for analyzers

func NewBaseAnalyzer

func NewBaseAnalyzer(name, description string) BaseAnalyzer

NewBaseAnalyzer creates a new BaseAnalyzer

func (*BaseAnalyzer) Description

func (a *BaseAnalyzer) Description() string

Description returns the analyzer description

func (*BaseAnalyzer) IsEnabled

func (a *BaseAnalyzer) IsEnabled() bool

IsEnabled returns whether the analyzer is enabled

func (*BaseAnalyzer) Name

func (a *BaseAnalyzer) Name() string

Name returns the analyzer name

func (*BaseAnalyzer) SetEnabled

func (a *BaseAnalyzer) SetEnabled(enabled bool)

SetEnabled sets the analyzer enabled state

type Calculator

type Calculator struct {
	// contains filtered or unexported fields
}

Calculator handles security score calculation

func NewCalculator

func NewCalculator(config *ScoreConfig) *Calculator

NewCalculator creates a new score calculator

func (*Calculator) Calculate

func (c *Calculator) Calculate(issues []Issue) *ScoreResult

Calculate computes the security score from a list of issues

type CategoryScore

type CategoryScore struct {
	Issues       int
	TotalPenalty int
	CappedAt     int  // If penalty was capped
	WasCapped    bool // Whether capping was applied
}

CategoryScore holds score breakdown for a category

type ContainerData

type ContainerData struct {
	// Basic identification
	ID    string
	Name  string
	Image string

	// Container configuration
	User        string            // User running in container
	Env         []string          // Environment variables
	Labels      map[string]string // Container labels
	Cmd         []string          // Command
	Entrypoint  []string          // Entrypoint
	WorkingDir  string            // Working directory
	Healthcheck *HealthcheckData  // Healthcheck configuration

	// Host configuration
	Privileged     bool     // Privileged mode
	ReadonlyRootfs bool     // Read-only filesystem
	NetworkMode    string   // Network mode (bridge, host, etc.)
	PidMode        string   // PID namespace mode
	IpcMode        string   // IPC namespace mode
	CapAdd         []string // Added capabilities
	CapDrop        []string // Dropped capabilities
	SecurityOpt    []string // Security options
	RestartPolicy  string   // Restart policy name

	// Resource limits
	MemoryLimit int64 // Memory limit in bytes
	MemorySwap  int64 // Memory+Swap limit
	CPUShares   int64 // CPU shares
	CPUQuota    int64 // CPU quota
	CPUPeriod   int64 // CPU period
	NanoCPUs    int64 // CPU limit in nano CPUs
	PidsLimit   int64 // PIDs limit

	// Networking
	Ports    []PortData    // Port mappings
	Networks []NetworkData // Network attachments

	// Storage
	Mounts []MountData // Volume mounts
	Binds  []string    // Bind mounts

	// State
	Running bool
	Health  string // healthy, unhealthy, starting, none
}

ContainerData holds all the information needed for security analysis. It's a normalized structure that abstracts the Docker API response.

func ContainerDataFromInspect

func ContainerDataFromInspect(inspect types.ContainerJSON) *ContainerData

ContainerDataFromInspect converts Docker API inspect response to ContainerData

type ContainerReportData

type ContainerReportData struct {
	ContainerID   string               `json:"container_id"`
	ContainerName string               `json:"container_name"`
	Image         string               `json:"image"`
	Score         int                  `json:"score"`
	Grade         models.SecurityGrade `json:"grade"`
	GradeColor    string               `json:"grade_color"`
	IssueCount    int                  `json:"issue_count"`
	CriticalCount int                  `json:"critical_count"`
	HighCount     int                  `json:"high_count"`
	MediumCount   int                  `json:"medium_count"`
	LowCount      int                  `json:"low_count"`
	Issues        []IssueReportData    `json:"issues,omitempty"`
	ScannedAt     time.Time            `json:"scanned_at"`
}

ContainerReportData holds data for a single container in a report

type DataPoint

type DataPoint struct {
	Timestamp time.Time `json:"timestamp"`
	Value     float64   `json:"value"`
}

DataPoint represents a data point in a trend

type DockerClient

type DockerClient interface {
	ContainerInspect(ctx context.Context, containerID string) (interface{}, error)
	ContainerList(ctx context.Context, all bool) ([]interface{}, error)
}

DockerClient interface for Docker operations needed by security service

type HealthcheckData

type HealthcheckData struct {
	Test        []string // Health check command
	Interval    int64    // Interval in nanoseconds
	Timeout     int64    // Timeout in nanoseconds
	Retries     int      // Number of retries
	StartPeriod int64    // Start period in nanoseconds
}

HealthcheckData represents healthcheck configuration

type HighRiskPort

type HighRiskPort struct {
	OpenPort
	ServiceName string `json:"service_name"`
	Risk        string `json:"risk"` // low, medium, high, critical
	Description string `json:"description"`
	Mitigation  string `json:"mitigation"`
}

HighRiskPort represents a port that is commonly associated with security risks

type HostPortAnalysis

type HostPortAnalysis struct {
	ScannedAt       time.Time      `json:"scanned_at"`
	Duration        time.Duration  `json:"duration"`
	TotalOpenPorts  int            `json:"total_open_ports"`
	TCPPorts        []OpenPort     `json:"tcp_ports"`
	UDPPorts        []OpenPort     `json:"udp_ports"`
	ExposedPorts    []OpenPort     `json:"exposed_ports"`    // Ports bound to 0.0.0.0 or ::
	PrivilegedPorts []OpenPort     `json:"privileged_ports"` // Ports < 1024
	HighRiskPorts   []HighRiskPort `json:"high_risk_ports"`  // Known risky services
	UnknownServices []OpenPort     `json:"unknown_services"` // Ports without known service
	Recommendations []string       `json:"recommendations,omitempty"`
	SecurityScore   int            `json:"security_score"` // 0-100
}

HostPortAnalysis represents the complete port analysis for a host

type HostPortScanner

type HostPortScanner struct {
	// contains filtered or unexported fields
}

HostPortScanner provides host-level port scanning capabilities

func NewHostPortScanner

func NewHostPortScanner(log *logger.Logger) *HostPortScanner

NewHostPortScanner creates a new host port scanner

func (*HostPortScanner) EnrichWithProcessInfo

func (s *HostPortScanner) EnrichWithProcessInfo(ports []OpenPort)

EnrichWithProcessInfo adds process information to open ports

func (*HostPortScanner) GetProcessForPort

func (s *HostPortScanner) GetProcessForPort(inode uint64) (int, string, error)

GetProcessForPort attempts to find the process using a given port This requires reading /proc/<pid>/fd symlinks which needs root privileges

func (*HostPortScanner) ScanHostPorts

func (s *HostPortScanner) ScanHostPorts(ctx context.Context) (*HostPortAnalysis, error)

ScanHostPorts performs a comprehensive scan of open ports on the host

type Issue

type Issue struct {
	CheckID        string // Unique check identifier (e.g., "USER_001")
	Severity       models.IssueSeverity
	Category       models.IssueCategory
	Title          string
	Description    string
	Recommendation string
	FixCommand     string                 // Command to fix the issue
	DocURL         string                 // Documentation URL
	Penalty        int                    // Score penalty
	Details        map[string]interface{} // Additional context
}

Issue represents a security issue found during analysis

func FilterIssuesByCategory

func FilterIssuesByCategory(issues []Issue, category models.IssueCategory) []Issue

FilterIssuesByCategory returns issues in the given category

func FilterIssuesBySeverity

func FilterIssuesBySeverity(issues []Issue, minSeverity models.IssueSeverity) []Issue

FilterIssuesBySeverity returns issues at or above the given severity

func NewIssue

func NewIssue(check models.SecurityCheck, description string) Issue

NewIssue creates a new Issue from a SecurityCheck definition

func SortIssuesBySeverity

func SortIssuesBySeverity(issues []Issue) []Issue

SortIssuesBySeverity sorts issues by severity (critical first)

func (Issue) WithDetail

func (i Issue) WithDetail(key string, value interface{}) Issue

WithDetail adds a single detail to an issue

func (Issue) WithDetails

func (i Issue) WithDetails(details map[string]interface{}) Issue

WithDetails adds details to an issue

type IssueReportData

type IssueReportData struct {
	ID             string               `json:"id"`
	ContainerName  string               `json:"container_name"`
	Severity       models.IssueSeverity `json:"severity"`
	SeverityColor  string               `json:"severity_color"`
	Category       models.IssueCategory `json:"category"`
	Title          string               `json:"title"`
	Description    string               `json:"description"`
	Recommendation string               `json:"recommendation"`
	FixCommand     string               `json:"fix_command,omitempty"`
	DocURL         string               `json:"doc_url,omitempty"`
	CVEID          string               `json:"cve_id,omitempty"`
	CVSSScore      float64              `json:"cvss_score,omitempty"`
}

IssueReportData holds data for a single issue in a report

type IssueRepository

type IssueRepository interface {
	CreateBatch(ctx context.Context, issues []models.SecurityIssue) error
	GetByID(ctx context.Context, id int64) (*models.SecurityIssue, error)
	GetByScanID(ctx context.Context, scanID uuid.UUID) ([]*models.SecurityIssue, error)
	GetByContainerID(ctx context.Context, containerID string, status *models.IssueStatus) ([]*models.SecurityIssue, error)
	GetByHostID(ctx context.Context, hostID uuid.UUID, opts ListIssuesOptions) ([]*models.SecurityIssue, int, error)
	UpdateStatus(ctx context.Context, id int64, status models.IssueStatus, userID *uuid.UUID) error
	GetOpenIssueCount(ctx context.Context, containerID string) (int, error)
	DeleteByScanID(ctx context.Context, scanID uuid.UUID) error
}

IssueRepository interface for persisting security issues

type ListIssuesOptions

type ListIssuesOptions struct {
	ContainerID *string
	ScanID      *uuid.UUID
	Severity    *models.IssueSeverity
	Category    *models.IssueCategory
	Status      *models.IssueStatus
	CheckID     *string
	Limit       int
	Offset      int
}

ListIssuesOptions holds options for listing issues

type ListScansOptions

type ListScansOptions struct {
	HostID      *uuid.UUID
	ContainerID *string
	MinScore    *int
	MaxScore    *int
	Grade       *models.SecurityGrade
	Since       *time.Time
	Limit       int
	Offset      int
}

ListScansOptions holds options for listing scans

type MountData

type MountData struct {
	Type        string // bind, volume, tmpfs
	Source      string
	Destination string
	Mode        string // rw, ro
	RW          bool
	Propagation string
}

MountData represents a mount point

type NetworkData

type NetworkData struct {
	Name      string
	NetworkID string
	IPAddress string
	Gateway   string
}

NetworkData represents network attachment information

type OpenPort

type OpenPort struct {
	Port      uint16 `json:"port"`
	Protocol  string `json:"protocol"` // tcp, tcp6, udp, udp6
	LocalAddr string `json:"local_addr"`
	State     string `json:"state"`
	PID       int    `json:"pid,omitempty"`
	Process   string `json:"process,omitempty"`
	UID       int    `json:"uid,omitempty"`
	Inode     uint64 `json:"inode,omitempty"`
}

OpenPort represents an open port on the host

type PortData

type PortData struct {
	ContainerPort uint16
	HostPort      uint16
	HostIP        string
	Protocol      string // tcp, udp
}

PortData represents a port mapping

type ReportData

type ReportData struct {
	// Report metadata
	ID          uuid.UUID `json:"id"`
	GeneratedAt time.Time `json:"generated_at"`
	Title       string    `json:"title"`

	// Scope
	HostID   *uuid.UUID `json:"host_id,omitempty"`
	HostName string     `json:"host_name,omitempty"`

	// Summary statistics
	TotalContainers   int     `json:"total_containers"`
	ScannedContainers int     `json:"scanned_containers"`
	AverageScore      float64 `json:"average_score"`
	LowestScore       int     `json:"lowest_score"`
	HighestScore      int     `json:"highest_score"`

	// Grade distribution
	GradeDistribution map[models.SecurityGrade]int `json:"grade_distribution"`

	// Issue summary
	TotalIssues    int                          `json:"total_issues"`
	SeverityCounts map[models.IssueSeverity]int `json:"severity_counts"`

	// Container details
	Containers []ContainerReportData `json:"containers"`

	// Top issues across all containers
	TopIssues []IssueReportData `json:"top_issues"`

	// Trends (if available)
	Trends *TrendsData `json:"trends,omitempty"`
}

ReportData holds all data for a security report

type ReportFormat

type ReportFormat string

ReportFormat represents the format of a security report

const (
	ReportFormatJSON     ReportFormat = "json"
	ReportFormatHTML     ReportFormat = "html"
	ReportFormatMarkdown ReportFormat = "markdown"
	ReportFormatText     ReportFormat = "text"
)

type ReportGenerator

type ReportGenerator struct {
	// contains filtered or unexported fields
}

ReportGenerator generates security reports

func NewReportGenerator

func NewReportGenerator() *ReportGenerator

NewReportGenerator creates a new report generator

func (*ReportGenerator) Generate

func (g *ReportGenerator) Generate(ctx context.Context, data *ReportData, opts *ReportOptions) ([]byte, error)

Generate generates a security report

type ReportOptions

type ReportOptions struct {
	Format          ReportFormat
	IncludeDetails  bool                 // Include full issue details
	IncludeTrends   bool                 // Include historical trends
	GroupByCategory bool                 // Group issues by category
	GroupBySeverity bool                 // Group issues by severity
	MinSeverity     models.IssueSeverity // Minimum severity to include
}

ReportOptions holds options for report generation

func DefaultReportOptions

func DefaultReportOptions() *ReportOptions

DefaultReportOptions returns the default report options

type ScanRepository

type ScanRepository interface {
	Create(ctx context.Context, scan *models.SecurityScan) error
	GetByID(ctx context.Context, id uuid.UUID) (*models.SecurityScan, error)
	GetByContainerID(ctx context.Context, containerID string, limit int) ([]*models.SecurityScan, error)
	GetByHostID(ctx context.Context, hostID uuid.UUID, limit int) ([]*models.SecurityScan, error)
	GetLatestByContainer(ctx context.Context, containerID string) (*models.SecurityScan, error)
	List(ctx context.Context, opts ListScansOptions) ([]*models.SecurityScan, int, error)
	Delete(ctx context.Context, id uuid.UUID) error
	DeleteOlderThan(ctx context.Context, before time.Time) (int64, error)
	GetScoreHistory(ctx context.Context, containerID string, days int) ([]models.TrendPoint, error)
	GetGlobalScoreHistory(ctx context.Context, days int) ([]models.TrendPoint, error)
	GetAverageScore(ctx context.Context, hostID *uuid.UUID) (float64, error)
}

ScanRepository interface for persisting scan results

type ScanResult

type ScanResult struct {
	// Scan metadata
	ID            uuid.UUID `json:"id"`
	ContainerID   string    `json:"container_id"`
	ContainerName string    `json:"container_name"`
	Image         string    `json:"image"`
	HostID        uuid.UUID `json:"host_id"`

	// Score and grade
	Score int                  `json:"score"`
	Grade models.SecurityGrade `json:"grade"`

	// Issues found
	Issues        []Issue `json:"issues"`
	IssueCount    int     `json:"issue_count"`
	CriticalCount int     `json:"critical_count"`
	HighCount     int     `json:"high_count"`
	MediumCount   int     `json:"medium_count"`
	LowCount      int     `json:"low_count"`

	// CVE information (if scanned)
	CVECount   int  `json:"cve_count"`
	IncludeCVE bool `json:"include_cve"`

	// Timing
	ScanDuration time.Duration `json:"scan_duration"`
	ScannedAt    time.Time     `json:"scanned_at"`

	// Errors during scan (non-fatal)
	Warnings []string `json:"warnings,omitempty"`
}

ScanResult holds the result of a security scan

func (*ScanResult) ToSecurityIssues

func (r *ScanResult) ToSecurityIssues() []models.SecurityIssue

ToSecurityIssues converts issues to models.SecurityIssue

func (*ScanResult) ToSecurityScan

func (r *ScanResult) ToSecurityScan() *models.SecurityScan

ToSecurityScan converts a ScanResult to a models.SecurityScan

type Scanner

type Scanner struct {
	// contains filtered or unexported fields
}

Scanner performs security analysis on Docker containers

func NewScanner

func NewScanner(config *ScannerConfig) *Scanner

NewScanner creates a new security scanner

func (*Scanner) IsTrivyAvailable

func (s *Scanner) IsTrivyAvailable() bool

IsTrivyAvailable returns true if Trivy is configured and available

func (*Scanner) QuickScan

func (s *Scanner) QuickScan(ctx context.Context, inspect types.ContainerJSON) (int, models.SecurityGrade, error)

QuickScan performs a quick scan returning only the score (no issues stored)

func (*Scanner) ScanContainer

func (s *Scanner) ScanContainer(ctx context.Context, inspect types.ContainerJSON, hostID uuid.UUID) (*ScanResult, error)

ScanContainer performs a security scan on a single container

func (*Scanner) ScanContainers

func (s *Scanner) ScanContainers(ctx context.Context, containers []types.ContainerJSON, hostID uuid.UUID) ([]*ScanResult, error)

ScanContainers performs security scans on multiple containers concurrently

func (*Scanner) SetAnalyzers

func (s *Scanner) SetAnalyzers(analyzers []Analyzer)

SetAnalyzers sets the analyzers to use

func (*Scanner) SetTrivyClient

func (s *Scanner) SetTrivyClient(client TrivyClient)

SetTrivyClient sets the optional Trivy client for CVE scanning

type ScannerConfig

type ScannerConfig struct {
	// Analyzers to use (nil for all defaults)
	Analyzers []Analyzer

	// Scoring configuration
	ScoreConfig *ScoreConfig

	// Timeout for scanning a single container
	ScanTimeout time.Duration

	// Whether to include CVE scanning (requires Trivy)
	IncludeCVE bool

	// Maximum concurrent scans
	MaxConcurrent int
}

ScannerConfig holds configuration for the security scanner

func DefaultScannerConfig

func DefaultScannerConfig() *ScannerConfig

DefaultScannerConfig returns the default scanner configuration

type ScoreConfig

type ScoreConfig struct {
	// Base score starts at 100
	BaseScore int

	// Individual check penalties (can be overridden)
	Penalties map[string]int

	// Severity multipliers (applied after individual penalties)
	SeverityMultipliers map[models.IssueSeverity]float64

	// Maximum penalties per category to prevent single category domination
	MaxPenaltyPerCategory map[models.IssueCategory]int

	// Minimum score (floor)
	MinScore int

	// Maximum score (ceiling)
	MaxScore int
}

ScoreConfig holds the penalty values for different security issues

func DefaultScoreConfig

func DefaultScoreConfig() *ScoreConfig

DefaultScoreConfig returns the default scoring configuration

type ScoreResult

type ScoreResult struct {
	// Final score (0-100)
	Score int

	// Grade (A-F)
	Grade models.SecurityGrade

	// Breakdown by category
	CategoryBreakdown map[models.IssueCategory]CategoryScore

	// Total penalties applied
	TotalPenalty int

	// Number of issues by severity
	SeverityCounts map[models.IssueSeverity]int

	// Top issues (sorted by penalty)
	TopIssues []Issue
}

ScoreResult holds the calculated score and breakdown

type SecuritySummary

type SecuritySummary struct {
	GeneratedAt       time.Time                    `json:"generated_at"`
	TotalContainers   int                          `json:"total_containers"`
	TotalIssues       int                          `json:"total_issues"`
	AverageScore      float64                      `json:"average_score"`
	GradeDistribution map[models.SecurityGrade]int `json:"grade_distribution"`
	SeverityCounts    map[models.IssueSeverity]int `json:"severity_counts"`
}

SecuritySummary holds aggregated security statistics

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service provides security scanning functionality

func NewService

func NewService(
	config *ServiceConfig,
	scanRepo ScanRepository,
	issueRepo IssueRepository,
	log *logger.Logger,
) *Service

NewService creates a new security service

func (*Service) CleanupOldScans

func (s *Service) CleanupOldScans(ctx context.Context) (int64, error)

CleanupOldScans removes scans older than the retention period

func (*Service) DeleteScan

func (s *Service) DeleteScan(ctx context.Context, id uuid.UUID) error

DeleteScan deletes a scan and its associated issues

func (*Service) GenerateReport

func (s *Service) GenerateReport(ctx context.Context, hostID uuid.UUID, opts *ReportOptions) ([]byte, error)

GenerateReport generates a security report in the specified format

func (*Service) GetAverageScore

func (s *Service) GetAverageScore(ctx context.Context, hostID *uuid.UUID) (float64, error)

GetAverageScore returns the current average security score

func (*Service) GetContainerIssues

func (s *Service) GetContainerIssues(ctx context.Context, containerID string, status *models.IssueStatus) ([]*models.SecurityIssue, error)

GetContainerIssues retrieves open issues for a container

func (*Service) GetContainerScans

func (s *Service) GetContainerScans(ctx context.Context, containerID string, limit int) ([]*models.SecurityScan, error)

GetContainerScans retrieves scans for a specific container

func (*Service) GetGlobalScoreHistory

func (s *Service) GetGlobalScoreHistory(ctx context.Context, days int) ([]models.TrendPoint, error)

GetGlobalScoreHistory returns average score across all containers over N days.

func (*Service) GetHostIssues

func (s *Service) GetHostIssues(ctx context.Context, hostID uuid.UUID, opts ListIssuesOptions) ([]*models.SecurityIssue, int, error)

GetHostIssues retrieves issues for a host

func (*Service) GetHostScans

func (s *Service) GetHostScans(ctx context.Context, hostID uuid.UUID, limit int) ([]*models.SecurityScan, error)

GetHostScans retrieves scans for all containers on a host

func (*Service) GetIssue

func (s *Service) GetIssue(ctx context.Context, id int64) (*models.SecurityIssue, error)

GetIssue retrieves a security issue by ID

func (*Service) GetLatestScan

func (s *Service) GetLatestScan(ctx context.Context, containerID string) (*models.SecurityScan, error)

GetLatestScan retrieves the most recent scan for a container

func (*Service) GetScan

func (s *Service) GetScan(ctx context.Context, id uuid.UUID) (*models.SecurityScan, error)

GetScan retrieves a scan by ID

func (*Service) GetScanner

func (s *Service) GetScanner() *Scanner

GetScanner returns the underlying scanner for direct access

func (*Service) GetScoreHistory

func (s *Service) GetScoreHistory(ctx context.Context, containerID string, days int) ([]models.TrendPoint, error)

GetScoreHistory retrieves the score history for a container over N days. If containerID is empty, returns average scores across all containers.

func (*Service) GetSecuritySummary

func (s *Service) GetSecuritySummary(ctx context.Context, hostID *uuid.UUID) (*SecuritySummary, error)

GetSecuritySummary returns a summary of security status

func (*Service) IsTrivyAvailable

func (s *Service) IsTrivyAvailable() bool

IsTrivyAvailable returns true if Trivy is configured and available

func (*Service) ListScans

func (s *Service) ListScans(ctx context.Context, opts ListScansOptions) ([]*models.SecurityScan, int, error)

ListScans lists security scans with filtering

func (*Service) SaveScanResult

func (s *Service) SaveScanResult(ctx context.Context, result *ScanResult) error

SaveScanResult persists a scan result to the database

func (*Service) ScanContainer

func (s *Service) ScanContainer(ctx context.Context, containerInspect interface{}, hostID uuid.UUID) (*models.SecurityScan, error)

ScanContainer performs a security scan on a container and persists results. It accepts either a types.ContainerJSON directly or a *types.ContainerJSON pointer and delegates to ScanContainerJSON for the actual scan.

func (*Service) ScanContainerJSON

func (s *Service) ScanContainerJSON(ctx context.Context, containerJSON types.ContainerJSON, hostID uuid.UUID) (*models.SecurityScan, error)

ScanContainerJSON performs a scan using Docker types.ContainerJSON and persists results

func (*Service) SetAnalyzers

func (s *Service) SetAnalyzers(analyzers []Analyzer)

SetAnalyzers sets the analyzers to use

func (*Service) SetTrivyClient

func (s *Service) SetTrivyClient(client TrivyClient)

SetTrivyClient sets the Trivy client for CVE scanning

func (*Service) UpdateIssueStatus

func (s *Service) UpdateIssueStatus(ctx context.Context, issueID int64, status models.IssueStatus, userID *uuid.UUID) error

UpdateIssueStatus updates the status of a security issue

type ServiceConfig

type ServiceConfig struct {
	// Scanner configuration
	ScannerConfig *ScannerConfig

	// Auto-scan interval (0 to disable)
	AutoScanInterval time.Duration

	// Retention period for scan history
	ScanRetentionDays int

	// Maximum scans to keep per container
	MaxScansPerContainer int
}

ServiceConfig holds configuration for the security service

func DefaultServiceConfig

func DefaultServiceConfig() *ServiceConfig

DefaultServiceConfig returns the default service configuration

type TrendsData

type TrendsData struct {
	Period        string      `json:"period"`
	AverageScores []DataPoint `json:"average_scores"`
	IssueCounts   []DataPoint `json:"issue_counts"`
	Improvement   float64     `json:"improvement_percent"`
}

TrendsData holds historical trend data

type TrivyClient

type TrivyClient interface {
	ScanImage(ctx context.Context, image string) ([]Issue, error)
	IsAvailable() bool
}

TrivyClient interface for CVE scanning (implemented separately)

Directories

Path Synopsis
Package analyzer provides individual security analyzers for container inspection.
Package analyzer provides individual security analyzers for container inspection.
Package trivy provides integration with Trivy vulnerability scanner.
Package trivy provides integration with Trivy vulnerability scanner.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL