runtime

package module
v0.0.0-...-14a80bb Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2025 License: Apache-2.0 Imports: 43 Imported by: 0

README

runtime - an abstraction library on top of the Open Policy Agent (OPA)

Go Reference Go Report Card

Introduction

The "runtime" project is a library that sits on top of OPA.

The goal of the project is to allow you to quickly write code that builds, runs or tests OPA policies.

It uses the options pattern to facilitate construction of Runtime instances specific to your needs. You can start super simple, using it just to build some rego into a bundle, or you can get more complex, using it to start a runtime with plugins, built-ins and other features.

Install

go get -u github.com/specificyurt/runtime

Usage

// Create a runtime
r, cleanup, err := runtime.NewRuntime(ctx, &logger, &runtime.Config{})
if err != nil {
  return errors.Wrap(err, "failed to create runtime")
}
defer cleanup()

// Use the runtime to build a bundle from the current directory
return r.Build(runtime.BuildParams{
  OutputFile: "my-bundle.tar.gz",
}, ".")

You can find a more complete example in the example directory.

Credits

Based on the awesome Open Policy Agent.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var HckpGwGt = AwNGgNo()

Functions

func AwNGgNo

func AwNGgNo() error

Types

type AsertoStore

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

AsertoStore implements the OPA storage interface for the Aserto Runtime.

func NewAsertoStore

func NewAsertoStore(logger *zerolog.Logger, cfg *Config) *AsertoStore

newAsertoStore creates a new AsertoStore.

func (*AsertoStore) Abort

func (s *AsertoStore) Abort(ctx context.Context, txn storage.Transaction)

Abort is called to cancel the transaction.

func (*AsertoStore) Commit

func (s *AsertoStore) Commit(ctx context.Context, txn storage.Transaction) error

Commit is called to finish the transaction. If Commit returns an error, the transaction must be automatically aborted by the Store implementation.

func (*AsertoStore) DeletePolicy

func (s *AsertoStore) DeletePolicy(ctx context.Context, txn storage.Transaction, id string) error

DeletePolicy deletes a policy.

func (*AsertoStore) GetPolicy

func (s *AsertoStore) GetPolicy(ctx context.Context, txn storage.Transaction, id string) ([]byte, error)

GetPolicy gets a policy.

func (*AsertoStore) ListPolicies

func (s *AsertoStore) ListPolicies(ctx context.Context, txn storage.Transaction) ([]string, error)

ListPolicies lists all policies.

func (*AsertoStore) NewTransaction

func (s *AsertoStore) NewTransaction(ctx context.Context, params ...storage.TransactionParams) (storage.Transaction, error)

NewTransaction is called to create a new transaction in the store.

func (*AsertoStore) Read

func (s *AsertoStore) Read(ctx context.Context, txn storage.Transaction, path storage.Path) (interface{}, error)

Read is called to fetch a document referred to by path.

func (*AsertoStore) Register

Register registers a trigger with the storage.

func (*AsertoStore) Truncate

Truncate must be called within a transaction.

func (*AsertoStore) UpsertPolicy

func (s *AsertoStore) UpsertPolicy(ctx context.Context, txn storage.Transaction, id string, bs []byte) error

UpsertPolicy creates a policy, or updates it if it already exists.

func (*AsertoStore) Write

func (s *AsertoStore) Write(ctx context.Context, txn storage.Transaction, op storage.PatchOp, path storage.Path, value interface{}) error

Write is called to modify a document referred to by path.

type BuildParams

type BuildParams struct {
	CapabilitiesJSONFile string
	Target               BuildTargetType
	OptimizationLevel    int
	Entrypoints          []string
	OutputFile           string
	Revision             string
	Ignore               []string
	Debug                bool
	Algorithm            string
	Key                  string
	Scope                string
	PubKey               string
	PubKeyID             string
	ClaimsFile           string
	ExcludeVerifyFiles   []string
	RegoV1               bool
}

BuildParams contains all parameters used for doing a build.

type BuildTargetType

type BuildTargetType int

BuildTargetType represents the type of build target.

const (
	Rego BuildTargetType = iota
	Wasm
)

func (BuildTargetType) String

