permissions

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2025 License: Apache-2.0 Imports: 29 Imported by: 4

Documentation

Overview

Package permissions implements an echo middleware to simplify checking permission checks in downstream handlers by adding a checking function to the context which may later be called to check permissions.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Error is the root error for all permissions related errors.
	Error = errors.New("permissions error")

	// AuthError is the root error all auth related errors stem from.
	AuthError = fmt.Errorf("%w: auth", Error) //nolint:revive,stylecheck // not returned directly, but used as a root error.

	// ErrNoAuthToken is the error returned when there is no auth token provided for the API request
	ErrNoAuthToken = echo.ErrBadRequest.WithInternal(fmt.Errorf("%w: no auth token provided for client", AuthError))

	// ErrInvalidAuthToken is the error returned when the auth token is not the expected value
	ErrInvalidAuthToken = echo.ErrBadRequest.WithInternal(fmt.Errorf("%w: invalid auth token", AuthError))

	// ErrPermissionDenied is the error returned when permission is denied to a call
	ErrPermissionDenied = echo.ErrUnauthorized.WithInternal(fmt.Errorf("%w: subject doesn't have access", AuthError))

	// ErrBadResponse is the error returned when we receive a bad response from the server
	ErrBadResponse = fmt.Errorf("%w: bad response from server", Error)

	// ErrCheckerNotFound is the error returned when CheckAccess does not find the appropriate checker context
	ErrCheckerNotFound = fmt.Errorf("%w: no checker found in context", Error)

	// ErrPermissionsMiddlewareMissing is returned when a permissions method has been called but the middleware is missing.
	ErrPermissionsMiddlewareMissing = fmt.Errorf("%w: permissions middleware missing", Error)
)
View Source
var (
	// AuthRelationshipRequestHandlerCtxKey is the context key used to set the auth relationship request handler.
	AuthRelationshipRequestHandlerCtxKey = authRelationshipRequestHandlerCtxKey{}
)

Functions

func CheckAccess

func CheckAccess(ctx context.Context, resource gidx.PrefixedID, action string) error

CheckAccess runs the checker function to check if the provided resource and action are supported.

func CheckAll added in v0.2.0

func CheckAll(ctx context.Context, requests ...AccessRequest) error

CheckAll runs the checker function to check if all the provided resources and actions are permitted.

func CreateAuthRelationships added in v0.2.0

func CreateAuthRelationships(ctx context.Context, topic string, resourceID gidx.PrefixedID, relations ...events.AuthRelationshipRelation) error

CreateAuthRelationships publishes a create auth relationship request, blocking until a response has been received.

func DeleteAuthRelationships added in v0.2.0

func DeleteAuthRelationships(ctx context.Context, topic string, resourceID gidx.PrefixedID, relations ...events.AuthRelationshipRelation) error

DeleteAuthRelationships publishes a delete auth relationship request, blocking until a response has been received.

func MustViperFlags

func MustViperFlags(v *viper.Viper, flags *pflag.FlagSet)

MustViperFlags adds permissions config flags and viper bindings

Types

type AccessRequest added in v0.2.0

type AccessRequest struct {
	ResourceID gidx.PrefixedID `json:"resource_id"`
	Action     string          `json:"action"`
}

AccessRequest defines the required fields to check permissions access.

type AuthRelationshipRequestHandler added in v0.2.0

type AuthRelationshipRequestHandler interface {
	CreateAuthRelationships(ctx context.Context, topic string, resourceID gidx.PrefixedID, relations ...events.AuthRelationshipRelation) error
	DeleteAuthRelationships(ctx context.Context, topic string, resourceID gidx.PrefixedID, relations ...events.AuthRelationshipRelation) error
}

AuthRelationshipRequestHandler defines the required methods to create or update an auth relationship.

type CheckConfig added in v0.6.1

type CheckConfig struct {
	// Scheme sets the check URI scheme.
	// Default is http unless discovered host port is 443 in which scheme is th en https
	Scheme string

	// Path sets the request path for checks.
	//
	// Default: /readyz
	Path string

	// Count defines the number of checks to run on each endpoint.
	//
	// Default: 5
	Count int

	// Interval specifies how frequently to run checks.
	//
	// Default: 1m
	Interval time.Duration

	// Delay specifies how long to wait between subsequent checks for the same host.
	//
	// Default: 200ms
	Delay time.Duration

	// Timeout defines the maximum time an individual check request can take.
	//
	// Default: 2s
	Timeout time.Duration

	// Concurrency defines the number of hosts which may be checked simultaneously.
	//
	// Default: 5
	Concurrency int
}

CheckConfig defines the configuration for host checks.

