model

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2023 License: Apache-2.0 Imports: 15 Imported by: 2

Documentation

Overview

Package model contains abstract representations of policy template and instance config objects.

Index

Constants

This section is empty.

Variables

View Source
var (
	// AnyType is equivalent to the CEL 'protobuf.Any' type in that the value may have any of the
	// types supported by CEL Policy Templates.
	AnyType = newSimpleType("any", decls.Any, nil)

	// BoolType is equivalent to the CEL 'bool' type.
	BoolType = newSimpleType("bool", decls.Bool, types.False)

	// BytesType is equivalent to the CEL 'bytes' type.
	BytesType = newSimpleType("bytes", decls.Bytes, types.Bytes([]byte{}))

	// DoubleType is equivalent to the CEL 'double' type which is a 64-bit floating point value.
	DoubleType = newSimpleType("double", decls.Double, types.Double(0))

	// DurationType is equivalent to the CEL 'duration' type.
	DurationType = newSimpleType("duration", decls.Duration, types.Duration{Duration: time.Duration(0)})

	// DynType is the equivalent of the CEL 'dyn' concept which indicates that the type will be
	// determined at runtime rather than compile time.
	DynType = newSimpleType("dyn", decls.Dyn, nil)

	// IntType is equivalent to the CEL 'int' type which is a 64-bit signed int.
	IntType = newSimpleType("int", decls.Int, types.IntZero)

	// NullType is equivalent to the CEL 'null_type'.
	NullType = newSimpleType("null_type", decls.Null, types.NullValue)

	// StringType is equivalent to the CEL 'string' type which is expected to be a UTF-8 string.
	// StringType values may either be string literals or expression strings.
	StringType = newSimpleType("string", decls.String, types.String(""))

	// PlainTextType is equivalent to the CEL 'string' type, but which has been specifically
	// designated as a string literal.
	PlainTextType = newSimpleType("string_lit", decls.String, types.String(""))

	// TimestampType corresponds to the well-known protobuf.Timestamp type supported within CEL.
	TimestampType = newSimpleType("timestamp", decls.Timestamp, types.Timestamp{Time: time.Time{}})

	// UintType is equivalent to the CEL 'uint' type.
	UintType = newSimpleType("uint", decls.Uint, types.Uint(0))

	// ListType is equivalent to the CEL 'list' type.
	ListType = NewListType(AnyType)

	// MapType is equivalent to the CEL 'map' type.
	MapType = NewMapType(AnyType, AnyType)
)

Functions

func FieldTypeMap

func FieldTypeMap(path string, t *DeclType) map[string]*DeclType

FieldTypeMap constructs a map of the field and object types nested within a given type.

Types

type BoolDecisionValue

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

BoolDecisionValue represents the decision value type associated with a decision.

func NewBoolDecisionValue

func NewBoolDecisionValue(name string, value types.Bool) *BoolDecisionValue

NewBoolDecisionValue returns a boolean decision with an initial value.

func (*BoolDecisionValue) And

func (dv *BoolDecisionValue) And(other ref.Val) *BoolDecisionValue

And logically ANDs the current decision value with the incoming CEL value.

And follows CEL semantics with respect to errors and unknown values where errors may be absorbed or short-circuited away by subsequent 'false' values. When unkonwns are encountered the unknown values combine and aggregate within the decision. Unknowns may also be absorbed per CEL semantics.

func (*BoolDecisionValue) Details

func (dv *BoolDecisionValue) Details() *cel.EvalDetails

Details implements the SingleDecisionValue interface method.

func (*BoolDecisionValue) Finalize

func (dv *BoolDecisionValue) Finalize(details *cel.EvalDetails, rule Rule) DecisionValue

Finalize marks the decision as immutable with additional input and indicates the rule and evaluation details which triggered the finalization.

func (*BoolDecisionValue) IsFinal

func (dv *BoolDecisionValue) IsFinal() bool

IsFinal returns whether the decision is final.

func (*BoolDecisionValue) Name

func (dv *BoolDecisionValue) Name() string

Name implements the DecisionValue interface method.

func (*BoolDecisionValue) Or

func (dv *BoolDecisionValue) Or(other ref.Val) *BoolDecisionValue

Or logically ORs the decision value with the incoming CEL value.

The ORing logic follows CEL semantics with respect to errors and unknown values. Errors may be absorbed or short-circuited away by subsequent 'true' values. When unkonwns are encountered the unknown values combine and aggregate within the decision. Unknowns may also be absorbed per CEL semantics.

func (*BoolDecisionValue) RuleID

func (dv *BoolDecisionValue) RuleID() int64

RuleID implements the SingleDecisionValue interface method.

func (*BoolDecisionValue) String

func (dv *BoolDecisionValue) String() string

String renders the decision value to a string for debug purposes.

func (*BoolDecisionValue) Value

func (dv *BoolDecisionValue) Value() ref.Val

Value implements the SingleDecisionValue interface method.

type Comment

type Comment struct {
	// Text contains the comment text.
	Text string

	// Style indicates where the comment appears relative to a source element.
	Style CommentStyle
}

Comment represents a comment within source.

func NewFootComment

func NewFootComment(txt string) *Comment

NewFootComment creates a new FootComment from the text.

