forked from arrikto/oidc-authservice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
116 lines (99 loc) · 2.67 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
// Copyright (c) 2018 Antti Myyrä
// Copyright © 2019 Arrikto Inc. All Rights Reserved.
package main
import (
"context"
"crypto/tls"
"crypto/x509"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"math/rand"
"net/http"
"net/url"
"os"
"strings"
)
func loggerForRequest(r *http.Request) *log.Entry {
return log.WithContext(r.Context()).WithFields(log.Fields{
"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 returnStatus(w http.ResponseWriter, statusCode int, errorMsg string) {
w.WriteHeader(statusCode)
w.Write([]byte(errorMsg))
}
func getEnvOrDefault(key, fallback string) string {
value, exists := os.LookupEnv(key)
if !exists {
log.Println("No ", key, " specified, using '"+fallback+"' as default.")
return fallback
}
return value
}
func getURLEnvOrDie(URLEnv string) *url.URL {
envContent := os.Getenv(URLEnv)
parsedURL, err := url.Parse(envContent)
if err != nil {
log.Fatal("Not a valid URL for env variable ", URLEnv, ": ", envContent, "\n")
}
return parsedURL
}
func getEnvOrDie(envVar string) string {
envContent := os.Getenv(envVar)
if len(envContent) == 0 {
log.Fatal("Env variable ", envVar, " missing, exiting.")
}
return envContent
}
func clean(s []string) []string {
res := []string{}
for _, elem := range s {
if elem != "" {
res = append(res, elem)
}
}
return res
}
func createNonce(length int) string {
nonceChars := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
var nonce = make([]rune, length)
for i := range nonce {
nonce[i] = nonceChars[rand.Intn(len(nonceChars))]
}
return string(nonce)
}
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 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))
}