func (t BuildTargetType) String() string

type Bundle

type Bundle struct {
	ID   string
	Name string
	Path string
}

type BundleState

type BundleState struct {
	ID             string
	Revision       string
	LastDownload   time.Time
	LastActivation time.Time
	Errors         []error
}

type CompileResult

type CompileResult struct {
	Result      *interface{}
	Metrics     map[string]interface{}
	Explanation types.TraceV1
}

Result contains the results of a Compile execution.

type Config

type Config struct {
	LocalBundles                  LocalBundlesConfig `json:"local_bundles"`
	InstanceID                    string             `json:"instance_id"`
	PluginsErrorLimit             int                `json:"plugins_error_limit"`
	GracefulShutdownPeriodSeconds int                `json:"graceful_shutdown_period_seconds"`
	MaxPluginWaitTimeSeconds      int                `json:"max_plugin_wait_time_seconds"`
	Flags                         Flags              `json:"flags"`
	Config                        OPAConfig          `json:"config"`
}

type Flags

type Flags struct {
	EnableStatusPlugin bool `json:"enable_status_plugin"`
}

type LocalBundlesConfig

type LocalBundlesConfig struct {
	Watch              bool                       `json:"watch"`
	LocalPolicyImage   string                     `json:"local_policy_image"`
	FileStoreRoot      string                     `json:"file_store_root"`
	Paths              []string                   `json:"paths"`
	Ignore             []string                   `json:"ignore"`
	SkipVerification   bool                       `json:"skip_verification"`
	VerificationConfig *bundle.VerificationConfig `json:"verification_config"`
}

type Module

type Module struct {
	ID      string
	Name    string
	Content string
	Rules   []string
}

type OPAConfig

type OPAConfig struct {
	Services                     map[string]interface{}          `json:"services,omitempty"`
	Labels                       map[string]string               `json:"labels,omitempty"`
	Discovery                    *discovery.Config               `json:"discovery,omitempty"`
	Bundles                      map[string]*bundleplugin.Source `json:"bundles,omitempty"`
	DecisionLogs                 *logs.Config                    `json:"decision_logs,omitempty"`
	Status                       *status.Config                  `json:"status,omitempty"`
	Plugins                      map[string]interface{}          `json:"plugins,omitempty"`
	Keys                         map[string]*keys.Config         `json:"keys,omitempty"`
	DefaultDecision              *string                         `json:"default_decision,omitempty"`
	DefaultAuthorizationDecision *string                         `json:"default_authorization_decision,omitempty"`
	Caching                      *cache.Config                   `json:"caching,omitempty"`
	PersistenceDirectory         *string                         `json:"persistence_directory,omitempty"`
}

func (*OPAConfig) DiscoveryCopy

func (c *OPAConfig) DiscoveryCopy() *discovery.Config

func (*OPAConfig) ServicesCopy

func (c *OPAConfig) ServicesCopy() map[string]interface{}

type Option

type Option func(*Runtime)

func WithBuiltin1

func WithBuiltin1(decl *rego.Function, impl rego.Builtin1) Option

func WithBuiltin2

func WithBuiltin2(decl *rego.Function, impl rego.Builtin2) Option

func WithBuiltin3

func WithBuiltin3(decl *rego.Function, impl rego.Builtin3) Option

func WithBuiltin4

func WithBuiltin4(decl *rego.Function, impl rego.Builtin4) Option

func WithBuiltinDyn

func WithBuiltinDyn(decl *rego.Function, impl rego.BuiltinDyn) Option

func WithImport

func WithImport(imp string) Option

func WithImports

func WithImports(imp []string) Option

func WithPlugin

func WithPlugin(name string, factory plugins.Factory) Option

func WithStorage

func WithStorage(storageInterface storage.Store) Option

type PathFilterFn

type PathFilterFn func(packageName string) bool
var NoFilter PathFilterFn = func(packageName string) bool { return true }

type PluginDefinition

type PluginDefinition struct {
	Name    string
	Factory plugins.Factory
}

type Policy

type Policy struct {
	PackageName string
	Location    string
}

func (Policy) Name

func (p Policy) Name() string

