-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathincorruptible.go
311 lines (262 loc) · 8.27 KB
/
incorruptible.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
// Copyright 2022 Teal.Finance/incorruptible contributors
// This file is part of Teal.Finance/incorruptible
// a tiny+secured cookie token licensed under the MIT License.
// SPDX-License-Identifier: MIT
package incorruptible
import (
"crypto/cipher"
crand "crypto/rand"
"encoding/binary"
"math/rand"
"net/http"
"net/url"
"path"
"time"
// baseN "github.com/teal-finance/BaseXX/base92" // use another package with same interface.
baseN "github.com/mtraver/base91"
"github.com/teal-finance/emo"
)
//nolint:gochecknoglobals // global logger
var log = emo.NewZone("incorr")
type Incorruptible struct {
writeErr WriteErr
SetIP bool // If true => put the remote IP in the token.
cookie http.Cookie
cipher cipher.AEAD
magic byte
baseN *baseN.Encoding
}
const (
authScheme = "Bearer "
tokenScheme = "i:" // See RFC 8959, here "i" means "incorruptible token format"
prefixScheme = authScheme + tokenScheme
)
// New creates a new Incorruptible. The order of the parameters are consistent with garcon.NewJWTChecker (see Teal-Finance/Garcon).
// The Garcon middleware constructors use a garcon.Writer as first parameter.
// Please share your thoughts/feedback, we can still change that.
func New(writeErr WriteErr, urls []*url.URL, secretKey []byte, cookieName string, maxAge int, setIP bool) *Incorruptible {
if writeErr == nil {
writeErr = defaultWriteErr
}
if len(urls) == 0 {
log.Panic("No URL => Cannot set cookie attributes: Domain, Secure and Path")
}
secure, dns, dir := extractMainDomain(urls[0])
cipher := NewCipher(secretKey)
// initialize the random generator with a reproducible secret seed
resetRandomGenerator(secretKey)
magic := magicCode()
encodingAlphabet := shuffle(noSpaceDoubleQuoteSemicolon)
// reset the random generator with a strong random seed
resetRandomGenerator(nil)
incorr := Incorruptible{
writeErr: writeErr,
SetIP: setIP,
cookie: newCookie(cookieName, secure, dns, dir, maxAge),
cipher: cipher,
magic: magic,
baseN: baseN.NewEncoding(encodingAlphabet),
}
incorr.addMinimalistToken()
log.Securityf("Cookie %s Domain=%v Path=%v Max-Age=%v Secure=%v SameSite=%v HttpOnly=%v Value=%d bytes",
incorr.cookie.Name, incorr.cookie.Domain, incorr.cookie.Path, incorr.cookie.MaxAge,
incorr.cookie.Secure, incorr.cookie.SameSite, incorr.cookie.HttpOnly, len(incorr.cookie.Value))
return &incorr
}
func (incorr *Incorruptible) addMinimalistToken() {
if !incorr.useMinimalistToken() {
return
}
// serialize a minimalist token
// including encryption and Base91-encoding
token, err := incorr.Encode(EmptyTValues())
if err != nil {
log.Panic(err)
}
// insert this generated token in the cookie
incorr.cookie.Value = tokenScheme + token
}
func (incorr *Incorruptible) useMinimalistToken() bool {
return (incorr.cookie.MaxAge <= 0) && (!incorr.SetIP)
}
// equalMinimalistToken compares with the default token.
func (incorr *Incorruptible) equalMinimalistToken(base91 string) bool {
const schemeSize = len(tokenScheme) // to skip the token scheme
return incorr.useMinimalistToken() && (base91 == incorr.cookie.Value[schemeSize:])
}
// resetRandomGenerator resets the "math.rand" generator from 16 bytes.
// This function is used to initialize the random generator with a reproducible secret seed.
// If no bytes are passed, resetRandomGenerator resets the "math.rand" generator with a strong random seed.
func resetRandomGenerator(bytes []byte) {
if len(bytes) == 0 {
bytes = make([]byte, 16)
_, err := crand.Read(bytes)
if err != nil {
log.Panic(err)
}
}
seed := binary.BigEndian.Uint64(bytes)
seed += binary.BigEndian.Uint64(bytes[8:])
rand.New(rand.NewSource(int64(seed)))
}
func magicCode() byte {
//nolint:gosec // Reproduce MagicCode from same secret seed
return byte(rand.Int63())
}
// shuffle randomizes order of the input string.
func shuffle(s string) string {
r := []rune(s)
rand.Shuffle(len(r), func(i, j int) { r[i], r[j] = r[j], r[i] })
return string(r)
}
// NewCookie creates a new cookie based on default values.
// the HTTP request parameter is used to get the remote IP (only when incorr.SetIP is true).
func (incorr *Incorruptible) NewCookie(r *http.Request, keyValues ...KVal) (*http.Cookie, TValues, error) {
cookie := incorr.cookie // local copy of the default cookie
tv, err := incorr.NewTValues(r)
if err != nil {
return &cookie, tv, err
}
if !incorr.useMinimalistToken() || (len(keyValues) > 0) {
err := tv.Set(keyValues...)
if err != nil {
return &cookie, tv, err
}
token, err := incorr.Encode(tv)
if err != nil {
return &cookie, tv, err
}
cookie.Value = tokenScheme + token
}
return &cookie, tv, nil
}
func (incorr *Incorruptible) NewTValues(r *http.Request, keyValues ...KVal) (TValues, error) {
var tv TValues
if !incorr.useMinimalistToken() {
tv.SetExpiry(incorr.cookie.MaxAge)
if incorr.SetIP {
err := tv.SetRemoteIP(r)
if err != nil {
return tv, err
}
}
}
err := tv.Set(keyValues...)
return tv, err
}
func (incorr *Incorruptible) NewCookieFromValues(tv TValues) (*http.Cookie, error) {
token, err := incorr.Encode(tv)
if err != nil {
return &incorr.cookie, err
}
cookie := incorr.NewCookieFromToken(token, tv.MaxAge())
return cookie, nil
}
func (incorr *Incorruptible) NewCookieFromToken(token string, maxAge int) *http.Cookie {
cookie := incorr.cookie
cookie.Value = tokenScheme + token
cookie.MaxAge = maxAge
return &cookie
}
// DeadCookie returns an Incorruptible cookie without Value and with "Max-Age=0"
// in order to delete the Incorruptible cookie in the current HTTP session.
//
// Example:
//
// func logout(w http.ResponseWriter, r *http.Request) {
// http.SetCookie(w, Incorruptible.DeadCookie())
// }
func (incorr *Incorruptible) DeadCookie() *http.Cookie {
cookie := incorr.cookie // local copy of the default cookie
cookie.Value = ""
cookie.MaxAge = -1 // MaxAge<0 means "delete cookie now"
return &cookie
}
// Cookie returns a pointer to the default cookie values.
// This can be used to customize some cookie values (may break),
// and also to facilitate testing.
func (incorr *Incorruptible) Cookie(_ int) *http.Cookie {
return &incorr.cookie
}
func (incorr *Incorruptible) CookieName() string {
return incorr.cookie.Name
}
// URL schemes.
const (
HTTP = "http"
HTTPS = "https"
)
//nolint:nonamedreturns // we want to document the returned values.
func extractMainDomain(u *url.URL) (secure bool, dns, dir string) {
if u == nil {
log.Panic("No URL => Cannot set Cookie domain")
}
switch {
case u.Scheme == HTTP:
secure = false
case u.Scheme == HTTPS:
secure = true
default:
log.Panicf("Unexpected protocol scheme in %+v", u)
}
return secure, u.Hostname(), u.Path
}
// This function was used to trigger the dev. mode
// func isLocalhost(urls []*url.URL) bool {
// if len(urls) > 0 && urls[0].Scheme == "http" {
// host, _, _ := net.SplitHostPort(urls[0].Host)
// if host == "localhost" {
// log.Security("DevMode accepts missing/invalid token from", urls[0])
// return true
// }
// }
//
// log.Security("ProdMode requires valid token: no http://localhost in first of", urls)
// return false
// }
func newCookie(name string, secure bool, dns, dir string, maxAge int) http.Cookie {
dir = path.Clean(dir)
if dir == "." {
dir = "/"
}
if name == "" {
name = "session"
for i := len(dir) - 2; i >= 0; i-- {
if dir[i] == byte('/') {
name = dir[i+1:]
break
}
}
}
// cookie prefix for enhanced security
if secure && name[0] != '_' {
if dir == "/" {
// "__Host-" when cookie has "Secure" flag, has no "Domain",
// has "Path=/" and is sent from a secure origin.
dns = ""
name = "__Host-" + name
} else {
// "__Secure-" when cookie has "Secure" flag and is sent from a secure origin
// "__Host-" is better than the "__Secure-" prefix.
name = "__Secure-" + name
}
}
// sameSite = Strict works when using two backends like:
// localhost:3000 (node) and localhost:8080 (API)
// https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie/SameSite
const sameSite = http.SameSiteStrictMode
return http.Cookie{
Name: name,
Value: "", // emptyCookie because no token
Path: dir,
Domain: dns,
Expires: time.Time{},
RawExpires: "",
MaxAge: maxAge,
Secure: secure,
HttpOnly: true,
SameSite: sameSite,
Raw: "",
Unparsed: nil,
}
}