-
Notifications
You must be signed in to change notification settings - Fork 0
/
radix_middleware.go
97 lines (79 loc) · 2.62 KB
/
radix_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
package utils
import (
"context"
"net/http"
"time"
"github.com/equinor/radix-api/api/metrics"
"github.com/equinor/radix-api/models"
radixhttp "github.com/equinor/radix-common/net/http"
"github.com/gorilla/mux"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// RadixMiddleware The middleware between router and radix handler functions
type RadixMiddleware struct {
kubeUtil KubeUtil
path string
method string
allowNoAuth bool
next models.RadixHandlerFunc
}
// NewRadixMiddleware Constructor for radix middleware
func NewRadixMiddleware(kubeUtil KubeUtil, path, method string, allowUnauthenticatedUsers bool, next models.RadixHandlerFunc) *RadixMiddleware {
handler := &RadixMiddleware{
kubeUtil,
path,
method,
allowUnauthenticatedUsers,
next,
}
return handler
}
// Handle Wraps radix handler methods
func (handler *RadixMiddleware) Handle(w http.ResponseWriter, r *http.Request) {
start := time.Now()
defer func() {
httpDuration := time.Since(start)
metrics.AddRequestDuration(handler.path, handler.method, httpDuration)
}()
switch {
case handler.allowNoAuth:
handler.handleAnonymous(w, r)
default:
handler.handleAuthorization(w, r)
}
}
func (handler *RadixMiddleware) handleAuthorization(w http.ResponseWriter, r *http.Request) {
token, err := radixhttp.GetBearerTokenFromHeader(r)
if err != nil {
radixhttp.ErrorResponse(w, r, err)
return
}
impersonation, err := radixhttp.GetImpersonationFromHeader(r)
if err != nil {
radixhttp.ErrorResponse(w, r, radixhttp.UnexpectedError("Problems impersonating", err))
return
}
inClusterClient, inClusterRadixClient := handler.kubeUtil.GetInClusterKubernetesClient()
outClusterClient, outClusterRadixClient := handler.kubeUtil.GetOutClusterKubernetesClientWithImpersonation(token, impersonation)
accounts := models.NewAccounts(
inClusterClient,
inClusterRadixClient,
outClusterClient,
outClusterRadixClient,
token,
impersonation)
// Check if registration of application exists for application-specific requests
if appName, exists := mux.Vars(r)["appName"]; exists {
if _, err := accounts.UserAccount.RadixClient.RadixV1().RadixRegistrations().Get(context.TODO(), appName, metav1.GetOptions{}); err != nil {
radixhttp.ErrorResponse(w, r, err)
return
}
}
handler.next(accounts, w, r)
}
func (handler *RadixMiddleware) handleAnonymous(w http.ResponseWriter, r *http.Request) {
inClusterClient, inClusterRadixClient := handler.kubeUtil.GetInClusterKubernetesClient()
sa := models.NewServiceAccount(inClusterClient, inClusterRadixClient)
accounts := models.Accounts{ServiceAccount: sa}
handler.next(accounts, w, r)
}