rule

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2026 License: GPL-3.0 Imports: 6 Imported by: 0

Documentation

Overview

Package rule provides domain entities for rule management. Rules are security scanning rules/templates from various sources (platform defaults, Git repos, HTTP URLs) that can be customized per tenant.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bundle

type Bundle struct {
	ID       shared.ID
	TenantID shared.ID
	ToolID   shared.ID

	// Version info
	Version     string // e.g., "20240115-a1b2c3d4"
	ContentHash string // SHA256 of bundle content (for change detection)

	// Statistics
	RuleCount   int
	SourceCount int
	SizeBytes   int64

	// Sources included
	SourceIDs    []shared.ID
	SourceHashes map[string]string // source_id -> content_hash

	// Storage location
	StoragePath string // S3 key or local path

	// Build status
	Status           BundleStatus
	BuildError       string
	BuildStartedAt   *time.Time
	BuildCompletedAt *time.Time

	CreatedAt time.Time
	ExpiresAt *time.Time
}

Bundle represents a pre-compiled rule package for agents. Bundles contain actual YAML files (platform + custom rules) as a tar.gz archive stored in object storage (S3/MinIO/local).

Structure inside bundle.tar.gz:

rules/
├── platform/        # Platform default rules
│   ├── rule1.yaml
│   └── rule2.yaml
├── custom/          # Tenant custom rules (all sources merged)
│   ├── source1/
│   │   └── rule3.yaml
│   └── source2/
│       └── rule4.yaml
└── manifest.json    # Bundle metadata

func NewBundle

func NewBundle(tenantID, toolID shared.ID) *Bundle

NewBundle creates a new bundle.

func (*Bundle) IsExpired

func (b *Bundle) IsExpired() bool

IsExpired checks if the bundle has expired.

func (*Bundle) IsReady

func (b *Bundle) IsReady() bool

IsReady checks if the bundle is ready for download.

func (*Bundle) MarkBuildFailed

func (b *Bundle) MarkBuildFailed(err string)

MarkBuildFailed marks the bundle build as failed.

func (*Bundle) MarkBuildStarted

func (b *Bundle) MarkBuildStarted()

MarkBuildStarted marks the bundle build as started.

func (*Bundle) MarkBuildSuccess

func (b *Bundle) MarkBuildSuccess(
	version string,
	hash string,
	storagePath string,
	ruleCount int,
	sizeBytes int64,
	sourceIDs []shared.ID,
	sourceHashes map[string]string,
)

MarkBuildSuccess marks the bundle build as successful.

func (*Bundle) NeedsRebuild

func (b *Bundle) NeedsRebuild(currentSourceHashes map[string]string) bool

NeedsRebuild checks if the bundle needs to be rebuilt based on source hashes.

type BundleFilter

type BundleFilter struct {
	TenantID *shared.ID
	ToolID   *shared.ID
	Status   *BundleStatus
}

BundleFilter represents filter options for listing bundles.

type BundleManifest

type BundleManifest struct {
	Version     string            `json:"version"`
	ToolName    string            `json:"tool_name"`
	ContentHash string            `json:"content_hash"`
	CreatedAt   time.Time         `json:"created_at"`
	RuleCount   int               `json:"rule_count"`
	Sources     []BundleSourceRef `json:"sources"`
}

BundleManifest is stored inside the bundle as manifest.json

type BundleRepository

type BundleRepository interface {
	// Create creates a new bundle.
	Create(ctx context.Context, bundle *Bundle) error

	// GetByID retrieves a bundle by ID.
	GetByID(ctx context.Context, id shared.ID) (*Bundle, error)

	// GetByTenantAndID retrieves a bundle by tenant and ID.
	GetByTenantAndID(ctx context.Context, tenantID, id shared.ID) (*Bundle, error)

	// GetLatest retrieves the latest ready bundle for a tenant and tool.
	GetLatest(ctx context.Context, tenantID, toolID shared.ID) (*Bundle, error)

	// GetByContentHash retrieves a bundle by content hash.
	GetByContentHash(ctx context.Context, hash string) (*Bundle, error)

	// List lists bundles with filters.
	List(ctx context.Context, filter BundleFilter) ([]*Bundle, error)

	// Update updates a bundle.
	Update(ctx context.Context, bundle *Bundle) error

	// Delete deletes a bundle.
	Delete(ctx context.Context, id shared.ID) error

	// DeleteExpired deletes all expired bundles.
	DeleteExpired(ctx context.Context) (int64, error)
}

BundleRepository defines the interface for rule bundle persistence.

type BundleSourceRef