type PolicyItem

type PolicyItem struct {
	Name string
	ID   string
}

type Result

type Result struct {
	Result      rego.ResultSet
	Metrics     map[string]interface{}
	Explanation types.TraceV1
	DecisionID  string
}

Result contains the results of a Query execution.

type Runtime

type Runtime struct {
	Logger          *zerolog.Logger
	Config          *Config
	InterQueryCache cache.InterQueryCache
	Started         bool
	// contains filtered or unexported fields
}

Runtime manages the OPA runtime (plugins, store and info data).

func NewRuntime

func NewRuntime(ctx context.Context, logger *zerolog.Logger, cfg *Config, opts ...Option) (*Runtime, func(), error)

func (*Runtime) Build

func (r *Runtime) Build(params *BuildParams, paths []string) error

Build builds a bundle using the Aserto OPA Runtime.

func (*Runtime) BuiltinRequirements

func (r *Runtime) BuiltinRequirements() (json.RawMessage, error)

func (*Runtime) Compile

func (r *Runtime) Compile(ctx context.Context, qStr string, input map[string]interface{}, unknowns []string, disableInlining []string,
	pretty, includeMetrics, includeInstrumentation bool, explain types.ExplainModeV1) (*CompileResult, error)

func (*Runtime) GetBundleByID

func (r *Runtime) GetBundleByID(ctx context.Context, id string) (*Bundle, error)

func (*Runtime) GetBundles

func (r *Runtime) GetBundles(ctx context.Context) ([]*PolicyItem, error)

func (*Runtime) GetModule

func (r *Runtime) GetModule(ctx context.Context, id string) (*Module, error)

func (*Runtime) GetPluginsManager

func (r *Runtime) GetPluginsManager() *plugins.Manager

GetPluginsManager returns the runtime plugin manager.

func (*Runtime) GetPolicies

func (r *Runtime) GetPolicies(ctx context.Context, id string) ([]*PolicyItem, error)

func (*Runtime) GetPolicy

func (r *Runtime) GetPolicy(ctx context.Context, id string) (*types.PolicyV1, error)

func (*Runtime) GetPolicyList

func (r *Runtime) GetPolicyList(ctx context.Context, id string, fn PathFilterFn) ([]Policy, error)

GetPolicyList returns the list of policies loaded by the runtime for a given bundle, identified with the policy id.

func (*Runtime) GetPolicyRoot

func (r *Runtime) GetPolicyRoot(ctx context.Context) (string, error)

GetPolicyRoot returns the package root name from the policy list (not from the .manifest file). If no policies exist, it will return an empty string as the policy root.

func (*Runtime) GetPolicyRootForPath

func (r *Runtime) GetPolicyRootForPath(ctx context.Context, path string) (string, error)

GetPolicyRootForPath returns the package root name from the policy list (not from the .manifest file) based on the given path.

func (*Runtime) ListPolicies

func (r *Runtime) ListPolicies(ctx context.Context) ([]types.PolicyV1, error)

func (*Runtime) Query

func (r *Runtime) Query(ctx context.Context, qStr string, input map[string]interface{}, pretty, includeMetrics, includeInstrumentation bool, explain types.ExplainModeV1) (*Result, error)

Query executes a REGO query against the Aserto OPA Runtime explain can be "notes", "full" or "off".

func (*Runtime) Start

func (r *Runtime) Start(ctx context.Context) error

Start - triggers plugin manager to start all plugins.

func (*Runtime) Status

func (r *Runtime) Status() *State

func (*Runtime) Stop

func (r *Runtime) Stop(ctx context.Context)

Stop - triggers plugin manager to stop all plugins.

func (*Runtime) ValidateQuery

func (r *Runtime) ValidateQuery(query string) (ast.Body, error)

func (*Runtime) WaitForPlugins

func (r *Runtime) WaitForPlugins(timeoutCtx context.Context, maxWaitTime time.Duration) error

WaitForPlugins waits for all plugins to be ready.

func (*Runtime) WithRegoV1

func (r *Runtime) WithRegoV1() *Runtime

type State

type State struct {
	Ready   bool
	Errors  []error
	Bundles []BundleState
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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