This repository has been archived by the owner on Oct 23, 2024. It is now read-only.
forked from arrikto/oidc-authservice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
235 lines (209 loc) · 6.06 KB
/
util.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// Copyright (c) 2018 Antti Myyrä
// Copyright © 2019 Arrikto Inc. All Rights Reserved.
package main
import (
"context"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/base64"
"fmt"
"net/http"
"net/url"
"path"
"path/filepath"
"strings"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"k8s.io/apiserver/pkg/authentication/user"
)
type Cacheable interface {
getCacheKey(r *http.Request) string
}
func realpath(path string) (string, error) {
path, err := filepath.Abs(path)
if err != nil {
return "", err
}
path, err = filepath.EvalSymlinks(path)
if err != nil {
return "", err
}
return path, nil
}
func loggerForRequest(r *http.Request, info string) *log.Entry {
return log.WithContext(r.Context()).WithFields(log.Fields{
"context": info, // include info about the module generating the log
"ip": getUserIP(r),
"request": r.URL.String(),
})
}
func getUserIP(r *http.Request) string {
headerIP := r.Header.Get("X-Forwarded-For")
if headerIP != "" {
return headerIP
}
return strings.Split(r.RemoteAddr, ":")[0]
}
func returnHTML(w http.ResponseWriter, statusCode int, html string) {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(statusCode)
_, err := w.Write([]byte(html))
if err != nil {
log.Errorf("Failed to write body: %v", err)
}
}
func returnMessage(w http.ResponseWriter, statusCode int, msg string) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(statusCode)
_, err := w.Write([]byte(msg))
if err != nil {
log.Errorf("Failed to write body: %v", err)
}
}
func returnJSONMessage(w http.ResponseWriter, statusCode int, jsonMsg interface{}) {
jsonBytes, err := json.Marshal(jsonMsg)
if err != nil {
log.Errorf("Failed to marshal struct to json: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
_, err = w.Write(jsonBytes)
if err != nil {
log.Errorf("Failed to write body: %v", err)
}
}
func deleteCookie(w http.ResponseWriter, name string) {
http.SetCookie(w, &http.Cookie{Name: name, MaxAge: -1, Path: "/"})
}
func createNonce(length int) (string, error) {
// XXX: To avoid modulo bias, 256 / len(nonceChars) MUST equal 0.
// In this case, 256 / 64 = 0. See:
// https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
const nonceChars = "abcdefghijklmnopqrstuvwxyz:ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789"
nonce := make([]byte, length)
if _, err := rand.Read(nonce); err != nil {
return "", err
}
for i := range nonce {
nonce[i] = nonceChars[int(nonce[i])%len(nonceChars)]
}
return string(nonce), nil
}
func setTLSContext(ctx context.Context, caBundle []byte) context.Context {
if len(caBundle) == 0 {
return ctx
}
rootCAs, err := x509.SystemCertPool()
if err != nil {
log.Warning("Could not load system cert pool")
rootCAs = x509.NewCertPool()
}
if ok := rootCAs.AppendCertsFromPEM(caBundle); !ok {
log.Warning("Could not append custom CA bundle, using system certs only")
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: rootCAs},
}
tlsConf := &http.Client{Transport: tr}
return context.WithValue(ctx, oauth2.HTTPClient, tlsConf)
}
func mustParseURL(rawURL string) *url.URL {
url, err := url.Parse(rawURL)
if err != nil {
panic(err)
}
return url
}
func resolvePathReference(u *url.URL, p string) *url.URL {
ret := *u
ret.Path = path.Join(ret.Path, p)
return &ret
}
func doRequest(ctx context.Context, req *http.Request) (*http.Response, error) {
client := http.DefaultClient
if c, ok := ctx.Value(oauth2.HTTPClient).(*http.Client); ok {
client = c
}
// TODO: Consider retrying the request if response code is 503
// See: https://tools.ietf.org/html/rfc7009#section-2.2.1
return client.Do(req.WithContext(ctx))
}
func getBearerToken(value string) string {
value = strings.TrimSpace(value)
if strings.HasPrefix(value, "Bearer ") {
return strings.TrimPrefix(value, "Bearer ")
}
return value
}
func userInfoToHeaders(info user.Info, opts *httpHeaderOpts, transformer *UserIDTransformer) map[string]string {
res := map[string]string{}
res[opts.userIDHeader] = opts.userIDPrefix + transformer.Transform(info.GetName())
res[opts.groupsHeader] = strings.Join(info.GetGroups(), ",")
if authMethodArr, ok := info.GetExtra()["auth-method"]; ok {
if len(authMethodArr) > 0 && authMethodArr[0] != "" {
res[opts.authMethodHeader] = authMethodArr[0]
}
}
return res
}
func interfaceSliceToStringSlice(in []interface{}) []string {
if in == nil {
return nil
}
res := []string{}
for _, elem := range in {
res = append(res, elem.(string))
}
return res
}
// The `aud` claim of a JWT token can be one of the following types:
// * string
// * []string
// Similarly to the https://github.com/coreos/go-oidc/blob/v3/oidc/oidc.go
// we introduce a custom UnmarshalJSON function that allows us to
// handle both types.
type audience []string
func (a *audience) UnmarshalJSON(b []byte) error {
var s string
if json.Unmarshal(b, &s) == nil {
*a = audience{s}
return nil
}
var auds []string
if err := json.Unmarshal(b, &auds); err != nil {
return err
}
*a = auds
return nil
}
// We copy the parseJWT() from: https://github.com/coreos/go-oidc/blob/v3/oidc/verify.go
// to perform one of the necessary local tests for the JWT authenticator.
func parseJWT(p string) ([]byte, error) {
parts := strings.Split(p, ".")
if len(parts) < 3 {
return nil, fmt.Errorf("malformed jwt, expected 3 parts got %d", len(parts))
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, fmt.Errorf("malformed jwt payload: %v", err)
}
return payload, nil
}
// This function examines if there is at least one common element between
// two []string objects. The JWT authenticator uses this function to verify
// that at least one of the audiences of the examined JWT tokens exists in
// the list of the audiences that the AuthService accepts.
func contains(sli []string, ele []string) bool {
for _, s := range sli {
for _, elem := range ele {
if s == elem {
return true
}
}
}
return false
}