forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 4
/
auth.go
306 lines (257 loc) · 8.21 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
299
300
301
302
303
304
305
306
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package auth
import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net/http"
"path"
"strings"
"sync"
"time"
"github.com/golang-jwt/jwt"
"github.com/gorilla/rpc/v2"
"github.com/MetalBlockchain/metalgo/utils/json"
"github.com/MetalBlockchain/metalgo/utils/logging"
"github.com/MetalBlockchain/metalgo/utils/password"
"github.com/MetalBlockchain/metalgo/utils/timer/mockable"
)
const (
headerKey = "Authorization"
headerValStart = "Bearer "
// number of bytes to use when generating a new random token ID
tokenIDByteLen = 20
// defaultTokenLifespan is how long a token lives before it expires
defaultTokenLifespan = time.Hour * 12
maxEndpoints = 128
)
var (
errNoToken = errors.New("auth token not provided")
errAuthHeaderNotParsable = fmt.Errorf(
"couldn't parse auth token. Header \"%s\" should be \"%sTOKEN.GOES.HERE\"",
headerKey,
headerValStart,
)
errInvalidSigningMethod = errors.New("auth token didn't specify the HS256 signing method correctly")
errTokenRevoked = errors.New("the provided auth token was revoked")
errTokenInsufficientPermission = errors.New("the provided auth token does not allow access to this endpoint")
errWrongPassword = errors.New("incorrect password")
errSamePassword = errors.New("new password can't be same as old password")
errNoPassword = errors.New("no password")
errNoEndpoints = errors.New("must name at least one endpoint")
errTooManyEndpoints = fmt.Errorf("can only name at most %d endpoints", maxEndpoints)
_ Auth = &auth{}
)
type Auth interface {
// Create and return a new token that allows access to each API endpoint for
// [duration] such that the API's path ends with an element of [endpoints].
// If one of the elements of [endpoints] is "*", all APIs are accessible.
NewToken(pw string, duration time.Duration, endpoints []string) (string, error)
// Revokes [token]; it will not be accepted as authorization for future API
// calls. If the token is invalid, this is a no-op. If a token is revoked
// and then the password is changed, and then changed back to the current
// password, the token will be un-revoked. Therefore, passwords shouldn't be
// re-used before previously revoked tokens have expired.
RevokeToken(pw, token string) error
// Authenticates [token] for access to [url].
AuthenticateToken(token, url string) error
// Change the password required to create and revoke tokens.
// [oldPW] is the current password.
// [newPW] is the new password. It can't be the empty string and it can't be
// unreasonably long.
// Changing the password makes tokens issued under a previous password
// invalid.
ChangePassword(oldPW, newPW string) error
// Create the API endpoint for this auth handler.
CreateHandler() (http.Handler, error)
// WrapHandler wraps an http.Handler. Before passing a request to the
// provided handler, the auth token is authenticated.
WrapHandler(h http.Handler) http.Handler
}
type auth struct {
// Used to mock time.
clock mockable.Clock
log logging.Logger
endpoint string
lock sync.RWMutex
// Can be changed via API call.
password password.Hash
// Set of token IDs that have been revoked
revoked map[string]struct{}
}
func New(log logging.Logger, endpoint, pw string) (Auth, error) {
a := &auth{
log: log,
endpoint: endpoint,
revoked: make(map[string]struct{}),
}
return a, a.password.Set(pw)
}
func NewFromHash(log logging.Logger, endpoint string, pw password.Hash) Auth {
return &auth{
log: log,
endpoint: endpoint,
password: pw,
revoked: make(map[string]struct{}),
}
}
func (a *auth) NewToken(pw string, duration time.Duration, endpoints []string) (string, error) {
if pw == "" {
return "", errNoPassword
}
if l := len(endpoints); l == 0 {
return "", errNoEndpoints
} else if l > maxEndpoints {
return "", errTooManyEndpoints
}
a.lock.RLock()
defer a.lock.RUnlock()
if !a.password.Check(pw) {
return "", errWrongPassword
}
canAccessAll := false
for _, endpoint := range endpoints {
if endpoint == "*" {
canAccessAll = true
break
}
}
idBytes := [tokenIDByteLen]byte{}
if _, err := rand.Read(idBytes[:]); err != nil {
return "", fmt.Errorf("failed to generate the unique token ID due to %w", err)
}
id := base64.URLEncoding.EncodeToString(idBytes[:])
claims := endpointClaims{
StandardClaims: jwt.StandardClaims{
ExpiresAt: a.clock.Time().Add(duration).Unix(),
Id: id,
},
}
if canAccessAll {
claims.Endpoints = []string{"*"}
} else {
claims.Endpoints = endpoints
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, &claims)
return token.SignedString(a.password.Password[:]) // Sign the token and return its string repr.
}
func (a *auth) RevokeToken(tokenStr, pw string) error {
if tokenStr == "" {
return errNoToken
}
if pw == "" {
return errNoPassword
}
a.lock.Lock()
defer a.lock.Unlock()
if !a.password.Check(pw) {
return errWrongPassword
}
// See if token is well-formed and signature is right
token, err := jwt.ParseWithClaims(tokenStr, &endpointClaims{}, a.getTokenKey)
if err != nil {
return err
}
// If the token isn't valid, it has essentially already been revoked.
if !token.Valid {
return nil
}
claims, ok := token.Claims.(*endpointClaims)
if !ok {
return fmt.Errorf("expected auth token's claims to be type endpointClaims but is %T", token.Claims)
}
a.revoked[claims.Id] = struct{}{}
return nil
}
func (a *auth) AuthenticateToken(tokenStr, url string) error {
a.lock.RLock()
defer a.lock.RUnlock()
token, err := jwt.ParseWithClaims(tokenStr, &endpointClaims{}, a.getTokenKey)
if err != nil { // Probably because signature wrong
return err
}
// Make sure this token gives access to the requested endpoint
claims, ok := token.Claims.(*endpointClaims)
if !ok {
// Error is intentionally dropped here as there is nothing left to do
// with it.
return fmt.Errorf("expected auth token's claims to be type endpointClaims but is %T", token.Claims)
}
_, revoked := a.revoked[claims.Id]
if revoked {
return errTokenRevoked
}
for _, endpoint := range claims.Endpoints {
if endpoint == "*" || strings.HasSuffix(url, endpoint) {
return nil
}
}
return errTokenInsufficientPermission
}
func (a *auth) ChangePassword(oldPW, newPW string) error {
if oldPW == newPW {
return errSamePassword
}
a.lock.Lock()
defer a.lock.Unlock()
if !a.password.Check(oldPW) {
return errWrongPassword
}
if err := password.IsValid(newPW, password.OK); err != nil {
return err
}
if err := a.password.Set(newPW); err != nil {
return err
}
// All the revoked tokens are now invalid; no need to mark specifically as
// revoked.
a.revoked = make(map[string]struct{})
return nil
}
func (a *auth) CreateHandler() (http.Handler, error) {
server := rpc.NewServer()
codec := json.NewCodec()
server.RegisterCodec(codec, "application/json")
server.RegisterCodec(codec, "application/json;charset=UTF-8")
return server, server.RegisterService(
&Service{auth: a},
"auth",
)
}
func (a *auth) WrapHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Don't require auth token to hit auth endpoint
if path.Base(r.URL.Path) == a.endpoint {
h.ServeHTTP(w, r)
return
}
// Should be "Bearer AUTH.TOKEN.HERE"
rawHeader := r.Header.Get(headerKey)
if rawHeader == "" {
writeUnauthorizedResponse(w, errNoToken)
return
}
if !strings.HasPrefix(rawHeader, headerValStart) {
// Error is intentionally dropped here as there is nothing left to
// do with it.
writeUnauthorizedResponse(w, errAuthHeaderNotParsable)
return
}
// Returns actual auth token. Slice guaranteed to not go OOB
tokenStr := rawHeader[len(headerValStart):]
if err := a.AuthenticateToken(tokenStr, r.URL.Path); err != nil {
writeUnauthorizedResponse(w, err)
return
}
h.ServeHTTP(w, r)
})
}
// getTokenKey returns the key to use when making and parsing tokens
func (a *auth) getTokenKey(t *jwt.Token) (interface{}, error) {
if t.Method != jwt.SigningMethodHS256 {
return nil, errInvalidSigningMethod
}
return a.password.Password[:], nil
}