polai

package module
v0.0.0-...-d97edb6 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2023 License: MIT Imports: 12 Imported by: 0

README

polai

Warning This project is experimental and is not recommended for use

Foreword

This project was an experimental project to understand the complexity of the Cedar policy language. The project is incomplete and doesn't feature the automated reasoning guarantees that the official engine has. For use in a production context, consume the official engine directly or via one of the bindings.


GoDoc

A Cedar policy language lexer, parser & evaluator.

Installation

go get github.com/iann0036/polai

Please add -u flag to update in the future.

Usage

Basic Usage
package main

import (
    "fmt"
    "strings"

    "github.com/iann0036/polai"
)

func main() {
    e := polai.NewEvaluator(strings.NewReader(`
    permit (
        principal,
        action,
        resource == Folder::"My Folder"
    ) when {
        context.ssl == true
    };`))

    result, _ := e.Evaluate(`User::"alice"`, `Action::"listFiles"`, `Folder::"My Folder"`, `{
        "ssl": true
    }`)

    if result {
        fmt.Println("Authorized")
    } else {
        fmt.Println("Not Authorized")
    }
}
Advanced Options
package main

import (
    "fmt"
    "strings"

    "github.com/iann0036/polai"
)

func main() {
    e := polai.NewEvaluator(strings.NewReader(`
    permit (
        principal,
        action,
        resource == Folder::"My Folder"
    ) when {
        if context.ssl == true && principal.hasTraining
        then true
        else principal.invalidproperty
    };`))

    e.AllowShortCircuiting = true // evaluation will fail when set to false

    e.SetEntities(strings.NewReader(`
    [
        {
            "uid": "User::\"alice\"",
            "attrs": {
                "hasTraining": true
            }
        },
        {
            "uid": "User::\"kate\"",
            "attrs": {
                "hasTraining": false
            }
        }
    ]`))

    result, _ := e.Evaluate(`User::"alice"`, `Action::"listFiles"`, `Folder::"My Folder"`, `{
        "ssl": true
    }`)

    if result {
        fmt.Println("Authorized")
    } else {
        fmt.Println("Not Authorized")
    }
}

Features

  • Policy language interpreter
  • Basic permit and forbid evaluation logic
  • Equality / inequality operator within principal, action, and resource within the scope block
  • Inheritance (in) within scope block
  • Basic set (in) for action within scope block
  • Basic when and unless evaluation logic
  • Logical operators for basic types (string, long, boolean) within condition block
  • Entity store interpreter
  • Inheritance (in) within condition block
  • Entity attributes evaluation
  • IP and Decimal extensions
  • Context object
  • Set operations
  • has operation
  • Logical not ! operation
  • like operator
  • if-then-else ternary
  • Enforce Action:: namespace for actions
  • && and || short-circuiting
  • if-then-else short-circuiting
  • Embedded if-then-else
  • 4x limit on unary
  • Syntactic constraint on multiply operator
  • Anonymous records / sets
  • __entity / __extn syntax in context / entities
  • Policy templates

License

This project is under MIT license. See the LICENSE file for the full license text.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var LEFT_ASSOCIATIVE = map[Token]bool{
	OR:          true,
	LT:          true,
	LTE:         true,
	GT:          true,
	GTE:         true,
	IN:          true,
	LIKE:        true,
	DASH:        true,
	EXCLAMATION: true,
	PERIOD:      true,
	FUNCTION:    true,
	RIGHT_SQB:   true,
	RIGHT_BRACE: true,
}
View Source
var OP_PRECEDENCE = map[Token]int{
	AND:         2,
	OR:          2,
	EQUALITY:    3,
	INEQUALITY:  3,
	LT:          3,
	LTE:         3,
	GT:          3,
	GTE:         3,
	IN:          3,
	LIKE:        3,
	PLUS:        4,
	DASH:        4,
	MULTIPLIER:  5,
	EXCLAMATION: 5,
	PERIOD:      6,
	FUNCTION:    7,
	RIGHT_SQB:   7,
	RIGHT_BRACE: 7,
}

Functions

This section is empty.

Types

type Attribute

type Attribute struct {
	Name         string
	StringValue  *string
	LongValue    *int64
	BooleanValue *bool
	RecordValue  *map[string]interface{}
	SetValue     *[]interface{}
}

type ConditionClause

type ConditionClause struct {
	Type     Token
	Sequence []SequenceItem
}