func NewHeadComment

func NewHeadComment(txt string) *Comment

NewHeadComment creates a new HeadComment from the text.

func NewLineComment

func NewLineComment(txt string) *Comment

NewLineComment creates a new LineComment from the text.

type CommentStyle

type CommentStyle int

CommentStyle type used to indicate where a comment occurs.

const (
	// HeadComment indicates that the comment is defined in the lines preceding the source element.
	HeadComment CommentStyle = iota + 1

	// LineComment indicates that the comment occurs on the same line after the source element.
	LineComment

	// FootComment indicates that the comment occurs after the source element with at least one
	// blank line before the next source element.
	FootComment
)

type CustomRule

type CustomRule struct {
	*DynValue
}

CustomRule embeds the DynValue and represents rules whose type definition is provided in the policy template.

func (*CustomRule) GetFieldID

func (c *CustomRule) GetFieldID(field string) int64

GetFieldID returns the parse-time generated ID pointing to the rule field. If field is not specified or is not found, falls back to the ID of the rule node.

func (*CustomRule) GetID

func (c *CustomRule) GetID() int64

GetID returns the parse-time generated ID of the rule node.

type Decision

type Decision struct {
	Name      string
	Reference *cel.Ast
	Output    *cel.Ast
}

Decision contains a decision name, or reference to a decision name, and an output expression.

func NewDecision

func NewDecision() *Decision

NewDecision returns an empty Decision instance.

type DecisionSelector

type DecisionSelector func(decision string) bool

DecisionSelector determines whether the given decision is the decision set requested by the caller.

type DecisionValue

type DecisionValue interface {
	fmt.Stringer

	// Name returns the decision name.
	Name() string

	// IsFinal returns whether the decision value will change with additional rule evaluations.
	//
	// When a decision is final, additional productions and rules which may also trigger the same
	// decision may be skipped.
	IsFinal() bool
}

DecisionValue represents a named decision and value.

type DeclField

type DeclField struct {
	Name     string
	Type     *DeclType
	Required bool
	// contains filtered or unexported fields
}

DeclField describes the name, ordinal, and optionality of a field declaration within a type.

func (*DeclField) DefaultValue

func (f *DeclField) DefaultValue() ref.Val

DefaultValue returns the zero value associated with the field.

func (*DeclField) EnumValues

func (f *DeclField) EnumValues() []ref.Val

EnumValues returns the set of values that this field may take.

func (*DeclField) TypeName

func (f *DeclField) TypeName() string

TypeName returns the string type name of the field.

type DeclType

type DeclType struct {
	fmt.Stringer

	Fields    map[string]*DeclField
	KeyType   *DeclType
	ElemType  *DeclType
	TypeParam bool
	Metadata  map[string]string
	// contains filtered or unexported fields
}

DeclType represents the universal type descriptor for Policy Templates.

func NewListType

func NewListType(elem *DeclType) *DeclType

NewListType returns a parameterized list type with a specified element type.

func NewMapType

func NewMapType(key, elem *DeclType) *DeclType

NewMapType returns a parameterized map type with the given key and element types.

func NewObjectType

func NewObjectType(name string, fields map[string]*DeclField) *DeclType

NewObjectType creates an object type with a qualified name and a set of field declarations.

func NewObjectTypeRef

func NewObjectTypeRef(name string) *DeclType

NewObjectTypeRef returns a reference to an object type by name

func NewTypeParam

func NewTypeParam(name string) *DeclType

NewTypeParam creates a type parameter type with a simple name.

Type parameters are resolved at compilation time to concrete types, or CEL 'dyn' type if no type assignment can be inferred.

func (*DeclType) DefaultValue

func (t *DeclType) DefaultValue() ref.Val

DefaultValue returns the CEL ref.Val representing the default value for this object type, if one exists.

func (*DeclType) ExprType

func (t *DeclType) ExprType() *exprpb.Type

ExprType returns the CEL expression type of this declaration.

func (*DeclType) FindField

func (t *DeclType) FindField(name string) (*DeclField, bool)

FindField returns the DeclField with the given name if present.

func (*DeclType) HasTrait

func (t *DeclType) HasTrait(trait int) bool

HasTrait implements the CEL ref.Type interface making this type declaration suitable for use within the CEL evaluator.

func (*DeclType) IsList

func (t *DeclType) IsList() bool

IsList returns whether the declaration is a `list` type which defines a parameterized element type, but not a parameterized key type or fields.

func (*DeclType) IsMap

func (t *DeclType) IsMap() bool

IsMap returns whether the declaration is a 'map' type which defines parameterized key and element types, but not fields.

func (*DeclType) IsObject

func (t *DeclType) IsObject() bool

IsObject returns whether the declartion is an 'object' type which defined a set of typed fields.

func (*DeclType) MaybeAssignTypeName

func (t *DeclType) MaybeAssignTypeName(name string) *DeclType

MaybeAssignTypeName attempts to set the DeclType name to a fully qualified name, if the type is of `object` type.

The DeclType must return true for `IsObject` or this assignment will error.

func (*DeclType) String

func (t *DeclType) String() string

String implements the fmt.Stringer interface method.

func (*DeclType) TypeName

func (t *DeclType) TypeName() string

