bundle

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Overview

Package bundle defines the rule bundle format (docs/bundle-format.md): parsing, validation, signature and key manifest verification.

Index

Constants

View Source
const (
	MaxArchiveBytes = 16 << 20
	MaxMemberBytes  = 4 << 20
	MaxMembers      = 512
)

Archive limits enforced during extraction.

View Source
const (
	ManifestFile  = "bundle.yaml"
	DirState      = "state"
	DirPrometheus = "prometheus"
	DirLoki       = "loki"
)

Archive layout.

View Source
const (
	ClassState  = "state"
	ClassPromQL = "promql"
	ClassLogQL  = "logql"
)

Rule classes (PRD R3).

View Source
const (
	ScopeNode    = "node"
	ScopeCluster = "cluster"
)

Evaluation scopes (PRD R4).

View Source
const (
	TargetKubernetes = "kubernetes"
	TargetHost       = "host"
)

Target types (PRD H7).

View Source
const (
	CapInventory = "inventory"
	CapMetrics   = "metrics"
	CapLogs      = "logs"
)

Capabilities a rule can require (PRD 5.2).

View Source
const (
	ResolveRecovery = "recovery"
	ResolveManual   = "manual"
)

Resolution semantics.

View Source
const (
	DomainKeyManifest = "EMBv1/keymanifest"
	DomainBundle      = "EMBv1/bundle"
)

Signature domains (docs/bundle-format.md).

View Source
const (
	FileArchive     = "bundle.tar.gz"
	FileSignature   = "bundle.sig"
	FileKeyManifest = "keymanifest.json"
)

Air-gap file names.

View Source
const DefaultKeepVersions = 5

DefaultKeepVersions is how many verified versions the store retains for rollback.

View Source
const DirKeyManifestChain = "keymanifests"

DirKeyManifestChain is the air-gap subdirectory holding earlier key manifests.

View Source
const EngineVersion = 1

EngineVersion is the rule engine version implemented by this agent (PRD U1, U4).

View Source
const ReasonUpgradeRequired = "agent upgrade required"

ReasonUpgradeRequired marks rules that need a newer rule engine (PRD U4).

View Source
const SchemaVersion = 1

SchemaVersion is the bundle.yaml schema version implemented by this agent.

Variables

View Source
var (
	// ErrNoRoots means the agent has no trust root and verifies nothing.
	ErrNoRoots = errors.New("bundle: no trust roots configured: set trust.roots or trust.rootsFile to the root key set of your ExitMesh deployment (shown on its onboarding page next to the enrollment token), so no key manifest or bundle can be trusted until then")
	// ErrUntrusted wraps every signature and key manifest failure.
	ErrUntrusted = errors.New("bundle: untrusted")
)
View Source
var ErrInvalid = errors.New("bundle: invalid")

ErrInvalid wraps every archive, schema, and validation failure.

View Source
var ErrNotStored = errors.New("bundle: version is not stored")

ErrNotStored means the requested version is not retained.

Functions

func Build

func Build(dir string) ([]byte, error)

Build packs a bundle directory into a reproducible bundle.tar.gz and checks that it parses.

func ParseSignedManifest

func ParseSignedManifest(b []byte) (*SignedManifest, *KeyManifest, error)

ParseSignedManifest decodes the wrapper and the manifest without verifying signatures.

func Sign

func Sign(archive []byte, key SigningKey) ([]byte, error)

Sign signs a bundle archive and returns the signature document.

func SignManifest

func SignManifest(m *KeyManifest, roots ...SigningKey) ([]byte, error)

SignManifest signs a manifest with one or more root keys.

Types

type Active

type Active struct {
	Bundle *Bundle
	Result Result
	KeyID  string
}

Active is a verified, validated bundle ready to activate between evaluation cycles.

type AlertRule

type AlertRule struct {
	Meta          RuleMeta
	File          string
	Group         string
	GroupInterval time.Duration
	Alert         string
	Expr          string
	For           time.Duration
	KeepFiringFor time.Duration
	Labels        map[string]string
	Annotations   map[string]string
}

AlertRule is one PromQL or LogQL alerting rule resolved from an upstream rule-group file.

type Budget

