opa

package
v0.15.1 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2024 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	InputPrefixRoot           = `input`
	InputPrefixAuthentication = `auth`
	InputPrefixRequest        = `request`
	InputPrefixResource       = `resource`
)
View Source
const (
	PackagePrefixResource = `resource`
)
View Source
const PropertiesPrefix = "security.opa"

Variables

View Source
var (
	ErrInternal           = NewError("internal error")
	ErrAccessDenied       = NewError("Access Denied")
	ErrQueriesNotResolved = NewError(`OPA cannot resolve partial queries`)
)

Functions

func Allow

func Allow(ctx context.Context, opts ...QueryOptions) error

Allow is generic API for querying policy. This function only populate minimum input data like authentication. For more specialized function, see AllowResource, AllowRequest, etc.

func AllowRequest

func AllowRequest(ctx context.Context, req *http.Request, opts ...RequestQueryOptions) error

func AllowResource

func AllowResource(ctx context.Context, resType string, op ResourceOperation, opts ...ResourceQueryOptions) error

func EmbeddedOPA

func EmbeddedOPA() *sdk.OPA

func FilterResource

func FilterResource(ctx context.Context, resType string, op ResourceOperation, opts ...ResourceFilterOptions) (*sdk.PartialResult, error)

func NewOPALogger

func NewOPALogger(logger log.Logger, lvl log.LoggingLevel) opalogging.Logger

func PrepareGenericDecisionQuery

func PrepareGenericDecisionQuery(ctx context.Context, query *Query) (*sdk.DecisionOptions, error)

func PrepareRequestDecisionQuery

func PrepareRequestDecisionQuery(ctx context.Context, policy string, req *http.Request, opt *RequestQuery) (*sdk.DecisionOptions, error)

func PrepareResourceDecisionQuery

func PrepareResourceDecisionQuery(ctx context.Context, policy string, resType string, op ResourceOperation, res *ResourceQuery) (*sdk.DecisionOptions, error)

func PrepareResourcePartialQuery

func PrepareResourcePartialQuery(ctx context.Context, policy string, resType string, op ResourceOperation, res *ResourceFilter) (*sdk.PartialOptions, error)

Types

type AuthenticationClause

type AuthenticationClause struct {
	// Required fields
	UserID      string   `json:"user_id"`
	Permissions []string `json:"permissions"`
	// Optional fields
	Username          string                 `json:"username,omitempty"`
	TenantID          string                 `json:"tenant_id,omitempty"`
	ProviderID        string                 `json:"provider_id,omitempty"`
	Roles             []string               `json:"roles,omitempty"`
	AccessibleTenants []string               `json:"accessible_tenants,omitempty"`
	Client            *OAuthClientClause     `json:"client"`
	ExtraData         map[string]interface{} `json:"-"`
}

func NewAuthenticationClause

func NewAuthenticationClause() *AuthenticationClause

func (AuthenticationClause) MarshalJSON

func (c AuthenticationClause) MarshalJSON() ([]byte, error)

type BundleServerProperties

type BundleServerProperties struct {
	Name string `json:"name"`
	URL  string `json:"url"`
	PollingProperties
}

type BundleSourceProperties

type BundleSourceProperties struct {
	Path string `json:"path"`
	PollingProperties
}

type Config

type Config struct {
	Services                     map[string]*oparest.Config `json:"services,omitempty"`
	Labels                       map[string]string          `json:"labels,omitempty"`
	Discovery                    *opadiscovery.Config       `json:"discovery,omitempty"`
	Bundles                      map[string]*bundle.Source  `json:"bundles,omitempty"`
	DecisionLogs                 *opalogs.Config            `json:"decision_logs,omitempty"`
	Status                       *opastatus.Config          `json:"status,omitempty"`
	Plugins                      map[string]interface{}     `json:"plugins,omitempty"`
	Keys                         map[string]*opakeys.Config `json:"keys,omitempty"`
	DefaultDecision              *string                    `json:"default_decision,omitempty"`
	DefaultAuthorizationDecision *string                    `json:"default_authorization_decision,omitempty"`
	Caching                      *opacache.Config           `json:"caching,omitempty"`
	NDBuiltinCache               bool                       `json:"nd_builtin_cache,omitempty"`
	PersistenceDirectory         *string                    `json:"persistence_directory,omitempty"`
	DistributedTracing           *distributedTracingConfig  `json:"distributed_tracing,omitempty"`
	Storage                      *storageConfig             `json:"storage,omitempty"`
	ExtraConfig                  map[string]interface{}     `json:"-"`
}

Config is a subset OPA Config with typed field see OPA's Config.Config and Config.ParseConfig

func LoadConfig

func LoadConfig(ctx context.Context, props Properties, customizers ...ConfigCustomizer) (*Config, error)

LoadConfig create config and combine values from defaults and properties

func (Config) JSONReader

func (c Config) JSONReader(ctx context.Context) (io.Reader, error)