func (*ConditionClause) ToString

func (cc *ConditionClause) ToString() string

type Entity

type Entity struct {
	Identifier string
	Parents    []string
	Attributes []Attribute
}

type EntityStore

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

EntityStore represents the complete set of known entities within the system.

func NewEntityStore

func NewEntityStore(r io.Reader) *EntityStore

NewEntityStore returns a new instance of EntityStore.

func (*EntityStore) GetEntities

func (e *EntityStore) GetEntities() ([]Entity, error)

GetEntities retrieves all entities.

func (*EntityStore) GetEntityDescendents

func (e *EntityStore) GetEntityDescendents(parents []string) ([]Entity, error)

GetEntityDescendents retrieves all entities that match or are descendents of those passed in.

func (*EntityStore) SetEntities

func (e *EntityStore) SetEntities(r io.Reader)

SetEntities overrides all entities.

type Evaluator

type Evaluator struct {
	AllowShortCircuiting bool
	// contains filtered or unexported fields
}

Evaluator represents an evaluator.

func NewEvaluator

func NewEvaluator(policyReader io.Reader) *Evaluator

NewEvaluator returns a new instance of Evaluator.

func (*Evaluator) Evaluate

func (e *Evaluator) Evaluate(principal, action, resource, context string) (bool, error)

func (*Evaluator) SetEntities

func (e *Evaluator) SetEntities(entityReader io.Reader)

type Parser

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

Parser represents a parser.

func NewParser

func NewParser(r io.Reader) *Parser

NewParser returns a new instance of Parser.

func (*Parser) Parse

func (p *Parser) Parse() (*[]PolicyStatement, error)

Parse parses a policy.

type PolicyStatement

type PolicyStatement struct {
	Effect          Token
	AnyPrincipal    bool
	Principal       string
	PrincipalParent string
	AnyAction       bool
	Action          string
	ActionParents   []string
	AnyResource     bool
	Resource        string
	ResourceParent  string
	Conditions      []ConditionClause
}

PolicyStatement represents a set of Cedar policy statements

type Scanner

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

Scanner represents a lexical scanner.

func NewScanner

func NewScanner(r io.Reader) *Scanner

NewScanner returns a new instance of Scanner.

func (*Scanner) Scan

func (s *Scanner) Scan() (tok Token, lit string)

Scan returns the next token and literal value.

type SequenceItem

type SequenceItem struct {
	Token      Token
	Literal    string
	Normalized string

	RecordKeyValuePairs map[string]SequenceItem
}

type Token

type Token int

Token represents a lexical token.

const (
	ILLEGAL Token = iota
	EOF
	WHITESPC
	ERROR

	IDENT       // unknown identifier
	LONG        // 123 | -123
	DBLQUOTESTR // "...abc..."
	COMMENT     // // ...abc...

	ENTITY    // Namespace::"ID"
	ATTRIBUTE // entity.attribute
	RECORDKEY // {x: ...}
	SET       // [...]
	FUNCTION  // xyz()
	RECORD    // {...}

	ELSE_TRUE
	ELSE_FALSE
	THEN_TRUE_ELSE_TRUE
	THEN_TRUE_ELSE_FALSE
	THEN_FALSE_ELSE_TRUE
	THEN_FALSE_ELSE_FALSE
	THEN_TRUE_ELSE_ERROR
	THEN_FALSE_ELSE_ERROR
	THEN_ERROR_ELSE_TRUE
	THEN_ERROR_ELSE_FALSE

	IP
	DECIMAL

	LEFT_PAREN  // (
	RIGHT_PAREN // )
	LEFT_SQB    // [
	RIGHT_SQB   // ]
	LEFT_BRACE  // {
	RIGHT_BRACE // }
	PERIOD      // .
	COMMA       // ,
	SEMICOLON   // ;
	EXCLAMATION // !
	LT          // <
	GT          // >
	DASH        // -
	PLUS        // +
	MULTIPLIER  // *
	COLON       // :

	NAMESPACE  // ::
	EQUALITY   // ==
	INEQUALITY // !=
	LTE        // <=
	GTE        // >=
	AND        // &&
	OR         // ||

	PERMIT
	FORBID
	WHEN
	UNLESS
	TRUE
	FALSE
	IF
	THEN
	ELSE
	IN
	LIKE
	HAS
	PRINCIPAL
	ACTION
	RESOURCE
	CONTEXT
)

Jump to

Keyboard shortcuts

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