policytest

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 39 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AllPolicyTests = &RegisteredPolicyTests{}

Functions

func CheckCLIFlags added in v1.8.0

func CheckCLIFlags(info *tetragoninfo.Info, flags []CLIFlag) string

CheckCLIFlags returns a skip reason when agent configuration does not satisfy the required CLI flags.

func DumpResults

func DumpResults(out io.Writer, results []*NamedResult)

func RegisterPolicyTestAtInit

func RegisterPolicyTestAtInit(t *T)

RegisterPolicyTestAtInit registers a policytest at init, so it does not synchronize access to the global slice

Types

type ActionCounts

type ActionCounts struct {
	Post           *uint64
	Signal         *uint64
	Override       *uint64
	NotifyEnforcer *uint64
	Set            *uint64
}

type Builder

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

Builder offers an ergonomic way to build policy tests (using method chaining)

func NewBuilder

func NewBuilder(name string) *Builder

func (*Builder) AddScenario

func (b *Builder) AddScenario(fn func(c *Conf) *Scenario) *Builder

Add a scenario to the builder

func (*Builder) RegisterAtInit

func (b *Builder) RegisterAtInit() any

RegisterAtInit registers the policy at initilization time (i.e., in init or in top-level global declaration) NB: return something so that we can use this in a var top-level declaration

func (*Builder) WithCLIFlags added in v1.8.0

func (b *Builder) WithCLIFlags(flags ...CLIFlag) *Builder

WithCLIFlags adds agent CLI flag requirements to a policy test.

func (*Builder) WithLabels

func (b *Builder) WithLabels(labels ...string) *Builder

func (*Builder) WithParameter

func (b *Builder) WithParameter(p Parameter) *Builder

func (*Builder) WithPolicyTemplate

func (b *Builder) WithPolicyTemplate(tmpl string) *Builder

WithPolicyTemplate adds a policy to a policy test using a text template.

In the template, the following functions are supported

  • testBinary: generate a test binary path from the binary name (Conf.TestBinary())
  • tempFile: generate a temporary file and save it in the conf

func (*Builder) WithSkip

func (b *Builder) WithSkip(fn func(*SkipInfo) string) *Builder

func (*Builder) WithTemplateFunc added in v1.8.0

func (b *Builder) WithTemplateFunc(name string, fn any) *Builder

type CLIFlag added in v1.8.0

type CLIFlag struct {
	Name  string
	Value any
}

CLIFlag describes an agent CLI flag value required by a policy test.

type CmdTrigger

type CmdTrigger struct {
	Bin  string
	Args []string
}

CmdTrigger simply wraps a exec.CommandContext().Run() into a Trigger

func NewCmdTrigger

func NewCmdTrigger(bin string, args ...string) *CmdTrigger

func (*CmdTrigger) ExpectExitCode

func (c *CmdTrigger) ExpectExitCode(val int) *ExecTester

func (*CmdTrigger) ExpectSignal

func (c *CmdTrigger) ExpectSignal(sig syscall.Signal) *ExecTester

func (*CmdTrigger) ExpectStdout added in v1.8.0

func (c *CmdTrigger) ExpectStdout(s string) *ExecTester

ExpectStdout expects the given string to be present in a single line (minus '\n') command's stdout

func (*CmdTrigger) Trigger

func (c *CmdTrigger) Trigger(ctx context.Context) error

type Conf

type Conf struct {
	// Test Binaries directory
	BinsDir string
	// Agent GRPC address
	GrpcAddr string

	// configuration for the current test
	TestConf *TestConf

	// Directory to save the generated policies in. Each policy is saved in a file named
	// after the policy (<name>.yaml). The directory is created if it does not exist.
	DumpPolicyPath string

	// Timeout for the policy tests
	Timeout time.Duration
	// Timeout for each Scenario
	ScenarioTimeout time.Duration

	// Set as spec.podSelector of every policy
	PodSelector map[string]string
}

Conf is the runtime configuration for a sequence of policy tests

func (*Conf) CleanupTempFiles added in v1.8.0

func (c *Conf) CleanupTempFiles()

func (*Conf) TempFile added in v1.8.0

func (c *Conf) TempFile(key string) (string, error)

TempFile returns the path of the temporary file identified by key for the current test, creating it if needed. The files are owned by Conf.TestConf.

func (*Conf) TempFileMust added in v1.8.0

func (c *Conf) TempFileMust(key string) string

func (*Conf) TestBinary

func (c *Conf) TestBinary(s string) string

type ExecTestError

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

ExecTestError will be returned if the command did not exit as expected. That is, either via the expected signal or with the expected error code

func NewExecTestErr

func NewExecTestErr(format string, args ...any) *ExecTestError