type Budget struct {
	MaxEvalTime   time.Duration `yaml:"max_eval_time,omitempty"`
	MaxSamples    int           `yaml:"max_samples,omitempty"`
	MaxSeries     int           `yaml:"max_series,omitempty"`
	MaxComplexity int           `yaml:"max_complexity,omitempty"`
	CounterBytes  int           `yaml:"counter_bytes,omitempty"`
}

Budget bounds evaluation cost per rule (PRD R6).

type Bundle

type Bundle struct {
	Manifest Manifest
	Digest   [32]byte
	State    []StateRule
	PromQL   []AlertRule
	LogQL    []AlertRule
	// Files holds the raw archive members for inspection and persistence.
	Files map[string][]byte
}

Bundle is a parsed, verified rule bundle.

func Parse

func Parse(archive []byte) (*Bundle, error)

Parse extracts and decodes bundle.tar.gz and binds every rule to its metadata.

func (*Bundle) Only

func (b *Bundle) Only(ids []string) *Bundle

Only returns a copy of b that keeps only the listed rules, for example Result.Active.

type EvidencePolicy

type EvidencePolicy struct {
	MaxSamples   int `yaml:"max_samples,omitempty"`
	MaxBytes     int `yaml:"max_bytes,omitempty"`
	ContextLines int `yaml:"context_lines,omitempty"`
}

EvidencePolicy bounds evidence per rule (PRD L5, L7).

type KeyManifest

type KeyManifest struct {
	Sequence       uint64          `json:"sequence"`
	IssuedAt       time.Time       `json:"issued_at"`
	SigningKeys    []ManifestKey   `json:"signing_keys"`
	SuccessorRoots []SuccessorRoot `json:"successor_roots,omitempty"`
}

KeyManifest lists bundle signing keys and successor roots.

func NewKeyManifest

func NewKeyManifest(sequence uint64, issuedAt time.Time, keys []ManifestKey, successors []SuccessorRoot) (*KeyManifest, error)

NewKeyManifest builds and checks a key manifest.

func (*KeyManifest) Key

func (m *KeyManifest) Key(id string) (ManifestKey, bool)

Key returns the signing key with id.

func (*KeyManifest) Validate

func (m *KeyManifest) Validate() error

Validate checks manifest structure.

type Manifest

type Manifest struct {
	Version       string     `yaml:"version"`
	EngineVersion int        `yaml:"engine_version"`
	SchemaVersion int        `yaml:"schema_version"`
	TargetType    string     `yaml:"target_type"`
	CreatedAt     time.Time  `yaml:"created_at"`
	Rules         []RuleMeta `yaml:"rules"`
}

Manifest is bundle.yaml.

type ManifestKey

type ManifestKey struct {
	ID        string            `json:"id"`
	PublicKey ed25519.PublicKey `json:"public_key"`
	NotBefore time.Time         `json:"not_before"`
	NotAfter  time.Time         `json:"not_after"`
	RevokedAt *time.Time        `json:"revoked_at,omitempty"`
}

ManifestKey is a bundle signing key with its validity window.

func (ManifestKey) RevokedBy

func (k ManifestKey) RevokedBy(t time.Time) bool

RevokedBy reports whether the key is revoked at t.

func (ManifestKey) ValidAt

func (k ManifestKey) ValidAt(t time.Time) bool

ValidAt reports whether the key may verify bundles at t.

type Policy

type Policy struct {
	// TargetType, when set, must equal the bundle target type.
	TargetType      string
	DefaultBudget   Budget
	MaxBudget       Budget
	DefaultEvidence EvidencePolicy
	MaxEvidence     EvidencePolicy
	DefaultInterval time.Duration
	MinInterval     time.Duration
	MaxInterval     time.Duration
	MaxFor          time.Duration
	MaxRules        int
}

Policy is the local administrator upper bound. Bundle values above a maximum are capped.

func DefaultPolicy

func DefaultPolicy() Policy

DefaultPolicy returns the built-in upper bounds.

type ResourceRef

type ResourceRef struct {
	Kind      string `yaml:"kind"`
	Namespace string `yaml:"namespace,omitempty"`
	Name      string `yaml:"name"`
}

ResourceRef names the alert labels that identify an affected resource.

type Result

type Result struct {
	Active      []string
	Disabled    []string
	Unsupported map[string]string
	Rejected    map[string]string
}

Result holds per-rule verdicts in manifest order.

func Validate

func Validate(b *Bundle, v Validators, p Policy) (Result, error)

