sample

package module
v0.0.0-...-87a3248 Latest Latest
Warning

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

Go to latest
Published: May 15, 2023 License: Apache-2.0 Imports: 17 Imported by: 0

README

Entitlements - Go Sample

This application demonstrates how to use Entitlements in two possible ways - using OPA as a sidecar, or embedding OPA using the OPA SDK. To reduce duplicated code, both methods of utilizing OPA are implemented, and are hidden behind an abstraction layer.

The abstraction is implemented in opa.go, and is a simple wrapper interface, SDKDecider which presents a unified way of getting a decision from OPA. Allow-all, deny-all, sidecar, and SDK based implementations are implemented in the same file. In a production setting, it is suggested to choose one specific way of working with OPA rather than using an abstraction such as this one.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DeleteCar

func DeleteCar(id string)

DeleteCar deletes the car, as well as any associated status. If the car with the given ID does not exist, this has no effect.

func GetAPIHandler

func GetAPIHandler() http.Handler

func GetCarIDs

func GetCarIDs() []string

GetCarIDs returns a list of all extant car IDs.

func LoadFromDisk

func LoadFromDisk()

LoadFromDisk loads the persistence data from the disk.

func NextCarID

func NextCarID() string

NextCarID returns the next valid unused car ID.

func SaveToDisk

func SaveToDisk()

SaveToDisk saves the persistance data to the disk.

func SetCar

func SetCar(id string, car Car) bool

SetCar stores the specified car at the given ID, returning true if a car with that ID already existed. The status of the car is not updated - the caller may wish to delete or modify the status of the car if the ID existed already. The caller must validate the ID before calling this function.

func SetStatus

func SetStatus(id string, status Status) (bool, error)

SetStatus overwrites the status for the specified car ID. It returns true if the status already existed before (e.g. this was an overwrite). It return an error if the specified ID does not exist in the cars list.

func SetStorageDir

func SetStorageDir(path string) error

func ValidateID

func ValidateID(id string) bool

ValidateID returns true if the given ID is valid. A car ID must be of the form "carXXX" where "XXX" is an integer with no leading zeros

Types

type Car

type Car struct {
	// Make is the car's make, for example "Honda"
	Make string `json:"make"`

	// Model is the car's model, for example "Accord"
	Model string `json:"model"`

	// Year is the car's year of manufacture, for example 2017
	Year int `json:"year"`

	// Color is the color of the car's paint
	Color string `json:"color"`
}

Car represents information about a car on the lot.

func GetCar

func GetCar(id string) (Car, bool)

GetCar returns the car with the specified ID, and a boolean indicating if the requested ID existed or not.

type DummyDecider

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

func (*DummyDecider) Decision

func (d *DummyDecider) Decision(input interface{}) (*OPADecision, error)

Decision implement OPADecider.Decision.

type EntitlementsHandler

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

EntitlementsHandler is an http.Handler that checks all requests against an OPADecider, which is expected to return EntitlementsResult objects in it's result field.

Because this is intended to be a simple example, we don't do any fancy authentication.

The "User" is used as the subject field for entitlements requests.

URL.Path is used as the resource field for entitlements requests.

Method is used as the Action field for entitlements requests.

All HTTP headers are passed into the Context field for entitlements requests in the "headers" sub-field.

func NewEntitlementsHandler

func NewEntitlementsHandler(decider OPADecider, handler http.Handler) *EntitlementsHandler

NewEntitlementsHandler instances a new EntitlementsHandler.

func (*EntitlementsHandler) ServeHTTP

