forked from lastlogin-net/obligator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
435 lines (366 loc) · 9.13 KB
/
utils.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package obligator
import (
"crypto/rand"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/lestrrat-go/jwx/v2/jwt"
)
func Hash(input string) string {
sha2 := sha256.New()
io.WriteString(sha2, input)
return fmt.Sprintf("%x", sha2.Sum(nil))
}
func saveJson(data interface{}, filePath string) error {
jsonStr, err := json.MarshalIndent(data, "", " ")
if err != nil {
return errors.New("Error serializing JSON")
} else {
err := os.WriteFile(filePath, jsonStr, 0644)
if err != nil {
return errors.New("Error saving JSON")
}
}
return nil
}
func printJson(data interface{}) {
d, _ := json.MarshalIndent(data, "", " ")
fmt.Println(string(d))
}
func genRandomKey() (string, error) {
const chars string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
id := ""
for i := 0; i < 32; i++ {
randIndex, err := rand.Int(rand.Reader, big.NewInt(int64(len(chars))))
if err != nil {
return "", err
}
id += string(chars[randIndex.Int64()])
}
return id, nil
}
func genRandomCode() (string, error) {
const chars string = "0123456789"
id := ""
for i := 0; i < 4; i++ {
randIndex, err := rand.Int(rand.Reader, big.NewInt(int64(len(chars))))
if err != nil {
return "", err
}
id += string(chars[randIndex.Int64()])
}
return id, nil
}
func buildCookieDomain(fullUrl string) (string, error) {
rootUrlParsed, err := url.Parse(fullUrl)
if err != nil {
return "", err
}
hostParts := strings.Split(rootUrlParsed.Host, ".")
if len(hostParts) < 3 {
// apex domain
return rootUrlParsed.Host, nil
} else {
cookieDomain := strings.Join(hostParts[1:], ".")
return cookieDomain, nil
}
}
func validUser(email string, users []User) bool {
for _, user := range users {
if email == user.Email {
return true
}
}
return false
}
func addIdentToCookie(storage Storage, cookieValue string, i *Identity) (*http.Cookie, error) {
return addIdentityToCookie(storage, i.ProviderName, i.Id, i.Email, cookieValue, i.EmailVerified)
}
func addIdentityToCookie(storage Storage, providerName, id, email, cookieValue string, emailVerified bool) (*http.Cookie, error) {
key, exists := storage.GetJWKSet().Key(0)
if !exists {
return nil, errors.New("No keys available")
}
idType := "email"
if providerName == "URL" {
idType = "url"
}
newIdent := &Identity{
IdType: idType,
Id: id,
ProviderName: providerName,
Email: email,
EmailVerified: emailVerified,
}
idents := []*Identity{newIdent}
keyJwt := jwt.New()
if cookieValue != "" {
publicJwks, err := jwk.PublicSetOf(storage.GetJWKSet())
if err != nil {
return nil, err
}
parsed, err := jwt.Parse([]byte(cookieValue), jwt.WithKeySet(publicJwks))
if err != nil {
// Only add identities from current cookie if it's valid
} else {
keyJwt = parsed
tokIdentsInterface, exists := parsed.Get("identities")
if exists {
if tokIdents, ok := tokIdentsInterface.([]*Identity); ok {
for _, ident := range tokIdents {
if ident.Id != newIdent.Id {
idents = append(idents, ident)
}
}
}
}
}
}
issuedAt := time.Now().UTC()
err := keyJwt.Set("iat", issuedAt)
if err != nil {
return nil, err
}
nonce, err := genRandomKey()
if err != nil {
return nil, err
}
err = keyJwt.Set("nonce", nonce)
if err != nil {
return nil, err
}
err = keyJwt.Set("identities", idents)
if err != nil {
return nil, err
}
signed, err := jwt.Sign(keyJwt, jwt.WithKey(jwa.RS256, key))
if err != nil {
return nil, err
}
unhashedLoginKey := string(signed)
cookieDomain, err := buildCookieDomain(storage.GetRootUri())
if err != nil {
return nil, err
}
loginKeyName := storage.GetPrefix() + "login_key"
cookie := &http.Cookie{
Domain: cookieDomain,
Name: loginKeyName,
Value: unhashedLoginKey,
Secure: true,
HttpOnly: true,
MaxAge: 86400 * 365,
Path: "/",
SameSite: http.SameSiteLaxMode,
//SameSite: http.SameSiteStrictMode,
}
return cookie, nil
}
func addLoginToCookie(storage Storage, currentCookieValue, clientId string, newLogin *Login) (*http.Cookie, error) {
key, exists := storage.GetJWKSet().Key(0)
if !exists {
return nil, errors.New("No keys available")
}
issuedAt := time.Now().UTC()
newLogin.Timestamp = issuedAt.Format(time.RFC3339)
logins := make(map[string][]*Login)
keyJwt := jwt.New()
if currentCookieValue != "" {
publicJwks, err := jwk.PublicSetOf(storage.GetJWKSet())
if err != nil {
return nil, err
}
parsed, err := jwt.Parse([]byte(currentCookieValue), jwt.WithKeySet(publicJwks))
if err != nil {
// Only add identities from current cookie if it's valid
} else {
keyJwt = parsed
loginsInterface, exists := parsed.Get("logins")
if exists {
if tokLogins, ok := loginsInterface.(map[string][]*Login); ok {
logins = tokLogins
}
}
}
}
_, exists = logins[clientId]
if exists {
// Search for and update existing login, otherwise add a new entry
found := false
for _, login := range logins[clientId] {
if login.Id == newLogin.Id && login.ProviderName == newLogin.ProviderName {
login.Timestamp = newLogin.Timestamp
found = true
}
}
if !found {
logins[clientId] = append(logins[clientId], newLogin)
}
} else {
logins[clientId] = []*Login{newLogin}
}
err := keyJwt.Set("iat", issuedAt)
if err != nil {
return nil, err
}
nonce, err := genRandomKey()
if err != nil {
return nil, err
}
err = keyJwt.Set("nonce", nonce)
if err != nil {
return nil, err
}
err = keyJwt.Set("logins", logins)
if err != nil {
return nil, err
}
signed, err := jwt.Sign(keyJwt, jwt.WithKey(jwa.RS256, key))
if err != nil {
return nil, err
}
loginKey := string(signed)
cookieDomain, err := buildCookieDomain(storage.GetRootUri())
if err != nil {
return nil, err
}
loginKeyName := storage.GetPrefix() + "login_key"
cookie := &http.Cookie{
Domain: cookieDomain,
Name: loginKeyName,
Value: loginKey,
Secure: true,
HttpOnly: true,
MaxAge: 86400 * 365,
Path: "/",
SameSite: http.SameSiteLaxMode,
//SameSite: http.SameSiteStrictMode,
}
return cookie, nil
}
func deleteLoginKeyCookie(storage Storage, w http.ResponseWriter) error {
cookieDomain, err := buildCookieDomain(storage.GetRootUri())
if err != nil {
return err
}
loginKeyName := storage.GetPrefix() + "login_key"
cookie := &http.Cookie{
Domain: cookieDomain,
Name: loginKeyName,
Value: "",
Path: "/",
SameSite: http.SameSiteLaxMode,
Secure: true,
HttpOnly: true,
}
http.SetCookie(w, cookie)
return nil
}
func claimFromToken(claim string, token jwt.Token) string {
valIface, exists := token.Get(claim)
if !exists {
return ""
}
val, ok := valIface.(string)
if !ok {
return ""
}
return val
}
func getJwtFromCookie(cookieKey string, storage Storage, w http.ResponseWriter, r *http.Request) (jwt.Token, error) {
// TODO: would tying to login key increase security?
//loginKeyCookie, err := r.Cookie(storage.GetLoginKeyName())
//if err != nil {
// return nil, err
//}
publicJwks, err := jwk.PublicSetOf(storage.GetJWKSet())
if err != nil {
return nil, err
}
//hashedLoginKey := Hash(loginKeyCookie.Value)
authReqCookie, err := r.Cookie(cookieKey)
if err != nil {
return nil, err
}
parsedAuthReq, err := jwt.Parse([]byte(authReqCookie.Value), jwt.WithKeySet(publicJwks))
if err != nil {
return nil, err
}
//reqLoginKey := claimFromToken("login_key_hash", parsedAuthReq)
//if reqLoginKey != hashedLoginKey {
// return nil, errors.New("Not your request")
//}
return parsedAuthReq, nil
}
func setJwtCookie(storage Storage, jot jwt.Token, cookieKey string, maxAge time.Duration, w http.ResponseWriter, r *http.Request) {
key, exists := storage.GetJWKSet().Key(0)
if !exists {
w.WriteHeader(500)
fmt.Fprintf(os.Stderr, "No keys available")
return
}
signedReqJwt, err := jwt.Sign(jot, jwt.WithKey(jwa.RS256, key))
if err != nil {
w.WriteHeader(400)
io.WriteString(w, err.Error())
return
}
cookieDomain, err := buildCookieDomain(storage.GetRootUri())
if err != nil {
w.WriteHeader(500)
io.WriteString(w, err.Error())
return
}
cookie := &http.Cookie{
Domain: cookieDomain,
Name: cookieKey,
Value: string(signedReqJwt),
Path: "/",
SameSite: http.SameSiteLaxMode,
Secure: true,
HttpOnly: true,
MaxAge: int(maxAge.Seconds()),
}
http.SetCookie(w, cookie)
}
func clearCookie(storage Storage, cookieKey string, w http.ResponseWriter) {
cookieDomain, err := buildCookieDomain(storage.GetRootUri())
if err != nil {
w.WriteHeader(500)
io.WriteString(w, err.Error())
return
}
cookie := &http.Cookie{
Domain: cookieDomain,
Name: cookieKey,
Value: "",
Path: "/",
MaxAge: -1,
}
http.SetCookie(w, cookie)
}
func getRemoteIp(r *http.Request, behindProxy bool) (string, error) {
remoteIp, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return "", err
}
if behindProxy {
xffHeader := r.Header.Get("X-Forwarded-For")
if xffHeader != "" {
parts := strings.Split(xffHeader, ",")
remoteIp = parts[0]
}
}
return remoteIp, nil
}