ast

package
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package ast provides functions for programmatically constructing a Cedar policy AST.

Programmatically generated policies are germinated by calling one of the following top-level functions:

Example

This example shows a basic programmatic AST construction via the Permit() builder:

package main

import (
	"fmt"

	"github.com/cedar-policy/cedar-go/ast"
	"github.com/cedar-policy/cedar-go/types"
)

func main() {
	johnny := types.NewEntityUID("FolkHeroes", "johnnyChapman")
	sow := types.NewEntityUID("Action", "sow")
	cast := types.NewEntityUID("Action", "cast")
	midwest := types.NewEntityUID("Locations::USA::Regions", "midwest")

	policy := ast.Permit().
		PrincipalEq(johnny).
		ActionInSet(sow, cast).
		ResourceIs("Crops::Apple").
		When(ast.Context().Access("location").In(ast.Value(midwest))).
		Unless(ast.Context().Access("season").Equal(ast.String("winter")))

	fmt.Println(string(policy.MarshalCedar()))

}
Output:

permit (
    principal == FolkHeroes::"johnnyChapman",
    action in [Action::"sow", Action::"cast"],
    resource is Crops::Apple
)
when { context.location in Locations::USA::Regions::"midwest" }
unless { context.season == "winter" };
Example (Annotation)

To programmatically create policies with annotations, use the Annotation() builder:

package main

import (
	"fmt"

	"github.com/cedar-policy/cedar-go/ast"
)

func main() {
	policy := ast.Annotation("example1", "value").
		Annotation("example2", "").
		Forbid()

	fmt.Println(string(policy.MarshalCedar()))

}
Output:

@example1("value")
@example2("")
forbid ( principal, action, resource );
Example (ExplicitExtensionCall)

Extension functions can be explicitly called by using the appropriate builder with the ExtensionCall suffix. This example demonstrates the use of DecimalExtensionCall():

package main

import (
	"fmt"

	"github.com/cedar-policy/cedar-go/ast"
)

func main() {
	policy := ast.Forbid().
		When(
			ast.Resource().Access("angleRadians").DecimalGreaterThan(
				ast.DecimalExtensionCall(ast.String("3.1415")),
			),
		)

	fmt.Println(string(policy.MarshalCedar()))

}
Output:

forbid ( principal, action, resource )
when { resource.angleRadians.greaterThan(decimal("3.1415")) };
Example (Precedence)

This example shows how precedence can be expressed using the AST builder syntax:

package main

import (
	"fmt"

	"github.com/cedar-policy/cedar-go/ast"
)

func main() {
	// The argument passed to .Add() is the entire right-hand side of the expression, so 1 + 5 is evaluated with
	// higher precedence than the subsequent multiplication by 10.
	policy := ast.Permit().
		When(ast.Long(1).Add(ast.Long(5)).Multiply(ast.Long(10)).Equal(ast.Long(60)))

	fmt.Println(string(policy.MarshalCedar()))

}
Output:

permit ( principal, action, resource )
when { (1 + 5) * 10 == 60 };

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Annotations

type Annotations ast.Annotations

Annotations allows access to Cedar annotations on a policy

func Annotation

func Annotation(key types.Ident, value types.String) *Annotations

Annotation allows AST constructors to make policy in a similar shape to textual Cedar with annotations appearing before the actual policy scope:

ast := Annotation("foo", "bar").
    Annotation("baz", "quux").
	Permit().
	PrincipalEq(superUser)

func (*Annotations) Annotation

func (a *Annotations) Annotation(key types.Ident, value types.String) *Annotations

Annotation adds an annotation. If a previous annotation exists with the same key, this builder will replace it.

func (*Annotations) Forbid

func (a *Annotations) Forbid() *Policy

Forbid begins a forbid policy from the given annotations.

func (*Annotations) Permit

func (a *Annotations) Permit() *Policy

Permit begins a permit policy from the given annotations.

type Node

type Node struct {
	ast.Node
}

Node is a wrapper type for all the Cedar language operators. See the Cedar operators documentation for details.

func Action

func Action() Node

Action represents the action in the request

func Boolean

func Boolean[T ~bool](b T) Node

Boolean creates a value node containing a Boolean.

func Context

func Context() Node

Context represents the context in the request

func Datetime added in v1.0.0

func Datetime(t time.Time) Node

Datetime creates a value node containing a timestamp