type Checker

type Checker func(ctx context.Context, requests ...AccessRequest) error

Checker defines the checker function definition

var (
	// CheckerCtxKey is the context key used to set the checker handling function
	CheckerCtxKey = checkerCtxKey{}

	// DefaultAllowChecker defaults to allow when checker is disabled or skipped
	DefaultAllowChecker Checker = func(_ context.Context, _ ...AccessRequest) error {
		return nil
	}

	// DefaultDenyChecker defaults to denied when checker is disabled or skipped
	DefaultDenyChecker Checker = func(_ context.Context, _ ...AccessRequest) error {
		return ErrPermissionDenied
	}
)

type Config

type Config struct {
	// URL should point to a permissions-api authorization API route, such as https://example.com/api/v1/allow.
	// If not set, all permissions checks will be denied by default. To override this behavior, set DefaultAllow
	// to true.
	URL string

	// IgnoreNoResponders will ignore no responder errors when auth relationship requests are published.
	IgnoreNoResponders bool

	// DefaultAllow if set to true, will allow all permissions checks when URL is not set.
	DefaultAllow bool

	// Discovery defines the host discovery configuration.
	Discovery DiscoveryConfig
}

Config defines the permissions configuration structure

type DiscoveryConfig added in v0.6.1

type DiscoveryConfig struct {
	// Disable disables host discovery.
	//
	// Default: false
	Disable bool

	// Interval sets the frequency at which SRV records are rediscovered.
	//
	// Default: 15m
	Interval time.Duration

	// Quick ensures a quick startup, allowing for a more optimal host to be chosen after discovery has occurred.
	// When Quick is enabled, the default fallback address or default host is immediately returned.
	// Once the discovery process has completed, a discovered host will be selected.
	//
	// Default: false
	Quick *bool

	// Optional uses the fallback address or default host without throwing errors.
	// The discovery process continues to run in the background, in the chance that SRV records are added at a later point.
	//
	// Default: true
	Optional *bool

	// Check customizes the target health checking process.
	Check CheckConfig

	// Prefer specifies a preferred host.
	// If the host is not discovered or has an error, it will not be used.
	Prefer string

	// Fallback specifies a fallback host if no hosts are discovered or all hosts are currently failing.
	//
	// Default: [Config] URL Host
	Fallback string
}

DiscoveryConfig represents the host discovery configuration.

type Option

type Option func(p *Permissions) error

Option defines an option configurator

func WithDefaultChecker

func WithDefaultChecker(checker Checker) Option

WithDefaultChecker sets the default checker if the middleware is skipped

func WithDiscoveryOptions added in v0.6.1

func WithDiscoveryOptions(opts ...selecthost.Option) Option

WithDiscoveryOptions provides additional select host discovery options

func WithEventsPublisher added in v0.2.0

func WithEventsPublisher(publisher events.AuthRelationshipPublisher) Option

WithEventsPublisher sets the underlying event publisher the auth handler uses

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets the underlying http client the auth handler uses

func WithLogger

func WithLogger(logger *zap.SugaredLogger) Option

WithLogger sets the logger for the auth handler

func WithSkipper

func WithSkipper(skipper middleware.Skipper) Option

WithSkipper sets the echo middleware skipper function

type Permissions

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

Permissions handles supporting authorization checks

func New

func New(config Config, options ...Option) (*Permissions, error)

New creates a new Permissions instance

func (*Permissions) CreateAuthRelationships added in v0.2.0

func (p *Permissions) CreateAuthRelationships(ctx context.Context, topic string, resourceID gidx.PrefixedID, relations ...events.AuthRelationshipRelation) error

CreateAuthRelationships publishes a create auth relationship request, blocking until a response has been received.

func (*Permissions) DeleteAuthRelationships added in v0.2.0

func (p *Permissions) DeleteAuthRelationships(ctx context.Context, topic string, resourceID gidx.PrefixedID, relations ...events.AuthRelationshipRelation) error

DeleteAuthRelationships publishes a delete auth relationship request, blocking until a response has been received.

func (*Permissions) Middleware

func (p *Permissions) Middleware() echo.MiddlewareFunc

Middleware produces echo middleware to handle authorization checks

Directories

Path Synopsis
internal
selecthost
Package selecthost handles host discovery via DNS SRV records, keeps track of healthy and selects the most optimal host for use.
Package selecthost handles host discovery via DNS SRV records, keeps track of healthy and selects the most optimal host for use.
Package mockpermissions implements permissions.AuthRelationshipRequestHandler.
Package mockpermissions implements permissions.AuthRelationshipRequestHandler.

Jump to

Keyboard shortcuts

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