TypeName returns the fully qualified type name for the DeclType.

type DynValue

type DynValue struct {
	ID          int64
	EncodeStyle EncodeStyle
	// contains filtered or unexported fields
}

DynValue is a dynamically typed value used to describe unstructured content. Whether the value has the desired type is determined by where it is used within the Instance or Template, and whether there are schemas which might enforce a more rigid type definition.

func NewDynValue

func NewDynValue(id int64, val interface{}) (*DynValue, error)

NewDynValue returns a DynValue that corresponds to a parse node id and value.

func NewEmptyDynValue

func NewEmptyDynValue() *DynValue

NewEmptyDynValue returns the zero-valued DynValue.

func (*DynValue) ConvertToNative

func (dv *DynValue) ConvertToNative(typeDesc reflect.Type) (interface{}, error)

ConvertToNative is an implementation of the CEL ref.Val method used to adapt between CEL types and Go-native types.

The default behavior of this method is to first convert to a CEL type which has a well-defined set of conversion behaviors and proxy to the CEL ConvertToNative method for the type.

func (*DynValue) DeclType

func (dv *DynValue) DeclType() *DeclType

DeclType returns the policy model type of the dyn value.

func (*DynValue) Equal

func (dv *DynValue) Equal(other ref.Val) ref.Val

Equal returns whether the dyn value is equal to a given CEL value.

func (*DynValue) ExprValue

func (dv *DynValue) ExprValue() ref.Val

ExprValue converts the DynValue into a CEL value.

func (*DynValue) SetValue added in v0.1.1

func (dv *DynValue) SetValue(value interface{}) error

SetValue updates the underlying value held by this reference.

func (*DynValue) Type

func (dv *DynValue) Type() ref.Type

Type returns the CEL type for the given value.

func (*DynValue) Value

func (dv *DynValue) Value() interface{}

Value returns the underlying value held by this reference.

type EncodeStyle

type EncodeStyle int

EncodeStyle is a hint for string encoding of parsed values.

const (
	// BlockValueStyle is the default string encoding which preserves whitespace and newlines.
	BlockValueStyle EncodeStyle = iota

	// FlowValueStyle indicates that the string is an inline representation of complex types.
	FlowValueStyle

	// FoldedValueStyle is a multiline string with whitespace and newlines trimmed to a single
	// a whitespace. Repeated newlines are replaced with a single newline rather than a single
	// whitespace.
	FoldedValueStyle

	// LiteralStyle is a multiline string that preserves newlines, but trims all other whitespace
	// to a single character.
	LiteralStyle
)

type Env

type Env struct {
	Name      string
	Container string
	Functions []*Function
	Vars      []*Var
	Types     map[string]*DeclType
}

Env declares a set of variables, functions, and types available to a given set of CEL expressions.

The Env name must be fully qualified as it will be referenced within template evaluators, validators, and possibly within the metadata of the instance rule schema.

Note, the Types values currently only holds type definitions associated with a variable declaration. Any type mentioned in the environment which does not have a definition is treated as a reference to a type which must be supplied in the base CEL environment provided by the policy engine.

func NewEnv

func NewEnv(name string) *Env

NewEnv creates an empty Env instance with a fully qualified name that may be referenced within templates.

func (*Env) ExprEnvOptions

func (e *Env) ExprEnvOptions() []cel.EnvOption

ExprEnvOptions returns a set of CEL environment options to be used when extending the base policy engine CEL environment.

type Evaluator

type Evaluator struct {
	Environment string
	Ranges      []*Range
	Terms       []*Term
	Productions []*Production
}

Evaluator contains a set of production rules used to validate policy templates or evaluate template instances.

The evaluator may optionally specify a named and versioned Environment as the basis for the variables and functions exposed to the CEL expressions within the Evaluator, and an optional set of terms.

Terms are like template-local variables. Terms may rely on other terms which precede them. Term order matters, and no cycles are permitted among terms by design and convention.

func NewEvaluator

func NewEvaluator() *Evaluator

NewEvaluator returns an empty instance of a Template Evaluator.

func (*Evaluator) DecisionCount

func (e *Evaluator) DecisionCount() int

DecisionCount returns the number of possible decisions which could be emitted by this evaluator.

type ExpressionSelector

type ExpressionSelector struct {
	// Label name being matched.
	Label string

	// Operator determines the evaluation behavior. Must be one of Exists, NotExists, In, or NotIn.
	Operator string

	// Values set, optional, to be used in the NotIn, In set membership tests.
	Values []interface{}
}

ExpressionSelector matches a label against an existence condition.

type Field

type Field struct {
	ID   int64
	Name string
	Ref  *DynValue
}

Field specifies a field name and a reference to a dynamic value.

func NewField

func NewField(id int64, name string) *Field

NewField returns a MapField instance with an empty DynValue that refers to the specified parse node id and field name.

type Function

type Function struct {
	Name      string
	Overloads []*Overload
}

Function represents a simple name and a set of overload signatures.

func NewFunction

func NewFunction(name string, overloads ...*Overload) *Function

NewFunction creates a Function instance with a simple function name and a set of overload signatures.

func (*Function) ExprDecl

func (f *Function) ExprDecl() *exprpb.Decl

