security

package
v1.2.12 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	SeverityCritical = "critical"
	SeverityHigh     = "high"
	SeverityMedium   = "medium"
)

Severity levels for security insights.

View Source
const (
	CategoryTLS             = "tls"
	CategoryCVEs            = "cves"
	CategoryUpdates         = "updates"
	CategoryNetworkExposure = "network_exposure"
	CategoryImageAge        = "image_age"
)

Category names.

View Source
const (
	WeightCVEs            = 30
	WeightNetworkExposure = 25
	WeightTLS             = 20
	WeightUpdates         = 15
	WeightImageAge        = 10
)

Category weights (must sum to 100).

Variables

This section is empty.

Functions

func ColorLevel

func ColorLevel(score int) string

ColorLevel returns the color indicator for a given score.

func FormatAlertMessage

func FormatAlertMessage(insights []Insight) string

FormatAlertMessage builds a human-readable alert message for a container's insights.

func HighestSeverity

func HighestSeverity(insights []Insight) string

HighestSeverity returns the most severe level from a list of insights.

func InsightFindingKey added in v1.2.2

func InsightFindingKey(i Insight) string

InsightFindingKey returns the dedup key for an insight's finding.

func Now

func Now() time.Time

Now returns the current time (extracted for testing).

Types

type AcknowledgmentStore

type AcknowledgmentStore interface {
	InsertAcknowledgment(ctx context.Context, ack *RiskAcknowledgment) (int64, error)
	DeleteAcknowledgment(ctx context.Context, id int64) error
	ListAcknowledgments(ctx context.Context, containerExternalID string) ([]*RiskAcknowledgment, error)
	GetAcknowledgment(ctx context.Context, id int64) (*RiskAcknowledgment, error)
	IsAcknowledged(ctx context.Context, containerExternalID, findingType, findingKey string) (bool, error)
}

AcknowledgmentStore persists risk acknowledgments.

type AlertCallback

type AlertCallback func(containerID int64, containerName string, insights []Insight, isRecover bool)

AlertCallback is called when security insights change and an alert should be fired.

type CVEInfo

type CVEInfo struct {
	CVEID    string
	Severity string // "critical", "high", "medium", "low"
}

CVEInfo holds a single CVE for scoring.

type CVEReader

type CVEReader interface {
	ListCVEsForContainer(ctx context.Context, containerExternalID string) ([]CVEInfo, error)
}

CVEReader provides CVE data for a container.

type CategoryScore

type CategoryScore struct {
	Name       string `json:"name"`
	Weight     int    `json:"weight"`
	SubScore   int    `json:"sub_score"`
	Applicable bool   `json:"applicable"`
	IssueCount int    `json:"issue_count"`
	Summary    string `json:"summary"`
}

CategoryScore represents one dimension of the security score.

type CategorySummary

type CategorySummary struct {
	Name        string `json:"name"`
	TotalIssues int    `json:"total_issues"`
	Summary     string `json:"summary"`
}

CategorySummary holds aggregated category data across all containers.

type CertificateInfo

type CertificateInfo struct {
	Status        string // "valid", "expiring", "expired", "error"
	DaysRemaining int
}

CertificateInfo holds certificate monitor status for scoring.

type CertificateReader

type CertificateReader interface {
	ListCertificatesForContainer(ctx context.Context, containerExternalID string) ([]CertificateInfo, error)
}

CertificateReader provides certificate data for a container.

type ContainerInfo

type ContainerInfo struct {
	ID         int64
	ExternalID string
	Name       string
}

ContainerInfo holds minimal container data for infrastructure scoring.

type ContainerInsights

type ContainerInsights struct {
	ContainerID     int64     `json:"container_id"`
	ContainerName   string    `json:"container_name"`
	HighestSeverity *string   `json:"highest_severity"`
	Count           int       `json:"count"`
	Insights        []Insight `json:"insights"`
}

ContainerInsights holds all active insights for a single container.

type ContainerRisk

type ContainerRisk struct {
	ContainerID   int64  `json:"container_id"`
	ContainerName string `json:"container_name"`
	Score         int    `json:"score"`
	ColorLevel    string `json:"color"`
	TopIssue      string `json:"top_issue"`
}

ContainerRisk is a container's score entry for ranking purposes.

