-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathauthorization.go
48 lines (35 loc) · 1.22 KB
/
authorization.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
// Copyright 2020-2021 Clastix Labs
// SPDX-License-Identifier: Apache-2.0
package middleware
import (
"fmt"
"net/http"
"regexp"
"github.com/go-logr/logr"
"github.com/gorilla/mux"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/clastix/capsule-proxy/internal/webserver/errors"
)
const (
regexPatternForAuthHeader = "^(Bearer ([\\w-]*\\.[\\w-]*\\.[\\w-]*))$"
)
func CheckAuthorization(client client.Client, log logr.Logger, tls bool) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
err := fmt.Errorf("forbidden access")
isCertificates := request.TLS != nil && len(request.TLS.PeerCertificates) > 0
isBearerToken, errBT := checkBearerToken(request.Header.Get("Authorization"))
unauthorized := errBT != nil || (tls && (!isCertificates && !isBearerToken)) || (!tls && !isBearerToken)
if unauthorized {
errors.HandleUnauthorized(writer, err, "unauthorized")
}
next.ServeHTTP(writer, request)
})
}
}
func checkBearerToken(authorizationHeader string) (bool, error) {
if authorizationHeader == "" {
return false, nil
}
return regexp.MatchString(regexPatternForAuthHeader, authorizationHeader)
}