ExprDecl produces a CEL proto declaration for the function and its overloads.

type Instance

type Instance struct {
	APIVersion  string
	Kind        string
	Metadata    *InstanceMetadata
	Description string

	// Selectors determine whether the instance applies to the current evaluation context.
	// All Selector values must return true for the policy instance to be included in policy
	// evaluation step.
	Selectors []Selector

	// Rules represent reference data to be used in evaluation policy decisions.
	// Depending on the nature of the decisions being emitted, some or all Rules may be evaluated
	// and the results aggregated according to the decision types being emitted.
	Rules []Rule

	// Meta represents the source metadata from the input instance.
	Meta SourceMetadata
}

Instance represents the compiled, type-checked, and validated policy instance.

func NewInstance

func NewInstance(info SourceMetadata) *Instance

NewInstance returns an empty policy instance.

func (*Instance) MetadataMap

func (i *Instance) MetadataMap() map[string]interface{}

MetadataMap returns the metadata name to value map, which can be used in evaluation. Only "name" field is supported for now.

type InstanceMetadata

type InstanceMetadata struct {
	UID       string
	Name      string
	Namespace string
}

InstanceMetadata contains standard metadata which may be associated with an instance.

type LabelSelector

type LabelSelector struct {
	// LabelValues provides a map of the string keys and values expected.
	LabelValues map[string]string
}

LabelSelector matches key, value pairs of labels associated with the evaluation context.

In Kubernetes, the such labels are provided as 'resource.labels'.

type ListDecisionValue

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

ListDecisionValue represents a named decision which collects into a list of values.

func NewListDecisionValue

func NewListDecisionValue(name string) *ListDecisionValue

NewListDecisionValue returns a named decision value which contains a list of CEL values produced by one or more policy instances and / or production rules.

func (*ListDecisionValue) Append

func (dv *ListDecisionValue) Append(val ref.Val, det *cel.EvalDetails, rule Rule)

Append accumulates the incoming CEL value into the decision's value list.

func (*ListDecisionValue) Details

func (dv *ListDecisionValue) Details() []*cel.EvalDetails

Details returns the list of evaluation details observed in computing the values in the decision. The details indices correlate 1:1 with the value indices.

func (*ListDecisionValue) Finalize

func (dv *ListDecisionValue) Finalize() DecisionValue

Finalize marks the list decision complete.

func (*ListDecisionValue) IsFinal

func (dv *ListDecisionValue) IsFinal() bool

IsFinal implements the DecisionValue interface method.

func (*ListDecisionValue) Name

func (dv *ListDecisionValue) Name() string

Name implements the DecisionValue interface method.

func (*ListDecisionValue) RuleIDs

func (dv *ListDecisionValue) RuleIDs() []int64

RuleIDs returns the list of rule ids which produced the evaluation results. The indices of the ruleIDs correlate 1:1 with the value indices.

func (*ListDecisionValue) String

func (dv *ListDecisionValue) String() string

func (*ListDecisionValue) Values

func (dv *ListDecisionValue) Values() []ref.Val

Values implements the MultiDecisionValue interface method.

type ListValue

type ListValue struct {
	Entries []*DynValue
	// contains filtered or unexported fields
}

ListValue contains a list of dynamically typed entries.

func NewListValue

func NewListValue() *ListValue

NewListValue returns an empty ListValue instance.

func (*ListValue) Add

func (lv *ListValue) Add(other ref.Val) ref.Val

Add concatenates two lists together to produce a new CEL list value.

func (*ListValue) Append

func (lv *ListValue) Append(entry *DynValue)

Append adds another entry into the ListValue.

func (*ListValue) Contains

func (lv *ListValue) Contains(val ref.Val) ref.Val

Contains returns whether the input `val` is equal to an element in the list.

If any pair-wise comparison between the input value and the list element is an error, the operation will return an error.

func (*ListValue) ConvertToNative

func (lv *ListValue) ConvertToNative(typeDesc reflect.Type) (interface{}, error)

ConvertToNative is an implementation of the CEL ref.Val method used to adapt between CEL types and Go-native array-like types.

func (*ListValue) ConvertToType

func (lv *ListValue) ConvertToType(t ref.Type) ref.Val

ConvertToType converts the ListValue to another CEL type.

func (*ListValue) Equal

func (lv *ListValue) Equal(other ref.Val) ref.Val

Equal returns true if two lists are of the same size, and the values at each index are also equal.

func (*ListValue) Get

func (lv *ListValue) Get(idx ref.Val) ref.Val

Get returns the value at the given index.

If the index is negative or greater than the size of the list, an error is returned.

func (*ListValue) Iterator

func (lv *ListValue) Iterator() traits.Iterator

Iterator produces a traits.Iterator suitable for use in CEL comprehension macros.

func (*ListValue) Size

func (lv *ListValue) Size() ref.Val

Size returns the number of elements in the list.

func (*ListValue) Type

func (lv *ListValue) Type() ref.Type

Type returns the CEL ref.Type for the list.

func (*ListValue) Value

func (lv *ListValue) Value() interface{}

Value returns the Go-native value.

type MapValue

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

MapValue declares an object with a set of named fields whose values are dynamically typed.

func NewMapValue

func NewMapValue() *MapValue

