Documentation
¶
Overview ¶
Package cedar provides an implementation of the Cedar language authorizer.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/cedar-policy/cedar-go"
)
const policyCedar = `permit (
principal == User::"alice",
action == Action::"view",
resource in Album::"jane_vacation"
);
`
const entitiesJSON = `[
{
"uid": { "type": "User", "id": "alice" },
"attrs": { "age": 18 },
"parents": []
},
{
"uid": { "type": "Photo", "id": "VacationPhoto94.jpg" },
"attrs": {},
"parents": [{ "type": "Album", "id": "jane_vacation" }]
}
]`
func main() {
var policy cedar.Policy
if err := policy.UnmarshalCedar([]byte(policyCedar)); err != nil {
fmt.Println("policy unmarshal error:", err)
return
}
ps := cedar.NewPolicySet()
ps.Add("policy0", &policy)
var entities cedar.EntityMap
if err := json.Unmarshal([]byte(entitiesJSON), &entities); err != nil {
fmt.Println("entity unmarshal error:", err)
return
}
req := cedar.Request{
Principal: cedar.NewEntityUID("User", "alice"),
Action: cedar.NewEntityUID("Action", "view"),
Resource: cedar.NewEntityUID("Photo", "VacationPhoto94.jpg"),
Context: cedar.NewRecord(cedar.RecordMap{
"demoRequest": cedar.True,
}),
}
ok, diag := cedar.Authorize(ps, entities, req)
fmt.Println("Decision:", ok)
fmt.Println("Permitted by:")
for _, d := range diag.Reasons {
fmt.Println(" *", d.PolicyID)
}
}
Output: Decision: allow Permitted by: * policy0
Index ¶
- Constants
- func Authorize(policies PolicyIterator, entities types.EntityGetter, req Request) (Decision, Diagnostic)
- type AnnotationKey
- type Annotations
- type Boolean
- type Datetime
- type Decimal
- type Decision
- type Decoder
- type Diagnostic
- type DiagnosticError
- type DiagnosticReason
- type Duration
- type Effect
- type Encoder
- type Entity
- type EntityGetter
- type EntityMap
- type EntityType
- type EntityUID
- type EntityUIDSet
- type IPAddr
- type Long
- type Path
- type Pattern
- type Policy
- func (p *Policy) AST() *ast.Policy
- func (p *Policy) Annotations() Annotations
- func (p *Policy) Effect() Effect
- func (p *Policy) MarshalCedar() []byte
- func (p *Policy) MarshalJSON() ([]byte, error)
- func (p *Policy) Position() Position
- func (p *Policy) SetFilename(fileName string)
- func (p *Policy) UnmarshalCedar(b []byte) error
- func (p *Policy) UnmarshalJSON(b []byte) error
- type PolicyID
- type PolicyIterator
- type PolicyList
- type PolicyMap
- type PolicySet
- func (p *PolicySet) Add(policyID PolicyID, policy *Policy) bool
- func (p *PolicySet) All() iter.Seq2[PolicyID, *Policy]
- func (p *PolicySet) Get(policyID PolicyID) *Policy
- func (p *PolicySet) IsAuthorized(entities types.EntityGetter, req Request) (Decision, Diagnostic)deprecated
- func (p *PolicySet) Map() PolicyMapdeprecated
- func (p *PolicySet) MarshalCedar() []byte
- func (p *PolicySet) MarshalJSON() ([]byte, error)
- func (p *PolicySet) Remove(policyID PolicyID) bool
- func (p *PolicySet) UnmarshalJSON(b []byte) error
- type Position
- type Record
- type RecordMap
- type Request
- type Set
- type String
- type Value
- type Wildcard
Examples ¶
Constants ¶
const ( Allow = types.Allow Deny = types.Deny )
Each authorization results in one of these Decisions.
const ( Permit = types.Permit Forbid = types.Forbid )
Each Policy has a Permit or Forbid effect that is determined during parsing.
const ( True = types.True False = types.False )
Variables ¶
This section is empty.
Functions ¶
func Authorize ¶ added in v1.2.0
func Authorize(policies PolicyIterator, entities types.EntityGetter, req Request) (Decision, Diagnostic)
Authorize uses the combination of the PolicySet and Entities to determine if the given Request to determine Decision and Diagnostic.
Types ¶
type AnnotationKey ¶ added in v1.9.4
type AnnotationKey = types.AnnotationKey
AnnotationKey is the key of a policy annotation, e.g. in `@id("p1")`, `id` is the key. Create an AnnotationKey with NewAnnotationKey. Converting an arbitrary string directly to an AnnotationKey is unsupported: the result may marshal to Cedar text that means something other than intended.
func NewAnnotationKey ¶ added in v1.9.4
func NewAnnotationKey(s string) (AnnotationKey, error)
NewAnnotationKey returns the AnnotationKey named by s, or an error if s isn't a single Cedar identifier. Unlike most identifiers in Cedar, annotation keys may be reserved keywords, such as `if` or `true`.
type Annotations ¶
type Annotations = types.Annotations
An Annotations is a map of key, value pairs found in the policy. Annotations have no impact on policy evaluation.
type Datetime ¶ added in v0.4.0
Datetime represents a Cedar datetime value
func NewDatetime ¶ added in v1.0.0
NewDatetime returns a Cedar Datetime from a Go time.Time value.
The provided time.Time is truncated to millisecond precision. The result is undefined if the Unix time in milliseconds cannot be represented by an int64 (a date more than 292 million years before or after 1970).
func NewDatetimeFromMillis ¶ added in v1.0.0
NewDatetimeFromMillis returns a Datetime from a count of milliseconds since January 1, 1970 @ 00:00:00 UTC.
func ParseDatetime ¶ added in v1.9.4
ParseDatetime returns a Cedar datetime when the argument provided represents a compatible datetime or an error
Cedar RFC 80 defines valid datetime strings as one of:
- "YYYY-MM-DD" (date only, with implied time 00:00:00, UTC) - "YYYY-MM-DDThh:mm:ssZ" (date and time, UTC) - "YYYY-MM-DDThh:mm:ss.SSSZ" (date and time with millisecond, UTC) - "YYYY-MM-DDThh:mm:ss(+/-)hhmm" (date and time, time zone offset) - "YYYY-MM-DDThh:mm:ss.SSS(+/-)hhmm" (date and time with millisecond, time zone offset)
Cedar RFC 110 extends this with ISO 8601 expanded year format:
- "(+/-)YYYYYYYYY-MM-DD" (9-digit year, date only) - "(+/-)YYYYYYYYY-MM-DDThh:mm:ssZ" (9-digit year, date and time, UTC) - "(+/-)YYYYYYYYY-MM-DDThh:mm:ss.SSSZ" (9-digit year with millisecond, UTC) - "(+/-)YYYYYYYYY-MM-DDThh:mm:ss(+/-)hhmm" (9-digit year with time zone offset) - "(+/-)YYYYYYYYY-MM-DDThh:mm:ss.SSS(+/-)hhmm" (9-digit year with millisecond and offset)
type Decimal ¶
A Decimal is a value with both a whole number part and a decimal part of no more than four digits. A decimal value can range from -922337203685477.5808 to 922337203685477.5807.
func NewDecimal ¶ added in v1.0.0
NewDecimal returns a Decimal value of i * 10^exponent.
func NewDecimalFromFloat ¶ added in v1.0.0
func NewDecimalFromFloat[T constraints.Float](f T) (Decimal, error)
NewDecimalFromFloat returns a Decimal that approximates the given floating point value. The value of the Decimal is calculated by multiplying it by 10^4, truncating it to an int64 representation to cut off any digits beyond the four allowed, and passing it as an integer to NewDecimal() with -4 as the exponent.
WARNING: decimal representations of more than 6 significant digits for float32s and 15 significant digits for float64s can be lossy in terms of precision. To create a precise Decimal above those sizes, use the NewDecimal constructor.
func NewDecimalFromInt ¶ added in v1.0.0
func NewDecimalFromInt[T constraints.Signed](i T) (Decimal, error)
NewDecimalFromInt returns a Decimal with the whole integer value provided
func ParseDecimal ¶
ParseDecimal takes a string representation of a decimal number and converts it into a Decimal type.
type Decoder ¶ added in v1.2.7
type Decoder struct {
// contains filtered or unexported fields
}
Decoder reads, parses and compiles Policy statements in the human-readable format specified by the Cedar documentation from an io.Reader.
func NewDecoder ¶ added in v1.2.7
NewDecoder returns a new Decoder.
type Diagnostic ¶
type Diagnostic = types.Diagnostic
A Diagnostic details the errors and reasons for an authorization decision.
The Cedar specification doesn't define a JSON encoding for Diagnostic. Its JSON struct tags are provided for convenience.
type DiagnosticError ¶ added in v0.3.1
type DiagnosticError = types.DiagnosticError
An DiagnosticError details the PolicyID within a PolicySet, the Position within the text document if applicable, and the resulting error message.
The Cedar specification doesn't define a JSON encoding for DiagnosticError. JSON struct tags are provided for convenience.
type DiagnosticReason ¶ added in v0.3.1
type DiagnosticReason = types.DiagnosticReason
A DiagnosticReason details the PolicyID within a PolicySet and the Position within the text document, if applicable.
The Cedar specification doesn't define a JSON encoding for DiagnosticReason. JSON struct tags are provided for convenience.
type Duration ¶ added in v0.4.0
A Duration is a value representing a span of time in milliseconds.
func NewDuration ¶ added in v1.0.0
NewDuration returns a Cedar Duration from a Go time.Duration
func NewDurationFromMillis ¶ added in v1.0.0
NewDurationFromMillis returns a Duration from milliseconds
func ParseDuration ¶ added in v1.9.4
ParseDuration parses a Cedar Duration from a string
Cedar RFC 80 defines a valid duration string as collapsed sequence of quantity-unit pairs, possibly with a leading `-`, indicating a negative duration. The units must appear in order from longest timeframe to smallest. - d: days - h: hours - m: minutes - s: seconds - ms: milliseconds
type Effect ¶
An Effect specifies the intent of the policy, to either permit or forbid any request that matches the scope and conditions specified in the policy.
type Encoder ¶ added in v1.2.7
type Encoder struct {
// contains filtered or unexported fields
}
Encoder encodes Policy statements in the human-readable format specified by the Cedar documentation and writes them to an io.Writer.
func NewEncoder ¶ added in v1.2.7
NewEncoder returns a new Encoder.
type EntityGetter ¶ added in v1.0.6
type EntityGetter = types.EntityGetter
An EntityGetter is an interface for retrieving an Entity by EntityUID.
type EntityMap ¶ added in v1.0.0
An EntityMap is a collection of all the entities that are needed to evaluate authorization requests. The key is an EntityUID which uniquely identifies the Entity (it must be the same as the UID within the Entity itself.)
type EntityType ¶ added in v0.4.0
type EntityType = types.EntityType
EntityType is the type portion of an EntityUID. Create an EntityType with NewEntityType, or by converting a Path created with NewPath. Converting an arbitrary string directly to an EntityType is unsupported and may result in unsafe marshaled Cedar text in policy.
func NewEntityType ¶ added in v1.9.4
func NewEntityType(s string) (EntityType, error)
NewEntityType returns the EntityType named by s, or an error if s isn't a valid Cedar path. See NewPath.
type EntityUID ¶
An EntityUID is the identifier for a principal, action, or resource.
func NewEntityUID ¶
func NewEntityUID(typ EntityType, id String) EntityUID
NewEntityUID returns an EntityUID given an EntityType and identifier.
type EntityUIDSet ¶ added in v1.0.0
type EntityUIDSet = types.EntityUIDSet
func NewEntityUIDSet ¶ added in v1.0.0
func NewEntityUIDSet(args ...EntityUID) EntityUIDSet
NewEntityUIDSet returns an immutable EntityUIDSet ready for use.
type IPAddr ¶
An IPAddr is value that represents an IP address. It can be either IPv4 or IPv6. The value can represent an individual address or a range of addresses. There's some special casing around 4in6 addresses which are formatted a bit differently.
func ParseIPAddr ¶
ParseIPAddr takes a string representation of an IP address and converts it into an IPAddr type.
type Long ¶
A Long is a whole number without decimals that can range from -9223372036854775808 to 9223372036854775807.
type Path ¶ added in v1.9.4
Path is a series of idents separated by ::. Create a Path with NewPath, which rejects strings that aren't valid Cedar paths. Converting an arbitrary string directly to a Path is unsupported and may result in unsafe marshaled Cedar text in policy.
type Pattern ¶ added in v0.4.0
Pattern is used to define a string used for the like operator. It does not conform to the Value interface, as it is not one of the Cedar types.
func NewPattern ¶ added in v0.4.0
NewPattern permits for the programmatic construction of a Pattern out of a slice of pattern components. The pattern components may be one of string, types.String, or types.Wildcard. Any other types will cause a panic.
type Policy ¶
type Policy struct {
// contains filtered or unexported fields
}
A Policy is the parsed form of a single Cedar language policy statement.
func NewPolicyFromAST ¶ added in v0.2.0
NewPolicyFromAST lets you create a new policy statement from a programmatically created AST. Do not modify the *ast.Policy after passing it into NewPolicyFromAST.
func (*Policy) AST ¶ added in v0.3.1
AST retrieves the AST of this policy. Do not modify the AST, as the compiled policy will no longer be in sync with the AST.
func (*Policy) Annotations ¶
func (p *Policy) Annotations() Annotations
Annotations retrieves the annotations associated with this policy.
func (*Policy) MarshalCedar ¶ added in v0.2.0
MarshalCedar encodes a single Policy statement in the human-readable format specified by the Cedar documentation.
func (*Policy) MarshalJSON ¶ added in v0.2.0
MarshalJSON encodes a single Policy statement in the JSON format specified by the Cedar documentation.
func (*Policy) SetFilename ¶ added in v0.2.0
SetFilename sets the filename of this policy.
func (*Policy) UnmarshalCedar ¶ added in v0.2.0
UnmarshalCedar parses and compiles a single Policy statement in the human-readable format specified by the Cedar documentation.
func (*Policy) UnmarshalJSON ¶ added in v0.2.0
UnmarshalJSON parses and compiles a single Policy statement in the JSON format specified by the Cedar documentation.
type PolicyIterator ¶ added in v1.2.1
type PolicyIterator interface {
// All returns an iterator over all the policies in the set
All() iter.Seq2[PolicyID, *Policy]
}
PolicyIterator is an interface which abstracts an iterable set of policies.
type PolicyList ¶ added in v0.2.0
type PolicyList []*Policy
PolicyList represents a list of un-named Policy's. Cedar documents, unlike the PolicySet form, don't have a means of naming individual policies.
func NewPolicyListFromBytes ¶ added in v0.2.0
func NewPolicyListFromBytes(fileName string, document []byte) (PolicyList, error)
NewPolicyListFromBytes will create a Policies from the given text document with the given file name used in Position data. If there is an error parsing the document, it will be returned.
func (PolicyList) MarshalCedar ¶ added in v0.2.0
func (p PolicyList) MarshalCedar() []byte
MarshalCedar emits a concatenated Cedar representation of the policies.
func (*PolicyList) UnmarshalCedar ¶ added in v0.2.0
func (p *PolicyList) UnmarshalCedar(b []byte) error
UnmarshalCedar parses a concatenation of un-named Cedar policy statements. Names can be assigned to these policies when adding them to a PolicySet.
type PolicySet ¶
type PolicySet struct {
// contains filtered or unexported fields
}
PolicySet is a set of named policies against which a request can be authorized.
func NewPolicySetFromBytes ¶ added in v0.2.0
NewPolicySetFromBytes will create a PolicySet from the given text document with the given file name used in Position data. If there is an error parsing the document, it will be returned.
NewPolicySetFromBytes assigns default PolicyIDs to the policies contained in fileName in the format "policy<n>" where <n> is incremented for each new policy found in the file.
func (*PolicySet) Add ¶ added in v1.0.0
Add inserts or updates a policy with the given ID. Returns true if a policy with the given ID did not already exist in the set.
func (*PolicySet) All ¶ added in v1.2.0
All returns an iterator over the (PolicyID, *Policy) tuples in the PolicySet
func (*PolicySet) Get ¶ added in v0.2.0
Get returns the Policy with the given ID. If a policy with the given ID does not exist, nil is returned.
func (*PolicySet) IsAuthorized
deprecated
func (p *PolicySet) IsAuthorized(entities types.EntityGetter, req Request) (Decision, Diagnostic)
IsAuthorized uses the combination of the PolicySet and Entities to determine if the given Request to determine Decision and Diagnostic.
Deprecated: Use the Authorize() function instead
func (*PolicySet) MarshalCedar ¶ added in v0.2.0
MarshalCedar emits a concatenated Cedar representation of a PolicySet. The policy names are stripped, but policies are emitted in lexicographical order by ID.
func (*PolicySet) MarshalJSON ¶ added in v0.2.0
MarshalJSON encodes a PolicySet in the JSON format specified by the Cedar documentation.
func (*PolicySet) Remove ¶ added in v1.0.0
Remove removes a policy from the PolicySet. Returns true if a policy with the given ID already existed in the set.
func (*PolicySet) UnmarshalJSON ¶ added in v0.2.0
UnmarshalJSON parses and compiles a PolicySet in the JSON format specified by the Cedar documentation.
type Position ¶
A Position describes an arbitrary source position including the file, line, and column location.
The Cedar specification doesn't define a JSON encoding for Position. JSON struct tags are provided for convenience.
type Record ¶
A Record is an immutable collection of attributes. Each attribute consists of a name and an associated value. Names are simple strings. Values can be of any type.
type Request ¶
A Request is the Principal, Action, Resource, and Context portion of an authorization request.
The Cedar specification doesn't define a JSON encoding for Request. JSON struct tags are provided for convenience.
type Value ¶
Value defines the interface for all Cedar values (String, Long, Set, Record, Boolean, etc ...)
Implementations of Value _must_ be able to be safely copied shallowly, which means they must either be immutable or be made up of data structures that are free of pointers (e.g. slices and maps).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package ast provides functions for programmatically constructing a Cedar policy AST.
|
Package ast provides functions for programmatically constructing a Cedar policy AST. |
|
cmd/reexport
command
Command reexport generates a file that re-exports the API of another package: an alias for each exported type, a constant for each exported constant, and a wrapper for each exported function, each with the original's doc comment.
|
Command reexport generates a file that re-exports the API of another package: an alias for each exported type, a constant for each exported constant, and a wrapper for each exported function, each with the original's doc comment. |
|
testvalidate
Package testvalidate provides shared validation test helpers used by both the top-level corpus tests and the x/exp/schema/validate corpus tests.
|
Package testvalidate provides shared validation test helpers used by both the top-level corpus tests and the x/exp/schema/validate corpus tests. |
|
Package types contains primitive, plain-old-data types including:
|
Package types contains primitive, plain-old-data types including: |
|
x
|
|
|
exp/ast
Package ast exposes the internal AST used within cedar-go.
|
Package ast exposes the internal AST used within cedar-go. |
|
exp/batch
Package batch allows for performant batch evaluations of Cedar policy given a set of principals, actions, resources, and/or context as variables.
|
Package batch allows for performant batch evaluations of Cedar policy given a set of principals, actions, resources, and/or context as variables. |
|
exp/eval
Package eval provides a simple interface for evaluating or partially evaluating a policy node in a given environment.
|
Package eval provides a simple interface for evaluating or partially evaluating a policy node in a given environment. |
|
exp/schema
Package schema provides schema parsing, serialization, and resolution.
|
Package schema provides schema parsing, serialization, and resolution. |
|
exp/schema/ast
Package ast provides types for constructing Cedar schema ASTs programmatically.
|
Package ast provides types for constructing Cedar schema ASTs programmatically. |
|
exp/schema/internal/json
Package json provides JSON marshaling and unmarshaling for Cedar schema ASTs.
|
Package json provides JSON marshaling and unmarshaling for Cedar schema ASTs. |
|
exp/schema/internal/parser
Package parser provides Cedar schema text parsing and formatting.
|
Package parser provides Cedar schema text parsing and formatting. |
|
exp/schema/resolved
Package resolved transforms an AST schema into a resolved schema where all type references are fully qualified and common types are inlined.
|
Package resolved transforms an AST schema into a resolved schema where all type references are fully qualified and common types are inlined. |