type BundleSourceRef struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	ContentHash string `json:"content_hash"`
	RuleCount   int    `json:"rule_count"`
	Priority    int    `json:"priority"`
	IsDefault   bool   `json:"is_default"`
}

BundleSourceRef references a source included in the bundle

type BundleStatus

type BundleStatus string

BundleStatus represents the build status of a rule bundle.

const (
	BundleStatusBuilding BundleStatus = "building"
	BundleStatusReady    BundleStatus = "ready"
	BundleStatusFailed   BundleStatus = "failed"
	BundleStatusExpired  BundleStatus = "expired"
)

type GitConfig

type GitConfig struct {
	URL           string `json:"url"`
	Branch        string `json:"branch"`
	Path          string `json:"path"`           // Subdirectory containing rules
	AuthType      string `json:"auth_type"`      // none, ssh, token
	CredentialsID string `json:"credentials_id"` // Reference to stored credentials
}

GitConfig represents configuration for Git-based rule sources.

type HTTPConfig

type HTTPConfig struct {
	URL           string `json:"url"`
	AuthType      string `json:"auth_type"`      // none, basic, bearer
	CredentialsID string `json:"credentials_id"` // Reference to stored credentials
}

HTTPConfig represents configuration for HTTP-based rule sources.

type LocalConfig

type LocalConfig struct {
	Path string `json:"path"`
}

LocalConfig represents configuration for local file-based rule sources.

type Override

type Override struct {
	ID       shared.ID
	TenantID shared.ID
	ToolID   *shared.ID

	// What to override
	RulePattern string // Glob pattern (e.g., "java.lang.*") or exact rule_id
	IsPattern   bool   // true = glob pattern, false = exact match

	// Override settings
	Enabled          bool     // Force enable or disable
	SeverityOverride Severity // Override severity (empty = no override)

	// Optional scope
	AssetGroupID  *shared.ID
	ScanProfileID *shared.ID

	// Audit
	Reason    string
	CreatedBy *shared.ID

	CreatedAt time.Time
	UpdatedAt time.Time
	ExpiresAt *time.Time // Optional expiration
}

Override represents a tenant-specific rule enable/disable configuration. Overrides allow tenants to: - Disable noisy/false-positive rules - Enable rules that are disabled by default - Override severity for specific rules

func NewOverride

func NewOverride(
	tenantID shared.ID,
	toolID *shared.ID,
	rulePattern string,
	isPattern bool,
	enabled bool,
	reason string,
	createdBy *shared.ID,
) *Override

NewOverride creates a new rule override.

func (*Override) IsExpired

func (o *Override) IsExpired() bool

IsExpired checks if the override has expired.

func (*Override) Matches

func (o *Override) Matches(ruleID string) bool

Matches checks if this override matches a given rule ID.

func (*Override) SetExpiration

func (o *Override) SetExpiration(expiresAt *time.Time)

SetExpiration sets the expiration time.

func (*Override) SetScope

func (o *Override) SetScope(assetGroupID, scanProfileID *shared.ID)

SetScope sets the scope (asset group and/or scan profile).

func (*Override) SetSeverityOverride

func (o *Override) SetSeverityOverride(severity Severity)

SetSeverityOverride sets the severity override.

type OverrideFilter

type OverrideFilter struct {
	TenantID      *shared.ID
	ToolID        *shared.ID
	AssetGroupID  *shared.ID
	ScanProfileID *shared.ID
	Enabled       *bool
}

OverrideFilter represents filter options for listing overrides.

type OverrideRepository

type OverrideRepository interface {
	// Create creates a new override.
	Create(ctx context.Context, override *Override) error

	// GetByID retrieves an override by ID.
	GetByID(ctx context.Context, id shared.ID) (*Override, error)

	// GetByTenantAndID retrieves an override by tenant and ID.
	GetByTenantAndID(ctx context.Context, tenantID, id shared.ID) (*Override, error)

	// List lists overrides with filters and pagination.
	List(ctx context.Context, filter OverrideFilter, page pagination.Pagination) (pagination.Result[*Override], error)

	// ListByTenantAndTool lists all overrides for a tenant and tool.
	ListByTenantAndTool(ctx context.Context, tenantID shared.ID, toolID *shared.ID) ([]*Override, error)

	// Update updates an override.
	Update(ctx context.Context, override *Override) error

	// Delete deletes an override.
	Delete(ctx context.Context, id shared.ID) error

	// DeleteExpired deletes all expired overrides.
	DeleteExpired(ctx context.Context) (int64, error)
}

OverrideRepository defines the interface for rule override persistence.

type Rule