func DatetimeExtensionCall added in v1.0.0

func DatetimeExtensionCall(rhs Node) Node

DatetimeExtensionCall wraps a node with the cedar `datetime()` extension call

func DecimalExtensionCall added in v1.0.0

func DecimalExtensionCall(rhs Node) Node

DecimalExtensionCall wraps a node with the cedar `decimal()` extension call

func Duration added in v1.0.0

func Duration(d time.Duration) Node

Duration creates a value node containing a duration

func DurationExtensionCall added in v1.0.0

func DurationExtensionCall(rhs Node) Node

DurationExtensionCall wraps a node with the cedar `duration()` extension call

func EntityUID

func EntityUID(typ types.Ident, id types.String) Node

EntityUID creates a value node containing an EntityUID.

func False

func False() Node

False creates a value node containing False.

func IPAddr

func IPAddr[T netip.Prefix | types.IPAddr](i T) Node

IPAddr creates a value node containing an IPAddr.

func IPExtensionCall added in v1.0.0

func IPExtensionCall(rhs Node) Node

IPExtensionCall wraps a node with the cedar `ip()` extension call

func IfThenElse

func IfThenElse(condition Node, thenNode Node, elseNode Node) Node

IfThenElse builds an AST node representing the if (CONDITIONAL) operator

func Long

func Long[T ~int | ~int64](l T) Node

Long creates a value node containing a Long.

func Negate

func Negate(rhs Node) Node

Negate builds an AST node representing the ! operator

func Not

func Not(rhs Node) Node

Not builds an AST node representing the ! operator

func Principal

func Principal() Node

Principal represents the principal in the request

func Record

func Record(elements Pairs) Node

Record creates a record node. In the case where duplicate keys exist, the latter value will be preserved.

Example
package main

import (
	"fmt"

	"github.com/cedar-policy/cedar-go/ast"
	"github.com/cedar-policy/cedar-go/types"
)

func main() {
	// Literal records can be constructed and passed via the ast.Value() builder
	literalRecord := types.NewRecord(types.RecordMap{
		"x": types.String("value1"),
		"y": types.String("value2"),
	})

	// Records with internal expressions are constructed via the ast.Record() builder
	exprRecord := ast.Record(ast.Pairs{
		{
			Key:   "x",
			Value: ast.Long(1).Add(ast.Context().Access("fooCount")),
		},
		{
			Key:   "y",
			Value: ast.Long(8),
		},
	})

	policy := ast.Forbid().
		When(
			ast.Value(literalRecord).Access("x").Equal(ast.String("value1")),
		).
		When(
			exprRecord.Access("x").Equal(ast.Long(3)),
		)

	fmt.Println(string(policy.MarshalCedar()))

}
Output:

forbid ( principal, action, resource )
when { {"x":"value1", "y":"value2"}.x == "value1" }
when { {"x":(1 + context.fooCount), "y":8}.x == 3 };

func Resource

func Resource() Node

Resource represents the resource in the request

func Set

func Set(nodes ...Node) Node

Set allows for a complex set definition with values potentially being Cedar expressions of their own. For example, this Cedar text:

[1, 2 + 3, context.fooCount]

could be expressed in Golang as:

ast.Set(
    ast.Long(1),
    ast.Long(2).Plus(ast.Long(3)),
    ast.Context().Access("fooCount"),
)

func String

func String[T ~string](s T) Node

String creates a value node containing a String.

func True

func True() Node

True creates a value node containing True.

func Value

func Value(v types.Value) Node

Value creates a value node from any value.

func (Node) Access

func (lhs Node) Access(attr types.String) Node

Access builds an AST node representing the . and [] operators to access entity attributes

func (Node) Add

func (lhs Node) Add(rhs Node) Node

Add builds an AST node representing the + operator

func (Node) And

func (lhs Node) And(rhs Node) Node

And builds an AST node representing the && operator

func (Node) Contains

func (lhs Node) Contains(rhs Node) Node

Contains builds an AST node representing the .contains() operator

func (Node) ContainsAll

func (lhs Node) ContainsAll(rhs Node) Node

ContainsAll builds an AST node representing the .containsAll() operator

func (Node) ContainsAny

func (lhs Node) ContainsAny(rhs Node) Node

ContainsAny builds an AST node representing the .containsAny() operator

func (Node) DecimalGreaterThan

