summaryrefslogtreecommitdiff
path: root/pkg/policies
diff options
context:
space:
mode:
authormo khan <mo@mokhan.ca>2025-04-02 09:45:37 -0600
committermo khan <mo@mokhan.ca>2025-04-02 09:45:37 -0600
commitc75ceda92ce98c654747457c4fdfd32766487653 (patch)
tree7af774e87806f9522930a51d1d08ef67b9ece602 /pkg/policies
parentc851e7d0ff5cbc33dfec8df068529aeb2c70ebfc (diff)
feat: embed cedar policies in policies package
Diffstat (limited to 'pkg/policies')
-rw-r--r--pkg/policies/init.go72
-rw-r--r--pkg/policies/project.cedar5
2 files changed, 77 insertions, 0 deletions
diff --git a/pkg/policies/init.go b/pkg/policies/init.go
new file mode 100644
index 0000000..9916b11
--- /dev/null
+++ b/pkg/policies/init.go
@@ -0,0 +1,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
+}
diff --git a/pkg/policies/project.cedar b/pkg/policies/project.cedar
new file mode 100644
index 0000000..6ba3cbd
--- /dev/null
+++ b/pkg/policies/project.cedar
@@ -0,0 +1,5 @@
+permit (
+ principal == User::"alice",
+ action == Action::"view",
+ resource in Album::"jane_vacation"
+);