-
Notifications
You must be signed in to change notification settings - Fork 39
/
authenticator.go
597 lines (564 loc) · 26.2 KB
/
authenticator.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
package authenticator
import (
"context"
"encoding/hex"
"fmt"
"net/http"
"strings"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/bnb-chain/greenfield-storage-provider/base/gfspapp"
"github.com/bnb-chain/greenfield-storage-provider/base/types/gfsperrors"
"github.com/bnb-chain/greenfield-storage-provider/core/module"
coremodule "github.com/bnb-chain/greenfield-storage-provider/core/module"
"github.com/bnb-chain/greenfield-storage-provider/core/rcmgr"
"github.com/bnb-chain/greenfield-storage-provider/core/spdb"
"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"
paymenttypes "github.com/bnb-chain/greenfield/x/payment/types"
permissiontypes "github.com/bnb-chain/greenfield/x/permission/types"
storagetypes "github.com/bnb-chain/greenfield/x/storage/types"
)
var (
ErrUnsupportedAuthType = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20001, "unsupported auth op type")
ErrMismatchSp = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20002, "mismatched primary sp")
ErrUnexpectedObjectStatus = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20003, "")
ErrNotSealedState = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20004, "object has not been sealed state")
ErrPaymentState = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20005, "payment account is not active")
ErrInvalidAddress = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20006, "the user address format is invalid")
ErrNoSuchBucket = gfsperrors.Register(module.AuthenticationModularName, http.StatusNotFound, 20007, "no such bucket")
ErrNoSuchObject = gfsperrors.Register(module.AuthenticationModularName, http.StatusNotFound, 20008, "no such object")
ErrRepeatedBucket = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20009, "repeated bucket")
ErrRepeatedObject = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20010, "repeated object")
ErrNoPermission = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20011, "no permission")
ErrBadSignature = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20012, "bad signature")
ErrSignedMsgFormat = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20013, "signed msg must be formatted as ${actionContent}_${expiredTimestamp}")
ErrExpiredTimestampFormat = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20014, "expiredTimestamp in signed msg must be a unix epoch time in milliseconds")
ErrPublicKeyExpired = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20015, "user public key is expired")
ErrInvalidAddressOrDomain = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20016, "userAddress or domain can't be null")
ErrInvalidAddressOrDomainOrPublicKey = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20017, "userAddress, domain or publicKey can't be null")
ErrInvalidPublicKeyLength = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20018, "The length of publicKeys must be less or equal to 100")
ErrPublicKeyNotExist = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20019, "The publicKey was not registered")
ErrBucketIsRateLimited = gfsperrors.Register(module.AuthenticationModularName, http.StatusBadRequest, 20020, "bucket is rate limited")
)
func ErrUnexpectedObjectStatusWithDetail(objectName string, expectedStatus storagetypes.ObjectStatus, actualStatus storagetypes.ObjectStatus) *gfsperrors.GfSpError {
return &gfsperrors.GfSpError{
CodeSpace: module.AuthenticationModularName,
HttpStatusCode: int32(http.StatusBadRequest),
InnerCode: int32(20003),
Description: fmt.Sprintf("object %s is expected to be %s status but actually %s status", objectName, expectedStatus, actualStatus),
}
}
func ErrConsensusWithDetail(detail string) *gfsperrors.GfSpError {
return gfsperrors.Register(module.AuthenticationModularName, http.StatusInternalServerError, 25002, detail)
}
var _ module.Authenticator = &AuthenticationModular{}
type AuthenticationModular struct {
baseApp *gfspapp.GfSpBaseApp
scope rcmgr.ResourceScope
spID uint32
}
func (a *AuthenticationModular) getSPID() (uint32, error) {
if a.spID != 0 {
return a.spID, nil
}
spInfo, err := a.baseApp.Consensus().QuerySP(context.Background(), a.baseApp.OperatorAddress())
if err != nil {
return 0, err
}
a.spID = spInfo.GetId()
return a.spID, nil
}
func (a *AuthenticationModular) Name() string {
return module.AuthenticationModularName
}
func (a *AuthenticationModular) Start(ctx context.Context) error {
scope, err := a.baseApp.ResourceManager().OpenService(a.Name())
if err != nil {
return err
}
a.scope = scope
return nil
}
func (a *AuthenticationModular) Stop(ctx context.Context) error {
a.scope.Release()
return nil
}
func (a *AuthenticationModular) ReserveResource(
ctx context.Context,
state *rcmgr.ScopeStat) (
rcmgr.ResourceScopeSpan,
error) {
span, err := a.scope.BeginSpan()
if err != nil {
return nil, err
}
err = span.ReserveResources(state)
if err != nil {
return nil, err
}
return span, nil
}
func (a *AuthenticationModular) ReleaseResource(
ctx context.Context,
span rcmgr.ResourceScopeSpan) {
span.Done()
}
// GetAuthNonce get the auth nonce for which the Dapp or client can generate EDDSA key pairs.
func (a *AuthenticationModular) GetAuthNonce(ctx context.Context, account string, domain string) (*spdb.OffChainAuthKey, error) {
if account == "" || domain == "" {
return nil, ErrInvalidAddressOrDomain
}
authKey, err := a.baseApp.GfSpDB().GetAuthKey(account, domain)
if err != nil {
log.CtxErrorw(ctx, "failed to GetAuthKey", "error", err)
return nil, err
}
log.CtxInfow(ctx, "succeed to GetAuthNonce")
return authKey, nil
}
// UpdateUserPublicKey updates the user public key once the Dapp or client generates the EDDSA key pairs.
func (a *AuthenticationModular) UpdateUserPublicKey(ctx context.Context, account string, domain string, currentNonce int32, nonce int32, userPublicKey string, expiryDate int64) (bool, error) {
err := a.baseApp.GfSpDB().UpdateAuthKey(account, domain, currentNonce, nonce, userPublicKey, time.UnixMilli(expiryDate))
if err != nil {
log.CtxErrorw(ctx, "failed to updateUserPublicKey when saving key")
return false, err
}
log.CtxInfow(ctx, "succeed to UpdateUserPublicKey")
return true, nil
}
// VerifyGNFD1EddsaSignature verifies the signature signed by user's EDDSA private key.
// no need to verify if the sig is expired. This method only need verify the account address and leave the expiration checking to gateway.
func (a *AuthenticationModular) VerifyGNFD1EddsaSignature(ctx context.Context, account string, domain string, offChainSig string, realMsgToSign []byte) (bool, error) {
signature, err := hex.DecodeString(offChainSig)
if err != nil {
return false, ErrBadSignature
}
getAuthNonceResp, err := a.GetAuthNonce(ctx, account, domain)
if err != nil {
return false, err
}
if time.Until(getAuthNonceResp.ExpiryDate).Seconds() < 0 {
return false, ErrPublicKeyExpired
}
userPublicKey := getAuthNonceResp.CurrentPublicKey
err = VerifyEddsaSignature(userPublicKey, signature, realMsgToSign)
if err != nil {
return false, gfsperrors.MakeGfSpError(err)
}
log.CtxInfow(ctx, "succeed to VerifyOffChainSignature")
return true, nil
}
// GetAuthKeyV2 can check if the given account/domain/public_key was registered in this system.
func (a *AuthenticationModular) GetAuthKeyV2(ctx context.Context, account string, domain string, publicKey string) (*spdb.OffChainAuthKeyV2, error) {
if account == "" || domain == "" || publicKey == "" {
return nil, ErrInvalidAddressOrDomainOrPublicKey
}
authKey, err := a.baseApp.GfSpDB().GetAuthKeyV2(account, domain, publicKey)
if err != nil {
log.CtxErrorw(ctx, "failed to GetAuthKeyV2", "error", err)
return nil, err
}
log.CtxInfow(ctx, "succeed to GetAuthKeyV2")
return authKey, nil
}
// ListAuthKeysV2 can list user public keys
func (a *AuthenticationModular) ListAuthKeysV2(ctx context.Context, account string, domain string) ([]string, error) {
if account == "" || domain == "" {
return nil, ErrInvalidAddressOrDomain
}
authKeys, err := a.baseApp.GfSpDB().ListAuthKeysV2(account, domain)
if err != nil {
log.CtxErrorw(ctx, "failed to ListAuthKeysV2", "error", err)
return nil, err
}
log.CtxInfow(ctx, "succeed to ListAuthKeysV2")
return authKeys, nil
}
// DeleteAuthKeysV2 can delete user public keys
func (a *AuthenticationModular) DeleteAuthKeysV2(ctx context.Context, account string, domain string, publicKeys []string) (bool, error) {
if account == "" || domain == "" {
return false, ErrInvalidAddressOrDomain
}
if len(publicKeys) == 0 {
return true, nil
}
if len(publicKeys) > 100 {
return false, ErrInvalidPublicKeyLength
}
result, err := a.baseApp.GfSpDB().DeleteAuthKeysV2(account, domain, publicKeys)
if err != nil {
log.CtxErrorw(ctx, "failed to DeleteAuthKeysV2", "error", err)
return false, err
}
log.CtxInfow(ctx, "succeed to DeleteAuthKeysV2")
return result, nil
}
// UpdateUserPublicKeyV2 registered the user public key once the dApp or client generates the EDDSA key pairs.
func (a *AuthenticationModular) UpdateUserPublicKeyV2(ctx context.Context, account string, domain string, publicKey string, expiryDate int64) (bool, error) {
newRecord := &spdb.OffChainAuthKeyV2{
UserAddress: account,
Domain: domain,
PublicKey: publicKey,
ExpiryDate: time.UnixMilli(expiryDate),
CreatedTime: time.Now(),
ModifiedTime: time.Now(),
}
err := a.baseApp.GfSpDB().InsertAuthKeyV2(newRecord)
if err != nil {
log.CtxErrorw(ctx, "failed to UpdateUserPublicKeyV2 when saving key", "error", err)
return false, err
}
log.CtxInfow(ctx, "succeed to UpdateUserPublicKeyV2")
return true, nil
}
// VerifyGNFD2EddsaSignature verifies the signature signed by user's EDDSA private key.
func (a *AuthenticationModular) VerifyGNFD2EddsaSignature(ctx context.Context, account string, domain string, publicKey string, offChainSig string, realMsgToSign []byte) (bool, error) {
signature, err := hex.DecodeString(offChainSig)
if err != nil {
return false, ErrBadSignature
}
getAuthKeyV2Resp, err := a.GetAuthKeyV2(ctx, account, domain, publicKey)
if err != nil {
return false, err
}
if getAuthKeyV2Resp == nil {
return false, ErrPublicKeyNotExist
}
if time.Until(getAuthKeyV2Resp.ExpiryDate).Seconds() < 0 {
return false, ErrPublicKeyExpired
}
userPublicKey := getAuthKeyV2Resp.PublicKey
err = VerifyEddsaSignatureV2(userPublicKey, signature, realMsgToSign)
if err != nil {
return false, gfsperrors.MakeGfSpError(err)
}
log.CtxInfow(ctx, "succeed to VerifyGNFD2EddsaSignature")
return true, nil
}
// VerifyAuthentication verifies the account has the operation's permission.
// TODO:: supports permission path verification and query
func (a *AuthenticationModular) VerifyAuthentication(
ctx context.Context,
authType coremodule.AuthOpType,
account, bucket, object string) (
bool, error) {
// check the account if it is a valid address
_, err := sdk.AccAddressFromHexUnsafe(account)
if err != nil {
return false, ErrInvalidAddress
}
switch authType {
case coremodule.AuthOpAskCreateBucketApproval:
queryTime := time.Now()
bucketInfo, _ := a.baseApp.Consensus().QueryBucketInfo(ctx, bucket)
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_create_bucket_approval_query_bucket_time").Observe(time.Since(queryTime).Seconds())
if bucketInfo != nil {
log.CtxErrorw(ctx, "failed to verify authentication of asking create bucket "+
"approval, bucket repeated", "bucket", bucket)
return false, ErrRepeatedBucket
}
return true, nil
case coremodule.AuthOpAskMigrateBucketApproval:
queryTime := time.Now()
bucketInfo, _ := a.baseApp.Consensus().QueryBucketInfo(ctx, bucket)
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_migrate_bucket_approval_query_bucket_time").Observe(time.Since(queryTime).Seconds())
if bucketInfo == nil {
log.CtxErrorw(ctx, "failed to verify authentication of asking migrate bucket "+
"approval, bucket not existed", "bucket", bucket)
return false, ErrNoSuchBucket
}
return true, nil
case coremodule.AuthOpTypeQueryBucketMigrationProgress:
queryTime := time.Now()
bucketInfo, _ := a.baseApp.Consensus().QueryBucketInfo(ctx, bucket)
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_migrate_bucket_progress_query_bucket_time").Observe(time.Since(queryTime).Seconds())
if bucketInfo == nil {
log.CtxErrorw(ctx, "failed to verify authentication of asking query migrate bucket "+
"progress, bucket not existed", "bucket", bucket)
return false, ErrNoSuchBucket
}
return true, nil
case coremodule.AuthOpAskCreateObjectApproval:
queryTime := time.Now()
bucketInfo, objectInfo, _ := a.baseApp.Consensus().QueryBucketInfoAndObjectInfo(ctx, bucket, object)
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_create_object_approval_query_bucket_object_time").Observe(time.Since(queryTime).Seconds())
if bucketInfo == nil {
log.CtxErrorw(ctx, "failed to verify authentication of asking create object "+
"approval, no such bucket to ask create object approval", "bucket", bucket, "object", object)
return false, ErrNoSuchBucket
}
if objectInfo != nil {
log.CtxErrorw(ctx, "failed to verify authentication of asking create object "+
"approval, object has been created", "bucket", bucket, "object", object)
return false, ErrRepeatedObject
}
return true, nil
case coremodule.AuthOpTypeAgentPutObject:
permissionTime := time.Now()
allow, err := a.baseApp.Consensus().VerifyPutObjectPermission(ctx, account, bucket, object)
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_put_object_verify_permission_time").Observe(time.Since(permissionTime).Seconds())
if err != nil {
log.CtxErrorw(ctx, "failed to verify put object permission from consensus", "error", err)
return false, err
}
return allow, nil
case coremodule.AuthOpTypeAgentUpdateObject:
permissionTime := time.Now()
allow, err := a.baseApp.Consensus().VerifyUpdateObjectPermission(ctx, account, bucket, object)
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_update_object_verify_permission_time").Observe(time.Since(permissionTime).Seconds())
if err != nil {
log.CtxErrorw(ctx, "failed to verify update object content permission from consensus", "error", err)
return false, err
}
return allow, nil
case coremodule.AuthOpTypePutObject:
queryTime := time.Now()
bucketInfo, objectInfo, err := a.baseApp.Consensus().QueryBucketInfoAndObjectInfo(ctx, bucket, object)
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_put_object_query_bucket_object_time").Observe(time.Since(queryTime).Seconds())
if err != nil {
log.CtxErrorw(ctx, "failed to get bucket and object info from consensus", "error", err)
// refer to https://github.com/bnb-chain/greenfield/blob/master/x/storage/types/errors.go
if strings.Contains(err.Error(), "No such bucket") {
return false, ErrNoSuchBucket
}
if strings.Contains(err.Error(), "No such object") {
return false, ErrNoSuchObject
}
return false, ErrConsensusWithDetail("failed to get bucket and object info from consensus, error: " + err.Error())
}
spID, err := a.getSPID()
if err != nil {
return false, ErrConsensusWithDetail("getSPID error: " + err.Error())
}
bucketSPID, err := util.GetBucketPrimarySPID(ctx, a.baseApp.Consensus(), bucketInfo)
if err != nil {
return false, ErrConsensusWithDetail("GetBucketPrimarySPID error: " + err.Error())
}
if bucketSPID != spID {
log.CtxErrorw(ctx, "sp operator address mismatch", "actual_sp_id", spID,
"expected_sp_id", bucketSPID)
return false, ErrMismatchSp
}
permissionTime := time.Now()
switch objectInfo.GetObjectStatus() {
case storagetypes.OBJECT_STATUS_CREATED:
allow, err := a.baseApp.Consensus().VerifyPutObjectPermission(ctx, account, bucket, object)
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_put_object_verify_permission_time").Observe(time.Since(permissionTime).Seconds())
if err != nil {
log.CtxErrorw(ctx, "failed to verify put object permission from consensus", "error", err)
return false, err
}
return allow, nil
case storagetypes.OBJECT_STATUS_SEALED:
if !objectInfo.IsUpdating {
return false, ErrUnexpectedObjectStatusWithDetail(objectInfo.ObjectName, storagetypes.OBJECT_STATUS_CREATED, objectInfo.GetObjectStatus())
}
allow, err := a.baseApp.Consensus().VerifyUpdateObjectPermission(ctx, account, bucket, object)
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_put_object_verify_permission_time").Observe(time.Since(permissionTime).Seconds())
if err != nil {
log.CtxErrorw(ctx, "failed to verify update object permission from consensus", "error", err)
return false, err
}
return allow, nil
default:
log.CtxErrorw(ctx, "object state should be OBJECT_STATUS_CREATED", "state", objectInfo.GetObjectStatus())
return false, ErrUnexpectedObjectStatusWithDetail(objectInfo.ObjectName, storagetypes.OBJECT_STATUS_CREATED, objectInfo.GetObjectStatus())
}
case coremodule.AuthOpTypeGetUploadingState:
queryTime := time.Now()
bucketInfo, _, err := a.baseApp.Consensus().QueryBucketInfoAndObjectInfo(ctx, bucket, object)
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_get_object_process_query_bucket_object_time").Observe(time.Since(queryTime).Seconds())
if err != nil {
log.CtxErrorw(ctx, "failed to get bucket and object info from consensus", "error", err)
// refer to https://github.com/bnb-chain/greenfield/blob/master/x/storage/types/errors.go
if strings.Contains(err.Error(), "No such bucket") {
return false, ErrNoSuchBucket
}
if strings.Contains(err.Error(), "No such object") {
return false, ErrNoSuchObject
}
return false, ErrConsensusWithDetail("failed to get bucket and object info from consensus, error: " + err.Error())
}
spID, err := a.getSPID()
if err != nil {
return false, ErrConsensusWithDetail("getSPID error: " + err.Error())
}
bucketSPID, err := util.GetBucketPrimarySPID(ctx, a.baseApp.Consensus(), bucketInfo)
if err != nil {
return false, ErrConsensusWithDetail("GetBucketPrimarySPID error: " + err.Error())
}
if bucketSPID != spID {
log.CtxErrorw(ctx, "sp operator address mismatch", "actual_sp_id", spID,
"expected_sp_id", bucketSPID)
return false, ErrMismatchSp
}
return true, nil
case coremodule.AuthOpTypeGetObject:
queryTime := time.Now()
bucketInfo, objectInfo, err := a.baseApp.Consensus().QueryBucketInfoAndObjectInfo(ctx, bucket, object)
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_get_object_query_bucket_object_time").Observe(time.Since(queryTime).Seconds())
if err != nil {
log.CtxErrorw(ctx, "failed to get bucket and object info from consensus", "error", err)
// refer to https://github.com/bnb-chain/greenfield/blob/master/x/storage/types/errors.go
if strings.Contains(err.Error(), "No such bucket") {
return false, ErrNoSuchBucket
}
if strings.Contains(err.Error(), "No such object") {
return false, ErrNoSuchObject
}
return false, ErrConsensusWithDetail("failed to get bucket and object info from consensus, error: " + err.Error())
}
bucketExtraInfo, err := a.baseApp.Consensus().QueryBucketExtraInfo(ctx, bucket)
if err != nil {
log.CtxErrorw(ctx, "failed to get bucket extra info from consensus", "error", err)
if strings.Contains(err.Error(), "No such bucket") {
return false, ErrNoSuchBucket
}
return false, ErrConsensusWithDetail("failed to get bucket extra info from consensus, error: " + err.Error())
}
if bucketExtraInfo != nil {
if bucketExtraInfo.IsRateLimited {
return false, ErrBucketIsRateLimited
}
}
spID, err := a.getSPID()
if err != nil {
return false, ErrConsensusWithDetail("getSPID error: " + err.Error())
}
bucketSPID, err := util.GetBucketPrimarySPID(ctx, a.baseApp.Consensus(), bucketInfo)
if err != nil {
return false, ErrConsensusWithDetail("GetBucketPrimarySPID error: " + err.Error())
}
if bucketSPID != spID {
log.CtxErrorw(ctx, "sp operator address mismatch", "actual_sp_id", spID,
"expected_sp_id", bucketSPID)
return false, ErrMismatchSp
}
if objectInfo.GetObjectStatus() != storagetypes.OBJECT_STATUS_SEALED &&
objectInfo.GetObjectStatus() != storagetypes.OBJECT_STATUS_CREATED {
log.CtxErrorw(ctx, "object state is not sealed or created", "state", objectInfo.GetObjectStatus())
return false, ErrNoPermission
}
streamTime := time.Now()
streamRecord, err := a.baseApp.Consensus().QueryPaymentStreamRecord(ctx, bucketInfo.GetPaymentAddress())
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_get_object_query_stream_time").Observe(time.Since(streamTime).Seconds())
if err != nil {
log.CtxErrorw(ctx, "failed to query payment stream record from consensus", "error", err)
return false, err
}
if streamRecord.Status != paymenttypes.STREAM_ACCOUNT_STATUS_ACTIVE {
log.CtxErrorw(ctx, "failed to check payment due to account status is not active", "status", streamRecord.Status)
return false, ErrPaymentState
}
permissionTime := time.Now()
var permission *permissiontypes.Effect
var allow bool
permission, err = a.baseApp.GfSpClient().VerifyPermission(ctx, account, bucket, object, permissiontypes.ACTION_GET_OBJECT)
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_get_object_verify_permission_time").Observe(time.Since(permissionTime).Seconds())
if err != nil {
log.CtxErrorw(ctx, "failed to get bucket and object info from meta", "error", err)
return false, err
}
if *permission == permissiontypes.EFFECT_ALLOW {
allow = true
}
return allow, nil
case coremodule.AuthOpTypeGetRecoveryPiece:
bucketInfo, objectInfo, err := a.baseApp.Consensus().QueryBucketInfoAndObjectInfo(ctx, bucket, object)
if err != nil {
log.CtxErrorw(ctx, "failed to get bucket and object info from consensus", "error", err)
if strings.Contains(err.Error(), "No such bucket") {
return false, ErrNoSuchBucket
}
if strings.Contains(err.Error(), "No such object") {
return false, ErrNoSuchObject
}
return false, ErrConsensusWithDetail("failed to get bucket and object info from consensus, error: " + err.Error())
}
spID, err := a.getSPID()
if err != nil {
return false, ErrConsensusWithDetail("getSPID error: " + err.Error())
}
_, isSecondarySp, err := util.ValidateAndGetSPIndexWithinGVGSecondarySPs(ctx, a.baseApp.GfSpClient(), spID, bucketInfo.Id.Uint64(), objectInfo.LocalVirtualGroupId)
if err != nil {
log.CtxErrorw(ctx, "failed to global virtual group info from metaData", "error", err)
return false, ErrConsensusWithDetail("failed to global virtual group info from metaData, error: " + err.Error())
}
if !isSecondarySp {
return false, ErrMismatchSp
}
if objectInfo.GetObjectStatus() != storagetypes.OBJECT_STATUS_SEALED {
log.CtxErrorw(ctx, "object state is not sealed", "state", objectInfo.GetObjectStatus())
return false, ErrNotSealedState
}
var permission *permissiontypes.Effect
var allow bool
permission, err = a.baseApp.GfSpClient().VerifyPermission(ctx, account, bucket, object, permissiontypes.ACTION_GET_OBJECT)
if err != nil {
log.CtxErrorw(ctx, "failed to get bucket and object info from meta", "error", err)
return false, err
}
if *permission == permissiontypes.EFFECT_ALLOW {
allow = true
}
return allow, nil
case coremodule.AuthOpTypeGetChallengePieceInfo:
challengeIsFromValidator := false
queryTime := time.Now()
validators, err := a.baseApp.Consensus().ListBondedValidators(ctx)
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_challenge_query_validator_time").Observe(time.Since(queryTime).Seconds())
if err != nil {
log.CtxErrorw(ctx, "failed to list validator from consensus", "error", err)
return false, ErrConsensusWithDetail("failed to list validator from consensus, error: " + err.Error())
}
for _, validator := range validators {
if strings.EqualFold(validator.ChallengerAddress, account) {
challengeIsFromValidator = true
break
}
}
if !challengeIsFromValidator {
log.CtxErrorw(ctx, "failed to get challenge info due to it is not in bonded validator list",
"actual_challenge_address", account)
return false, ErrNoPermission
}
queryTime = time.Now()
bucketInfo, objectInfo, err := a.baseApp.Consensus().QueryBucketInfoAndObjectInfo(ctx, bucket, object)
metrics.PerfAuthTimeHistogram.WithLabelValues("auth_server_challenge_query_bucket_object_time").Observe(time.Since(queryTime).Seconds())
if err != nil {
log.CtxErrorw(ctx, "failed to get object info from consensus", "error", err)
// refer to https://github.com/bnb-chain/greenfield/blob/master/x/storage/types/errors.go
if strings.Contains(err.Error(), "No such bucket") {
return false, ErrNoSuchBucket
}
if strings.Contains(err.Error(), "No such object") {
return false, ErrNoSuchObject
}
return false, ErrConsensusWithDetail("failed to get object info from consensus, error: " + err.Error())
}
spID, err := a.getSPID()
if err != nil {
return false, ErrConsensusWithDetail("getSPID error: " + err.Error())
}
bucketSPID, err := util.GetBucketPrimarySPID(ctx, a.baseApp.Consensus(), bucketInfo)
if err != nil {
return false, ErrConsensusWithDetail("GetBucketPrimarySPID error: " + err.Error())
}
if bucketSPID == spID {
return true, nil
}
_, isSecondarySp, err := util.ValidateAndGetSPIndexWithinGVGSecondarySPs(ctx, a.baseApp.GfSpClient(), spID, bucketInfo.Id.Uint64(), objectInfo.LocalVirtualGroupId)
if err != nil {
log.CtxErrorw(ctx, "failed to global virtual group info from metaData", "error", err)
return false, ErrConsensusWithDetail("failed to global virtual group info from metaData, error: " + err.Error())
}
if !isSecondarySp {
return false, ErrMismatchSp
}
return true, nil
default:
return false, ErrUnsupportedAuthType
}
}