summaryrefslogtreecommitdiff
path: root/pkg/policies/init.go
blob: 9916b119940de613741736eda05d6ca626db1e22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package policies

import (
	"embed"
	_ "embed"
	"encoding/json"
	"fmt"
	"io/fs"
	"log"

	"github.com/cedar-policy/cedar-go"
	"github.com/cedar-policy/cedar-go/types"
	"github.com/xlgmokha/x/pkg/x"
)

//go:embed *.cedar
var files embed.FS

var All *cedar.PolicySet = cedar.NewPolicySet()

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 init() {
	err := fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}

		if d.IsDir() {
			return nil
		}

		content, err := fs.ReadFile(files, path)
		if err != nil {
			return err
		}

		var policy cedar.Policy
		if err := policy.UnmarshalCedar(content); err != nil {
			return err
		}

		All.Add(cedar.PolicyID(path), &policy)
		return nil
	})

	if err != nil {
		log.Fatal(err)
	}
}

func Allowed(request cedar.Request) bool {
	var entities cedar.EntityMap
	x.Check(json.Unmarshal([]byte(entitiesJSON), &entities))

	ok, diagnostic := All.IsAuthorized(entities, request)
	if len(diagnostic.Errors) > 0 || len(diagnostic.Reasons) > 0 {
		fmt.Printf("%v %v\n", diagnostic.Errors, diagnostic.Reasons)
	}
	return ok == types.Allow
}