type Deps

type Deps struct {
	Logger        *slog.Logger  // required
	AlertCallback AlertCallback // optional — nil-safe
	EventCallback EventCallback // optional — nil-safe
}

Deps holds all dependencies for the security Service.

type DockerSecurityConfig

type DockerSecurityConfig struct {
	Privileged  bool
	NetworkMode string
	Bindings    []PortBinding
}

DockerSecurityConfig holds the security-relevant fields extracted from Docker's ContainerInspect.

type EventCallback

type EventCallback func(eventType string, data any)

EventCallback is called to broadcast SSE events.

type InfrastructurePosture

type InfrastructurePosture struct {
	Score          int               `json:"score"`
	ColorLevel     string            `json:"color"`
	ContainerCount int               `json:"container_count"`
	ScoredCount    int               `json:"scored_count"`
	IsPartial      bool              `json:"is_partial"`
	Categories     []CategorySummary `json:"categories"`
	TopRisks       []ContainerRisk   `json:"top_risks"`
	ComputedAt     time.Time         `json:"computed_at"`
}

InfrastructurePosture is the top-level aggregation across all containers.

type Insight

type Insight struct {
	Type          InsightType    `json:"type"`
	Severity      string         `json:"severity"`
	ContainerID   int64          `json:"container_id"`
	ContainerName string         `json:"container_name"`
	Title         string         `json:"title"`
	Description   string         `json:"description"`
	Details       map[string]any `json:"details"`
	DetectedAt    time.Time      `json:"detected_at"`
}

Insight represents a single detected dangerous configuration.

func AnalyzeDocker

func AnalyzeDocker(containerID int64, containerName string, cfg DockerSecurityConfig, now time.Time) []Insight

AnalyzeDocker inspects a Docker container's security configuration and returns all detected insights.

type InsightType

type InsightType string

InsightType enumerates the categories of dangerous configurations.

const (
	PortExposedAllInterfaces InsightType = "port_exposed_all_interfaces"
	DatabasePortExposed      InsightType = "database_port_exposed"
	PrivilegedContainer      InsightType = "privileged_container"
	HostNetworkMode          InsightType = "host_network_mode"
	ServiceLoadBalancer      InsightType = "service_load_balancer"
	ServiceNodePort          InsightType = "service_node_port"
	MissingNetworkPolicy     InsightType = "missing_network_policy"
)

type PortBinding

type PortBinding struct {
	HostIP   string
	HostPort string
	Port     int
	Protocol string
}

PortBinding represents a single host port binding from Docker HostConfig.

type PostureAlertCallback

type PostureAlertCallback func(score int, previousScore int, color string, isBreach bool)

PostureAlertCallback is called when the infrastructure score crosses a threshold.

type PostureEventCallback

type PostureEventCallback func(eventType string, data any)

PostureEventCallback is called to emit SSE events for posture changes.

type RiskAcknowledgment

type RiskAcknowledgment struct {
	ID                  int64     `json:"id"`
	ContainerExternalID string    `json:"container_external_id"`
	FindingType         string    `json:"finding_type"`
	FindingKey          string    `json:"finding_key"`
	AcknowledgedBy      string    `json:"acknowledged_by"`
	Reason              string    `json:"reason"`
	AcknowledgedAt      time.Time `json:"acknowledged_at"`
}

RiskAcknowledgment is a user-created marker indicating a specific risk finding is accepted.

type Scorer

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

Scorer computes security posture scores for containers and infrastructure.

func NewScorer

func NewScorer(d ScorerDeps) *Scorer

NewScorer creates a new Scorer with the given data source readers. All readers are optional — categories with nil readers are skipped during scoring.

func (*Scorer) CheckPostureThreshold

func (s *Scorer) CheckPostureThreshold(score int, color string)

CheckPostureThreshold compares the current score against the threshold and fires alerts.

func (*Scorer) InvalidateCache

func (s *Scorer) InvalidateCache(containerID int64)

InvalidateCache removes a container's cached score.

func (*Scorer) ScoreContainer

func (s *Scorer) ScoreContainer(ctx context.Context, containerID int64, containerExternalID string, containerName string) (*SecurityScore, error)

ScoreContainer computes the security score for a single container.

func (*Scorer) ScoreInfrastructure