func (Config) MarshalJSON

func (c Config) MarshalJSON() ([]byte, error)

func (Config) MarshalText

func (c Config) MarshalText() ([]byte, error)

type ConfigCustomizer

type ConfigCustomizer interface {
	Customize(ctx context.Context, cfg *Config)
}

type ContextAwarePartialQueryMapper

type ContextAwarePartialQueryMapper interface {
	sdk.PartialQueryMapper
	WithContext(ctx context.Context) sdk.PartialQueryMapper
	Context() context.Context
}

type CurrentResourceValues

type CurrentResourceValues ResourceValues

type EmbeddedOPAOption

type EmbeddedOPAOption struct {
	// SDKOptions raw sdk.Options
	SDKOptions sdk.Options
	// Config struct overrides SDKOptions.Config
	Config *Config
	// InputCustomizers installed as global input customizers for any OPA queries
	InputCustomizers []InputCustomizer
	// Properties for extra configuration that not included in Config
	Properties *Properties
}

type EmbeddedOPAOptions

type EmbeddedOPAOptions func(opts *EmbeddedOPAOption)

func WithConfig

func WithConfig(cfg *Config) EmbeddedOPAOptions

func WithInputCustomizers

func WithInputCustomizers(customizers ...InputCustomizer) EmbeddedOPAOptions

func WithLogLevel

func WithLogLevel(level log.LoggingLevel) EmbeddedOPAOptions

func WithLogger

func WithLogger(logger opalogging.Logger) EmbeddedOPAOptions

func WithProperties

func WithProperties(props Properties) EmbeddedOPAOptions

func WithRawConfig

func WithRawConfig(jsonReader io.Reader) EmbeddedOPAOptions

type EmbeddedOPAReadyCH

type EmbeddedOPAReadyCH <-chan struct{}

func NewEmbeddedOPA

func NewEmbeddedOPA(ctx context.Context, opts ...EmbeddedOPAOptions) (*sdk.OPA, EmbeddedOPAReadyCH, error)

NewEmbeddedOPA create a new sdk.OPA instance and make it available via EmbeddedOPA function. Caller is responsible to call (*sdk.OPA).Stop to release resources

type Error

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

func NewError

func NewError(tmpl string, args ...interface{}) Error

func (Error) Error

func (e Error) Error() string

func (Error) Is

func (e Error) Is(err error) bool

func (Error) WithMessage

func (e Error) WithMessage(tmpl string, args ...interface{}) Error

type Input

type Input struct {
	Authentication *AuthenticationClause  `json:"auth,omitempty"`
	Request        *RequestClause         `json:"request,omitempty"`
	Resource       *ResourceClause        `json:"resource,omitempty"`
	ExtraData      map[string]interface{} `json:"-"`
}

func NewInput

func NewInput() *Input

func (Input) MarshalJSON

func (c Input) MarshalJSON() ([]byte, error)

type InputCustomizer

type InputCustomizer interface {
	Customize(ctx context.Context, input *Input) error
}

type InputCustomizerFunc

type InputCustomizerFunc func(ctx context.Context, input *Input) error

func (InputCustomizerFunc) Customize

func (fn InputCustomizerFunc) Customize(ctx context.Context, input *Input) error

type LoggingProperties

type LoggingProperties struct {
	LogLevel          log.LoggingLevel `json:"level"`
	DecisionLogsLevel log.LoggingLevel `json:"decision-logs-level"`
}

type OAuthClientClause

type OAuthClientClause struct {
	ClientID  string   `json:"client_id"`
	GrantType string   `json:"grant_type,omitempty"`
	Scopes    []string `json:"scopes"`
}

type PollingProperties

type PollingProperties struct {
	PollingMinDelay    *utils.Duration `json:"polling-min-delay,omitempty"`    // min amount of time to wait between successful poll attempts
	PollingMaxDelay    *utils.Duration `json:"polling-max-delay,omitempty"`    // max amount of time to wait between poll attempts
	LongPollingTimeout *utils.Duration `json:"long-polling-timeout,omitempty"` // max amount of time the server should wait before issuing a timeout if there's no update available
}

type Properties

type Properties struct {
	Server  BundleServerProperties            `json:"server"`
	Bundles map[string]BundleSourceProperties `json:"bundles"`
	Logging LoggingProperties                 `json:"logging"`
}

func NewProperties

func NewProperties() *Properties

type Query

type Query struct {
	OPA              *sdk.OPA
	Policy           string
	InputCustomizers []InputCustomizer
	RawInput         interface{}
	// LogLevel override decision log level when presented
	LogLevel *log.LoggingLevel
}

type QueryOptions

type QueryOptions func(q *Query)

func QueryWithInputCustomizer

func QueryWithInputCustomizer(customizer InputCustomizerFunc) QueryOptions

func QueryWithPolicy

func QueryWithPolicy(policy string) QueryOptions

func SilentQuery

func SilentQuery() QueryOptions

type RequestClause

