-
Notifications
You must be signed in to change notification settings - Fork 22
/
auth.go
196 lines (164 loc) · 4.45 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
// Copyright (C) 2023 Gobalsky Labs Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package v1
import (
"crypto/rsa"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"sync"
"time"
vgcrypto "code.vegaprotocol.io/vega/libs/crypto"
vgrand "code.vegaprotocol.io/vega/libs/rand"
"github.com/dgrijalva/jwt-go/v4"
"go.uber.org/zap"
)
const (
LengthForSessionHashSeed = 10
jwtBearer = "Bearer "
)
var ErrSessionNotFound = errors.New("session not found")
type auth struct {
log *zap.Logger
// sessionID -> wallet name
sessions map[string]string
privKey *rsa.PrivateKey
pubKey *rsa.PublicKey
tokenExpiry time.Duration
mu sync.Mutex
}
func NewAuth(log *zap.Logger, cfgStore RSAStore, tokenExpiry time.Duration) (Auth, error) { //revive:disable:unexported-return
keys, err := cfgStore.GetRsaKeys()
if err != nil {
return nil, err
}
priv, err := jwt.ParseRSAPrivateKeyFromPEM(keys.Priv)
if err != nil {
return nil, fmt.Errorf("couldn't parse private RSA key: %w", err)
}
pub, err := jwt.ParseRSAPublicKeyFromPEM(keys.Pub)
if err != nil {
return nil, fmt.Errorf("couldn't parse public RSA key: %w", err)
}
return &auth{
sessions: map[string]string{},
privKey: priv,
pubKey: pub,
log: log,
tokenExpiry: tokenExpiry,
}, nil
}
type Claims struct {
jwt.StandardClaims
Session string
Wallet string
}
func (a *auth) NewSession(walletName string) (string, error) {
a.mu.Lock()
defer a.mu.Unlock()
expiresAt := time.Now().Add(a.tokenExpiry)
session := genSession()
claims := &Claims{
Session: session,
Wallet: walletName,
StandardClaims: jwt.StandardClaims{
// these are seconds
ExpiresAt: jwt.NewTime((float64)(expiresAt.Unix())),
Issuer: "vega wallet",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodPS256, claims)
ss, err := token.SignedString(a.privKey)
if err != nil {
a.log.Error("unable to sign token", zap.Error(err))
return "", err
}
a.sessions[session] = walletName
return ss, nil
}
// VerifyToken returns the wallet name associated for this session.
func (a *auth) VerifyToken(token string) (string, error) {
a.mu.Lock()
defer a.mu.Unlock()
claims, err := a.parseToken(token)
if err != nil {
return "", err
}
walletName, ok := a.sessions[claims.Session]
if !ok {
return "", ErrSessionNotFound
}
return walletName, nil
}
func (a *auth) Revoke(token string) (string, error) {
a.mu.Lock()
defer a.mu.Unlock()
claims, err := a.parseToken(token)
if err != nil {
return "", err
}
w, ok := a.sessions[claims.Session]
if !ok {
return "", ErrSessionNotFound
}
delete(a.sessions, claims.Session)
return w, nil
}
func (a *auth) RevokeAllToken() {
a.mu.Lock()
defer a.mu.Unlock()
a.sessions = map[string]string{}
}
func (a *auth) parseToken(tokenStr string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (interface{}, error) {
return a.pubKey, nil
})
if err != nil {
return nil, fmt.Errorf("couldn't parse JWT token: %w", err)
}
if !token.Valid {
return nil, ErrInvalidToken
}
if claims, ok := token.Claims.(*Claims); ok {
return claims, nil
}
return nil, ErrInvalidClaims
}
func extractToken(r *http.Request) (string, error) {
token := strings.TrimSpace(r.Header.Get("Authorization"))
if !strings.HasPrefix(token, jwtBearer) {
return "", ErrInvalidOrMissingToken
}
return strings.TrimSpace(token[len(jwtBearer):]), nil
}
func genSession() string {
return hex.EncodeToString(vgcrypto.Hash(vgrand.RandomBytes(LengthForSessionHashSeed)))
}
func writeError(w http.ResponseWriter, e error) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
buf, err := json.Marshal(e)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
_, err = w.Write(buf)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}