summaryrefslogtreecommitdiff
path: root/pkg/authz/cedar.go
blob: 80bb2a3a96ea3d638a7a93cf28cb786ddfa82644 (plain)
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
package authz

import (
	"net"
	"net/http"

	cedar "github.com/cedar-policy/cedar-go"
	"gitlab.com/mokhax/spike/pkg/gid"
	xlog "gitlab.com/mokhax/spike/pkg/log"
	"gitlab.com/mokhax/spike/pkg/policies"
)

func WithCedar() Authorizer {
	return AuthorizerFunc(func(r *http.Request) bool {
		host, _, err := net.SplitHostPort(r.Host)
		if err != nil {
			xlog.WithFields(r, xlog.Fields{"error": err})
			return false
		}
		subject, found := TokenFrom(r).Subject()
		if !found {
			subject = "gid://User/*"
		}

		return policies.Allowed(cedar.Request{
			Principal: gid.NewEntityUID(subject),
			Action:    cedar.NewEntityUID("HttpMethod", cedar.String(r.Method)),
			Resource:  cedar.NewEntityUID("HttpPath", cedar.String(r.URL.Path)),
			Context: cedar.NewRecord(cedar.RecordMap{
				"host": cedar.String(host),
			}),
		})
	})
}