type Rule struct {
	ID       shared.ID
	SourceID shared.ID
	TenantID shared.ID
	ToolID   *shared.ID

	// Rule identification (tool-specific)
	RuleID string // e.g., "java.lang.security.audit.sqli"
	Name   string

	// Classification
	Severity    Severity
	Category    string
	Subcategory string
	Tags        []string

	// Metadata
	Description    string
	Recommendation string
	References     []string
	CWEIDs         []string
	OWASPIDs       []string

	// File info within source
	FilePath    string
	ContentHash string

	// Additional metadata
	Metadata map[string]any

	CreatedAt time.Time
	UpdatedAt time.Time
}

Rule represents an individual security rule from a source.

func NewRule

func NewRule(
	sourceID shared.ID,
	tenantID shared.ID,
	toolID *shared.ID,
	ruleID string,
	name string,
	severity Severity,
) *Rule

NewRule creates a new rule from sync data.

func (*Rule) SetClassification

func (r *Rule) SetClassification(category, subcategory string, tags []string)

SetClassification sets the rule classification.

func (*Rule) SetReferences

func (r *Rule) SetReferences(refs, cweIDs, owaspIDs []string)

SetReferences sets security references.

func (*Rule) Update

func (r *Rule) Update(
	name string,
	severity Severity,
	category string,
	description string,
	contentHash string,
)

Update updates the rule from sync data.

type RuleFilter

type RuleFilter struct {
	TenantID *shared.ID
	ToolID   *shared.ID
	SourceID *shared.ID
	Severity *Severity
	Category string
	Tags     []string
	RuleIDs  []string // Filter by specific rule IDs
	Search   string
}

RuleFilter represents filter options for listing rules.

type RuleRepository

type RuleRepository interface {
	// Create creates a new rule.
	Create(ctx context.Context, rule *Rule) error

	// CreateBatch creates multiple rules in batch.
	CreateBatch(ctx context.Context, rules []*Rule) error

	// GetByID retrieves a rule by ID.
	GetByID(ctx context.Context, id shared.ID) (*Rule, error)

	// GetByTenantAndID retrieves a rule by tenant and ID.
	GetByTenantAndID(ctx context.Context, tenantID, id shared.ID) (*Rule, error)

	// GetBySourceAndRuleID retrieves a rule by source and rule ID.
	GetBySourceAndRuleID(ctx context.Context, sourceID shared.ID, ruleID string) (*Rule, error)

	// List lists rules with filters and pagination.
	List(ctx context.Context, filter RuleFilter, page pagination.Pagination) (pagination.Result[*Rule], error)

	// ListBySource lists all rules for a source.
	ListBySource(ctx context.Context, sourceID shared.ID) ([]*Rule, error)

	// Update updates a rule.
	Update(ctx context.Context, rule *Rule) error

	// UpsertBatch upserts multiple rules (insert or update).
	UpsertBatch(ctx context.Context, rules []*Rule) error

	// Delete deletes a rule.
	Delete(ctx context.Context, id shared.ID) error

	// DeleteBySource deletes all rules for a source.
	DeleteBySource(ctx context.Context, sourceID shared.ID) error

	// CountBySource counts rules for a source.
	CountBySource(ctx context.Context, sourceID shared.ID) (int, error)

	// CountByTenantAndTool counts rules for a tenant and tool.
	CountByTenantAndTool(ctx context.Context, tenantID shared.ID, toolID *shared.ID) (int, error)
}

RuleRepository defines the interface for rule persistence.

type Severity

type Severity string

Severity represents the rule severity level.

const (
	SeverityCritical Severity = "critical"
	SeverityHigh     Severity = "high"
	SeverityMedium   Severity = "medium"
	SeverityLow      Severity = "low"
	SeverityInfo     Severity = "info"
	SeverityUnknown  Severity = "unknown"
)

func (Severity) IsValid

func (s Severity) IsValid() bool

IsValid checks if the severity is valid.

type Source

type Source struct {
	ID          shared.ID
	TenantID    shared.ID
	ToolID      *shared.ID // Optional: if nil, applies to all tools
	Name        string
	Description string

	// Source configuration
	SourceType SourceType
	Config     json.RawMessage // GitConfig, HTTPConfig, or LocalConfig

	// Credentials reference (not stored directly)
	CredentialsID *shared.ID

	// Sync configuration
	SyncEnabled         bool
	SyncIntervalMinutes int

	// Sync status
	LastSyncAt       *time.Time
	LastSyncStatus   SyncStatus
	LastSyncError    string
	LastSyncDuration time.Duration
	ContentHash      string // SHA256 of synced content

	// Statistics
	RuleCount int

	// Priority for merge order (higher = applied later)
	Priority int

	// Platform default (managed by system)
	IsPlatformDefault bool

	Enabled   bool
	CreatedAt time.Time
	UpdatedAt time.Time
}