func (lhs Node) DecimalGreaterThan(rhs Node) Node

DecimalGreaterThan builds an AST node representing the .greaterThan() operator

func (Node) DecimalGreaterThanOrEqual

func (lhs Node) DecimalGreaterThanOrEqual(rhs Node) Node

DecimalGreaterThanOrEqual builds an AST node representing the .greaterThanOrEqual() operator

func (Node) DecimalLessThan

func (lhs Node) DecimalLessThan(rhs Node) Node

DecimalLessThan builds an AST node representing the .lessThan() operator

func (Node) DecimalLessThanOrEqual

func (lhs Node) DecimalLessThanOrEqual(rhs Node) Node

DecimalLessThanOrEqual builds an AST node representing the .lessThanOrEqual() operator

func (Node) DurationSince added in v1.0.0

func (lhs Node) DurationSince(rhs Node) Node

DurationSince builds an AST node representing the .durationSince() operator

func (Node) Equal

func (lhs Node) Equal(rhs Node) Node

Equal builds an AST node representing the = operator

func (Node) GetTag added in v1.1.0

func (lhs Node) GetTag(rhs Node) Node

GetTag builds an AST node representing the .getTag() operator

func (Node) GreaterThan

func (lhs Node) GreaterThan(rhs Node) Node

GreaterThan builds an AST node representing the > operator

func (Node) GreaterThanOrEqual

func (lhs Node) GreaterThanOrEqual(rhs Node) Node

GreaterThanOrEqual builds an AST node representing the >= operator

func (Node) Has

func (lhs Node) Has(attr types.String) Node

Has builds an AST node representing the has operator

func (Node) HasTag added in v1.1.0

func (lhs Node) HasTag(rhs Node) Node

HasTag builds an AST node representing the .hasTag() operator

func (Node) In

func (lhs Node) In(rhs Node) Node

In builds an AST node representing the in operator

func (Node) Is

func (lhs Node) Is(entityType types.EntityType) Node

Is builds an AST node representing the is operator

func (Node) IsEmpty added in v1.2.0

func (lhs Node) IsEmpty() Node

IsEmpty builds an AST node representing the .isEmpty() operator

func (Node) IsIn

func (lhs Node) IsIn(entityType types.EntityType, rhs Node) Node

IsIn builds an AST node representing the "is in" operator

func (Node) IsInRange

func (lhs Node) IsInRange(rhs Node) Node

IsInRange builds an AST node representing the .isInRange() operator

func (Node) IsIpv4

func (lhs Node) IsIpv4() Node

IsIpv4 builds an AST node representing the .isIpv4() operator

func (Node) IsIpv6

func (lhs Node) IsIpv6() Node

IsIpv6 builds an AST node representing the .isIpv6() operator

func (Node) IsLoopback

func (lhs Node) IsLoopback() Node

IsLoopback builds an AST node representing the .isLoopback() operator

func (Node) IsMulticast

func (lhs Node) IsMulticast() Node

IsMulticast builds an AST node representing the .isMulticast() operator

func (Node) LessThan

func (lhs Node) LessThan(rhs Node) Node

LessThan builds an AST node representing the < operator

func (Node) LessThanOrEqual

func (lhs Node) LessThanOrEqual(rhs Node) Node

LessThanOrEqual builds an AST node representing the <= operator

func (Node) Like

func (lhs Node) Like(pattern types.Pattern) Node

Like builds an AST node representing the like operator

func (Node) Multiply

func (lhs Node) Multiply(rhs Node) Node

Multiply builds an AST node representing the * operator

func (Node) NotEqual

func (lhs Node) NotEqual(rhs Node) Node

NotEqual builds an AST node representing the != operator

func (Node) Offset added in v1.0.0

func (lhs Node) Offset(rhs Node) Node

Offset builds an AST node representing the .offset() operator

func (Node) Or

func (lhs Node) Or(rhs Node) Node

Or builds an AST node representing the || operator

func (Node) Subtract

func (lhs Node) Subtract(rhs Node) Node

Subtract builds an AST node representing the - operator

func (Node) ToDate added in v1.0.0

func (lhs Node) ToDate() Node

ToDate builds an AST node representing the .toDate() operator

func (Node) ToDays added in v1.0.0

func (lhs Node) ToDays() Node

ToDays builds an AST node representing the .toDays() operator

