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
|
package authz
import (
"encoding/json"
"fmt"
"net"
"net/http"
"os"
cedar "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"
)
func WithCedar() 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 {
xlog.Logger.Error("Error", "error", err)
return nil
}
return AuthorizerFunc(func(r *http.Request) bool {
host, _, err := net.SplitHostPort(r.Host)
if err != nil {
return false
}
subject, found := 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
})
}
|