/
passenger.go
390 lines (319 loc) · 10.2 KB
/
passenger.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
// Package passenger revolves around the User associated with the
// request in flight.
//
// It establishes this link via the HTTP authorization header,
// which can be used to authenticate with basic authorization or
// token based authorization.
package passenger
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/subtle"
"encoding/binary"
"encoding/gob"
"encoding/hex"
"errors"
"fmt"
mathrand "math/rand"
"net/http"
"strings"
"time"
"google.golang.org/appengine/datastore"
"google.golang.org/appengine/memcache"
"github.com/coduno/api/model"
"github.com/coduno/api/util/password"
"golang.org/x/crypto/bcrypt"
"golang.org/x/net/context"
// Indirect import of SHA2, will be called by crypto.Hash.New()
_ "crypto/sha256"
_ "crypto/sha512"
// Indirect import of SHA3, will be called by crypto.Hash.New()
_ "golang.org/x/crypto/sha3"
)
const maxValidity = time.Hour * 24 * 365 * 2
const minValidity = time.Minute * 30
const defaultValidity = time.Hour * 24 * 14
const defaultHash = crypto.SHA3_256
const tokenLength = 8
var kinds = [2]string{model.UserKind, model.TokenKind}
var endianness = binary.LittleEndian
type key int64
var passengerKey key
// ErrNoAuthHeader signals that the request did not carry an Authorization
// header.
var ErrNoAuthHeader = errors.New("passenger: no authorization header present")
// ErrUnkAuthHeader is returned if the request contained an Authorization
// header, but it could not be parsed. The two accepted authorization
// methods are "Basic" and "Token".
var ErrUnkAuthHeader = errors.New("passenger: cannot interpret authorization header")
// ErrDigestMismatch is returned if the token provided by the user did not
// result in the same digest value after hashing as the one stored on the
// server.
var ErrDigestMismatch = errors.New("passenger: digest mismatch")
// ErrTokenNotAssociated can be returned if this package encounters invalid
// data during authentication. A Token must be child of a User.
var ErrTokenNotAssociated = errors.New("passenger: token not associated to any user")
// ErrTokenExpired is returned if the token is not valid anymore.
var ErrTokenExpired = errors.New("passenger: token expired")
// ErrTokenNotMatchingUser is returned if basic auth with token password
// was attempted, and the token could be found but does not match the user.
type ErrTokenNotMatchingUser struct {
Parent, Actual *datastore.Key
}
func (e ErrTokenNotMatchingUser) Error() string {
return fmt.Sprintf("passenger: parent of token %+v does not match with actual user %+v", e.Parent, e.Actual)
}
func init() {
passengerKey = key(mathrand.Int63())
}
// Passenger holds the currently authenticated user
// together with the token (if relevant).
type Passenger struct {
User *datastore.Key
Token *model.Token
}
// HasScope can be used to check whether this Passenger was
// granted access to a given scope.
// Note that a user authenticated via username and password
// (not via token) will have access to all scopes by
// default.
func (p *Passenger) HasScope(scope string) (has bool) {
for _, grantedScope := range p.Token.Scopes {
if scope == grantedScope {
return true
}
}
return
}
// Save will persist the passenger to Datastore and send it to Memcache.
func (p *Passenger) Save(ctx context.Context) (*datastore.Key, error) {
now := time.Now()
key, err := p.Token.PutWithParent(ctx, p.User)
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
if err = gob.NewEncoder(buf).Encode(p); err != nil {
return nil, err
}
item := &memcache.Item{
Key: key.Encode(),
Value: buf.Bytes(),
Expiration: p.Token.Expiry.Sub(now) + 10*time.Second,
}
if err = memcache.Set(ctx, item); err != nil {
return nil, err
}
return key, nil
}
func (p *Passenger) check(raw []byte) error {
digest := crypto.Hash(p.Token.Hash).New().Sum(raw)
if subtle.ConstantTimeCompare(digest, p.Token.Digest) != 1 {
return ErrDigestMismatch
}
if p.Token.Expiry.Before(time.Now()) {
return ErrTokenExpired
}
return nil
}
// IssueToken creates a new Token for the authenticated user. Callers should
// prefill the Token with whatever values they like and leave zero values
// to be set.
// The generated token will also be persisted and can be handed to the client
// with no more handling.
func (p *Passenger) IssueToken(ctx context.Context, token *model.Token) (string, error) {
now := time.Now()
token.Creation = now
if token.Expiry == (time.Time{}) {
token.Expiry = now.Add(defaultValidity)
} else {
if token.Expiry.Before(now.Add(minValidity)) {
return "", fmt.Errorf("passenger: token must be valid at least %s", minValidity)
}
if token.Expiry.After(now.Add(maxValidity)) {
return "", fmt.Errorf("passenger: token must be valid at most %s", maxValidity)
}
}
// TODO(flowlo): This will reject all scopes for now, as we are not using them.
// As soon as we introduce scopes, this check must be rewritten accordingly.
if len(token.Scopes) > 0 {
return "", fmt.Errorf("passenger: unknown scopes: %s", strings.Join(token.Scopes, ", "))
}
if len(token.Description) > 512 || len(token.Description) < 4 {
return "", fmt.Errorf("passenger: description has bad len %d", len(token.Description))
}
var raw [tokenLength]byte
if _, err := rand.Read(raw[:]); err != nil {
return "", err
}
if token.Hash == 0 {
token.Hash = int(defaultHash)
}
token.Digest = crypto.Hash(token.Hash).New().Sum(raw[:])
// TODO(flowlo): Set token.RemoteAddr.
clone := Passenger{
User: p.User,
Token: token,
}
key, err := clone.Save(ctx)
if err != nil {
return "", err
}
return encodeToken(key, &raw)
}
// FromToken tries do identify a Passenger by the token he gave us.
// It will look up the Token and consequently the corresponding User.
func FromToken(ctx context.Context, Token string) (*Passenger, error) {
key, raw, err := decodeToken(ctx, Token)
if err != nil {
return nil, err
}
var p *Passenger
if p, err = fromCache(ctx, key); err != nil {
if p, err = fromDatastore(ctx, key); err != nil {
return nil, err
}
}
return p, p.check(raw)
}
func fromCache(ctx context.Context, key *datastore.Key) (*Passenger, error) {
item, err := memcache.Get(ctx, key.Encode())
if err != nil {
return nil, err
}
p := new(Passenger)
if err := gob.NewDecoder(bytes.NewReader(item.Value)).Decode(&p); err != nil {
return nil, err
}
return p, nil
}
func fromDatastore(ctx context.Context, key *datastore.Key) (*Passenger, error) {
p := &Passenger{
Token: &model.Token{},
}
if err := datastore.Get(ctx, key, p.Token); err != nil {
return nil, err
}
if p.User = key.Parent(); p.User == nil {
return nil, ErrTokenNotAssociated
}
return p, nil
}
// FromBasicAuth tries do identify a Passenger by the token he gave us.
// It will look up the the user by username and try to match password.
func FromBasicAuth(ctx context.Context, username, pw string) (p *Passenger, err error) {
p = new(Passenger)
var user model.User
p.User, err = model.NewQueryForUser().
Filter("Nick =", username).
Limit(1).
Run(ctx).
Next(&user)
if err != nil {
return nil, err
}
err = password.Check([]byte(pw), user.HashedPassword)
// TODO(flowlo): Depending on bcrypt is very fragile. We
// should encapsulate that.
if err == bcrypt.ErrMismatchedHashAndPassword {
userKey := p.User
p, err = FromToken(ctx, pw)
if err != nil {
return
}
if !p.User.Equal(userKey) {
return nil, ErrTokenNotMatchingUser{Parent: p.User, Actual: userKey}
}
}
return
}
// FromRequest inspects the HTTP Authorization header of the given request
// and tries to identify a passenger.
func FromRequest(ctx context.Context, r *http.Request) (*Passenger, error) {
cookie, err := r.Cookie("token")
if err != nil && err != http.ErrNoCookie {
return nil, err
}
if err == nil {
if p, err := FromToken(ctx, cookie.Value); err == nil {
return p, err
}
}
auth := ""
if auth = r.Header.Get("Authorization"); auth == "" {
return nil, ErrNoAuthHeader
}
if strings.HasPrefix(auth, "Token ") {
return FromToken(ctx, auth[6:])
}
username, password, ok := "", "", false
if username, password, ok = r.BasicAuth(); !ok {
return nil, ErrUnkAuthHeader
}
return FromBasicAuth(ctx, username, password)
}
// FromContext returns the Passenger value stored in ctx if any.
func FromContext(ctx context.Context) (p *Passenger, ok bool) {
p, ok = ctx.Value(passengerKey).(*Passenger)
return
}
// NewContext returns a new Context that carries value p.
func NewContext(ctx context.Context, p *Passenger) context.Context {
return context.WithValue(ctx, passengerKey, p)
}
// NewContextFromRequest wraps FromRequest and NewContext.
func NewContextFromRequest(ctx context.Context, r *http.Request) (context.Context, error) {
p, err := FromRequest(ctx, r)
if err != nil {
return ctx, err
}
return NewContext(ctx, p), nil
}
// DecodeToken will take a token as sent by a client and translate it into a
// key to look up the full token on the server side and the raw secret.
func decodeToken(ctx context.Context, token string) (*datastore.Key, []byte, error) {
b, err := hex.DecodeString(token)
if err != nil {
return nil, nil, err
}
if len(b) != len(kinds)*8+tokenLength {
return nil, nil, errors.New("token length mismatch")
}
var intIDs [len(kinds)]int64
for i := range intIDs {
intID, n := binary.Varint(b[i*8 : (i+1)*8])
if n < 8 {
return nil, nil, errors.New("varint read mismatch")
}
intIDs[len(intIDs)-1-i] = intID
}
var key *datastore.Key
for i := range intIDs {
if intIDs[i] == 0 {
continue
}
key = datastore.NewKey(ctx, kinds[i], "", intIDs[i], key)
if key == nil {
return nil, nil, errors.New("could not construct key from token")
}
}
return key, b[len(kinds)*8:], nil
}
// EncodeToken translates the key and raw secret of a newly generated token to
// a form suitable for the client.
func encodeToken(key *datastore.Key, raw *[tokenLength]byte) (string, error) {
// Buffer size will be 8 (size of an int64) times the number of keys
// in the hirarchy plus the length of the raw token itself.
var b [len(kinds)*8 + tokenLength]byte
for i := range kinds {
if n := binary.PutVarint(b[i*8:(i+1)*8], key.IntID()); n < 8 {
return "", errors.New("short write when encoding token")
}
if key != nil {
key = key.Parent()
}
}
copy(b[len(kinds)*8:len(kinds)*8+tokenLength], raw[:])
return hex.EncodeToString(b[:]), nil
}