/
auth.go
271 lines (244 loc) · 5.76 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
package node
import (
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/labstack/echo/v4"
"github.com/icon-project/goloop/common"
"github.com/icon-project/goloop/common/crypto"
"github.com/icon-project/goloop/common/errors"
"github.com/icon-project/goloop/common/log"
)
const (
AuthScheme = "goloop"
)
type Auth struct {
skips map[string]map[string]bool
users map[string]int64
addrs map[string]string
filePath string
prefix string
SkipIfEmptyUsers bool
mtx sync.Mutex
}
func (a *Auth) MiddlewareFunc() echo.MiddlewareFunc {
//middleware.KeyAuth response http.StatusBadRequest when 'missing key' error
//return middleware.KeyAuthWithConfig(middleware.KeyAuthConfig{
// Skipper: a.skipper,
// //KeyLookup: "header:" + echo.HeaderAuthorization, //middleware.DefaultKeyAuthConfig.KeyLookup
// AuthScheme: AuthScheme,
// Validator: a.validator,
//})
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error {
if a.skipper(ctx) {
return next(ctx)
}
key, err := a.extractor(ctx)
if err != nil {
return echo.NewHTTPError(http.StatusUnauthorized, err.Error())
}
valid, err := a.validator(key, ctx)
if err != nil {
return err
} else if valid {
return next(ctx)
}
return echo.ErrUnauthorized
}
}
}
func (a *Auth) SetSkip(r *echo.Route, skip bool) {
m, ok := a.skips[r.Method]
if !ok {
m = make(map[string]bool)
a.skips[r.Method] = m
}
m[r.Path] = skip
}
func (a *Auth) skipper(ctx echo.Context) bool {
if a.SkipIfEmptyUsers && a.IsEmptyUsers() {
return true
}
method := ctx.Request().Method
if m, ok := a.skips[method]; ok {
if skip, has := m[ctx.Path()]; has {
return skip
}
}
return method == http.MethodGet
}
func (a *Auth) extractor(ctx echo.Context) (string, error) {
auth := ctx.Request().Header.Get(echo.HeaderAuthorization)
if auth == "" {
return "", errors.New("missing key in request header")
}
l := len(AuthScheme)
if len(auth) > l+1 && auth[:l] == AuthScheme {
return auth[l+1:], nil
}
return "", errors.New("invalid key in the request header")
}
func parse(s string) map[string]string {
m := make(map[string]string)
if s != "" {
kvs := strings.Split(s, ",")
for _, kv := range kvs {
if kv != "" {
idx := strings.Index(kv, "=")
if idx > 0 {
m[kv[:idx]] = kv[(idx + 1):]
} else {
m[kv] = ""
}
}
}
}
return m
}
func (a *Auth) validator(s string, ctx echo.Context) (b bool, err error) {
log.Traceln("validator:", s)
m := parse(s)
var timestamp int64
if timestamp, err = strconv.ParseInt(m["Timestamp"], 0, 64); err != nil{
return
}
var signature []byte
if signature, err = hex.DecodeString(m["Signature"]); err != nil {
return
}
var sig *crypto.Signature
if sig, err = crypto.ParseSignature(signature); err != nil {
return
}
url := strings.Replace(ctx.Request().URL.EscapedPath(),a.prefix,"",1)
serialized := fmt.Sprintf("Method=%s,Url=%s,Timestamp=%s",
ctx.Request().Method, url, m["Timestamp"])
var pubKey *crypto.PublicKey
if pubKey, err = sig.RecoverPublicKey(crypto.SHA3Sum256([]byte(serialized))); err != nil {
return
}
addr := common.NewAccountAddressFromPublicKey(pubKey).String()
log.Traceln("addr:",addr,"serialized:", serialized)
a.mtx.Lock()
defer a.mtx.Unlock()
if id, ok := a.addrs[addr]; ok {
if ts := a.users[id]; ts < timestamp {
a.users[id] = timestamp
log.Traceln("valid signature", ts, timestamp)
return true, nil
}
log.Traceln("old signature", a.users[id], timestamp)
return false, nil
}
log.Traceln("not found user", addr)
return false, nil
}
func (a *Auth) AddUser(id string) error {
a.mtx.Lock()
defer a.mtx.Unlock()
if _, ok := a.users[id]; ok {
return errors.Wrapf(ErrAlreadyExists, "User(id=%s) already exists", id)
}
addr := &common.Address{}
if err := addr.SetString(id); err != nil {
return errors.Wrap(err, "invalid address format")
}
if _, ok := a.addrs[addr.String()]; ok {
return errors.Wrapf(ErrAlreadyExists, "User(addr=%s) already exists", addr.String())
}
a.users[id] = time.Now().Unix()
a.addrs[addr.String()] = id
if err := a._export(); err != nil {
panic(err)
}
return nil
}
func (a *Auth) RemoveUser(id string) error {
a.mtx.Lock()
defer a.mtx.Unlock()
if _, ok := a.users[id]; !ok {
return errors.Wrapf(ErrNotExists, "User(id=%s) not exists", id)
}
delete(a.users, id)
var addr string
for k, v := range a.addrs {
if v == id {
addr = k
break
}
}
delete(a.addrs, addr)
if err := a._export(); err != nil {
panic(err)
}
return nil
}
func (a *Auth) _users() []string {
users := make([]string, 0)
for user := range a.users {
users = append(users, user)
}
return users
}
func (a *Auth) IsEmptyUsers() bool {
a.mtx.Lock()
defer a.mtx.Unlock()
return len(a.users) == 0
}
func (a *Auth) GetUsers() []string {
a.mtx.Lock()
defer a.mtx.Unlock()
return a._users()
}
func (a *Auth) _export() error {
if a.filePath != "" {
users := a._users()
if b, err := json.Marshal(users); err != nil {
return err
}else {
if err = os.WriteFile(a.filePath, b, 0644); err != nil {
return err
}
}
}
return nil
}
func NewAuth(filePath, prefix string) *Auth {
a := &Auth{
skips: make(map[string]map[string]bool),
users: make(map[string]int64),
addrs: make(map[string]string),
filePath: filePath,
prefix: prefix,
}
if a.filePath != "" {
if _, err := os.Stat(filePath); err != nil {
if os.IsNotExist(err) {
if err = a._export(); err != nil {
panic(err)
}
}
}
if b, err := os.ReadFile(filePath); err != nil {
panic(err)
} else {
var users []string
if err = json.Unmarshal(b, &users); err != nil {
panic(err)
}
for _, user := range users {
if err = a.AddUser(user); err != nil {
panic(err)
}
}
}
}
return a
}