-
Notifications
You must be signed in to change notification settings - Fork 9
/
middleware.go
90 lines (82 loc) 路 2.18 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
package authz
import (
"context"
"fmt"
"net/http"
"time"
"github.com/labstack/echo/v4"
"github.com/patrickmn/go-cache"
v1 "k8s.io/api/authentication/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
client "k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
type (
Authz struct {
Cache *cache.Cache
Client client.Clientset
Audience string
ServiceAccounts []string
}
)
func NewAuthz() *Authz {
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
clientset, err := client.NewForConfig(config)
if err != nil {
panic(err.Error())
}
return &Authz{
Cache: cache.New(5*time.Minute, 10*time.Minute),
Client: *clientset,
}
}
func (a *Authz) SetAudience(audience string) {
a.Audience = audience
}
func (a *Authz) AddServiceAccount(namespace string, name string) {
a.ServiceAccounts = append(a.ServiceAccounts, fmt.Sprintf("system:serviceaccount:%s:%s", namespace, name))
}
// Process is the middleware function.
func (a *Authz) Process(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
authz := c.Request().Header.Get("Authorization")
if authz == "" {
return echo.NewHTTPError(http.StatusUnauthorized, "missing Authorization header")
}
_, found := a.Cache.Get(authz)
if found {
return next(c)
}
ctx := context.Background()
tr := &v1.TokenReview{
Spec: v1.TokenReviewSpec{
Token: authz,
Audiences: []string{a.Audience},
},
}
result, err := a.Client.AuthenticationV1().TokenReviews().Create(ctx, tr, metav1.CreateOptions{})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "error validating token")
}
if !result.Status.Authenticated {
return echo.NewHTTPError(http.StatusUnauthorized, "invalid token")
}
fmt.Printf("%s", result.Status.User.Username)
if !a.isServiceAccountAllowed(result.Status.User.Username) {
return echo.NewHTTPError(http.StatusUnauthorized, "unauthorized user")
}
a.Cache.Set(authz, true, cache.DefaultExpiration)
return next(c)
}
}
func (a *Authz) isServiceAccountAllowed(username string) bool {
for _, sa := range a.ServiceAccounts {
if sa == username {
return true
}
}
return false
}