NewMapValue returns an empty MapValue.

func (MapValue) AddField

func (sv MapValue) AddField(field *Field)

AddField appends a MapField to the MapValue and indexes the field by name.

func (*MapValue) Contains

func (m *MapValue) Contains(key ref.Val) ref.Val

Contains returns whether the given key is contained in the MapValue.

func (MapValue) ConvertToNative

func (sv MapValue) ConvertToNative(typeDesc reflect.Type) (interface{}, error)

ConvertToNative converts the MapValue type to a native go types.

func (*MapValue) ConvertToObject

func (m *MapValue) ConvertToObject(declType *DeclType) *ObjectValue

ConvertToObject produces an ObjectValue from the MapValue with the associated schema type.

The conversion is shallow and the memory shared between the Object and Map as all references to the map are expected to be replaced with the Object reference.

func (*MapValue) ConvertToType

func (m *MapValue) ConvertToType(t ref.Type) ref.Val

ConvertToType converts the MapValue to another CEL type, if possible.

func (*MapValue) Equal

func (m *MapValue) Equal(other ref.Val) ref.Val

Equal returns true if the maps are of the same size, have the same keys, and the key-values from each map are equal.

func (*MapValue) Find

func (m *MapValue) Find(name ref.Val) (ref.Val, bool)

Find returns the value for the key in the map, if found.

func (*MapValue) Get

func (m *MapValue) Get(key ref.Val) ref.Val

Get returns the value for the key in the map, or error if not found.

func (MapValue) GetField

func (sv MapValue) GetField(name string) (*Field, bool)

GetField returns a MapField by name if one exists.

func (MapValue) IsSet

func (sv MapValue) IsSet(key ref.Val) ref.Val

IsSet returns whether the given field, which is defined, has also been set.

func (*MapValue) Iterator

func (m *MapValue) Iterator() traits.Iterator

Iterator produces a traits.Iterator which walks over the map keys.

The Iterator is frequently used within comprehensions.

func (*MapValue) Size

func (m *MapValue) Size() ref.Val

Size returns the number of keys in the map.

func (*MapValue) Type

func (m *MapValue) Type() ref.Type

Type returns the CEL ref.Type for the map.

func (*MapValue) Value

func (m *MapValue) Value() interface{}

Value returns the Go-native representation of the MapValue.

type MultiDecisionValue

type MultiDecisionValue interface {
	DecisionValue

	// Values returns the collection of values produced for the decision.
	Values() []ref.Val

	// Details returns the evaluation details for each value in the decision.
	// The value index correponds to the details index. The details may be nil.
	Details() []*cel.EvalDetails

	// RulesIDs returns the rule id within an instance which produce the decision values.
	// The value index corresponds to the rule id index.
	RuleIDs() []int64
}

MultiDecisionValue extends the DecisionValue which contains a set of decision values as well as the corresponding metadata about how each value was produced.

type MultilineStringValue

type MultilineStringValue struct {
	Value string
	Raw   string
}

MultilineStringValue is a multiline string value which has been parsed in a way which omits whitespace as well as a raw form which preserves whitespace.

type ObjectValue

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

ObjectValue is a struct with a custom schema type which indicates the fields and types associated with the structure.

func NewObjectValue

func NewObjectValue(sType *DeclType) *ObjectValue

NewObjectValue creates a struct value with a schema type and returns the empty ObjectValue.

func (ObjectValue) AddField

func (sv ObjectValue) AddField(field *Field)

AddField appends a MapField to the MapValue and indexes the field by name.

func (ObjectValue) ConvertToNative

func (sv ObjectValue) ConvertToNative(typeDesc reflect.Type) (interface{}, error)

ConvertToNative converts the MapValue type to a native go types.

func (*ObjectValue) ConvertToType

func (o *ObjectValue) ConvertToType(t ref.Type) ref.Val

ConvertToType is an implementation of the CEL ref.Val interface method.

func (*ObjectValue) Equal

func (o *ObjectValue) Equal(other ref.Val) ref.Val

Equal returns true if the two object types are equal and their field values are equal.

func (*ObjectValue) Get

func (o *ObjectValue) Get(name ref.Val) ref.Val

Get returns the value of the specified field.

If the field is set, its value is returned. If the field is not set, the default value for the field is returned thus allowing for safe-traversal and preserving proto-like field traversal semantics for Open API Schema backed types.

func (ObjectValue) GetField

func (sv ObjectValue) GetField(name string) (*Field, bool)

GetField returns a MapField by name if one exists.

func (ObjectValue) IsSet

func (sv ObjectValue) IsSet(key ref.Val) ref.Val

IsSet returns whether the given field, which is defined, has also been set.

func (*ObjectValue) Type

func (o *ObjectValue) Type() ref.Type

Type returns the CEL type value of the object.

func (*ObjectValue) Value

func (o *ObjectValue) Value() interface{}

Value returns the Go-native representation of the object.

type OpenAPISchema

