sim

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 15, 2025 License: GPL-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DEFAULT_TIME_FORMAT = "2006-01-02T15:04:05"
	EMPTY               = ""
	TRUE                = "true"
	FALSE               = "false"
)

Static values

Variables

View Source
var ConditionOperatorMap = map[string]CondInner{

	condition.StringEquals: Mod_ResolveVariables(
		Cond_MatchAny(
			Cond_StringEquals,
		),
	),
	condition.StringNotEquals: Mod_ResolveVariables(
		Mod_Not(
			Cond_MatchAny(
				Cond_StringEquals,
			),
		),
	),
	condition.StringEqualsIgnoreCase: Mod_ResolveVariables(
		Cond_MatchAny(
			Mod_IgnoreCase(
				Cond_StringEquals,
			),
		),
	),
	condition.StringNotEqualsIgnoreCase: Mod_ResolveVariables(
		Mod_Not(
			Cond_MatchAny(
				Mod_IgnoreCase(
					Cond_StringEquals,
				),
			),
		),
	),
	condition.StringLike: Mod_ResolveVariables(
		Cond_MatchAny(
			Cond_StringLike,
		),
	),
	condition.StringNotLike: Mod_ResolveVariables(
		Mod_Not(
			Cond_MatchAny(
				Cond_StringLike,
			),
		),
	),

	condition.NumericEquals: Cond_MatchAny(
		Mod_Number(
			Cond_NumericEquals,
		),
	),
	condition.NumericNotEquals: Mod_Not(
		Cond_MatchAny(
			Mod_Number(
				Cond_NumericEquals,
			),
		),
	),
	condition.NumericLessThan: Cond_MatchAny(
		Mod_Number(
			Cond_NumericLessThan,
		),
	),
	condition.NumericLessThanEquals: Cond_MatchAny(
		Mod_Number(
			Cond_NumericLessThanEquals,
		),
	),
	condition.NumericGreaterThan: Cond_MatchAny(
		Mod_Number(
			Cond_NumericGreaterThan,
		),
	),
	condition.NumericGreaterThanEquals: Cond_MatchAny(
		Mod_Number(
			Cond_NumericGreaterThanEquals,
		),
	),

	condition.DateEquals: Cond_MatchAny(
		Mod_Date(
			Cond_NumericEquals,
		),
	),
	condition.DateNotEquals: Mod_Not(
		Cond_MatchAny(
			Mod_Date(
				Cond_NumericEquals,
			),
		),
	),
	condition.DateLessThan: Cond_MatchAny(
		Mod_Date(
			Cond_NumericLessThan,
		),
	),
	condition.DateLessThanEquals: Cond_MatchAny(
		Mod_Date(
			Cond_NumericLessThanEquals,
		),
	),
	condition.DateGreaterThan: Cond_MatchAny(
		Mod_Date(
			Cond_NumericGreaterThan,
		),
	),
	condition.DateGreaterThanEquals: Cond_MatchAny(
		Mod_Date(
			Cond_NumericGreaterThanEquals,
		),
	),

	condition.Bool: Mod_ResolveVariables(
		Cond_MatchAny(
			Mod_Bool(
				Mod_IgnoreCase(
					Cond_StringEquals,
				),
			),
		),
	),

	condition.BinaryEquals: Cond_MatchAny(
		Mod_Binary(
			Cond_StringEquals,
		),
	),

	condition.IpAddress: Cond_MatchAny(
		Mod_Network(
			Cond_IpAddress,
		),
	),
	condition.NotIpAddress: Mod_Not(
		Cond_MatchAny(
			Mod_Network(
				Cond_IpAddress,
			),
		),
	),

	condition.ArnEquals: Mod_ResolveVariables(
		Cond_MatchAny(
			Cond_ArnLike,
		),
	),
	condition.ArnNotEquals: Mod_ResolveVariables(
		Mod_Not(
			Cond_MatchAny(
				Cond_ArnLike,
			),
		),
	),
	condition.ArnLike: Mod_ResolveVariables(
		Cond_MatchAny(
			Cond_ArnLike,
		),
	),
	condition.ArnNotLike: Mod_ResolveVariables(
		Mod_Not(
			Cond_MatchAny(
				Cond_ArnLike,
			),
		),
	),
}

