-
Notifications
You must be signed in to change notification settings - Fork 36
/
auth_handler.go
621 lines (549 loc) · 20.7 KB
/
auth_handler.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
package gater
import (
"context"
"encoding/xml"
"io"
"net/http"
"regexp"
"strings"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
commonhash "github.com/bnb-chain/greenfield-common/go/hash"
commonhttp "github.com/bnb-chain/greenfield-common/go/http"
"github.com/bnb-chain/greenfield-storage-provider/base/types/gfsperrors"
modelgateway "github.com/bnb-chain/greenfield-storage-provider/model/gateway"
"github.com/bnb-chain/greenfield-storage-provider/pkg/log"
"github.com/bnb-chain/greenfield-storage-provider/pkg/metrics"
"github.com/bnb-chain/greenfield-storage-provider/util"
)
const (
MaxExpiryAgeInSec int32 = commonhttp.MaxExpiryAgeInSec // 7 days
ExpiryDateFormat string = time.RFC3339
ExpectedEddsaPubKeyLength int = 64
SignedContentV2Pattern = `(.+) wants you to sign in with your BNB Greenfield account:\n*(.+)\n*Register your identity public key (.+)\n*URI: (.+)\n*Version: (.+)\n*Chain ID: (.+)\n*Issued At: (.+)\n*Expiration Time: (.+)`
)
type RequestNonceResp struct {
CurrentNonce int32 `xml:"CurrentNonce"`
NextNonce int32 `xml:"NextNonce"`
CurrentPublicKey string `xml:"CurrentPublicKey"`
ExpiryDate int64 `xml:"ExpiryDate"`
}
type UpdateUserPublicKeyResp struct {
Result bool `xml:"Result"`
}
type DeleteUserPublicKeyV2Resp struct {
Result bool `xml:"Result"`
}
type ListUserPublicKeyV2Resp struct {
PublicKeys []string `xml:"Result"`
}
// requestNonceHandler handle requestNonce request
func (g *GateModular) requestNonceHandler(w http.ResponseWriter, r *http.Request) {
var (
err error
b []byte
reqCtx *RequestContext
)
startTime := time.Now()
defer func() {
reqCtx.Cancel()
if err != nil {
reqCtx.SetError(gfsperrors.MakeGfSpError(err))
log.CtxErrorw(reqCtx.Context(), "failed to request nonce", "req_info", reqCtx.String())
modelgateway.MakeErrorResponse(w, gfsperrors.MakeGfSpError(err))
metrics.ReqCounter.WithLabelValues(GatewayTotalFailure).Inc()
metrics.ReqTime.WithLabelValues(GatewayTotalFailure).Observe(time.Since(startTime).Seconds())
} else {
metrics.ReqCounter.WithLabelValues(GatewayTotalSuccess).Inc()
metrics.ReqTime.WithLabelValues(GatewayTotalSuccess).Observe(time.Since(startTime).Seconds())
}
}()
// ignore the error, because the requestNonce does not need signature
reqCtx, _ = NewRequestContext(r, g)
account := reqCtx.request.Header.Get(GnfdUserAddressHeader)
domain := reqCtx.request.Header.Get(GnfdOffChainAuthAppDomainHeader)
// validate account header
if ok := common.IsHexAddress(account); !ok {
err = ErrInvalidHeader
log.Errorw("failed to check account address", "account_address", account, "error", err)
return
}
// validate domain header
if domain == "" {
log.CtxErrorw(reqCtx.Context(), "failed to check GnfdOffChainAuthAppDomainHeader header")
err = ErrInvalidDomainHeader
return
}
ctx := log.Context(context.Background(), account, domain)
currentNonce, nextNonce, currentPublicKey, expiryDate, err := g.baseApp.GfSpClient().GetAuthNonce(ctx, account, domain)
if err != nil {
log.CtxErrorw(reqCtx.Context(), "failed to get auth nonce", "error", err)
return
}
var resp = &RequestNonceResp{
CurrentNonce: currentNonce,
NextNonce: nextNonce,
CurrentPublicKey: currentPublicKey,
ExpiryDate: expiryDate,
}
b, err = xml.Marshal(resp)
if err != nil {
log.CtxErrorw(reqCtx.Context(), "failed to unmarshal get auth nonce response", "error", err)
err = ErrDecodeMsg
return
}
w.Header().Set(ContentTypeHeader, ContentTypeXMLHeaderValue)
w.Write(b)
}
func (g *GateModular) updateUserPublicKeyHandler(w http.ResponseWriter, r *http.Request) {
var (
err error
b []byte
reqCtx *RequestContext
account string
userPublicKey string
domain string
origin string
nonce string
expiryDateStr string
)
startTime := time.Now()
defer func() {
reqCtx.Cancel()
if err != nil {
reqCtx.SetError(gfsperrors.MakeGfSpError(err))
log.CtxErrorw(reqCtx.Context(), "failed to updateUserPublicKey", "req_info", reqCtx.String())
modelgateway.MakeErrorResponse(w, gfsperrors.MakeGfSpError(err))
metrics.ReqCounter.WithLabelValues(GatewayTotalFailure).Inc()
metrics.ReqTime.WithLabelValues(GatewayTotalFailure).Observe(time.Since(startTime).Seconds())
} else {
metrics.ReqCounter.WithLabelValues(GatewayTotalSuccess).Inc()
metrics.ReqTime.WithLabelValues(GatewayTotalSuccess).Observe(time.Since(startTime).Seconds())
}
}()
reqCtx, _ = NewRequestContext(r, g)
// verify personal sign signature
personalSignSignaturePrefix := commonhttp.Gnfd1EthPersonalSign + ","
requestSignature := reqCtx.request.Header.Get(GnfdAuthorizationHeader)
if !strings.HasPrefix(requestSignature, personalSignSignaturePrefix) {
err = ErrUnsupportedSignType
return
}
signedMsg, sigString, err := parseSignedMsgAndSigFromRequest(strings.TrimPrefix(requestSignature, personalSignSignaturePrefix))
if err != nil {
return
}
accAddress, personalSignVerifyErr := VerifyPersonalSignature(*signedMsg, *sigString)
if personalSignVerifyErr != nil {
log.CtxErrorw(reqCtx.Context(), "failed to verify signature", "error", personalSignVerifyErr)
err = personalSignVerifyErr
return
}
account = accAddress.String()
reqCtx.account = account
domain = reqCtx.request.Header.Get(GnfdOffChainAuthAppDomainHeader)
origin = reqCtx.request.Header.Get("Origin")
nonce = reqCtx.request.Header.Get(GnfdOffChainAuthAppRegNonceHeader)
userPublicKey = reqCtx.request.Header.Get(GnfdOffChainAuthAppRegPublicKeyHeader)
expiryDateStr = reqCtx.request.Header.Get(GnfdOffChainAuthAppRegExpiryDateHeader)
// validate headers
if domain == "" || domain != origin {
log.CtxErrorw(reqCtx.Context(), "failed to updateUserPublicKey due to bad origin or domain")
err = ErrInvalidDomainHeader
return
}
if userPublicKey == "" || len(userPublicKey) != ExpectedEddsaPubKeyLength {
log.CtxErrorw(reqCtx.Context(), "failed to updateUserPublicKey due to bad userPublicKey")
err = ErrInvalidPublicKeyHeader
return
}
ctx := log.Context(context.Background(), account, domain)
currentNonce, nextNonce, _, _, err := g.baseApp.GfSpClient().GetAuthNonce(ctx, account, domain)
if err != nil {
log.CtxErrorw(reqCtx.Context(), "failed to GetAuthNonce", "error", err)
return
}
nonceInt, err := util.StringToInt32(nonce)
if err != nil || nextNonce != nonceInt { // nonce must be the same as NextNonce
log.CtxErrorw(reqCtx.Context(), "failed to updateUserPublicKey due to bad nonce")
err = ErrInvalidRegNonceHeader
return
}
expiryDate, err := time.Parse(ExpiryDateFormat, expiryDateStr)
if err != nil {
log.CtxErrorw(reqCtx.Context(), "failed to updateUserPublicKey due to InvalidExpiryDateHeader")
err = ErrInvalidExpiryDateHeader
return
}
expiryAge := int32(time.Until(expiryDate).Seconds())
if MaxExpiryAgeInSec < expiryAge || expiryAge < 0 {
err = ErrInvalidExpiryDateHeader
log.CtxErrorw(reqCtx.Context(), "failed to updateUserPublicKey due to InvalidExpiryDateHeader")
return
}
err = g.verifySignedContent(*signedMsg, domain, nonce, userPublicKey, expiryDateStr)
if err != nil {
log.CtxErrorw(reqCtx.Context(), "failed to updateUserPublicKey due to bad signed content.")
return
}
updateUserPublicKeyResp, err := g.baseApp.GfSpClient().UpdateUserPublicKey(ctx, account, domain, currentNonce, nonceInt, userPublicKey, expiryDate.UnixMilli())
if err != nil {
log.Errorw("failed to updateUserPublicKey when saving key")
return
}
var resp = &UpdateUserPublicKeyResp{
Result: updateUserPublicKeyResp,
}
b, err = xml.Marshal(resp)
if err != nil {
log.CtxErrorw(reqCtx.Context(), "failed to unmarshal update user public key response", "error", err)
err = ErrDecodeMsg
return
}
w.Header().Set(ContentTypeHeader, ContentTypeXMLHeaderValue)
w.Write(b)
}
// updateUserPublicKeyV2Handler register users' EdDSA public key into off_chain_auth_key_v2 table
func (g *GateModular) updateUserPublicKeyV2Handler(w http.ResponseWriter, r *http.Request) {
var (
err error
b []byte
reqCtx *RequestContext
account string
userPublicKey string
domain string
origin string
expiryDateStr string
)
startTime := time.Now()
defer func() {
reqCtx.Cancel()
if err != nil {
reqCtx.SetError(gfsperrors.MakeGfSpError(err))
log.CtxErrorw(reqCtx.Context(), "failed to updateUserPublicKeyV2", "req_info", reqCtx.String())
modelgateway.MakeErrorResponse(w, gfsperrors.MakeGfSpError(err))
metrics.ReqCounter.WithLabelValues(GatewayTotalFailure).Inc()
metrics.ReqTime.WithLabelValues(GatewayTotalFailure).Observe(time.Since(startTime).Seconds())
} else {
metrics.ReqCounter.WithLabelValues(GatewayTotalSuccess).Inc()
metrics.ReqTime.WithLabelValues(GatewayTotalSuccess).Observe(time.Since(startTime).Seconds())
}
}()
reqCtx, _ = NewRequestContext(r, g)
// verify personal sign signature
personalSignSignaturePrefix := commonhttp.Gnfd1EthPersonalSign + ","
requestSignature := reqCtx.request.Header.Get(GnfdAuthorizationHeader)
if !strings.HasPrefix(requestSignature, personalSignSignaturePrefix) {
err = ErrUnsupportedSignType
return
}
signedMsg, sigString, err := parseSignedMsgAndSigFromRequest(strings.TrimPrefix(requestSignature, personalSignSignaturePrefix))
if err != nil {
return
}
accAddress, personalSignVerifyErr := VerifyPersonalSignature(*signedMsg, *sigString)
if personalSignVerifyErr != nil {
log.CtxErrorw(reqCtx.Context(), "failed to verify signature", "error", personalSignVerifyErr)
err = personalSignVerifyErr
return
}
account = accAddress.String()
reqCtx.account = account
domain = reqCtx.request.Header.Get(GnfdOffChainAuthAppDomainHeader)
origin = reqCtx.request.Header.Get("Origin")
userPublicKey = reqCtx.request.Header.Get(GnfdOffChainAuthAppRegPublicKeyHeader)
expiryDateStr = reqCtx.request.Header.Get(GnfdOffChainAuthAppRegExpiryDateHeader)
// validate headers
if domain == "" || domain != origin {
log.CtxErrorw(reqCtx.Context(), "failed to updateUserPublicKeyV2 due to bad origin or domain")
err = ErrInvalidDomainHeader
return
}
if userPublicKey == "" || len(userPublicKey) != ExpectedEddsaPubKeyLength {
log.CtxErrorw(reqCtx.Context(), "failed to updateUserPublicKeyV2 due to bad userPublicKey")
err = ErrInvalidPublicKeyHeader
return
}
expiryDate, err := time.Parse(ExpiryDateFormat, expiryDateStr)
if err != nil {
log.CtxErrorw(reqCtx.Context(), "failed to updateUserPublicKeyV2 due to InvalidExpiryDateHeader")
err = ErrInvalidExpiryDateHeader
return
}
expiryAge := int32(time.Until(expiryDate).Seconds())
if MaxExpiryAgeInSec < expiryAge || expiryAge < 0 {
err = ErrInvalidExpiryDateHeader
log.CtxErrorw(reqCtx.Context(), "failed to updateUserPublicKeyV2 due to InvalidExpiryDateHeader")
return
}
err = g.verifySignedContentV2(*signedMsg, domain, userPublicKey, expiryDateStr)
if err != nil {
log.CtxErrorw(reqCtx.Context(), "failed to updateUserPublicKeyV2 due to bad signed content.")
return
}
updateUserPublicKeyResp, err := g.baseApp.GfSpClient().UpdateUserPublicKeyV2(reqCtx.ctx, account, domain, userPublicKey, expiryDate.UnixMilli())
if err != nil {
log.Errorw("failed to updateUserPublicKeyV2 when saving key")
return
}
var resp = &UpdateUserPublicKeyResp{
Result: updateUserPublicKeyResp,
}
b, err = xml.Marshal(resp)
if err != nil {
log.CtxErrorw(reqCtx.Context(), "failed to unmarshal update user public key response", "error", err)
err = ErrDecodeMsg
return
}
w.Header().Set(ContentTypeHeader, ContentTypeXMLHeaderValue)
w.Write(b)
}
// listUserPublicKeyV2Handler list user public keys from off_chain_auth_key_v2 table
func (g *GateModular) listUserPublicKeyV2Handler(w http.ResponseWriter, r *http.Request) {
var (
err error
b []byte
reqCtx *RequestContext
)
startTime := time.Now()
defer func() {
reqCtx.Cancel()
if err != nil {
reqCtx.SetError(gfsperrors.MakeGfSpError(err))
log.CtxErrorw(reqCtx.Context(), "failed to listUserPublicKeyV2", "req_info", reqCtx.String())
modelgateway.MakeErrorResponse(w, gfsperrors.MakeGfSpError(err))
metrics.ReqCounter.WithLabelValues(GatewayTotalFailure).Inc()
metrics.ReqTime.WithLabelValues(GatewayTotalFailure).Observe(time.Since(startTime).Seconds())
} else {
metrics.ReqCounter.WithLabelValues(GatewayTotalSuccess).Inc()
metrics.ReqTime.WithLabelValues(GatewayTotalSuccess).Observe(time.Since(startTime).Seconds())
}
}()
// ignore the error, because the listUserPublicKeyV2 does not need signature
reqCtx, _ = NewRequestContext(r, g)
account := reqCtx.request.Header.Get(GnfdUserAddressHeader)
domain := reqCtx.request.Header.Get(GnfdOffChainAuthAppDomainHeader)
// validate account header
if ok := common.IsHexAddress(account); !ok {
err = ErrInvalidHeader
log.Errorw("failed to check account address", "account_address", account, "error", err)
return
}
// validate domain header
if domain == "" {
log.CtxErrorw(reqCtx.Context(), "failed to check GnfdOffChainAuthAppDomainHeader header")
err = ErrInvalidDomainHeader
return
}
userPublicKeys, err := g.baseApp.GfSpClient().ListAuthKeysV2(reqCtx.ctx, account, domain)
if err != nil {
log.CtxErrorw(reqCtx.Context(), "failed to listUserPublicKeyV2", "error", err)
return
}
var resp = &ListUserPublicKeyV2Resp{
PublicKeys: userPublicKeys,
}
b, err = xml.Marshal(resp)
if err != nil {
log.CtxErrorw(reqCtx.Context(), "failed to unmarshal listUserPublicKeyV2 response", "error", err)
err = ErrDecodeMsg
return
}
w.Header().Set(ContentTypeHeader, ContentTypeXMLHeaderValue)
w.Write(b)
}
func (g *GateModular) deleteUserPublicKeyV2Handler(w http.ResponseWriter, r *http.Request) {
var (
err error
b []byte
reqCtx *RequestContext
)
startTime := time.Now()
defer func() {
reqCtx.Cancel()
if err != nil {
reqCtx.SetError(gfsperrors.MakeGfSpError(err))
log.CtxErrorw(reqCtx.Context(), "failed to deleteUserPublicKeyV2", "req_info", reqCtx.String())
modelgateway.MakeErrorResponse(w, gfsperrors.MakeGfSpError(err))
metrics.ReqCounter.WithLabelValues(GatewayTotalFailure).Inc()
metrics.ReqTime.WithLabelValues(GatewayTotalFailure).Observe(time.Since(startTime).Seconds())
} else {
metrics.ReqCounter.WithLabelValues(GatewayTotalSuccess).Inc()
metrics.ReqTime.WithLabelValues(GatewayTotalSuccess).Observe(time.Since(startTime).Seconds())
}
}()
// deleteUserPublicKeyV2Handler requires the authentication
reqCtx, err = NewRequestContext(r, g)
if err != nil {
return
}
account := reqCtx.request.Header.Get(GnfdUserAddressHeader)
domain := reqCtx.request.Header.Get(GnfdOffChainAuthAppDomainHeader)
// validate account header
if ok := common.IsHexAddress(account); !ok {
err = ErrInvalidHeader
log.Errorw("failed to check account address", "account_address", account, "error", err)
return
}
if account != reqCtx.account {
err = ErrNoPermission
}
data, err := io.ReadAll(r.Body)
if err != nil {
log.CtxErrorw(reqCtx.Context(), "failed to read publicKeys from request body", "error", err)
err = ErrExceptionStream
return
}
publicKeys := strings.Split(string(data), ",")
// validate domain header
if domain == "" {
log.CtxErrorw(reqCtx.Context(), "failed to check GnfdOffChainAuthAppDomainHeader header")
err = ErrInvalidDomainHeader
return
}
result, err := g.baseApp.GfSpClient().DeleteAuthKeysV2(reqCtx.ctx, account, domain, publicKeys)
if err != nil {
log.CtxErrorw(reqCtx.Context(), "failed to deleteUserPublicKeyV2", "error", err)
return
}
var resp = &DeleteUserPublicKeyV2Resp{
Result: result,
}
b, err = xml.Marshal(resp)
if err != nil {
log.CtxErrorw(reqCtx.Context(), "failed to unmarshal DeleteUserPublicKeyV2Resp", "error", err)
err = ErrDecodeMsg
return
}
w.Header().Set(ContentTypeHeader, ContentTypeXMLHeaderValue)
w.Write(b)
}
// parseSignedMsgAndSigFromRequest get sig for personal auth, it expects the auth string should look like "Signature=xxxxx,SignedMsg=xxx".
func parseSignedMsgAndSigFromRequest(requestSignature string) (*string, *string, error) {
var (
signedMsg string
signature string
)
requestSignature = strings.ReplaceAll(requestSignature, "\\n", "\n")
signatureItems := strings.Split(requestSignature, ",")
if len(signatureItems) != 2 { // requestSignature should be "Signature=xxxxx,SignedMsg=xxxxx"
return nil, nil, ErrAuthorizationHeaderFormat
}
for _, item := range signatureItems {
pair := strings.Split(item, "=")
if len(pair) != 2 {
return nil, nil, ErrAuthorizationHeaderFormat
}
switch pair[0] {
case SignedMsg:
signedMsg = pair[1]
case Signature:
signature = pair[1]
default:
return nil, nil, ErrAuthorizationHeaderFormat
}
}
return &signedMsg, &signature, nil
}
func VerifyPersonalSignature(signedMsg string, sigString string) (sdk.AccAddress, error) {
var (
signature []byte
err error
)
if err != nil {
return nil, err
}
signature, err = hexutil.Decode(sigString)
if err != nil {
return nil, err
}
realMsgToSign := accounts.TextHash([]byte(signedMsg))
if len(signature) != crypto.SignatureLength {
log.Errorw("signature length (actual: %d) doesn't match typical [R||S||V] signature 65 bytes")
return nil, ErrSignature
}
if signature[crypto.RecoveryIDOffset] == 27 || signature[crypto.RecoveryIDOffset] == 28 {
signature[crypto.RecoveryIDOffset] -= 27
}
// check signature consistent
addr, _, err := commonhash.RecoverAddr(realMsgToSign, signature)
if err != nil {
log.Errorw("failed to recover address")
return nil, ErrSignature
}
return addr, nil
}
func (g *GateModular) verifySignedContent(signedContent string, expectedDomain string, expectedNonce string, expectedPublicKey string, expectedExpiryDate string) error {
pattern := `(.+) wants you to sign in with your BNB Greenfield account:\n*(.+)\n*Register your identity public key (.+)\n*URI: (.+)\n*Version: (.+)\n*Chain ID: (.+)\n*Issued At: (.+)\n*Expiration Time: (.+)\n*Resources:((?:\n- SP .+ \(name:.+\) with nonce: \d+)+)`
re := regexp.MustCompile(pattern)
patternMatches := re.FindStringSubmatch(signedContent)
if len(patternMatches) < 10 {
return ErrSignedMsgNotMatchTemplate
}
// Extract variable values
dappDomain := patternMatches[1]
// userAcct := patternMatches[2] // unused, but keep this line here to indicate the matched details so that they could be useful in the future.
publicKey := patternMatches[3]
// eip4361URI := patternMatches[4] // unused, but keep this line here to indicate the matched details so that they could be useful in the future.
// eip4361Version := patternMatches[5] // unused, but keep this line here to indicate the matched details so that they could be useful in the future.
// eip4361ChainId := patternMatches[6] // unused, but keep this line here to indicate the matched details so that they could be useful in the future.
// eip4361IssuedAt := patternMatches[7] // unused, but keep this line here to indicate the matched details so that they could be useful in the future.
eip4361ExpirationTime := patternMatches[8]
spsText := patternMatches[9]
spsPattern := `- SP (.+) \(name:(.+\S)\) with nonce: (\d+)`
spsRe := regexp.MustCompile(spsPattern)
spsMatch := spsRe.FindAllStringSubmatch(spsText, -1)
var found = false
for _, spInfoMatches := range spsMatch {
if len(spInfoMatches) < 4 {
return ErrSignedMsgNotMatchTemplate
}
spAddress := spInfoMatches[1]
// spName := spInfoMatches[2] // keep this line here to indicate spInfoMatches[2] means spName
spNonce := spInfoMatches[3]
if spAddress == g.baseApp.OperatorAddress() {
found = true
if expectedNonce != spNonce { // nonce doesn't match
return ErrSignedMsgNotMatchSPNonce
}
}
}
if !found { // the signed content is not for this SP (g.config.SpOperatorAddress)
return ErrSignedMsgNotMatchSPAddr
}
if dappDomain != expectedDomain {
return ErrSignedMsgNotMatchDomain
}
if publicKey != expectedPublicKey {
return ErrSignedMsgNotMatchPubKey
}
if eip4361ExpirationTime != expectedExpiryDate {
return ErrSignedMsgNotMatchExpiry
}
return nil
}
func (g *GateModular) verifySignedContentV2(signedContent string, expectedDomain string, expectedPublicKey string, expectedExpiryDate string) error {
re := regexp.MustCompile(SignedContentV2Pattern)
patternMatches := re.FindStringSubmatch(signedContent)
if len(patternMatches) < 9 {
return ErrSignedMsgNotMatchTemplate
}
// Extract variable values
dappDomain := patternMatches[1]
publicKey := patternMatches[3]
eip4361ExpirationTime := patternMatches[8]
if dappDomain != expectedDomain {
return ErrSignedMsgNotMatchDomain
}
if publicKey != expectedPublicKey {
return ErrSignedMsgNotMatchPubKey
}
if eip4361ExpirationTime != expectedExpiryDate {
return ErrSignedMsgNotMatchExpiry
}
return nil
}