type OpenAPISchema struct {
	Title                string                    `yaml:"title,omitempty"`
	Description          string                    `yaml:"description,omitempty"`
	Type                 string                    `yaml:"type,omitempty"`
	TypeParam            string                    `yaml:"type_param,omitempty"`
	TypeRef              string                    `yaml:"$ref,omitempty"`
	DefaultValue         interface{}               `yaml:"default,omitempty"`
	Enum                 []interface{}             `yaml:"enum,omitempty"`
	Format               string                    `yaml:"format,omitempty"`
	Items                *OpenAPISchema            `yaml:"items,omitempty"`
	Metadata             map[string]string         `yaml:"metadata,omitempty"`
	Required             []string                  `yaml:"required,omitempty"`
	Properties           map[string]*OpenAPISchema `yaml:"properties,omitempty"`
	AdditionalProperties *OpenAPISchema            `yaml:"additionalProperties,omitempty"`
}

OpenAPISchema declares a struct capable of representing a subset of Open API Schemas supported by Kubernetes which can also be specified within Protocol Buffers.

There are a handful of notable differences:

  • The validating constructs `allOf`, `anyOf`, `oneOf`, `not`, and type-related restrictsion are not supported as they can be better validated in the template 'validator' block.
  • The $ref field supports references to other schema definitions, but such aliases should be removed before being serialized.
  • The `additionalProperties` and `properties` fields are not currently mutually exclusive as is the case for Kubernetes.

See: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/#validation

var (

	// AnySchema indicates that the value may be of any type.
	AnySchema *OpenAPISchema
)

func NewOpenAPISchema

func NewOpenAPISchema() *OpenAPISchema

NewOpenAPISchema returns an empty instance of an OpenAPISchema object.

func (*OpenAPISchema) DeclType

func (s *OpenAPISchema) DeclType() *DeclType

DeclType returns the CEL Policy Templates type name associated with the schema element.

func (*OpenAPISchema) DeclTypes

func (s *OpenAPISchema) DeclTypes(maybeRootType string) (*DeclType, map[string]*DeclType)

DeclTypes constructs a top-down set of DeclType instances whose name is derived from the root type name provided on the call, if not set to a custom type.

func (*OpenAPISchema) FindProperty

func (s *OpenAPISchema) FindProperty(name string) (*OpenAPISchema, bool)

FindProperty returns the Open API Schema type for the given property name.

A property may either be explicitly defined in a `properties` map or implicitly defined in an `additionalProperties` block.

type Overload

type Overload struct {
	Name         string
	FreeFunction bool
	Args         []*DeclType
	ReturnType   *DeclType
}

Overload represents a single function overload signature.

func NewFreeFunctionOverload

func NewFreeFunctionOverload(name string, first *DeclType, rest ...*DeclType) *Overload

NewFreeFunctionOverload returns a free function overload for a given function name.

The overload name must follow the conventions laid out within the CEL overloads.go file:

// Free function style overload name:
<func>_<arg_type0>_<arg_typeN>

When the function name is global, <func> will refer to the simple function name. When the function has a qualified name, replace the '.' characters in the fully-qualified name with underscores.

Within this function, the last type supplied is used as the return type. At least one type must be specified for a zero-arity free function.

func NewOverload

func NewOverload(name string, first *DeclType, rest ...*DeclType) *Overload

NewOverload returns a receiver-style overload declaration for a given function.

The overload name must follow the conventions laid out within the CEL overloads.go file.

// Receiver-style overload name:
<receiver_type>_<func>_<arg_type0>_<arg_typeN>

Within this function, the first type supplied is the receiver type, and the last type supplied is used as the return type. At least two types must be specified for a zero-arity receiver function.

type ParsedValue

type ParsedValue struct {
	ID    int64
	Value *MapValue
	Meta  SourceMetadata
}

ParsedValue represents a top-level object representing either a template or instance value.

type PlainTextValue

type PlainTextValue string

PlainTextValue is a text string literal which must not be treated as an expression.

type Production

type Production struct {
	ID        int64
	Match     *cel.Ast
	Decisions []*Decision
}

Production describes an match-decision pair where the match, if set, indicates whether the Decision is applicable, and the decision indicates its name and output value.

func NewProduction

func NewProduction(id int64, match *cel.Ast) *Production

NewProduction returns an empty instance of a Production rule which minimally contains a single Decision.

type Range

type Range struct {
	ID    int64
	Key   *exprpb.Decl
	Value *exprpb.Decl
	Expr  *cel.Ast
}

Range expresses a looping condition where the key (or index) and value can be extracted from the range CEL expression.

type Registry

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

Registry defines a repository of environment, schema, template, and type definitions.

Registry instances are concurrency-safe.

func NewRegistry

func NewRegistry(stdExprEnv *cel.Env) *Registry

NewRegistry create a registry for keeping track of environments, schemas, templates, and more from a base cel.Env expression environment.

func (*Registry) FindEnv

func (r *Registry) FindEnv(name string) (*Env, bool)

FindEnv implements the Resolver interface method.

func (*Registry) FindExprEnv

func (r *Registry) FindExprEnv(name string) (*cel.Env, bool)

FindExprEnv implements the Resolver interface method.

func (*Registry) FindSchema

func (r *Registry) FindSchema(name string) (*OpenAPISchema, bool)

FindSchema implements the Resolver interface method.

func (*Registry) FindTemplate

func (r *Registry) FindTemplate(name string) (*Template, bool)

FindTemplate implements the Resolver interface method.