ConditionOperatorMap defines the mapping between operator names and functions

View Source
var DEFAULT_OPTIONS = NewOptions()

DEFAULT_OPTIONS uses all default configuration options for simulation

View Source
var TIME_FORMATS = []string{
	"2006",
	"2006-01",
	"2006-01-02",
	"2006-01-02T15:04",
	"2006-01-02T15:04-0700",
	"2006-01-02T15:04:05",
	"2006-01-02T15:04:05Z",
	"2006-01-02T15:04:05-0700",
	"2006-01-02T15:04:05.999",
	"2006-01-02T15:04:05.999Z",
	"2006-01-02T15:04:05.999-0700",
}

TestingSimulationOptions provides a specific set of simulation options appropriate for most tests. It allows for exercising difficult-to-reach error paths while also allowing us to bend the rules a bit for testing -- fewer checks around the specifics of the dummy resource calls we use

View Source
var VariableExpansionRegex = regexp.MustCompile(`\${([a-zA-Z0-9]+:\S+?)}`)

VariableExpansionRegex defines the variable to use for expanding policy variables

Functions

func Cond_ArnLike

func Cond_ArnLike(s *subject, left, right string) bool

Cond_ArnLike defines the `ArnLike` condition function

func Cond_IpAddress

func Cond_IpAddress(s *subject, left netip.Addr, right netip.Prefix) bool

Cond_IpAddress defines the `IpAddress` condition function

func Cond_NumericEquals

func Cond_NumericEquals(s *subject, left, right int) bool

Cond_NumericEquals defines the `NumericEquals` condition function

func Cond_NumericGreaterThan

func Cond_NumericGreaterThan(s *subject, left, right int) bool

Cond_NumericGreaterThan defines the `NumericGreaterThan` condition function

func Cond_NumericGreaterThanEquals

func Cond_NumericGreaterThanEquals(s *subject, left, right int) bool

Cond_NumericGreaterThanEquals defines the `NumericGreaterThanEquals` condition function

func Cond_NumericLessThan

func Cond_NumericLessThan(s *subject, left, right int) bool

Cond_NumericLessThan defines the `NumericLessThan` condition function

func Cond_NumericLessThanEquals

func Cond_NumericLessThanEquals(s *subject, left, right int) bool

Cond_NumericLessThanEquals defines the `NumericLessThanEquals` condition function

func Cond_StringEquals

func Cond_StringEquals(s *subject, left, right string) bool

Cond_StringEquals defines the `StringEquals` condition function

func Cond_StringLike

func Cond_StringLike(s *subject, left, right string) bool

Cond_StringLike defines the `StringLike` condition function

func Id

func Id(id string, idx int) string

Id is a helper function which takes in an index and an ID, returning the ID if it's non-empty and the index otherwise

It's most commonly used to resolve a valid identifier for a statement or policy, where a Policy ID or Sid is preferable but a relative index is a valid fallback

Types

type AccessTuple

type AccessTuple struct {
	Principal string
	Action    string
	Resource  string
	Result    *SimResult
}

type AuthContext

type AuthContext struct {
	Action    *types.Action
	Principal *entities.FrozenPrincipal
	Resource  *entities.FrozenResource

	Time                 time.Time
	Properties           Bag[string]
	MultiValueProperties Bag[[]string]
}

AuthContext defines the tertiary context of a request that can be used for authz decisions TODO(nsiow) decide if this should be public or private type

func (*AuthContext) ConditionKey

func (ac *AuthContext) ConditionKey(key string, opts Options) string

ConditionKey retrieves the value for the requested key from the AuthContext TODO(nsiow) key retrieval should be case insensitive... I think TODO(nsiow) support Trace object here for even lower level debugging

func (*AuthContext) MultiKey

