This repository has been archived by the owner on Jan 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
lookup.go
123 lines (99 loc) · 2.47 KB
/
lookup.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package k8s
import (
"io"
"io/ioutil"
"net/http"
"strings"
"time"
"encoding/json"
"github.com/pkg/errors"
"github.com/rancher/go-rancher/v3"
)
type Lookup struct {
httpClient http.Client
accessKey, secretKey string
clusterURL string
}
func NewLookup(clusterURL, accessKey, secretKey string) *Lookup {
return &Lookup{
httpClient: http.Client{
Timeout: 5 * time.Second,
},
accessKey: accessKey,
secretKey: secretKey,
clusterURL: clusterURL,
}
}
func (c *Lookup) Lookup(input *http.Request) (*client.Cluster, bool, error) {
clusterID := getClusterID(input)
if clusterID == "" {
return nil, false, nil
}
req, err := http.NewRequest("GET", c.clusterURL+"/"+clusterID, nil)
if err != nil {
return nil, false, err
}
req.SetBasicAuth(c.accessKey, c.secretKey)
cookie := getTokenCookie(input)
if cookie != nil {
req.AddCookie(cookie)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, false, err
}
defer close(resp)
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
c, err := parseCluster(resp)
return c, true, err
}
auth := input.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Bearer ") {
return nil, false, nil
}
auth = strings.TrimPrefix(auth, "Bearer ")
req.Header.Del("Authorization")
req.SetBasicAuth(c.accessKey, c.secretKey)
resp2, err := c.httpClient.Do(req)
if err != nil {
return nil, false, err
}
defer close(resp2)
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, false, nil
}
cluster, err := parseCluster(resp2)
if err != nil || cluster.K8sClientConfig == nil || cluster.K8sClientConfig.BearerToken != auth {
return nil, false, err
}
return cluster, false, nil
}
func parseCluster(resp *http.Response) (*client.Cluster, error) {
cluster := &client.Cluster{}
if err := json.NewDecoder(resp.Body).Decode(cluster); err != nil {
return nil, errors.Wrap(err, "Parsing clusters response")
}
return cluster, nil
}
func getClusterID(req *http.Request) string {
parts := strings.Split(req.URL.Path, "/")
if len(parts) > 3 && strings.HasPrefix(parts[2], "cluster") {
return parts[3]
}
return ""
}
func getAuthorizationHeader(req *http.Request) string {
return req.Header.Get("Authorization")
}
func getTokenCookie(req *http.Request) *http.Cookie {
for _, cookie := range req.Cookies() {
if cookie.Name == "token" {
return cookie
}
}
return nil
}
func close(resp *http.Response) error {
io.Copy(ioutil.Discard, resp.Body)
return resp.Body.Close()
}