forked from cedar-policy/cedar-go
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathexample_test.go
More file actions
65 lines (56 loc) · 1.37 KB
/
example_test.go
File metadata and controls
65 lines (56 loc) · 1.37 KB
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
package cedar_test
import (
"encoding/json"
"fmt"
"github.com/cedar-policy/cedar-go"
)
const policyCedar = `permit (
principal == User::"alice",
action == Action::"view",
resource in Album::"jane_vacation"
);
`
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 Example() {
var policy cedar.Policy
if err := policy.UnmarshalCedar([]byte(policyCedar)); err != nil {
fmt.Println("policy unmarshal error:", err)
return
}
ps := cedar.NewPolicySet()
ps.Add("policy0", &policy)
var entities cedar.EntityMap
if err := json.Unmarshal([]byte(entitiesJSON), &entities); err != nil {
fmt.Println("entity unmarshal error:", err)
return
}
req := cedar.Request{
Principal: cedar.NewEntityUID("User", "alice"),
Action: cedar.NewEntityUID("Action", "view"),
Resource: cedar.NewEntityUID("Photo", "VacationPhoto94.jpg"),
Context: cedar.NewRecord(cedar.RecordMap{
"demoRequest": cedar.True,
}),
}
ok, diag := cedar.Authorize(ps, entities, req)
fmt.Println("Decision:", ok)
fmt.Println("Permitted by:")
for _, d := range diag.Reasons {
fmt.Println(" *", d.PolicyID)
}
// Output:
// Decision: allow
// Permitted by:
// * policy0
}