func (ac *AuthContext) MultiKey(key string, opts Options) []string

MultiKey retrieves the values for the requested key from the AuthContext

func (*AuthContext) Substitute

func (ac *AuthContext) Substitute(value string, opts Options) string

Substitute resolves and replaces all IAM variables within the provided values

func (*AuthContext) Validate

func (ac *AuthContext) Validate(opts Options) error

Validate checks that the given AuthContext is valid and ready for simulation

type Bag

type Bag[T any] struct {
	// contains filtered or unexported fields
}

Bag implements a generic looser map interface which case-folds its string keys

func NewBag

func NewBag[T any]() Bag[T]

NewBag creates and returns a new case-folded bag with the specified value type T

func NewBagFromMap

func NewBagFromMap[T any](other map[string]T) Bag[T]

NewBagFroMap creates and returns a new case-folded bag with the specified value type T, seeded using the folded key/values from the provided map

func (*Bag[T]) Check

func (b *Bag[T]) Check(k string) (T, bool)

Check folds the input key and then checks the bag for a value matching the provided key

func (*Bag[T]) Delete

func (b *Bag[T]) Delete(k string)

Delete removes the key+value pair

func (*Bag[T]) Get

func (b *Bag[T]) Get(k string) T

Get folds the input key and then returns the matched value (or the zero-value for the registered type if a match cannot be found)

func (*Bag[T]) Put

func (b *Bag[T]) Put(k string, v T)

Put saves the provided value to our Bag after folding the input key

type Compare

type Compare = func(s *subject, left string, right string) bool

Compare defines a function used to compare a value to a single other value

The function should take in two strings where `left` is the observed value and `right` is what we are trying to match against

func Mod_Binary

func Mod_Binary(f func(*subject, string, string) bool) Compare

Mod_Binary validates and forwards on the base64 encoded values, allowing binary expressions

We reuse the string operators for this rather than a byte-by-byte comparison for ease, but for slightly faster comparison we should perform the byte-by-byte comparison to avoid the base64 encoding overhead

func Mod_Bool

func Mod_Bool(f func(*subject, string, string) bool) Compare

Mod_Bool converts the string inputs to bools, allowing boolean operations

func Mod_Date

func Mod_Date(f func(*subject, int, int) bool) Compare

Mod_Date converts the string inputs to dates, allowing datewise comparisons

func Mod_IgnoreCase

func Mod_IgnoreCase(f Compare) Compare

Mod_IgnoreCase defines a Condition modifier which ignores character casing

func Mod_Network

func Mod_Network(f func(*subject, netip.Addr, netip.Prefix) bool) Compare

Mod_Network converts the incoming strings into IP addresses/nets, allowing network expressions

func Mod_Number

func Mod_Number(f func(*subject, int, int) bool) Compare

Mod_Number converts the string inputs to numbers, allowing numerical comparisons

type CondInner

type CondInner = func(s *subject, left string, right policy.Value) bool

CondInner defines a function that accepts a left hand value and a right hand set of values and evaluates the outcome of the condition

func Cond_MatchAny

func Cond_MatchAny(f Compare) CondInner

func Mod_IfExists

func Mod_IfExists(f CondInner) CondInner

Mod_IfExists defines a Condition modifier which returns true if the key is not found

func Mod_MustExist

func Mod_MustExist(f CondInner) CondInner

Mod_MustExist defines a Condition modifier which returns false if the key is not found

func Mod_Not

func Mod_Not(f CondInner) CondInner

Mod_Not inverts the provided ConditionOperator

func Mod_ResolveVariables

func Mod_ResolveVariables(f CondInner) CondInner

Mod_ResolveVariables resolves and replaces all IAM variables within the provided values

type CondLift

type CondLift = func(CondInner) CondOuter

CondLift defines a function which "lifts" a ConditionInner operator

This function effectively contains the logic to map the "key" parameter of a ConditionOuter function to the "left" parameter of a ConditionInner function

type CondMod

type CondMod = func(CondInner) CondInner

CondMod defines a function which wraps a ConditionOperator to change its behavior