Validate checks b against the engine and local policy, applying defaults in place; any rejection fails the bundle.

type RootKey

type RootKey struct {
	ID        string            `json:"id"`
	PublicKey ed25519.PublicKey `json:"public_key"`
}

RootKey is a trusted root public key.

type Roots

type Roots struct {
	Threshold int       `json:"threshold,omitempty"`
	Keys      []RootKey `json:"keys"`
}

Roots is the deployment's configured root key set; Threshold distinct root signatures are required (default 1).

func LoadRoots

func LoadRoots(rootsFile string, inline []string, threshold int) (Roots, error)

LoadRoots builds the root key set from configuration: a roots file (ParseRoots format) and inline keys ("<id>:<base64 ed25519 public key>"), merged; an empty result is ErrNoRoots.

func ParseRoots

func ParseRoots(b []byte) (Roots, error)

ParseRoots decodes and checks a roots.json document.

type RuleMeta

type RuleMeta struct {
	ID      string `yaml:"id"`
	Version int    `yaml:"version"`
	Class   string `yaml:"class"`
	Target  string `yaml:"target"`
	Scope   string `yaml:"scope"`
	File    string `yaml:"file,omitempty"`
	Group   string `yaml:"group,omitempty"`
	Alert   string `yaml:"alert,omitempty"`
	// Match selects among alerting rules sharing File, Group, and Alert by their static labels.
	Match          map[string]string `yaml:"match,omitempty"`
	Category       string            `yaml:"category"`
	Severity       string            `yaml:"severity"`
	RequiredFields []string          `yaml:"required_fields,omitempty"`
	Capabilities   []string          `yaml:"capabilities"`
	Evidence       EvidencePolicy    `yaml:"evidence,omitempty"`
	DedupKey       string            `yaml:"dedup_key,omitempty"`
	Resolution     string            `yaml:"resolution,omitempty"`
	Budget         Budget            `yaml:"budget,omitempty"`
	MinEngine      int               `yaml:"min_engine,omitempty"`
	Disabled       bool              `yaml:"disabled,omitempty"`
	Summary        string            `yaml:"summary,omitempty"`
	// ResourceLabels maps alert labels to affected resources, for example
	// {kind: Pod, namespace: namespace, name: pod}.
	ResourceLabels *ResourceRef `yaml:"resource_labels,omitempty"`
}

RuleMeta carries the metadata of one rule (PRD R4). For PromQL and LogQL rules it references an alerting rule in an upstream rule-group file by File, Group, and Alert.

func (RuleMeta) DedupLabels

func (m RuleMeta) DedupLabels() []string

DedupLabels returns the label names listed in dedup_key (comma separated).

type Signature

type Signature struct {
	KeyID     string `json:"key_id"`
	Signature []byte `json:"signature"`
}

Signature is one signature over a domain-separated digest.

func ParseSignature

func ParseSignature(b []byte) (Signature, error)

ParseSignature decodes a bundle signature document.

type SignedManifest

type SignedManifest struct {
	Manifest   []byte      `json:"manifest"`
	Signatures []Signature `json:"signatures"`
}

SignedManifest carries the exact manifest bytes and root signatures.

type SigningKey

type SigningKey struct {
	ID         string             `json:"id"`
	PrivateKey ed25519.PrivateKey `json:"private_key"`
}

SigningKey is a private ed25519 key with its identifier.

func GenerateKey

func GenerateKey(id string) (SigningKey, error)

GenerateKey creates a new signing or root key.

func ParseSigningKey

func ParseSigningKey(b []byte) (SigningKey, error)

ParseSigningKey decodes a private key file.

func (SigningKey) Public

func (k SigningKey) Public() RootKey

Public returns the public half.

type StateRule

type StateRule struct {
	ID            string            `yaml:"id"`
	Version       int               `yaml:"version"`
	Target        string            `yaml:"target"`
	Kinds         []string          `yaml:"kinds"`
	Expr          string            `yaml:"expr"`
	For           time.Duration     `yaml:"for,omitempty"`
	KeepFiringFor time.Duration     `yaml:"keep_firing_for,omitempty"`
	Interval      time.Duration     `yaml:"interval,omitempty"`
	Labels        map[string]string `yaml:"labels,omitempty"`
	Meta          RuleMeta          `yaml:"-"`
}

