/
middleware.go
107 lines (92 loc) · 2.52 KB
/
middleware.go
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package dataplane
import (
"context"
"fmt"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/open-privacy/opv/pkg/apimodel"
"github.com/open-privacy/opv/pkg/repo"
)
const (
headerOPVGrantToken = "x-opv-grant-token"
contextAuthzSub = "authz.sub"
contextAuthzAct = "authz.act"
contextAuthzObj = "authz.obj"
contextAuthzDom = "authz.dom"
)
func (dp *DataPlane) middlewareGrantValidation() echo.MiddlewareFunc {
return middleware.KeyAuthWithConfig(middleware.KeyAuthConfig{
KeyLookup: fmt.Sprintf("header:%s", headerOPVGrantToken),
Validator: func(key string, c echo.Context) (bool, error) {
token := &apimodel.GrantToken{}
if err := token.ParseFromString(key); err != nil {
return false, err
}
sub := token.Hash(dp.Hasher)
act := c.Request().Method
obj := c.Request().URL.Path // obj will be like "/api/v1/facts/fact_somerandomid"
dom := token.Domain
c.Set(contextAuthzSub, sub)
c.Set(contextAuthzAct, act)
c.Set(contextAuthzObj, obj)
c.Set(contextAuthzDom, dom)
return dp.Enforcer.Enforce(repo.AuthzRequest{
Subject: sub,
Action: act,
Object: obj,
Domain: dom,
})
},
})
}
func currentDomain(c echo.Context) string {
return c.Get(contextAuthzDom).(string)
}
type auditLogContext struct {
echo.Context
}
func (a *auditLogContext) getContextStringPtr(name string) *string {
val := a.Get(name)
if val == nil {
return nil
}
s, ok := val.(string)
if !ok {
return nil
}
return &s
}
func (a *auditLogContext) mapCreateAPIOption() *repo.CreateAPIAuditOption {
return &repo.CreateAPIAuditOption{
Plane: repo.DataplaneName,
HashedGrantToken: a.getContextStringPtr(contextAuthzSub),
Domain: a.getContextStringPtr(contextAuthzDom),
HTTPMethod: &a.Request().Method,
HTTPPath: &a.Request().URL.Path,
SentHTTPStatus: &a.Response().Status,
}
}
func (dp *DataPlane) middlewareAPIAudit() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
res := next(c)
go func() {
ac := &auditLogContext{c}
_, err := dp.Repo.CreateAPIAudit(context.Background(), ac.mapCreateAPIOption())
if err != nil {
dp.Logger.Error(err)
}
}()
return res
}
}
}
// middlewareSetContext sets the echo.Context k/v pairs
func (dp *DataPlane) middlewareSetContext(k string, v interface{}) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Set(k, v)
return next(c)
}
}
}