type CondOuter

type CondOuter = func(s *subject, key string, right policy.Value) bool

CondOuter defines a function that accepts a key name and set of values and evaluates the outcome of the condition

func Mod_ForAllValues

func Mod_ForAllValues(f CondInner) CondOuter

Mod_ForAllValues defines a Condition modifier targeting match-all logic for multivalued conditions

func Mod_ForAnyValues

func Mod_ForAnyValues(f CondInner) CondOuter

Mod_ForAnyValues defines a Condition modifier targeting match-any logic for multivalued conditions

func Mod_ForSingleValue

func Mod_ForSingleValue(f CondInner) CondOuter

Mod_ForSIngleValue defines a Condition modifier targeting match-any logic for single-valued conditions (the default)

func ResolveConditionEvaluator

func ResolveConditionEvaluator(op string) (CondOuter, bool)

ResolveConditionEvaluator takes in an operator name and resolves it to a function

If the function could be resolved, the second return value is `true`. Otherwise, the second return value is `false`

type Decision

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

Decision maintains a unique list of Effect values

func (*Decision) Add

func (d *Decision) Add(effect policy.Effect)

Add takes the provided Effect and saves it to the Decision

func (*Decision) Allowed

func (d *Decision) Allowed() bool

Allowed determines whether or not the Decision corresponds to an IAM operation being allowed

func (*Decision) Denied

func (d *Decision) Denied() bool

Denied determines whether or not the Decision corresponds to an IAM operation being denied

func (*Decision) DeniedExplicit

func (d *Decision) DeniedExplicit() bool

DeniedExplicit determines whether or not the Decision corresponds to an IAM operation being denied based on an explicit DENY decision TODO(nsiow) check for other instances in the code base where this should be used

func (*Decision) Merge

func (d *Decision) Merge(others ...Decision)

Merge combines the provided Decision(s) with our target

type Extra

type Extra struct {
	ResourceAllowsExplicitPrincipal bool
}

Extra is a necessary evil of IAM evaluations quirks that need to be handled delicately

type OptionF

type OptionF func(*Options)

OptionF implements the functional options pattern for simulator options

func WithAdditionalProperties

func WithAdditionalProperties(props map[string]string) OptionF

WithAdditionalProperties adds the provided properties to the request context

func WithDefaultS3Key

func WithDefaultS3Key(key string) OptionF

WithDefaultS3Key sets the provided S3 key as the default for all buckets

func WithEnableFuzzyMatchArn

func WithEnableFuzzyMatchArn() OptionF

WithEnableFuzzyMatchArn turns on fuzzy-matching for ARN values

func WithForceFailure

func WithForceFailure() OptionF

WithForceFailure causes all simulations to fail

func WithOverlay

func WithOverlay(overlays *entities.Universe) OptionF

WithOverlay adds the provided "overlay" universe to our options

func WithSkipServiceAuthorizationValidation

func WithSkipServiceAuthorizationValidation() OptionF

WithSkipServiceAuthorizationValidation toggles SkipServiceAuthorizationValidation to true

func WithTracing

func WithTracing() OptionF

WithTracing toggles EnableTracing to true

type Options

type Options struct {
	// SkipServiceAuthorizationValidation foregoes the usual validation via the Service Authorization
	// Reference. This will result in faster simulation but at the cost of real-world accuracy
	SkipServiceAuthorizationValidation bool

	// EnableTracing turns on active tracing for requests. This incurs a minor performance penalty but
	// allows for helpful explanations of how a particular simulation result was achieved
	EnableTracing bool

	// Context specifies additional key/value pairs that should be carried along in the Authorization
	// context
	Context Bag[string]

	// Overlays allows one to specify a special "overlay" Universe in which entity lookup takes place
	// over the primary simulation Universe
	Overlay *entities.Universe

	// DefaultS3Key specifies which S3 object key should be used to expand S3 bucket ARNs by default.
	// In other words, it enables simulation against S3 object-level calls for operations where
	// individual object keys cannot be provided
	DefaultS3Key string

	// EnableFuzzyMatchArn enables fuzzy-matching for principal/resource values. This will do a
	// case-insensitive search based on user inputs, and return an error if more than one value
	// matches
	EnableFuzzyMatchArn bool

	// ForceFailure causes all simulation results to throw an error. Primarily used for testing and
	// debugging purposes
	ForceFailure bool
}

