policy

package
v0.10.1 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Package policy manages policy library download and discovery.

Package policy manages policy library operations including formatting.

Code generated by policy-gen. DO NOT EDIT.

Package policy manages policy library operations including rule and pack parsing.

Package policy manages policy library download and discovery.

Package policy manages policy library operations including rule and pack parsing.

Package policy manages policy library operations including validation.

Index

Constants

View Source
const (
	// DefaultRepo is empty so policy update defaults to the OSS policy archive.
	DefaultRepo = ""
	// DefaultPolicyVersion reads the latest policy version from the OSS version file.
	DefaultPolicyVersion = "latest"
	// DefaultPolicyGitRef is used when --repo is set without an explicit version.
	DefaultPolicyGitRef = "main"
)
View Source
const (
	// Rule validation error codes
	ErrCodeRuleMissingMeta       = "RULE_MISSING_META"
	ErrCodeRuleMissingID         = "RULE_MISSING_ID"
	ErrCodeRuleMissingName       = "RULE_MISSING_NAME"
	ErrCodeRuleMissingSeverity   = "RULE_MISSING_SEVERITY"
	ErrCodeRuleMissingReason     = "RULE_MISSING_REASON"
	ErrCodeRuleInvalidSeverity   = "RULE_INVALID_SEVERITY"
	ErrCodeRuleInvalidFieldType  = "RULE_INVALID_FIELD_TYPE"
	ErrCodeRuleMissingDeny       = "RULE_MISSING_DENY"
	ErrCodeRuleInvalidDenyFormat = "RULE_INVALID_DENY_FORMAT"

	// Pack validation error codes
	ErrCodePackMissingMeta      = "PACK_MISSING_META"
	ErrCodePackMissingID        = "PACK_MISSING_ID"
	ErrCodePackMissingName      = "PACK_MISSING_NAME"
	ErrCodePackMissingRules     = "PACK_MISSING_RULES"
	ErrCodePackInvalidFieldType = "PACK_INVALID_FIELD_TYPE"

	// General error codes
	ErrCodeSyntaxError = "SYNTAX_ERROR"
	ErrCodeReadError   = "READ_ERROR"
)

Error codes for validation errors

View Source
const (
	RulesPackagePrefix = "infraguard.rules."
	PacksPackagePrefix = "infraguard.packs."
)

Package name prefixes for InfraGuard policies

Variables

View Source
var EmbeddedIndex *models.PolicyIndex

EmbeddedIndex is a pre-computed index of all embedded policies. It is populated by the generated code in index_gen.go.

Functions

func DefaultPolicyDir

func DefaultPolicyDir() string

DefaultPolicyDir returns the default user-level policy storage directory (~/.infraguard/policies).

func DiscoverPacks

func DiscoverPacks(dir string) ([]*models.Pack, error)

DiscoverPacks finds all packs in a directory.

func DiscoverRegoFiles

func DiscoverRegoFiles(path string) ([]string, error)

DiscoverRegoFiles finds all .rego files from a path. If path is a directory, it recursively finds all .rego files. If path is a .rego file, it returns that single file.

func DiscoverRules

func DiscoverRules(dir string) ([]*models.Rule, error)

DiscoverRules finds all rules in a directory.

func DiscoverRulesWithExtraModules added in v0.1.2

func DiscoverRulesWithExtraModules(dir string, extraModules []RegoModule) ([]*models.Rule, error)

DiscoverRulesWithExtraModules finds all rules in a directory with additional helper modules. The extraModules parameter allows providing helper libraries (e.g., embedded helpers) that rules may depend on but are not present in the local directory.

func GenerateDiff

func GenerateDiff(original, formatted, filePath string) string

GenerateDiff generates a colored unified diff between original and formatted content. Output format matches git diff with hunk headers and colored lines.

func GenerateIDPrefix

func GenerateIDPrefix(filePath, baseDir, idType string) string

GenerateIDPrefix generates the ID prefix from the file path relative to the base directory. Supports provider-first structure: "policies/aliyun/rules/ecs_public_ip.rego" with base "policies/aliyun/rules" -> "rule:aliyun" For embedded FS paths: "aliyun/rules/ecs_public_ip.rego" with base "aliyun/rules" -> "rule:aliyun"

func GeneratePackID

