-
Notifications
You must be signed in to change notification settings - Fork 2
/
sessions.go
279 lines (253 loc) · 8.27 KB
/
sessions.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
package main
import (
cryptorand "crypto/rand"
"encoding/base64"
"encoding/gob"
"errors"
"fmt"
"log"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/shurcooL/home/httputil"
"github.com/shurcooL/users"
)
// global server state.
var global = state{sessions: make(map[string]session)}
type state struct {
mu sync.Mutex
sessions map[string]session // Access Token -> User Session.
}
// LoadAndRemove first loads state from file at path, then,
// if loading was successful, it removes the file.
func (s *state) LoadAndRemove(path string) error {
err := s.load(path)
if err != nil {
return err
}
// Remove only if load was successful.
return os.Remove(path)
}
func (s *state) load(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
s.mu.Lock()
err = gob.NewDecoder(f).Decode(&s.sessions)
s.mu.Unlock()
return err
}
// Save saves state to path with permission 0600.
func (s *state) Save(path string) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer f.Close()
s.mu.Lock()
err = gob.NewEncoder(f).Encode(s.sessions)
s.mu.Unlock()
return err
}
// AddNewSession adds a new session with the specified user.
// userSpec must be a valid existing (i.e., non-zero) user.
func (s *state) AddNewSession(userSpec users.UserSpec) (accessToken string, expiry time.Time) {
accessToken = string(cryptoRandBytes())
expiry = time.Now().Add(7 * 24 * time.Hour)
s.mu.Lock()
for token, user := range s.sessions { // Clean up expired sessions.
if time.Now().Before(user.Expiry) {
continue
}
delete(s.sessions, token)
}
s.sessions[accessToken] = session{
UserSpec: userSpec,
Expiry: expiry,
AccessToken: accessToken,
}
s.mu.Unlock()
return accessToken, expiry
}
func cryptoRandBytes() []byte {
b := make([]byte, 256)
_, err := cryptorand.Read(b)
if err != nil {
panic(err)
}
return b
}
const (
accessTokenCookieName = "accessToken"
returnParameterName = "return"
)
// contextKey is a value for use with context.WithValue. It's used as
// a pointer so it fits in an interface{} without allocation.
type contextKey struct {
name string
}
func (k *contextKey) String() string { return "github.com/shurcooL/home context value " + k.name }
// session is a user session. Nil session pointer represents no session.
// Non-nil session pointers are expected to have valid users.
type session struct {
// UserSpec is the spec of a valid existing (i.e., non-zero) user.
UserSpec users.UserSpec
Expiry time.Time
AccessToken string // Access token. Needed to be able to clear session when the user signs out.
}
func setAccessTokenCookie(w httputil.HeaderWriter, accessToken string, expiry time.Time) {
// TODO: Is base64 the best encoding for cookie values? Factor it out maybe?
encodedAccessToken := base64.RawURLEncoding.EncodeToString([]byte(accessToken))
httputil.SetCookie(w, &http.Cookie{Path: "/", Name: accessTokenCookieName, Value: encodedAccessToken, Expires: expiry, HttpOnly: false, Secure: *secureCookieFlag})
}
func clearAccessTokenCookie(w httputil.HeaderWriter) {
httputil.SetCookie(w, &http.Cookie{Path: "/", Name: accessTokenCookieName, MaxAge: -1})
}
// cookieAuth is a middleware that parses authentication information
// from request cookies, and sets session as a context value.
type cookieAuth struct {
Handler http.Handler
}
func (mw cookieAuth) ServeHTTP(w http.ResponseWriter, req *http.Request) {
s, extended, err := lookUpSessionViaCookie(req)
if err == errBadAccessToken {
// TODO: Is it okay if we later set the same cookie again? Or should we avoid doing this here?
clearAccessTokenCookie(w)
} else if err == nil && extended {
// TODO: Is it okay if we later set the same cookie again? Or should we avoid doing this here?
setAccessTokenCookie(w, s.AccessToken, s.Expiry)
}
mw.Handler.ServeHTTP(w, withSession(req, s))
}
// headerAuth is a middleware that parses authentication information
// from request headers, and sets session as a context value.
type headerAuth struct {
Handler http.Handler
}
func (mw headerAuth) ServeHTTP(w http.ResponseWriter, req *http.Request) {
s, err := lookUpSessionViaHeader(req)
if err != nil {
http.Error(w, "401 Unauthorized", http.StatusUnauthorized)
return
}
mw.Handler.ServeHTTP(w, withSession(req, s))
}
var errBadAccessToken = errors.New("bad access token")
// lookUpSessionViaCookie retrieves the session from req by looking up
// the request's access token (via accessTokenCookieName cookie) in the sessions map.
// It returns a valid session (possibly nil) and nil error,
// or nil session and errBadAccessToken.
// extended reports whether matched session expiry was extended.
func lookUpSessionViaCookie(req *http.Request) (s *session, extended bool, err error) {
cookie, err := req.Cookie(accessTokenCookieName)
if err == http.ErrNoCookie {
return nil, false, nil // No session.
} else if err != nil {
panic(fmt.Errorf("internal error: Request.Cookie is documented to return only nil or ErrNoCookie error, yet it returned %v", err))
}
accessTokenBytes, err := base64.RawURLEncoding.DecodeString(cookie.Value)
if err != nil {
return nil, false, errBadAccessToken
}
accessToken := string(accessTokenBytes)
global.mu.Lock()
if session, ok := global.sessions[accessToken]; ok {
if time.Now().Before(session.Expiry) {
// Extend expiry if 6 days or less left.
if time.Until(session.Expiry) <= 6*24*time.Hour {
session.Expiry = time.Now().Add(7 * 24 * time.Hour)
global.sessions[accessToken] = session
extended = true
}
s = &session
} else {
delete(global.sessions, accessToken) // This is unlikely to happen because cookie expires by then.
}
}
global.mu.Unlock()
if s == nil {
return nil, false, errBadAccessToken
}
return s, extended, nil // Existing session.
}
// lookUpSessionViaHeader retrieves the session from req by looking up
// the request's access token (via Authorization header) in the sessions map.
// It returns a valid session (possibly nil) and nil error,
// or nil session and errBadAccessToken.
func lookUpSessionViaHeader(req *http.Request) (*session, error) {
authorization, ok := req.Header["Authorization"]
if !ok {
return nil, nil // No session.
}
if len(authorization) != 1 {
return nil, errBadAccessToken
}
if !strings.HasPrefix(authorization[0], "Bearer ") {
return nil, errBadAccessToken
}
encodedAccessToken := authorization[0][len("Bearer "):] // THINK: Should access token be base64 encoded?
accessTokenBytes, err := base64.RawURLEncoding.DecodeString(encodedAccessToken)
if err != nil {
return nil, errBadAccessToken
}
accessToken := string(accessTokenBytes)
var s *session
global.mu.Lock()
if session, ok := global.sessions[accessToken]; ok {
if time.Now().Before(session.Expiry) {
s = &session
} else {
delete(global.sessions, accessToken)
}
}
global.mu.Unlock()
if s == nil {
return nil, errBadAccessToken
}
return s, nil // Existing session.
}
// lookUpSessionViaBasicAuth retrieves the session from req by looking up
// the request's access token (via Basic Auth password) in the sessions map,
// getting the associated user via usersService, and verifying that the
// provided Basic Auth username matches the user login.
// It returns a valid session (possibly nil) and nil error,
// or nil session and errBadAccessToken.
func lookUpSessionViaBasicAuth(req *http.Request, usersService users.Service) (*session, error) {
username, password, ok := req.BasicAuth()
if !ok {
return nil, nil // No session.
}
encodedAccessToken := password
accessTokenBytes, err := base64.RawURLEncoding.DecodeString(encodedAccessToken)
if err != nil {
return nil, errBadAccessToken
}
accessToken := string(accessTokenBytes)
var s *session
global.mu.Lock()
if session, ok := global.sessions[accessToken]; ok {
if time.Now().Before(session.Expiry) {
s = &session
} else {
delete(global.sessions, accessToken)
}
}
global.mu.Unlock()
if s == nil {
return nil, errBadAccessToken
}
// Existing session, now get user and verify the username matches.
user, err := usersService.Get(req.Context(), s.UserSpec)
if err != nil {
log.Println("lookUpSessionUserViaBasicAuth: failed to get user:", err)
return nil, errBadAccessToken
}
if username != user.Login {
return nil, errBadAccessToken
}
return s, nil // Existing session.
}