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
73
74
75
76
77
78
|
package policies
import (
"embed"
_ "embed"
"fmt"
"io/fs"
"os"
"strings"
"github.com/cedar-policy/cedar-go"
"github.com/cedar-policy/cedar-go/types"
"github.com/rs/zerolog"
"github.com/xlgmokha/x/pkg/log"
)
//go:embed *.cedar *.json
var files embed.FS
var All *cedar.PolicySet = cedar.NewPolicySet()
var Entities cedar.EntityMap = cedar.EntityMap{}
var Logger *zerolog.Logger = log.New(os.Stderr, log.Fields{"pkg": "policies"})
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
}
if strings.HasSuffix(path, ".cedar") {
content, err := fs.ReadFile(files, path)
if err != nil {
return err
}
policy := cedar.Policy{}
if err := policy.UnmarshalCedar(content); err != nil {
return err
}
policy.SetFilename(path)
All.Add(cedar.PolicyID(path), &policy)
} else if strings.HasSuffix(path, ".json") {
content, err := fs.ReadFile(files, path)
if err != nil {
return err
}
if err := Entities.UnmarshalJSON(content); err != nil {
return err
}
}
return nil
})
if err != nil {
Logger.Err(err)
}
}
func Allowed(request cedar.Request) bool {
ok, diagnostic := All.IsAuthorized(Entities, request)
fmt.Printf("%v: %v -> %v %v%v\n", ok, request.Principal, request.Action.ID, request.Context.Map(), request.Resource.ID)
if len(diagnostic.Errors) > 0 {
log.New(os.Stderr, log.Fields{"errors": diagnostic.Errors})
Logger.Error().Fields(log.Fields{"errors": diagnostic.Errors}.ToMap())
}
if len(diagnostic.Reasons) > 0 {
Logger.Warn().Fields(log.Fields{"reasons": diagnostic.Reasons}.ToMap())
}
return ok == types.Allow
}
|