func GeneratePackID(filePath, baseDir, packName string) string

GeneratePackID generates a full pack ID from the file path and pack name. e.g., "policies/aliyun/packs/security_baseline.rego" with name "security-baseline" -> "pack:aliyun:security-baseline"

func GenerateRuleID

func GenerateRuleID(filePath, baseDir, ruleName string) string

GenerateRuleID generates a full rule ID from the file path and rule name. e.g., "policies/aliyun/rules/ecs_public_ip.rego" with name "ecs-public-ip" -> "rule:aliyun:ecs-public-ip"

func MatchPattern

func MatchPattern(pattern, id string) bool

MatchPattern checks if an ID matches a wildcard pattern. The pattern supports `*` as a wildcard that matches zero or more characters. Examples:

  • "rule:*" matches all rule IDs
  • "rule:aliyun:ecs-*" matches "rule:aliyun:ecs-instance-no-public-ip"
  • "rule:aliyun:*-multi-zone" matches "rule:aliyun:rds-instance-multi-zone"

func ParsePackFromContentWithPath

func ParsePackFromContentWithPath(content, filePath, baseDir string) (*models.Pack, error)

ParsePackFromContentWithPath extracts pack metadata from rego content. The baseDir is used to auto-generate the pack ID prefix from the file path.

func ParseRuleFromContentWithModules

func ParseRuleFromContentWithModules(content, filePath, baseDir string, extraModules []RegoModule) (*models.Rule, error)

ParseRuleFromContentWithModules parses a rule from rego content with additional modules. The extraModules parameter allows loading helper libraries that the rule depends on.

func ValidatePath

func ValidatePath(path string) error

ValidatePath checks if a policy path exists and is valid. It supports both directories (containing .rego files) and single .rego files.

func WorkspacePolicyDir added in v0.1.2

func WorkspacePolicyDir() string

WorkspacePolicyDir returns the workspace-local policy directory (.infraguard/policies) relative to the current working directory.

Types

type FormatResult

type FormatResult struct {
	FilePath  string `json:"file_path"`
	Changed   bool   `json:"changed"`
	Original  string `json:"-"`
	Formatted string `json:"-"`
	Error     error  `json:"error,omitempty"`
}

FormatResult holds the result of formatting a single file.

func FormatFile

func FormatFile(filePath string, write bool) (*FormatResult, error)

FormatFile formats a single Rego file and returns the result. If write is true, the formatted content is written back to the file.

type FormatSummary

type FormatSummary struct {
	TotalFiles     int             `json:"total_files"`
	ChangedFiles   int             `json:"changed_files"`
	UnchangedFiles int             `json:"unchanged_files"`
	ErrorFiles     int             `json:"error_files"`
	Results        []*FormatResult `json:"results"`
}

FormatSummary holds the summary of formatting results.

func FormatDirectory

func FormatDirectory(dir string, write bool) (*FormatSummary, error)

FormatDirectory formats all Rego files in a directory recursively.

func FormatPath

func FormatPath(path string, write bool) (*FormatSummary, error)

FormatPath formats a file or directory.

type Loader

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

Loader handles policy loading with priority and indexing.

func LoadWithFallback

func LoadWithFallback() (*Loader, error)

LoadWithFallback loads policies by merging embedded, user-local, and workspace-local policies. Policy loading priority (highest to lowest):

  1. Workspace-local policies: .infraguard/policies/ (current working directory)
  2. User-local policies: ~/.infraguard/policies/
  3. Embedded policies: compiled into the binary

Policies with the same ID from higher-priority sources override lower-priority ones.

func (*Loader) GetAllPacks

func (l *Loader) GetAllPacks() []*models.Pack

GetAllPacks returns all loaded packs.

func (*Loader) GetAllRules

func (l *Loader) GetAllRules() []*models.Rule

GetAllRules returns all loaded rules.

func (*Loader) GetIndex

func (l *Loader) GetIndex() *models.PolicyIndex

GetIndex returns the loaded policy index.

func (*Loader) GetLibModules

func (l *Loader) GetLibModules() map[string]string

GetLibModules returns all loaded library modules.

func (*Loader) GetPack

func (l *Loader) GetPack(id string) *models.Pack

GetPack returns a pack by ID.

func (*Loader) GetRule

func (l *Loader) GetRule(id string) *models.Rule