func (*Registry) FindType

func (r *Registry) FindType(name string) (*DeclType, bool)

FindType implements the Resolver interface method.

func (*Registry) SetEnv

func (r *Registry) SetEnv(name string, env *Env) error

SetEnv registers an environment description by fully qualified name.

func (*Registry) SetSchema

func (r *Registry) SetSchema(name string, schema *OpenAPISchema) error

SetSchema registers an OpenAPISchema fragment by its relative name so that it may be referenced as a reusable schema unit within other OpenAPISchema instances.

Name format: '#<simpleName>'.

func (*Registry) SetTemplate

func (r *Registry) SetTemplate(name string, tmpl *Template) error

SetTemplate registers a template by its fully qualified name.

func (*Registry) SetType

func (r *Registry) SetType(name string, declType *DeclType) error

SetType registers a DeclType descriptor by its fully qualified name.

type RelativeSource

type RelativeSource struct {
	common.Source
	// contains filtered or unexported fields
}

RelativeSource represents an embedded source element within a larger source.

func (*RelativeSource) AbsoluteLocation

func (rel *RelativeSource) AbsoluteLocation() common.Location

AbsoluteLocation returns the location within the parent Source where the RelativeSource starts.

func (*RelativeSource) Content

func (rel *RelativeSource) Content() string

Content returns the embedded source snippet.

func (*RelativeSource) NewLocation

func (rel *RelativeSource) NewLocation(line, col int) common.Location

NewLocation creates an absolute common.Location based on a local line, column position from a relative source.

func (*RelativeSource) OffsetLocation

func (rel *RelativeSource) OffsetLocation(offset int32) (common.Location, bool)

OffsetLocation returns the absolute location given the relative offset, if found.

type Resolver

type Resolver interface {
	// FindEnv returns an Env object by its fully-qualified name, if present.
	FindEnv(name string) (*Env, bool)

	// FindExprEnv returns a CEL expression environment by its fully-qualified name, if present.
	//
	// Note, the CEL expression environment name corresponds with the model Environment name;
	// however, the expression environment may inherit configuration via the CEL env.Extend method.
	FindExprEnv(name string) (*cel.Env, bool)

	// FindSchema returns an Open API Schema instance by name, if present.
	//
	// Schema names start with a `#` sign as this method is only used to resolve references to
	// relative schema elements within `$ref` schema nodes.
	FindSchema(name string) (*OpenAPISchema, bool)

	// FindTemplate returns a Template by its fully-qualified name, if present.
	FindTemplate(name string) (*Template, bool)

	// FindType returns a DeclType instance corresponding to the given fully-qualified name, if
	// present.
	FindType(name string) (*DeclType, bool)
}

Resolver declares methods to find policy templates and related configuration objects.

type Rule

type Rule interface {
	GetID() int64
	GetFieldID(field string) int64
	// contains filtered or unexported methods
}

Rule interface indicates the value types that may be used as Rule instances.

Note, the code within the main repo deals exclusively with custom, yaml-based rules, but it is entirely possible to use a protobuf message as the rule container.

type RuleTypes

type RuleTypes struct {
	ref.TypeProvider
	Schema *OpenAPISchema
	// contains filtered or unexported fields
}

RuleTypes extends the CEL ref.TypeProvider interface and provides an Open API Schema-based type-system.

func NewRuleTypes

func NewRuleTypes(kind string,
	schema *OpenAPISchema,
	res Resolver) (*RuleTypes, error)

NewRuleTypes returns an Open API Schema-based type-system which is CEL compatible.

func (*RuleTypes) ConvertToRule

func (rt *RuleTypes) ConvertToRule(dyn *DynValue) Rule

ConvertToRule transforms an untyped DynValue into a typed object.

Conversion is done deeply and will traverse the object graph represented by the dyn value.

func (*RuleTypes) EnvOptions

func (rt *RuleTypes) EnvOptions(tp ref.TypeProvider) ([]cel.EnvOption, error)

EnvOptions returns a set of cel.EnvOption values which includes the Template's declaration set as well as a custom ref.TypeProvider.

Note, the standard declaration set includes 'rule' which is defined as the top-level rule-schema type if one is configured.

If the RuleTypes value is nil, an empty []cel.EnvOption set is returned.

func (*RuleTypes) FindDeclType

func (rt *RuleTypes) FindDeclType(typeName string) (*DeclType, bool)

FindDeclType returns the CPT type description which can be mapped to a CEL type.

func (*RuleTypes) FindFieldType

func (rt *RuleTypes) FindFieldType(typeName, fieldName string) (*ref.FieldType, bool)

FindFieldType returns a field type given a type name and field name, if found.

Note, the type name for an Open API Schema type is likely to be its qualified object path. If, in the future an object instance rather than a type name were provided, the field resolution might more accurately reflect the expected type model. However, in this case concessions were made to align with the existing CEL interfaces.

func (*RuleTypes) FindType

func (rt *RuleTypes) FindType(typeName string) (*exprpb.Type, bool)

FindType attempts to resolve the typeName provided from the template's rule-schema, or if not from the embedded ref.TypeProvider.

FindType overrides the default type-finding behavior of the embedded TypeProvider.

