main
1package policies
2
3import (
4 "embed"
5 _ "embed"
6 "fmt"
7 "io/fs"
8 "os"
9 "strings"
10
11 "github.com/cedar-policy/cedar-go"
12 "github.com/cedar-policy/cedar-go/types"
13 "github.com/rs/zerolog"
14 "github.com/xlgmokha/x/pkg/log"
15)
16
17//go:embed *.cedar *.json
18var files embed.FS
19
20var All *cedar.PolicySet = cedar.NewPolicySet()
21var Entities cedar.EntityMap = cedar.EntityMap{}
22var Logger *zerolog.Logger = log.New(os.Stderr, log.Fields{"pkg": "policies"})
23
24func init() {
25 err := fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error {
26 if err != nil {
27 return err
28 }
29
30 if d.IsDir() {
31 return nil
32 }
33
34 if strings.HasSuffix(path, ".cedar") {
35 content, err := fs.ReadFile(files, path)
36 if err != nil {
37 return err
38 }
39
40 policy := cedar.Policy{}
41 if err := policy.UnmarshalCedar(content); err != nil {
42 return err
43 }
44 policy.SetFilename(path)
45
46 All.Add(cedar.PolicyID(path), &policy)
47 } else if strings.HasSuffix(path, ".json") {
48 content, err := fs.ReadFile(files, path)
49 if err != nil {
50 return err
51 }
52
53 if err := Entities.UnmarshalJSON(content); err != nil {
54 return err
55 }
56 }
57
58 return nil
59 })
60
61 if err != nil {
62 Logger.Err(err)
63 }
64}
65
66func Allowed(request cedar.Request) bool {
67 ok, diagnostic := All.IsAuthorized(Entities, request)
68 fmt.Printf("%v: %v -> %v %v%v\n", ok, request.Principal, request.Action.ID, request.Context.Map(), request.Resource.ID)
69
70 if len(diagnostic.Errors) > 0 {
71 log.New(os.Stderr, log.Fields{"errors": diagnostic.Errors})
72 Logger.Error().Fields(log.Fields{"errors": diagnostic.Errors}.ToMap())
73 }
74 if len(diagnostic.Reasons) > 0 {
75 Logger.Warn().Fields(log.Fields{"reasons": diagnostic.Reasons}.ToMap())
76 }
77 return ok == types.Allow
78}