func (*ExecTestError) Error

func (e *ExecTestError) Error() string

type ExecTester

type ExecTester struct {
	MultiCmdTrigger
	// Execution should either terminate normally (with an exit code) or by a signal
	// only one of those should be not nill
	ExpectedExitCode []int
	ExpectedSignal   []syscall.Signal
	// If set, the command's stdout should match this string
	ExpectedStdout []string
}

func (*ExecTester) Trigger

func (et *ExecTester) Trigger(ctx context.Context) error

type JSONError added in v1.8.0

type JSONError struct {
	Err error
}

JSONError is an error that can be marshalled in JSON a string Unmarshalling is also supported, but it would not maintain the original error.

func (JSONError) Error added in v1.8.0

func (e JSONError) Error() string

func (JSONError) MarshalJSON added in v1.8.0

func (e JSONError) MarshalJSON() ([]byte, error)

func (*JSONError) UnmarshalJSON added in v1.8.0

func (e *JSONError) UnmarshalJSON(data []byte) error

type Label

type Label string

type LocalRunner

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

func NewLocalRunner

func NewLocalRunner(
	ctx context.Context,
	log *slog.Logger,
	cnf *Conf,
) (*LocalRunner, error)

NewLocalRunner creates a new local runner

For event testing, the local runner uses three goroutines:

  • receive (runRecv)
  • forward (runFwd)
  • check (runCheck)

receive blocks on the event stream and passes all events to the forward goroutine. forward either drops receieved events, or forwards them to the check goroutine check runs the EventChecker that is part of the test.

When a new scenario starts, a new check goroutine is created and the forwarder is configured to forward events to it.

func (*LocalRunner) AddPolicy

func (r *LocalRunner) AddPolicy(l *slog.Logger, test *T) (*PolicyHandler, error)

func (*LocalRunner) Close

func (r *LocalRunner) Close()

func (*LocalRunner) RunScenario

func (r *LocalRunner) RunScenario(
	l *slog.Logger, scenario *Scenario, polHandler *PolicyHandler, testConf *TestConf,
) ScenarioRes

func (*LocalRunner) RunTest

func (r *LocalRunner) RunTest(l *slog.Logger, test *T, testConf *TestConf) *Result

RunTest runs a policy test

func (*LocalRunner) RunTests added in v1.8.0

func (r *LocalRunner) RunTests(l *slog.Logger, runs []TestRun) []*Result

RunTests runs multiple policy tests by first loading the policies of all the tests, executing all scenarios, and, finally, unloading the policies.

The returned slice has one result for each element of runs, in the same order. A test whose policy fails to load gets an error result, and does not prevent the other tests from running.

type MultiCmdTrigger added in v1.8.0

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

MultiCmdTrigger simply wraps multiple exec.CommandContext().Run() into a Trigger

func NewMultiCmdTrigger added in v1.8.0

func NewMultiCmdTrigger(triggers []CmdTrigger) *MultiCmdTrigger

func (*MultiCmdTrigger) ExpectExitCodes added in v1.8.0

func (c *MultiCmdTrigger) ExpectExitCodes(vals []int) *ExecTester

func (*MultiCmdTrigger) ExpectSignals added in v1.8.0

func (c *MultiCmdTrigger) ExpectSignals(sigs []syscall.Signal) *ExecTester

func (*MultiCmdTrigger) ExpectStdout added in v1.8.0

func (c *MultiCmdTrigger) ExpectStdout(s []string) *ExecTester

ExpectStdout expects the given string to be present in a single line (minus '\n') command's stdout

func (*MultiCmdTrigger) Trigger added in v1.8.0

func (c *MultiCmdTrigger) Trigger(ctx context.Context) error

type NamedResult added in v1.8.0

type NamedResult struct {
	// Name is a policytest identifier
	Name string `json:"name"`
	// Results for the policytest
	Result *Result `json:"result"`
}

type ParamVals added in v1.8.0

type ParamVals map[string]any

func (ParamVals) String added in v1.8.0

func (pvs ParamVals) String() string

type Parameter

type Parameter struct {
	Name    string
	Default any
	Help    string
	// Values, if set, is used to generate values for this parameter when testing.
	// Values is meant to hold all values (including the one specified by Default)
	Values []any
}

func (*Parameter) HelpString added in v1.8.0

func (p *Parameter) HelpString() string

type Policy

type Policy string

Policies are represented as strings, because that's how they are loaded via gRPC

type PolicyCleanupFn added in v1.8.0

type PolicyCleanupFn func()

type PolicyHandler

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

func (*PolicyHandler) Cleanup

func (ph *PolicyHandler) Cleanup(l *slog.Logger, conf *Conf, client *cli.ClientWithContext) error

