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
79
|
package policies
import (
"embed"
_ "embed"
"encoding/json"
"io/fs"
"log"
"github.com/cedar-policy/cedar-go"
"github.com/cedar-policy/cedar-go/types"
"github.com/xlgmokha/x/pkg/x"
xlog "gitlab.com/mokhax/spike/pkg/log"
)
//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 {
for err := range diagnostic.Errors {
xlog.Default.Printf("%v\n", err)
}
}
if len(diagnostic.Reasons) > 0 {
for reason := range diagnostic.Reasons {
xlog.Default.Printf("%v\n", reason)
}
}
return ok == types.Allow
}
|