Note, when the type name is based on the Open API Schema, the name will reflect the object path where the type definition appears.

func (*RuleTypes) NativeToValue

func (rt *RuleTypes) NativeToValue(val interface{}) ref.Val

NativeToValue is an implementation of the ref.TypeAdapater interface which supports conversion of policy template values to CEL ref.Val instances.

func (*RuleTypes) TypeNames

func (rt *RuleTypes) TypeNames() []string

TypeNames returns the list of type names declared within the RuleTypes object.

type Selector

type Selector interface {
	// contains filtered or unexported methods
}

Selector interface indicates a pre-formatted instance selection condition.

The implementations of such conditions are expected to be platform specific.

Note, if there is a clear need to tailor selection more heavily, then the schema definition for a selector should be moved into the Template schema.

type SingleDecisionValue

type SingleDecisionValue interface {
	DecisionValue

	// Value returns the single value for the decision.
	Value() ref.Val

	// Details returns the evaluation details, if present, that produced the value.
	Details() *cel.EvalDetails

	// RuleID indicate which policy rule id within an instance that produced the decision.
	RuleID() int64
}

SingleDecisionValue extends the DecisionValue which contains a single decision value as well as some metadata about the evaluation details and the rule that spawned the value.

type Source

type Source struct {
	common.Source
}

Source represents the contents of a single source file.

func ByteSource

func ByteSource(contents []byte, location string) *Source

ByteSource converts a byte sequence and location description to a model.Source.

func StringSource

func StringSource(contents, location string) *Source

StringSource converts a string and location description to a model.Source.

func (*Source) Relative

func (src *Source) Relative(content string, line, col int) *RelativeSource

Relative produces a RelativeSource object for the content provided at the absolute location within the parent Source as indicated by the line and column.

type SourceInfo

type SourceInfo struct {
	// Comments mapped by source element id to a comment set.
	Comments map[int64][]*Comment

	// LineOffsets contains the list of character offsets where newlines occur in the source.
	LineOffsets []int32

	// Description indicates something about the source, such as its file name.
	Description string

	// Offsets map from source element id to the character offset where the source element starts.
	Offsets map[int64]int32
}

SourceInfo contains metadata about the Source such as comments, line positions, and source element offsets.

func NewSourceInfo

func NewSourceInfo(src common.Source) *SourceInfo

NewSourceInfo creates SourceInfo metadata from a Source object.

func (*SourceInfo) CommentsByID

func (info *SourceInfo) CommentsByID(id int64) ([]*Comment, bool)

CommentsByID returns the set of comments by expression id, if present.

func (*SourceInfo) LocationByID

func (info *SourceInfo) LocationByID(id int64) (common.Location, bool)

LocationByID returns the line and column location of source node by its id.

type SourceMetadata

type SourceMetadata interface {
	// CommentsByID returns the set of comments associated with the expression id, if present.
	CommentsByID(int64) ([]*Comment, bool)

	// LocationByID returns the CEL common.Location of the expression id, if present.
	LocationByID(int64) (common.Location, bool)
}

SourceMetadata enables the lookup for expression source metadata by expression id.

type Template

type Template struct {
	APIVersion  string
	Kind        string
	Metadata    *TemplateMetadata
	Description string
	RuleTypes   *RuleTypes
	Validator   *Evaluator
	Evaluator   *Evaluator
	Meta        SourceMetadata
}

Template represents the compiled and type-checked policy template.

func NewTemplate

func NewTemplate(info SourceMetadata) *Template

NewTemplate produces an empty policy Template instance.

func (*Template) EvaluatorDecisionCount

func (t *Template) EvaluatorDecisionCount() int

EvaluatorDecisionCount returns the number of decisions which can be produced by the template evaluator production rules.

func (*Template) MetadataMap

func (t *Template) MetadataMap() map[string]interface{}

MetadataMap returns the metadata name to value map, which can be used in evaluation. Only "name" field is supported for now.

type TemplateMetadata

type TemplateMetadata struct {
	UID       string
	Name      string
	Namespace string

	// PluralMame is the plural form of the template name to use when managing a collection of
	// template instances.
	PluralName string

	// Properties contains an optional set of key-value information which external applications
	// might find useful.
	Properties map[string]string
}

TemplateMetadata contains the top-level information about the Template, including its name and namespace.

func NewTemplateMetadata

func NewTemplateMetadata() *TemplateMetadata

NewTemplateMetadata returns an empty *TemplateMetadata instance.

type Term

type Term struct {
	ID   int64
	Name string
	Expr *cel.Ast
}

Term is a template-local variable whose name may shadow names in the Template environment and which may depend on preceding terms as input.

func NewTerm

func NewTerm(id int64, name string, expr *cel.Ast) *Term

NewTerm produces a named Term instance associated with a CEL Ast and a list of the input terms needed to evaluate the Ast successfully.

type Var

type Var struct {
	Name string
	Type *DeclType
}

Var represents a named instanced of a type.

func NewVar

func NewVar(name string, dt *DeclType) *Var

NewVar creates a new variable with a name and a type.

func (*Var) ExprDecl

func (v *Var) ExprDecl() *exprpb.Decl

ExprDecl produces a CEL proto declaration for the variable.

Jump to

Keyboard shortcuts

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