type RequestClause struct {
	Scheme    string                 `json:"scheme,omitempty"`
	Path      string                 `json:"path,omitempty"`
	Method    string                 `json:"method,omitempty"`
	Header    http.Header            `json:"header,omitempty"`
	Query     url.Values             `json:"query,omitempty"`
	ExtraData map[string]interface{} `json:"-"`
}

func NewRequestClause

func NewRequestClause(req *http.Request) *RequestClause

func (RequestClause) MarshalJSON

func (c RequestClause) MarshalJSON() ([]byte, error)

type RequestQuery

type RequestQuery struct {
	OPA              *sdk.OPA
	Policy           string
	ExtraData        map[string]interface{}
	InputCustomizers []InputCustomizer
	// RawInput overrides any input related options
	RawInput interface{}
	// LogLevel override decision log level when presented
	LogLevel *log.LoggingLevel
}

type RequestQueryOptions

type RequestQueryOptions func(opt *RequestQuery)

func RequestQueryWithPolicy

func RequestQueryWithPolicy(policy string) RequestQueryOptions

func SilentRequestQuery

func SilentRequestQuery() RequestQueryOptions

type ResourceClause

type ResourceClause struct {
	CurrentResourceValues
	Type      string            `json:"type"`
	Operation ResourceOperation `json:"op"`
	Delta     *ResourceValues   `json:"delta,omitempty"`
}

func NewResourceClause

func NewResourceClause(resType string, op ResourceOperation) *ResourceClause

func (ResourceClause) MarshalJSON

func (c ResourceClause) MarshalJSON() ([]byte, error)

type ResourceFilter

type ResourceFilter struct {
	// OPA (Optional) instance to use for evaluation. Default to EmbeddedOPA()
	OPA *sdk.OPA
	// Query (Optional) OPA query to evaluate.
	// Default to `data.resource.<resource_type>.filter_<resource_operation>`
	Query string
	// Unknowns (Required) List of unknown input fields for partial evaluation. Not providing "unknowns" would not
	// result in immediate error, but very like result in access denial.
	Unknowns []string
	// QueryMapper (Optional) Custom sdk.PartialQueryMapper for translating result rego.PartialQueries.
	// By default, partial result is *rego.PartialQueries. QueryMapper can translate it to other structure.
	// e.g. SQL "Where" clause
	QueryMapper sdk.PartialQueryMapper
	// Delta (Optional) Resource's "changed-to" fields and values. Delta is only applicable to "write" operation.
	// OPA policies may have rules on what values the resource's certain fields can be changed to.
	Delta *ResourceValues
	// ExtraData  (Optional) any key-value pairs in ExtraData will be added into query input under `input.resource.*`
	ExtraData map[string]interface{}
	// InputCustomizers customizers to finalize/modify query input before evaluation
	InputCustomizers []InputCustomizer
	// RawInput overrides any input related options
	RawInput interface{}
	// LogLevel override decision log level when presented
	LogLevel *log.LoggingLevel
}

type ResourceFilterOptions

type ResourceFilterOptions func(rf *ResourceFilter)

func SilentResourceFilter

func SilentResourceFilter() ResourceFilterOptions

type ResourceOperation

type ResourceOperation string
const (
	OpRead   ResourceOperation = `read`
	OpWrite  ResourceOperation = `write`
	OpCreate ResourceOperation = `create`
	OpDelete ResourceOperation = `delete`
)

type ResourceQuery

type ResourceQuery struct {
	// OPA (Optional) Instance to use for evaluation. Default to EmbeddedOPA()
	OPA *sdk.OPA
	// Policy (Optional) OPA query/policy to evaluate.
	// Default to `resource/<resource_type>/allow_<resource_operation>`
	Policy string
	// ResourceValues (Required) Resource's current fields and values that policy may be interested in
	ResourceValues
	// Delta (Optional) Resource's "changed-to" fields and values. Delta is only applicable to "write" operation.
	// OPA policies may have rules on what values the resource's certain fields can be changed to.
	Delta *ResourceValues
	// InputCustomizers customizers to finalize/modify query input before evaluation
	InputCustomizers []InputCustomizer
	// RawInput overrides any input related options
	RawInput interface{}
	// LogLevel override decision log level when presented
	LogLevel *log.LoggingLevel
}

type ResourceQueryOptions

type ResourceQueryOptions func(res *ResourceQuery)

func SilentResourceQuery

func SilentResourceQuery() ResourceQueryOptions

type ResourceValues

type ResourceValues struct {
	TenantID   string                         `json:"tenant_id,omitempty"`
	TenantPath []string                       `json:"tenant_path,omitempty"`
	OwnerID    string                         `json:"owner_id,omitempty"`
	Sharing    map[string][]ResourceOperation `json:"sharing,omitempty"`
	ExtraData  map[string]interface{}         `json:"-"`
}

func (ResourceValues) MarshalJSON

func (c ResourceValues) MarshalJSON() ([]byte, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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