Options contains all possible customizatons for simulator logic + behavior

func NewOptions

func NewOptions(funcs ...OptionF) Options

NewOptions creates and returns a new Options struct parameterized with the provided options

type Pool

type Pool struct {
	Simulator *Simulator // TODO(nsiow) revisit this: make default Pool useful?
	Ctx       context.Context
	// contains filtered or unexported fields
}

func NewPool

func NewPool(ctx context.Context, simulator *Simulator) *Pool

func (*Pool) BatchSize

func (p *Pool) BatchSize() int

func (*Pool) NumWorkers

func (p *Pool) NumWorkers() int

func (*Pool) SetBatchSize

func (p *Pool) SetBatchSize(num int)

func (*Pool) SetTimeout

func (p *Pool) SetTimeout(timeout time.Duration)

func (*Pool) SetWorkers

func (p *Pool) SetWorkers(num int)

func (*Pool) Start

func (p *Pool) Start()

func (*Pool) Submit

func (p *Pool) Submit(b simBatch)

func (*Pool) Timeout

func (p *Pool) Timeout() time.Duration

type SimResult

type SimResult struct {
	// Principal corresponds to the ARN of the Principal used for this evaluation
	Principal string

	// Action corresponds to the AWS API action used for this evaluation
	Action string

	// Resource corresponds to the ARN of the Resource used for this evaluation
	Resource string

	// IsAllowed corresponds to whether or not the operation was allowed
	IsAllowed bool

	// Trace contains an evaluation trace providing context as to the access evaluation process
	Trace *trace.Trace
}

SimResult defines the output of a policy simulation option

type Simulator

type Simulator struct {
	Universe *entities.Universe
	Pool     *Pool
}

Simulator provides the ability to simulate IAM policies and the interactions between Principals + Resources

func NewSimulator

func NewSimulator() (*Simulator, error)

NewSimulator creates and returns a Simulator with the provided options

func (*Simulator) AccessSummary

func (s *Simulator) AccessSummary(actions []string, opts Options) (map[string]int, error)

func (*Simulator) Product

func (s *Simulator) Product(ps, as, rs []string, opts Options) ([]AccessTuple, error)

Product is a mostly-helper function (that can be used directly!) which calculates the Cartesian product of the provided simulation identifiers, while also filtering out any combinations that are not allowed.

func (*Simulator) Simulate

func (s *Simulator) Simulate(ac AuthContext) (*SimResult, error)

Simulate determines whether the provided AuthContext would be allowed

func (*Simulator) SimulateByArn

func (s *Simulator) SimulateByArn(principalArn, action, resourceArn string) (*SimResult, error)

SimulateByArn determines whether the operation would be allowed between the Principal and Resource specified by the provided ARNs, using the Simulator's default options

func (*Simulator) SimulateByArnWithOptions

func (s *Simulator) SimulateByArnWithOptions(
	principalArn, action, resourceArn string, opts Options) (*SimResult, error)

SimulateByArnWithOptions determines whether the operation would be allowed between the Principal and Resource specified by the provided ARNs, using the provided simulation Options

func (*Simulator) SimulateWithOptions

func (s *Simulator) SimulateWithOptions(ac AuthContext, opts Options) (*SimResult, error)

Simulate determines whether the provided AuthContext would be allowed

func (*Simulator) WhichActions

func (s *Simulator) WhichActions(principal, resource string, opts Options) ([]string, error)

func (*Simulator) WhichPrincipals

func (s *Simulator) WhichPrincipals(action, resource string, opts Options) ([]string, error)

func (*Simulator) WhichResources

func (s *Simulator) WhichResources(principal, action string, opts Options) ([]string, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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