Cleanup unloads the policy. It is a no-op if ph is nil (i.e., the test has no policy).

func (*PolicyHandler) Configure

func (ph *PolicyHandler) Configure(
	l *slog.Logger, client *cli.ClientWithContext,
	enable *bool, mode *tetragon.TracingPolicyMode) error

Configure configures the policy. It is a no-op if ph is nil (i.e., the test has no policy).

func (*PolicyHandler) GetCounts

type RegisteredPolicyTests

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

func (*RegisteredPolicyTests) DoObserverTest

func (rpt *RegisteredPolicyTests) DoObserverTest(
	t *testing.T,
	testpolicyName string,
	params map[string]any,
)

func (*RegisteredPolicyTests) Get

func (rpt *RegisteredPolicyTests) Get(index int) *T

func (*RegisteredPolicyTests) GetByFunction

func (rpt *RegisteredPolicyTests) GetByFunction(fn func(t *T) bool) []*T

func (*RegisteredPolicyTests) GetByName

func (rpt *RegisteredPolicyTests) GetByName(name string) []*T

func (*RegisteredPolicyTests) GetByRegexps added in v1.8.0

func (rpt *RegisteredPolicyTests) GetByRegexps(exprs []string) ([]*T, error)

GetByRegexps returns the tests whose name matches any of the given regular expressions. Each expression is anchored, i.e., it has to match the whole test name, so that plain test names keep matching only themselves.

func (*RegisteredPolicyTests) Len

func (rpt *RegisteredPolicyTests) Len() int

type Result

type Result struct {
	Skipped      string        `json:"skipped,omitempty"` // if not empty, the policy was skipped and the string contains the reason
	Err          JSONError     `json:"error"`
	ScenariosRes []ScenarioRes `json:"scenarios"`
	TotalTime    time.Duration `json:"total_time"`
}

Result of a policytest (T)

type ResultsSummary added in v1.8.0

type ResultsSummary struct {
	Total   int
	Skipped int
	Errs    int
}

func NewResultsSummary added in v1.8.0

func NewResultsSummary() *ResultsSummary

func (*ResultsSummary) Err added in v1.8.0

func (s *ResultsSummary) Err() error

func (*ResultsSummary) Update added in v1.8.0

func (s *ResultsSummary) Update(res *Result)

type Scenario

type Scenario struct {
	Name                 string
	Trigger              Trigger
	EventChecker         ec.MultiEventChecker
	ActCountChecker      ActionCounts
	ExpectCheckerFailure bool
}

type ScenarioRes

type ScenarioRes struct {
	Name            string    `json:"name"`
	TriggerErr      JSONError `json:"trigger_error"`
	CheckerErr      JSONError `json:"checker_error"`
	ActionCountsErr JSONError `json:"action_counts_error"`
}

func (*ScenarioRes) Err

func (sr *ScenarioRes) Err() error

type SkipInfo

type SkipInfo struct {
	AgentInfo   *tetragoninfo.Info
	ParamValues ParamVals
}

type T

type T struct {
	// Name returns the name of the test
	Name string
	// Labels is a set of labels for the test
	Labels []Label

	// ShouldSkip returns a non-empty string if the policy test is to be skipped.
	// In that case, the string contains the reason that the test was skipped.
	ShouldSkip func(info *SkipInfo) string

	// Policy generates a policy for this test
	Policy func(c *Conf) (Policy, PolicyCleanupFn, error)

	Params []Parameter
	// CLIFlags lists agent CLI flag values required to run this test.
	CLIFlags []CLIFlag

	// Scenarios returns a list of scenarios to test the generated policy
	Scenarios []func(c *Conf) *Scenario
}

T defines a policy test

func (*T) AllParamValues added in v1.8.0

func (t *T) AllParamValues() iter.Seq[ParamVals]

AllParamValues returns a sequence of

type TestConf

type TestConf struct {
	MonitorMode bool
	ParamValues ParamVals
	// contains filtered or unexported fields
}

TestConf is the runtime configuration for a single policy test

A TestConf should not be shared between tests, because it also owns the temporary files of the test.

type TestRun added in v1.8.0

type TestRun struct {
	Test *T
	// Conf is the configuration of the test. It should not be shared with other runs.
	Conf *TestConf
}

TestRun is a test together with the configuration to run it with

type Trigger

type Trigger interface {
	Trigger(ctx context.Context) error
}

Trigger is a way to trigger a policy

Directories

Path Synopsis
Package k8sjob runs the policy tests as a Kubernetes Job.
Package k8sjob runs the policy tests as a Kubernetes Job.

Jump to

Keyboard shortcuts

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