diff options
Diffstat (limited to 'pkg/app')
| -rw-r--r-- | pkg/app/app.go | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/pkg/app/app.go b/pkg/app/app.go index fd6a3f1..6e50dad 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -1,11 +1,16 @@ package app import ( + "encoding/json" "fmt" + "log" "net" "net/http" + "os" "github.com/casbin/casbin/v3" + cedar "github.com/cedar-policy/cedar-go" + "github.com/cedar-policy/cedar-go/types" "github.com/xlgmokha/x/pkg/x" "gitlab.com/mokhax/spike/pkg/authz" "gitlab.com/mokhax/spike/pkg/cfg" @@ -36,9 +41,47 @@ func WithCasbin() authz.Authorizer { }) } +func WithCedar() authz.Authorizer { + var policy cedar.Policy + x.Check(policy.UnmarshalCedar(x.Must(os.ReadFile("cedar.conf")))) + + policies := cedar.NewPolicySet() + policies.Add("cedar.conf", &policy) + + var entities cedar.EntityMap + if err := json.Unmarshal(x.Must(os.ReadFile("cedar.json")), &entities); err != nil { + log.Fatal(err) + } + return authz.AuthorizerFunc(func(r *http.Request) bool { + host, _, err := net.SplitHostPort(r.Host) + if err != nil { + return false + } + + subject, found := authz.TokenFrom(r).Subject() + if !found { + subject = "*" + } + + req := cedar.Request{ + Principal: cedar.NewEntityUID("Subject", cedar.String(subject)), + Action: cedar.NewEntityUID("Action", cedar.String(r.Method)), + Resource: cedar.NewEntityUID("Path", cedar.String(r.URL.Path)), + Context: cedar.NewRecord(cedar.RecordMap{ + "Host": cedar.String(host), + }), + } + + ok, diagnostic := policies.IsAuthorized(entities, req) + fmt.Printf("%v: %v -> %v %v%v %v\n", ok, subject, r.Method, host, r.URL.Path, diagnostic.Reasons) + return ok == types.Allow + }) +} + func Start(bindAddr string) error { return srv.Run(cfg.New( bindAddr, + // cfg.WithMux(authz.HTTP(WithCedar(), Routes())), cfg.WithMux(authz.HTTP(WithCasbin(), Routes())), )) } |