func (h *EntitlementsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.ServeHTTP

type EntitlementsInput

type EntitlementsInput struct {
	Action            string                 `json:"action"`
	Context           map[string]interface{} `json:"context"`
	Groups            []string               `json:"groups"`
	JWT               string                 `json:"jwt"`
	Resource          string                 `json:"resource"`
	ResourceAttribute map[string]string      `json:"resource-attributes"`
	Roles             []string               `json:"roles"`
	Subject           string                 `json:"subject"`
	SubjectAttributes map[string]string      `json:"subject-attributes"`
}

Entitlements represents an OPA input document, structured appropriately for use with the Entitlements system.

type EntitlementsOutcome

type EntitlementsOutcome struct {
	Allow        bool                      `json:"allow"`
	DecisionType string                    `json:"decision_type"`
	Enforced     []*EntitlementsRuleResult `json:"enforced"`
	Monitored    []*EntitlementsRuleResult `json:"monitored"`
	PolicyType   string                    `json:"policy_type"`
	Stacks       interface{}               `json:"stacks"`
	SystemType   string                    `json:"system_type"`
}

EntitlementsOutcome represents the outcome field of an Entitlements result.

type EntitlementsResult

type EntitlementsResult struct {
	Allowed bool                 `json:"allowed"`
	Entz    interface{}          `json:"entz"`
	Outcome *EntitlementsOutcome `json:"outcome"`
}

EntitlementsResult represent an OPA result field created using an Entitlements policy.

type EntitlementsRuleResult

type EntitlementsRuleResult struct {
	Allowed bool        `json:"allowed"`
	Denied  bool        `json:"denied"`
	Entz    interface{} `json:"entz"`
	Message string      `json:"message"`
}

EntitlementsRuleResult represents the output of a single Entitlements rule.

type HTTPDecider

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

func (*HTTPDecider) Decision

func (d *HTTPDecider) Decision(input interface{}) (*OPADecision, error)

Decision implements OPADecider.Decision.

type HTTPDecision

type HTTPDecision struct {
	Labels       map[string]string `json:"labels"`
	DecisionID   string            `json:"decision_id"`
	Path         string            `json:"path"`
	Input        interface{}       `json:"input"`
	Result       interface{}       `json:"result"`
	Timestamp    string            `json:"timestamp`
	Metrics      map[string]int    `json:"metrics"`
	AgentID      string            `json:"agent_id"`
	SystemID     string            `json:"system_id"`
	SystemType   string            `json:"system_type"`
	PolicyType   string            `json:"policy_type"`
	Received     string            `json:"received"`
	Allowed      map[string]bool   `json:"allowed"`
	DecisionType string            `json:"decision_type"`
	Columns      []string          `json:"columns"`
}

HTTPDecision represents a decision obtained via HTTP. The SDK has it's own decision format.

type OPADecider

type OPADecider interface {

	// Decision should take an input, which must be JSON-serializeable,
	// and will be used as the input document for OPA.
	//
	// It returns the result object and an error, if any.
	Decision(input interface{}) (*OPADecision, error)
}

OPADecider represents something capable of obtaining OPA decisions.

func NewDummyDecider

func NewDummyDecider(decision *OPADecision) OPADecider

NewDummyDecider instances an OPADecider that always returns the specified decision.

func NewHTTPDecider

func NewHTTPDecider(url string) OPADecider

NewHTTPDecider instances an OPADecider that uses the OPA running as a sidecar, accessed using HTTP REST calls.

The url should be the URL at which OPA should be queried.

func NewSDKDecider

func NewSDKDecider(opa *sdk.OPA, ctx context.Context, path string) OPADecider

NewSDKDecider instances an OPADecider that uses the Go OPA SDK.

opa should be obtained using sdk.New()

path should be the rule path that is to be used when constructing sdk.DecisionOptions.

type OPADecision

type OPADecision struct {
	ID     string      `json:"ID"`
	Result interface{} `json:"result"`
}

OPADecision represents a decision (output document) from OPA.

type PersistanceData

type PersistanceData struct {
	Cars     map[string]Car    `json:"cars"`
	Statuses map[string]Status `json:"statuses"`
}

PersistanceData represents the JSON data stored to disk by the persistence layer.

type SDKDecider

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

func (*SDKDecider) Decision

func (d *SDKDecider) Decision(input interface{}) (*OPADecision, error)

Decision implements OPADecider.Decision.

type Status

type Status struct {
	// Sold is true if the car has already been sold.
	Sold bool `json:"sold"`

	// Ready is true if the car is ready to be sold.
	Ready bool `json:"ready"`

	// Price is the asking price for the car.
	Price float32 `json:"price"`
}

Status represents information about the status of the car.

func GetStatus

func GetStatus(id string) (Status, bool)

GetStatus returns the status of the specified car if one exists. The bool will be true if the status existed.

The existence of a car does not imply the existence of a status.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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