-
Notifications
You must be signed in to change notification settings - Fork 14
/
authorization_manager.go
499 lines (454 loc) · 18.7 KB
/
authorization_manager.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
package chain
import (
"github.com/eosspark/eos-go/chain/types"
. "github.com/eosspark/eos-go/chain/types/generated_containers"
"github.com/eosspark/eos-go/common"
"github.com/eosspark/eos-go/crypto/rlp"
"github.com/eosspark/eos-go/database"
"github.com/eosspark/eos-go/entity"
. "github.com/eosspark/eos-go/exception"
. "github.com/eosspark/eos-go/exception/try"
"github.com/eosspark/eos-go/log"
)
var noopCheckTime *func()
type AuthorizationManager struct {
control *Controller
db database.DataBase
}
func newAuthorizationManager(control *Controller) *AuthorizationManager {
azInstance := &AuthorizationManager{}
azInstance.control = control
azInstance.db = control.DB
return azInstance
}
type PermissionIdType common.IdType
func (a *AuthorizationManager) CreatePermission(account common.AccountName,
name common.PermissionName,
parent PermissionIdType,
auth types.Authority,
initialCreationTime common.TimePoint,
) *entity.PermissionObject {
creationTime := initialCreationTime
if creationTime == common.TimePoint(0) {
creationTime = a.control.PendingBlockTime()
}
permUsage := entity.PermissionUsageObject{}
permUsage.LastUsed = creationTime
err := a.db.Insert(&permUsage)
if err != nil {
log.Error("CreatePermission is error: %s", err)
}
perm := entity.PermissionObject{
UsageId: permUsage.ID,
Parent: common.IdType(parent),
Owner: account,
Name: name,
LastUpdated: creationTime,
Auth: auth.ToSharedAuthority(),
}
err = a.db.Insert(&perm)
if err != nil {
log.Error("CreatePermission is error: %s", err)
}
return &perm
}
func (a *AuthorizationManager) ModifyPermission(permission *entity.PermissionObject, auth *types.Authority) {
err := a.db.Modify(permission, func(po *entity.PermissionObject) {
po.Auth = (*auth).ToSharedAuthority()
po.LastUpdated = a.control.PendingBlockTime()
})
if err != nil {
log.Error("ModifyPermission is error: %s", err)
}
}
func (a *AuthorizationManager) RemovePermission(permission *entity.PermissionObject) {
index, err := a.db.GetIndex("byParent", entity.PermissionObject{})
if err != nil {
log.Error("RemovePermission is error: %s", err)
}
itr, err := index.LowerBound(entity.PermissionObject{Parent: permission.ID})
if err != nil {
log.Error("RemovePermission is error: %s", err)
}
EosAssert(index.CompareEnd(itr), &ActionValidateException{}, "Cannot remove a permission which has children. Remove the children first.")
usage := entity.PermissionUsageObject{ID: permission.UsageId}
err = a.db.Find("id", usage, &usage)
if err != nil {
log.Error("RemovePermission is error: %s", err)
}
err = a.db.Remove(&usage)
if err != nil {
log.Error("RemovePermission is error: %s", err)
}
err = a.db.Remove(permission)
if err != nil {
log.Error("RemovePermission is error: %s", err)
}
}
func (a *AuthorizationManager) UpdatePermissionUsage(permission *entity.PermissionObject) {
puo := entity.PermissionUsageObject{}
puo.ID = permission.UsageId
err := a.db.Find("id", puo, &puo)
if err != nil {
log.Error("UpdatePermissionUsage is error: %s", err)
}
err = a.db.Modify(&puo, func(p *entity.PermissionUsageObject) {
puo.LastUsed = a.control.PendingBlockTime()
})
if err != nil {
log.Error("UpdatePermissionUsage is error: %s", err)
}
}
func (a *AuthorizationManager) GetPermissionLastUsed(permission *entity.PermissionObject) common.TimePoint {
puo := entity.PermissionUsageObject{}
puo.ID = permission.UsageId
err := a.db.Find("id", puo, &puo)
if err != nil {
log.Error("GetPermissionLastUsed is error: %s", err)
}
return puo.LastUsed
}
func (a *AuthorizationManager) FindPermission(level *common.PermissionLevel) (p *entity.PermissionObject) {
Try(func() {
EosAssert(!level.Actor.Empty() && !level.Permission.Empty(), &InvalidPermission{}, "Invalid permission")
po := entity.PermissionObject{}
po.Owner = level.Actor
po.Name = level.Permission
err := a.db.Find("byOwner", po, &po)
if err != nil {
//log.Warn("%v@%v don't find", po.Owner, po.Name)
p = nil
return
}
p = &po
}).EosRethrowExceptions(&PermissionQueryException{}, "Failed to retrieve permission: %v", level)
return p
}
func (a *AuthorizationManager) GetPermission(level *common.PermissionLevel) (p *entity.PermissionObject) {
Try(func() {
EosAssert(!level.Actor.Empty() && !level.Permission.Empty(), &InvalidPermission{}, "Invalid permission")
po := entity.PermissionObject{}
po.Owner = level.Actor
po.Name = level.Permission
err := a.db.Find("byOwner", po, &po)
if err != nil {
//log.Warn("%v@%v don't find", po.Owner, po.Name)
EosAssert(false, &PermissionQueryException{}, "Failed to retrieve permission: %v", level)
}
p = &po
}).EosRethrowExceptions(&PermissionQueryException{}, "Failed to retrieve permission: %v", level)
return p
}
func (a *AuthorizationManager) LookupLinkedPermission(authorizerAccount common.AccountName,
scope common.AccountName,
actName common.ActionName,
) (p *common.PermissionName) {
Try(func() {
link := entity.PermissionLinkObject{}
link.Account = authorizerAccount
link.Code = scope
link.MessageType = actName
err := a.db.Find("byActionName", link, &link)
if err != nil {
link.MessageType = common.AccountName(common.N(""))
err = a.db.Find("byActionName", link, &link)
}
if err == nil {
p = &link.RequiredPermission
return
}
}).End()
return p
}
func (a *AuthorizationManager) LookupMinimumPermission(authorizerAccount common.AccountName,
scope common.AccountName,
actName common.ActionName,
) (p *common.PermissionName) {
if scope == common.DefaultConfig.SystemAccountName {
EosAssert(actName != UpdateAuth{}.GetName() &&
actName != DeleteAuth{}.GetName() &&
actName != LinkAuth{}.GetName() &&
actName != UnLinkAuth{}.GetName() &&
actName != CancelDelay{}.GetName(),
&UnlinkableMinPermissionAction{}, "cannot call lookup_minimum_permission on native actions that are not allowed to be linked to minimum permissions")
}
Try(func() {
linkedPermission := a.LookupLinkedPermission(authorizerAccount, scope, actName)
if common.Empty(linkedPermission) {
p = &common.DefaultConfig.ActiveName
return
}
if *linkedPermission == common.PermissionName(common.DefaultConfig.EosioAnyName) {
return
}
p = linkedPermission
return
}).End()
return p
}
func (a *AuthorizationManager) CheckUpdateAuthAuthorization(update UpdateAuth, auths []common.PermissionLevel) {
EosAssert(len(auths) == 1, &IrrelevantAuthException{}, "UpdateAuth action should only have one declared authorization")
auth := auths[0]
EosAssert(auth.Actor == update.Account, &IrrelevantAuthException{}, "the owner of the affected permission needs to be the actor of the declared authorization")
minPermission := a.FindPermission(&common.PermissionLevel{Actor: update.Account, Permission: update.Permission})
if minPermission == nil {
permission := a.GetPermission(&common.PermissionLevel{Actor: update.Account, Permission: update.Parent})
minPermission = permission
}
permissionIndex, err := a.db.GetIndex("id", entity.PermissionObject{})
if err != nil {
log.Error("CheckUpdateAuthAuthorization is error: %s", err)
}
EosAssert(a.GetPermission(&auth).Satisfies(*minPermission, permissionIndex), &IrrelevantAuthException{},
"UpdateAuth action declares irrelevant authority '%v'; minimum authority is %v", auth, common.PermissionLevel{update.Account, minPermission.Name})
}
func (a *AuthorizationManager) CheckDeleteAuthAuthorization(del DeleteAuth, auths []common.PermissionLevel) {
EosAssert(len(auths) == 1, &IrrelevantAuthException{}, "DeleteAuth action should only have one declared authorization")
auth := auths[0]
EosAssert(auth.Actor == del.Account, &IrrelevantAuthException{}, "the owner of the affected permission needs to be the actor of the declared authorization")
minPermission := a.GetPermission(&common.PermissionLevel{Actor: del.Account, Permission: del.Permission})
permissionIndex, err := a.db.GetIndex("id", entity.PermissionObject{})
if err != nil {
log.Error("CheckDeleteAuthAuthorization is error: %s", err)
}
EosAssert(a.GetPermission(&auth).Satisfies(*minPermission, permissionIndex), &IrrelevantAuthException{},
"DeleteAuth action declares irrelevant authority '%v'; minimum authority is %v", auth, common.PermissionLevel{minPermission.Owner, minPermission.Name})
}
func (a *AuthorizationManager) CheckLinkAuthAuthorization(link LinkAuth, auths []common.PermissionLevel) {
EosAssert(len(auths) == 1, &IrrelevantAuthException{}, "link action should only have one declared authorization")
auth := auths[0]
EosAssert(auth.Actor == link.Account, &IrrelevantAuthException{}, "the owner of the affected permission needs to be the actor of the declared authorization")
EosAssert(link.Type != UpdateAuth{}.GetName(), &ActionValidateException{}, "Cannot link eosio::updateauth to a minimum permission")
EosAssert(link.Type != DeleteAuth{}.GetName(), &ActionValidateException{}, "Cannot link eosio::deleteauth to a minimum permission")
EosAssert(link.Type != LinkAuth{}.GetName(), &ActionValidateException{}, "Cannot link eosio::linkauth to a minimum permission")
EosAssert(link.Type != UnLinkAuth{}.GetName(), &ActionValidateException{}, "Cannot link eosio::unlinkauth to a minimum permission")
EosAssert(link.Type != CancelDelay{}.GetName(), &ActionValidateException{}, "Cannot link eosio::canceldelay to a minimum permission")
linkedPermissionName := a.LookupMinimumPermission(link.Account, link.Code, link.Type)
if linkedPermissionName.Empty() {
return
}
permissionIndex, err := a.db.GetIndex("id", entity.PermissionObject{})
if err != nil {
log.Error("CheckLinkAuthAuthorization is error: %s", err)
}
EosAssert(a.GetPermission(&auth).Satisfies(*a.GetPermission(&common.PermissionLevel{link.Account, *linkedPermissionName}), permissionIndex), &IrrelevantAuthException{},
"LinkAuth action declares irrelevant authority '%v'; minimum authority is %v", auth, common.PermissionLevel{link.Account, *linkedPermissionName})
}
func (a *AuthorizationManager) CheckUnLinkAuthAuthorization(unlink UnLinkAuth, auths []common.PermissionLevel) {
EosAssert(len(auths) == 1, &IrrelevantAuthException{}, "unlink action should only have one declared authorization")
auth := auths[0]
EosAssert(auth.Actor == unlink.Account, &IrrelevantAuthException{},
"the owner of the affected permission needs to be the actor of the declared authorization")
unlinkedPermissionName := a.LookupLinkedPermission(unlink.Account, unlink.Code, unlink.Type)
EosAssert(!unlinkedPermissionName.Empty(), &TransactionException{},
"cannot unlink non-existent permission link of account '%v' for actions matching '%v::%v", unlink.Account, unlink.Code, unlink.Type)
if *unlinkedPermissionName == common.DefaultConfig.EosioAnyName {
return
}
permissionIndex, err := a.db.GetIndex("id", entity.PermissionObject{})
if err != nil {
log.Error("CheckUnLinkAuthAuthorization is error: %s", err)
}
EosAssert(a.GetPermission(&auth).Satisfies(*a.GetPermission(&common.PermissionLevel{unlink.Account, *unlinkedPermissionName}), permissionIndex), &IrrelevantAuthException{},
"unlink action declares irrelevant authority '%v'; minimum authority is %v", auth, common.PermissionLevel{unlink.Account, *unlinkedPermissionName})
}
func (a *AuthorizationManager) CheckCancelDelayAuthorization(cancel CancelDelay, auths []common.PermissionLevel) common.Microseconds {
EosAssert(len(auths) == 1, &IrrelevantAuthException{}, "CancelDelay action should only have one declared authorization")
auth := auths[0]
permissionIndex, err := a.db.GetIndex("id", entity.PermissionObject{})
if err != nil {
log.Error("CheckCancelDelayAuthorization is error: %s", err)
}
EosAssert(a.GetPermission(&auth).Satisfies(*a.GetPermission(&cancel.CancelingAuth), permissionIndex), &IrrelevantAuthException{},
"CancelDelay action declares irrelevant authority '%v'; specified authority to satisfy is %v", auth, cancel.CancelingAuth)
generatedTrx := entity.GeneratedTransactionObject{}
trxId := cancel.TrxId
generatedIndex, err := a.control.DB.GetIndex("byTrxId", entity.GeneratedTransactionObject{})
if err != nil {
log.Error("CheckCancelDelayAuthorization is error: %s", err)
}
itr, err := generatedIndex.LowerBound(entity.GeneratedTransactionObject{TrxId: trxId})
if err != nil {
log.Error("CheckCancelDelayAuthorization is error: %s", err)
}
err = itr.Data(&generatedTrx)
EosAssert(err == nil && generatedTrx.TrxId == trxId, &TxNotFound{},
"cannot cancel trx_id=%v, there is no deferred transaction with that transaction id", trxId)
trx := types.Transaction{}
rlp.DecodeBytes(generatedTrx.PackedTrx, &trx)
found := false
for _, act := range trx.Actions {
for _, auth := range act.Authorization {
if auth == cancel.CancelingAuth {
found = true
break
}
}
if found {
break
}
}
EosAssert(found, &ActionValidateException{}, "canceling_auth in CancelDelay action was not found as authorization in the original delayed transaction")
return common.Milliseconds(int64(generatedTrx.DelayUntil) - int64(generatedTrx.Published))
}
func (a *AuthorizationManager) CheckAuthorization(actions []*types.Action,
providedKeys *PublicKeySet,
providedPermissions *PermissionLevelSet,
providedDelay common.Microseconds,
checkTime *func(),
allowUnusedKeys bool,
) {
delayMaxLimit := common.Seconds(int64(a.control.GetGlobalProperties().Configuration.MaxTrxDelay))
var effectiveProvidedDelay common.Microseconds
if providedDelay >= delayMaxLimit {
effectiveProvidedDelay = common.MaxMicroseconds()
} else {
effectiveProvidedDelay = providedDelay
}
checker := types.MakeAuthChecker(func(p *common.PermissionLevel) types.SharedAuthority {
perm := a.GetPermission(p)
if perm != nil {
return perm.Auth
} else {
return types.SharedAuthority{}
}
},
a.control.GetGlobalProperties().Configuration.MaxAuthorityDepth,
providedKeys,
providedPermissions,
effectiveProvidedDelay,
checkTime,
)
permissionToSatisfy := make(map[common.PermissionLevel]common.Microseconds)
for _, act := range actions {
specialCase := false
delay := effectiveProvidedDelay
if act.Account == common.DefaultConfig.SystemAccountName {
specialCase = true
switch act.Name {
case UpdateAuth{}.GetName():
UpdateAuth := UpdateAuth{}
rlp.DecodeBytes(act.Data, &UpdateAuth)
a.CheckUpdateAuthAuthorization(UpdateAuth, act.Authorization)
case DeleteAuth{}.GetName():
DeleteAuth := DeleteAuth{}
rlp.DecodeBytes(act.Data, &DeleteAuth)
a.CheckDeleteAuthAuthorization(DeleteAuth, act.Authorization)
case LinkAuth{}.GetName():
LinkAuth := LinkAuth{}
rlp.DecodeBytes(act.Data, &LinkAuth)
a.CheckLinkAuthAuthorization(LinkAuth, act.Authorization)
case UnLinkAuth{}.GetName():
UnLinkAuth := UnLinkAuth{}
rlp.DecodeBytes(act.Data, &UnLinkAuth)
a.CheckUnLinkAuthAuthorization(UnLinkAuth, act.Authorization)
case CancelDelay{}.GetName():
CancelDelay := CancelDelay{}
rlp.DecodeBytes(act.Data, &CancelDelay)
a.CheckCancelDelayAuthorization(CancelDelay, act.Authorization)
default:
specialCase = false
}
}
for _, declaredAuth := range act.Authorization {
(*checkTime)()
if !specialCase {
minPermissionName := a.LookupMinimumPermission(declaredAuth.Actor, act.Account, act.Name)
if minPermissionName != nil {
minPermission := a.GetPermission(&common.PermissionLevel{Actor: declaredAuth.Actor, Permission: *minPermissionName})
permissionIndex, err := a.db.GetIndex("id", entity.PermissionObject{})
if err != nil {
log.Error("CheckAuthorization is error: %s", err)
}
EosAssert(a.GetPermission(&declaredAuth).Satisfies(*minPermission, permissionIndex), &IrrelevantAuthException{},
"action declares irrelevant authority '%v'; minimum authority is %v", declaredAuth, common.PermissionLevel{minPermission.Owner, minPermission.Name})
}
}
isExist := false
for first, second := range permissionToSatisfy {
if first == declaredAuth {
if second > delay {
second = delay
isExist = true
break
}
}
}
if !isExist {
permissionToSatisfy[declaredAuth] = delay
}
}
}
for p, q := range permissionToSatisfy {
(*checkTime)()
EosAssert(checker.SatisfiedLoc(&p, q, nil), &UnsatisfiedAuthorization{},
"transaction declares authority '%v', "+
"but does not have signatures for it under a provided delay of %v ms, "+
"provided permissions %v, and provided keys %v", p, providedDelay.Count()/1000, providedPermissions, providedKeys)
}
if !allowUnusedKeys {
EosAssert(checker.AllKeysUsed(), &TxIrrelevantSig{}, "transaction bears irrelevant signatures from these keys: %v", checker.GetUnusedKeys())
}
}
func (a *AuthorizationManager) CheckAuthorization2(account common.AccountName,
permission common.PermissionName,
providedKeys *PublicKeySet, //flat_set<public_key_type>
providedPermissions *PermissionLevelSet, //flat_set<permission_level>
providedDelay common.Microseconds,
checkTime *func(),
allowUnusedKeys bool,
) {
delayMaxLimit := common.Seconds(int64(a.control.GetGlobalProperties().Configuration.MaxTrxDelay))
var effectiveProvidedDelay common.Microseconds
if providedDelay >= delayMaxLimit {
effectiveProvidedDelay = common.MaxMicroseconds()
} else {
effectiveProvidedDelay = providedDelay
}
checker := types.MakeAuthChecker(func(p *common.PermissionLevel) types.SharedAuthority {
perm := a.GetPermission(p)
if perm != nil {
return perm.Auth
} else {
return types.SharedAuthority{}
}
},
a.control.GetGlobalProperties().Configuration.MaxAuthorityDepth,
providedKeys,
providedPermissions,
effectiveProvidedDelay,
checkTime,
)
EosAssert(checker.SatisfiedLc(&common.PermissionLevel{account, permission}, nil), &UnsatisfiedAuthorization{},
"permission '%v' was not satisfied under a provided delay of %v ms, provided permissions %v, and provided keys %v",
common.PermissionLevel{account, permission}, providedDelay.Count()/1000, providedPermissions, providedKeys)
if !allowUnusedKeys {
EosAssert(checker.AllKeysUsed(), &TxIrrelevantSig{}, "irrelevant keys provided: %v", checker.GetUnusedKeys())
}
}
func (a *AuthorizationManager) GetRequiredKeys(trx *types.Transaction,
candidateKeys *PublicKeySet,
providedDelay common.Microseconds) PublicKeySet {
checker := types.MakeAuthChecker(
func(p *common.PermissionLevel) types.SharedAuthority {
perm := a.GetPermission(p)
if perm != nil {
return perm.Auth
} else {
return types.SharedAuthority{}
}
},
a.control.GetGlobalProperties().Configuration.MaxAuthorityDepth,
candidateKeys,
NewPermissionLevelSet(),
providedDelay,
noopCheckTime,
)
for _, act := range trx.Actions {
for _, declaredAuth := range act.Authorization {
EosAssert(checker.SatisfiedLc(&declaredAuth, nil), &UnsatisfiedAuthorization{},
"transaction declares authority '%v', but does not have signatures for it.", declaredAuth)
}
}
return checker.GetUsedKeys()
}