Source represents a rule source where rules are fetched from.

func NewSource

func NewSource(
	tenantID shared.ID,
	toolID *shared.ID,
	name string,
	sourceType SourceType,
	config json.RawMessage,
) (*Source, error)

NewSource creates a new rule source.

func (*Source) GetGitConfig

func (s *Source) GetGitConfig() (*GitConfig, error)

GetGitConfig parses and returns the Git configuration.

func (*Source) GetHTTPConfig

func (s *Source) GetHTTPConfig() (*HTTPConfig, error)

GetHTTPConfig parses and returns the HTTP configuration.

func (*Source) GetLocalConfig

func (s *Source) GetLocalConfig() (*LocalConfig, error)

GetLocalConfig parses and returns the local configuration.

func (*Source) MarkSyncFailed

func (s *Source) MarkSyncFailed(errMsg string, duration time.Duration)

MarkSyncFailed marks the source sync as failed.

func (*Source) MarkSyncStarted

func (s *Source) MarkSyncStarted()

MarkSyncStarted marks the source as currently syncing.

func (*Source) MarkSyncSuccess

func (s *Source) MarkSyncSuccess(hash string, ruleCount int, duration time.Duration)

MarkSyncSuccess marks the source as successfully synced.

func (*Source) NeedsSync

func (s *Source) NeedsSync() bool

NeedsSync checks if the source needs to be synced based on interval.

func (*Source) SetEnabled

func (s *Source) SetEnabled(enabled bool)

SetEnabled enables or disables the source.

func (*Source) SetPriority

func (s *Source) SetPriority(priority int)

SetPriority sets the merge priority.

type SourceFilter

type SourceFilter struct {
	TenantID          *shared.ID
	ToolID            *shared.ID
	SourceType        *SourceType
	Enabled           *bool
	IsPlatformDefault *bool
	SyncStatus        *SyncStatus
	Search            string
}

SourceFilter represents filter options for listing sources.

type SourceRepository

type SourceRepository interface {
	// Create creates a new rule source.
	Create(ctx context.Context, source *Source) error

	// GetByID retrieves a source by ID.
	GetByID(ctx context.Context, id shared.ID) (*Source, error)

	// GetByTenantAndID retrieves a source by tenant and ID.
	GetByTenantAndID(ctx context.Context, tenantID, id shared.ID) (*Source, error)

	// List lists sources with filters and pagination.
	List(ctx context.Context, filter SourceFilter, page pagination.Pagination) (pagination.Result[*Source], error)

	// ListByTenantAndTool lists all sources for a tenant and tool.
	ListByTenantAndTool(ctx context.Context, tenantID shared.ID, toolID *shared.ID) ([]*Source, error)

	// ListNeedingSync lists sources that need synchronization.
	ListNeedingSync(ctx context.Context, limit int) ([]*Source, error)

	// Update updates a source.
	Update(ctx context.Context, source *Source) error

	// Delete deletes a source.
	Delete(ctx context.Context, id shared.ID) error
}

SourceRepository defines the interface for rule source persistence.

type SourceType

type SourceType string

SourceType represents the type of rule source.

const (
	SourceTypeGit   SourceType = "git"
	SourceTypeHTTP  SourceType = "http"
	SourceTypeLocal SourceType = "local"
)

func (SourceType) IsValid

func (t SourceType) IsValid() bool

IsValid checks if the source type is valid.

type SyncHistory

type SyncHistory struct {
	ID           shared.ID
	SourceID     shared.ID
	Status       SyncStatus
	RulesAdded   int
	RulesUpdated int
	RulesRemoved int
	Duration     time.Duration
	ErrorMessage string
	ErrorDetails map[string]any
	PreviousHash string
	NewHash      string
	CreatedAt    time.Time
}

SyncHistory represents a record of a rule source sync.

type SyncHistoryRepository

type SyncHistoryRepository interface {
	// Create creates a new sync history record.
	Create(ctx context.Context, history *SyncHistory) error

	// ListBySource lists sync history for a source.
	ListBySource(ctx context.Context, sourceID shared.ID, limit int) ([]*SyncHistory, error)
}

SyncHistoryRepository defines the interface for sync history persistence.

type SyncStatus

type SyncStatus string

SyncStatus represents the synchronization status.

const (
	SyncStatusPending SyncStatus = "pending"
	SyncStatusSyncing SyncStatus = "syncing"
	SyncStatusSuccess SyncStatus = "success"
	SyncStatusFailed  SyncStatus = "failed"
)

Jump to

Keyboard shortcuts

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