StateRule is one rule from state/*.yaml: a CEL predicate over normalized state.

type Store

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

Store keeps the last known good bundle and prior versions for rollback.

func NewStore

func NewStore(s kv.Store, v *Verifier, keep int) *Store

NewStore returns a Store; keep <= 0 uses DefaultKeepVersions.

func (*Store) Activate

func (s *Store) Activate(archive, signature []byte, vals Validators, pol Policy) (*Active, error)

Activate verifies and validates a bundle and makes it the last known good; on failure nothing changes.

func (*Store) ActivateFetch

func (s *Store) ActivateFetch(res protocol.BundleFetchResult, vals Validators, pol Policy) (*Active, error)

ActivateFetch accepts the key manifest of a bundle.fetch result, then activates its bundle.

func (*Store) Current

func (s *Store) Current() (string, bool, error)

Current returns the last known good version.

func (*Store) LoadLastKnownGood

func (s *Store) LoadLastKnownGood(vals Validators, pol Policy) (*Active, bool, error)

LoadLastKnownGood reloads the current version; key expiry is not re-checked, revocation is.

func (*Store) Rollback

func (s *Store) Rollback(version string, vals Validators, pol Policy) (*Active, error)

Rollback makes a retained version current again.

func (*Store) Versions

func (s *Store) Versions() ([]StoredVersion, error)

Versions lists retained versions, oldest first.

type StoredVersion

type StoredVersion struct {
	Version  string    `json:"version"`
	Digest   string    `json:"digest"`
	KeyID    string    `json:"key_id"`
	StoredAt time.Time `json:"stored_at"`
	Order    uint64    `json:"order"`
	Current  bool      `json:"-"`
}

StoredVersion describes one retained bundle version.

type SuccessorRoot

type SuccessorRoot struct {
	ID        string            `json:"id"`
	PublicKey ed25519.PublicKey `json:"public_key"`
	NotBefore time.Time         `json:"not_before"`
}

SuccessorRoot is a root key introduced by a manifest signed by the current root set.

type Validators

type Validators struct {
	PromQL func(AlertRule) error
	LogQL  func(AlertRule) error
	CEL    func(StateRule) error
}

Validators check expressions; callers inject them to avoid import cycles. A nil validator skips that class.

type Verifier

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

Verifier holds the trust state: pinned roots, adopted successor roots, and the latest verified key manifest.

func NewVerifier

func NewVerifier(roots Roots, store kv.Store) (*Verifier, error)

NewVerifier returns a Verifier over roots, loading persisted trust state from store.

func (*Verifier) AcceptManifest

func (v *Verifier) AcceptManifest(signed []byte) (*KeyManifest, error)

AcceptManifest verifies a signed key manifest against the current roots and persists it if it advances.

func (*Verifier) AcceptManifests

func (v *Verifier) AcceptManifests(chain ...[]byte) (*KeyManifest, error)

AcceptManifests accepts a chain of signed key manifests in ascending sequence, skipping ones older than the verified sequence, and returns the latest verified manifest (nil when none is known).

func (*Verifier) KeyRevoked

func (v *Verifier) KeyRevoked(keyID string) bool

KeyRevoked reports whether the latest verified manifest revokes keyID now.

func (*Verifier) Manifest

func (v *Verifier) Manifest() (*KeyManifest, bool)

Manifest returns the latest verified key manifest.

func (*Verifier) Sequence

func (v *Verifier) Sequence() uint64

Sequence returns the highest verified manifest sequence (0 when none).

func (*Verifier) SetClock

func (v *Verifier) SetClock(now func() time.Time)

SetClock replaces the clock used for validity windows.

func (*Verifier) TrustedRoots

func (v *Verifier) TrustedRoots() []RootKey

TrustedRoots returns the pinned roots followed by adopted successor roots, sorted by id.

func (*Verifier) VerifyBundle

func (v *Verifier) VerifyBundle(archive, signature []byte) (string, error)

VerifyBundle checks a bundle signature against the latest verified key manifest and returns the key id.

func (*Verifier) VerifyFiles

func (v *Verifier) VerifyFiles(dir string) (archive, signature []byte, err error)

VerifyFiles verifies an air-gap directory (optional keymanifests/*.json chain, keymanifest.json, bundle.tar.gz, bundle.sig) like tunnel delivery.

Jump to

Keyboard shortcuts

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