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
80
81
82
83
84
85
86
87
|
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"
"gitlab.com/mokhax/spike/pkg/srv"
)
func WithCasbin() authz.Authorizer {
enforcer := x.Must(casbin.NewEnforcer("casbin.conf", "casbin.csv"))
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 = "*"
}
ok, err := enforcer.Enforce(subject, host, r.Method, r.URL.Path)
if err != nil {
fmt.Printf("%v\n", err)
return false
}
fmt.Printf("%v: %v -> %v %v%v\n", ok, subject, r.Method, host, r.URL.Path)
return ok
})
}
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())),
))
}
|