func (Node) ToHours added in v1.0.0

func (lhs Node) ToHours() Node

ToHours builds an AST node representing the .toHours() operator

func (Node) ToMilliseconds added in v1.0.0

func (lhs Node) ToMilliseconds() Node

ToMilliseconds builds an AST node representing the .toMilliseconds() operator

func (Node) ToMinutes added in v1.0.0

func (lhs Node) ToMinutes() Node

ToMinutes builds an AST node representing the .toMinutes() operator

func (Node) ToSeconds added in v1.0.0

func (lhs Node) ToSeconds() Node

ToSeconds builds an AST node representing the .toSeconds() operator

func (Node) ToTime added in v1.0.0

func (lhs Node) ToTime() Node

ToTime builds an AST node representing the .toTime() operator

type Pair

type Pair struct {
	Key   types.String
	Value Node
}

Pair is map of Key string to Value node.

type Pairs

type Pairs []Pair

Pairs is a slice of Pair elements

type Policy

type Policy ast.Policy

Policy represents a single Cedar policy statement

func Forbid

func Forbid() *Policy

Forbid creates a new Forbid policy.

func Permit

func Permit() *Policy

Permit creates a new Permit policy.

func (*Policy) ActionEq

func (p *Policy) ActionEq(entity types.EntityUID) *Policy

ActionEq replaces the action scope condition.

func (*Policy) ActionIn

func (p *Policy) ActionIn(entity types.EntityUID) *Policy

ActionIn replaces the action scope condition.

func (*Policy) ActionInSet

func (p *Policy) ActionInSet(entities ...types.EntityUID) *Policy

ActionInSet replaces the action scope condition.

func (*Policy) Annotate

func (p *Policy) Annotate(key types.Ident, value types.String) *Policy

Annotate adds an annotation to a Policy. If a previous annotation exists with the same key, this builder will replace it.

func (*Policy) MarshalCedar added in v1.0.0

func (p *Policy) MarshalCedar() []byte

MarshalCedar encodes a single Policy statement in the human-readable format specified by the Cedar documentation.

func (*Policy) MarshalJSON added in v1.0.0

func (p *Policy) MarshalJSON() ([]byte, error)

MarshalJSON encodes a single Policy statement in the JSON format specified by the Cedar documentation.

func (*Policy) PrincipalEq

func (p *Policy) PrincipalEq(entity types.EntityUID) *Policy

PrincipalEq replaces the principal scope condition.

func (*Policy) PrincipalIn

func (p *Policy) PrincipalIn(entity types.EntityUID) *Policy

PrincipalIn replaces the principal scope condition.

func (*Policy) PrincipalIs

func (p *Policy) PrincipalIs(entityType types.EntityType) *Policy

PrincipalIs replaces the principal scope condition.

func (*Policy) PrincipalIsIn

func (p *Policy) PrincipalIsIn(entityType types.EntityType, entity types.EntityUID) *Policy

PrincipalIsIn replaces the principal scope condition.

func (*Policy) ResourceEq

func (p *Policy) ResourceEq(entity types.EntityUID) *Policy

ResourceEq replaces the resource scope condition.

func (*Policy) ResourceIn

func (p *Policy) ResourceIn(entity types.EntityUID) *Policy

ResourceIn replaces the resource scope condition.

func (*Policy) ResourceIs

func (p *Policy) ResourceIs(entityType types.EntityType) *Policy

ResourceIs replaces the resource scope condition.

func (*Policy) ResourceIsIn

func (p *Policy) ResourceIsIn(entityType types.EntityType, entity types.EntityUID) *Policy

ResourceIsIn replaces the resource scope condition.

func (*Policy) Unless

func (p *Policy) Unless(node Node) *Policy

Unless adds a conditional clause.

func (*Policy) UnmarshalCedar added in v1.0.0

func (p *Policy) UnmarshalCedar(b []byte) error

UnmarshalCedar parses and compiles a single Policy statement in the human-readable format specified by the Cedar documentation.

func (*Policy) UnmarshalJSON added in v1.0.0

func (p *Policy) UnmarshalJSON(b []byte) error

UnmarshalJSON parses and compiles a single Policy statement in the JSON format specified by the Cedar documentation.

func (*Policy) When

func (p *Policy) When(node Node) *Policy

When adds a conditional clause.

Jump to

Keyboard shortcuts

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