func (s *Scorer) ScoreInfrastructure(ctx context.Context, containers []ContainerInfo) (*InfrastructurePosture, error)

ScoreInfrastructure computes the infrastructure-wide security posture.

func (*Scorer) SetPostureAlertCallback

func (s *Scorer) SetPostureAlertCallback(cb PostureAlertCallback)

SetPostureAlertCallback sets the callback for posture threshold alerts.

func (*Scorer) SetPostureEventCallback

func (s *Scorer) SetPostureEventCallback(cb PostureEventCallback)

SetPostureEventCallback sets the callback for posture SSE events.

func (*Scorer) SetThreshold

func (s *Scorer) SetThreshold(threshold int)

SetThreshold configures the score threshold for alerts. 0 disables alerts.

func (*Scorer) Threshold

func (s *Scorer) Threshold() int

Threshold returns the current threshold value.

type ScorerDeps

type ScorerDeps struct {
	Certs                CertificateReader    // optional — nil skips TLS scoring
	CVEs                 CVEReader            // optional — nil skips CVE scoring
	Updates              UpdateReader         // optional — nil skips update scoring
	Security             *Service             // optional — nil skips network exposure scoring
	Acks                 AcknowledgmentStore  // required
	Threshold            int                  // optional — 0 disables alerts
	PostureAlertCallback PostureAlertCallback // optional — nil-safe
	PostureEventCallback PostureEventCallback // optional — nil-safe
}

ScorerDeps holds all dependencies for the security Scorer.

type SecurityScore

type SecurityScore struct {
	ContainerID     int64           `json:"container_id"`
	ContainerName   string          `json:"container_name"`
	TotalScore      int             `json:"score"`
	ColorLevel      string          `json:"color"`
	Categories      []CategoryScore `json:"categories"`
	ApplicableCount int             `json:"applicable_count"`
	ComputedAt      time.Time       `json:"computed_at"`
	IsPartial       bool            `json:"is_partial"`
}

SecurityScore represents the computed security health score for a single container.

type Service

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

Service manages in-memory security insight state and emits alerts/events on changes.

func NewService

func NewService(d Deps) *Service

NewService creates a new security insight service.

func (*Service) GetAllInsights

func (s *Service) GetAllInsights() []ContainerInsights

GetAllInsights returns insights grouped by container.

func (*Service) GetContainerInsights

func (s *Service) GetContainerInsights(containerID int64) *ContainerInsights

GetContainerInsights returns the current insights for a container.

func (*Service) GetSummary

func (s *Service) GetSummary(totalContainers int) Summary

GetSummary returns aggregated counts across all containers.

func (*Service) InsightCount

func (s *Service) InsightCount(containerID int64) (int, string)

InsightCount returns the count and highest severity for a container (used by container list API).

func (*Service) RemoveContainer

func (s *Service) RemoveContainer(containerID int64)

RemoveContainer cleans up state for a container that no longer exists.

func (*Service) SetAlertCallback

func (s *Service) SetAlertCallback(cb AlertCallback)

SetAlertCallback sets the callback for alert events.

func (*Service) SetEventCallback

func (s *Service) SetEventCallback(cb EventCallback)

SetEventCallback sets the callback for SSE broadcasting.

func (*Service) UpdateContainer

func (s *Service) UpdateContainer(containerID int64, containerName string, newInsights []Insight)

UpdateContainer processes new insights for a single container, computes diffs, and emits alerts/events as needed.

type Summary

type Summary struct {
	TotalContainersMonitored int            `json:"total_containers_monitored"`
	TotalContainersAffected  int            `json:"total_containers_affected"`
	TotalInsights            int            `json:"total_insights"`
	BySeverity               map[string]int `json:"by_severity"`
	ByType                   map[string]int `json:"by_type"`
}

Summary provides aggregated counts across all containers.

type UpdateInfo

type UpdateInfo struct {
	UpdateType  string // "major", "minor", "patch", "digest_only"
	PublishedAt *time.Time
}

UpdateInfo holds update availability for scoring.

type UpdateReader

type UpdateReader interface {
	ListUpdatesForContainer(ctx context.Context, containerExternalID string) ([]UpdateInfo, error)
}

UpdateReader provides update and image age data for a container.

Jump to

Keyboard shortcuts

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