GetRule returns a rule by ID.

func (*Loader) GetRulesForPack

func (l *Loader) GetRulesForPack(packID string) []*models.Rule

GetRulesForPack returns all rules for a given pack ID.

func (*Loader) Load

func (l *Loader) Load() error

Load discovers and loads all rules and packs from the policy directory. Supports two directory structures:

  1. Provider-first: {provider}/rules/, {provider}/packs/, {provider}/lib/
  2. Flat: {name}/*.rego (rules directly in subdirectory)

func (*Loader) LoadEmbedded

func (l *Loader) LoadEmbedded() error

LoadEmbedded loads policies from the embedded filesystem. Supports provider-first directory structure: {provider}/rules/, {provider}/packs/, {provider}/lib/

func (*Loader) MatchPacks

func (l *Loader) MatchPacks(pattern string) []*models.Pack

MatchPacks returns all packs matching the given pattern. The pattern supports `*` wildcard matching. Returns empty slice if no packs match.

func (*Loader) MatchRules

func (l *Loader) MatchRules(pattern string) []*models.Rule

MatchRules returns all rules matching the given pattern. The pattern supports `*` wildcard matching. Returns empty slice if no rules match.

type Manager

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

Manager handles policy library operations.

func NewManager

func NewManager(policyDir string) *Manager

NewManager creates a new policy manager.

func (*Manager) Clean added in v0.3.0

func (m *Manager) Clean() error

Clean removes the policy directory and all its contents. If the directory doesn't exist, this is not considered an error.

func (*Manager) Update

func (m *Manager) Update(repo, version string) error

Update downloads and updates the policy library. When repo is empty, it uses the default OSS policy archive. Otherwise it keeps backward-compatible git repository support.

func (*Manager) UpdateFromOSS added in v0.10.1

func (m *Manager) UpdateFromOSS(version string) error

UpdateFromOSS downloads a versioned policy archive from OSS and atomically replaces the local policy directory only after download and extraction succeed.

type RegoModule

type RegoModule struct {
	Path    string
	Content string
}

RegoModule represents a Rego module with its path and content.

type ValidationError

type ValidationError struct {
	FilePath   string `json:"file_path"`
	Line       int    `json:"line,omitempty"` // 0 if unknown
	ErrorCode  string `json:"error_code"`
	Message    string `json:"message"`
	Suggestion string `json:"suggestion"`
}

ValidationError represents a single validation error with context and fix suggestion.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

type ValidationResult

type ValidationResult struct {
	FilePath string             `json:"file_path"`
	FileType string             `json:"file_type"` // "rule", "pack", or "unknown"
	Valid    bool               `json:"valid"`
	Errors   []*ValidationError `json:"errors,omitempty"`
}

ValidationResult holds the validation result for a single file.

func ValidateContent

func ValidateContent(content, filePath string) (*ValidationResult, error)

ValidateContent validates Rego content for InfraGuard compliance.

func ValidateContentWithModules

func ValidateContentWithModules(content, filePath string, extraModules []RegoModule) (*ValidationResult, error)

ValidateContentWithModules validates Rego content with optional extra modules.

func ValidateFile

func ValidateFile(filePath string) (*ValidationResult, error)

ValidateFile validates a single Rego file for InfraGuard compliance. Returns a ValidationResult with any errors found.

func ValidateFileWithModules

func ValidateFileWithModules(filePath string, extraModules []RegoModule) (*ValidationResult, error)

ValidateFileWithModules validates a single Rego file with extra modules.

type ValidationSummary

type ValidationSummary struct {
	TotalFiles   int                 `json:"total_files"`
	PassedFiles  int                 `json:"passed_files"`
	FailedFiles  int                 `json:"failed_files"`
	SkippedFiles int                 `json:"skipped_files"`
	Results      []*ValidationResult `json:"results"`
	Skipped      []string            `json:"skipped,omitempty"` // Skipped file paths
}

ValidationSummary holds the summary of validation results.

func ValidateDirectory

func ValidateDirectory(dir string) (*ValidationSummary, error)

ValidateDirectory validates all Rego files in a directory recursively.

func ValidatePolicies

func ValidatePolicies(path string) (*ValidationSummary, error)

ValidatePolicies validates a file or directory for policy compliance.

Jump to

Keyboard shortcuts

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