forked from ajmyyra/ambassador-auth-oidc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
298 lines (242 loc) · 7.29 KB
/
auth.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package main
import (
"crypto/md5"
"encoding/base64"
"encoding/hex"
"encoding/json"
"log"
"net/http"
"os"
"reflect"
"strings"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/go-redis/redis"
)
var hostname string
var redisdb *redis.Client
var logoutCookie = false
var disableUserInfo = false
var whitelist []string
var blacklist []string // TODO Refactor to struct with expiration time, and add cleaner.
type blacklistItem struct {
Key string `json:"key"`
JWTHash string `json:"hash"`
Expiration time.Time `json:"exp"`
}
func init() {
redisAddr := getenvOrDefault("REDIS_ADDRESS", "")
redisPwd := getenvOrDefault("REDIS_PASSWORD", "")
if redisAddr != "" {
redisdb = redis.NewClient(&redis.Options{
Addr: redisAddr,
Password: redisPwd,
DB: 0,
})
_, err := redisdb.Ping().Result()
if err != nil {
log.Fatal("Problem connecting to Redis: ", err.Error())
}
log.Println("Using Redis at", redisAddr)
} else {
log.Println("No Redis address specified, storing items locally.")
redisdb = nil
}
whitelist = strings.Split(getenvOrDefault("SKIP_AUTH_URI", ""), " ")
if len(whitelist[0]) > 0 {
log.Println("Skipping authorization for URIs:", whitelist)
}
envContent := os.Getenv("LOGOUT_COOKIE")
if envContent == "true" {
logoutCookie = true
}
envContent = os.Getenv("DISABLE_USERINFO")
if envContent == "true" {
disableUserInfo = true
}
}
// LoginHandler processes login requests
func LoginHandler(w http.ResponseWriter, r *http.Request) {
beginOIDCLogin(w, r, "/")
}
// Wildcardhandler to provide ServeHTTP method required for Go's handlers
type wildcardHandler struct {
}
func (wh *wildcardHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
AuthReqHandler(w, r)
}
func newWildcardHandler() *wildcardHandler {
return &wildcardHandler{}
}
// AuthReqHandler processes all incoming requests by default, unless specific endpoint is mentioned
func AuthReqHandler(w http.ResponseWriter, r *http.Request) {
var userToken string
if len(whitelist[0]) > 0 {
for _, v := range whitelist {
if strings.HasPrefix(r.URL.String(), string(v)) {
log.Println(getUserIP(r), r.URL.String(), "URI is whitelisted. Accepted without authorization.")
returnStatus(w, http.StatusOK, "OK")
return
}
}
}
if len(r.Header.Get("X-Auth-Token")) != 0 { // Header available in request
userToken = r.Header.Get("X-Auth-Token")
} else {
cookie, err := r.Cookie("auth")
if err != nil {
log.Println(getUserIP(r), r.URL.String(), "Cookie not set, redirecting to login.")
beginOIDCLogin(w, r, r.URL.Path)
return
}
userToken = cookie.Value
}
deletionCookie := createCookie("", time.Now().AddDate(0, 0, -2), hostname)
if len(userToken) == 0 { // Cookie or auth header empty
log.Println(getUserIP(r), r.URL.String(), "Empty authorization header.")
http.SetCookie(w, deletionCookie)
beginOIDCLogin(w, r, r.URL.Path)
return
}
token, err := parseJWT(userToken)
if err != nil {
if err.Error() == "Token is expired" {
w.Header().Set("X-Unauthorized-Reason", "Token Expired")
log.Println(getUserIP(r), r.URL.String(), "JWT token expired.")
} else {
log.Println(getUserIP(r), r.URL.String(), "Problem validating JWT:", err.Error())
}
http.SetCookie(w, deletionCookie)
beginOIDCLogin(w, r, r.URL.Path)
returnStatus(w, http.StatusUnauthorized, "Cookie/header expired or malformed.")
return
}
if checkBlacklist(hashString(token.Raw)) {
log.Println(getUserIP(r), r.URL.String(), "Token in blacklist.")
http.SetCookie(w, deletionCookie)
beginOIDCLogin(w, r, r.URL.Path)
return
}
uifClaim, err := base64decode(token.Claims.(jwt.MapClaims)["uif"].(string))
if err != nil {
log.Println(getUserIP(r), r.URL.String(), "Not able to decode base64 content:", err.Error())
http.SetCookie(w, deletionCookie)
beginOIDCLogin(w, r, r.URL.Path)
return
}
log.Println(getUserIP(r), r.URL.String(), "Authorized & accepted.")
w.Header().Set("X-Auth-Userinfo", string(uifClaim[:]))
returnStatus(w, http.StatusOK, "OK")
}
// LogoutHandler blacklists user token
func LogoutHandler(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("auth")
if err != nil {
log.Println(getUserIP(r), r.URL.String(), "Cookie not set, not able to logout.")
returnStatus(w, http.StatusBadRequest, "Cookie not set.")
return
}
token, err := parseJWT(cookie.Value)
if err != nil {
log.Println(getUserIP(r), r.URL.String(), "Not able to use JWT:", err.Error())
returnStatus(w, http.StatusBadRequest, "Malformed JWT in cookie.")
return
}
tokenHash := hashString(token.Raw)
if checkBlacklist(tokenHash) {
log.Println(getUserIP(r), r.URL.String(), "Token already blacklisted, cannot to logout again.")
returnStatus(w, http.StatusForbidden, "Not logged in.")
return
}
jwtExp := int64(token.Claims.(jwt.MapClaims)["exp"].(float64))
_, err = addToBlacklist(tokenHash, time.Unix(jwtExp, 0))
if err != nil {
log.Println(getUserIP(r), "Problem setting JWT to Redis blacklist:", err.Error())
returnStatus(w, http.StatusInternalServerError, "Problem logging out.")
return
}
log.Println(getUserIP(r), r.URL.String(), "Logged out, token added to blacklist.")
if logoutCookie { // Sends empty expired cookie to remove the logged out one.
newCookie := createCookie("", time.Now().AddDate(0, 0, -2), hostname)
http.SetCookie(w, newCookie)
}
returnStatus(w, http.StatusOK, "Succesfully logged out.")
}
func returnStatus(w http.ResponseWriter, statusCode int, errorMsg string) {
w.WriteHeader(statusCode)
w.Write([]byte(errorMsg))
}
func getUserIP(r *http.Request) string {
headerIP := r.Header.Get("X-Forwarded-For")
if headerIP != "" {
return headerIP
}
return strings.Split(r.RemoteAddr, ":")[0]
}
func hashString(str string) string {
hasher := md5.New()
hasher.Write([]byte(str))
return hex.EncodeToString(hasher.Sum(nil))
}
func base64encode(data []byte) string {
str := base64.StdEncoding.EncodeToString(data)
return str
}
func base64decode(str string) ([]byte, error) {
arr, err := base64.StdEncoding.DecodeString(str)
if err != nil {
return nil, err
}
return arr, nil
}
func addToBlacklist(tokenHash string, exp time.Time) (bool, error) {
blKey := createNonce(8)
blItem := &blacklistItem{Key: blKey, JWTHash: tokenHash, Expiration: exp}
if redisdb != nil {
blJSON, err := json.Marshal(blItem)
if err != nil {
panic(err)
}
err = redisdb.HSet("blacklist", blKey, string(blJSON)).Err()
if err != nil {
return false, err
}
}
blacklist = append(blacklist, tokenHash)
return true, nil
}
func updateBlacklist() {
res, err := redisdb.HVals("blacklist").Result()
if err != nil {
panic(err)
}
var newBlacklist []string
for _, i := range res {
var blItem blacklistItem
err = json.Unmarshal([]byte(i), &blItem)
if err != nil {
panic(err)
}
if blItem.Expiration.Before(time.Now()) {
log.Println("Removing expired token", blItem.Key, "from blacklist.")
err = redisdb.HDel("blacklist", blItem.Key).Err()
if err != nil {
panic(err)
}
continue
}
newBlacklist = append(newBlacklist, blItem.JWTHash)
}
if !reflect.DeepEqual(blacklist, newBlacklist) {
blacklist = newBlacklist
log.Println("Blacklist changes in Redis, local blacklist recreated.")
}
}
func checkBlacklist(jwtHash string) bool {
for _, elem := range blacklist {
if jwtHash == elem {
return true
}
}
return false
}