forked from StellarRouter/StellarRouter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1782 lines (1547 loc) · 63.7 KB
/
Copy pathlib.rs
File metadata and controls
1782 lines (1547 loc) · 63.7 KB
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![no_std]
//! # router-access
//!
//! Role-based access control for the stellar-router suite.
//! Supports arbitrary roles, multi-admin, per-address whitelisting,
//! and a role hierarchy where parent roles implicitly include child roles.
//!
//! ## Role Hierarchy
//!
//! Roles can be arranged in a parent -> child relationship. Granting a parent
//! role to an address implicitly grants all of its child roles (transitively).
//! For example, if `admin` is the parent of `editor`, and `editor` is the
//! parent of `viewer`, then an address with `admin` also has `editor` and
//! `viewer` without needing explicit grants.
//!
//! ## Events (following naming convention: past tense verbs in snake_case)
//! - `role_granted` -- Role granted to address (role, account, expiry_timestamp)
//! - `role_revoked` -- Role revoked from address (role, target)
//! - `role_parent_set` -- Parent role set (role, parent_role)
//! - `role_parent_removed` -- Parent role removed (role, parent_role)
//! - `role_admin_set` -- Admin set for role (role, admin)
//! - `address_blacklisted` -- Address blacklisted (address)
//! - `address_unblacklisted` -- Address unblacklisted (address)
//! - `role_expired` -- Role grant expired (role, target)
//! - `admin_transferred` -- Admin transferred (old_admin, new_admin)
//!
//! The hierarchy is stored as a directed acyclic graph (DAG). Cycles are
//! prevented by `set_role_parent` -- a role cannot be set as its own ancestor.
//!
//! ## Storage model
//!
//! - `HasRole(role, address)` -- explicit direct grant
//! - `RoleParent(role)` -- the single parent role of `role` (if any)
//! - `RoleAdmin(role)` -- address allowed to grant/revoke `role`
use soroban_sdk::{
contract, contracterror, contractimpl, contracttype, Address, Env, String, Symbol, Vec,
};
// ── Storage Keys ──────────────────────────────────────────────────────────────
#[contracttype]
pub enum DataKey {
SuperAdmin,
HasRole(String, Address), // (role, address) -> bool (direct grant only)
RoleAdmin(String), // role -> Address who manages it
Blacklisted(Address),
RoleParent(String), // role -> parent role name (hierarchy edge)
RoleMember(String, u32), // (role, index) -> Address
RoleMemberIndex(String, Address), // (role, account) -> index
RoleMemberCount(String), // role -> total indexed member count
AddressRoles(Address), // address -> Vec<String>
RoleExpiry(String, Address),
BlacklistReason(Address),
BlacklistExpiry(Address),
BlacklistCount, // instance -> total distinct blacklisted addresses
AllRoles, // instance -> Vec<String> of every role name ever granted
}
// ── Errors ────────────────────────────────────────────────────────────────────
#[contracterror]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum AccessError {
AlreadyInitialized = 1,
NotInitialized = 2,
Unauthorized = 3,
AlreadyHasRole = 4,
RoleNotFound = 5,
Blacklisted = 6,
CannotBlacklistAdmin = 7,
HierarchyCycle = 8,
}
// ── Contract ──────────────────────────────────────────────────────────────────
#[contract]
pub struct RouterAccess;
// Maximum depth to walk when resolving inherited roles. Prevents infinite
// loops in the unlikely event of a storage inconsistency.
const MAX_HIERARCHY_DEPTH: u32 = 16;
#[contractimpl]
impl RouterAccess {
/// Initialize with a super-admin.
///
/// # Errors
/// * [`AccessError::AlreadyInitialized`] -- called more than once.
pub fn initialize(env: Env, super_admin: Address) -> Result<(), AccessError> {
if env.storage().instance().has(&DataKey::SuperAdmin) {
return Err(AccessError::AlreadyInitialized);
}
env.storage()
.instance()
.set(&DataKey::SuperAdmin, &super_admin);
Ok(())
}
/// Grant a role to an address. Caller must be super-admin or role admin.
/// `expires_at` is an absolute ledger timestamp; `None` creates a permanent grant.
///
/// Only the direct role is stored. Inherited roles are resolved at
/// check time via [`Self::has_role`].
///
/// # Errors
/// * [`AccessError::Unauthorized`] -- caller is not super-admin or role admin.
/// * [`AccessError::AlreadyHasRole`] -- target already holds the role directly.
/// * [`AccessError::Blacklisted`] -- target is blacklisted.
pub fn grant_role(
env: Env,
admin: Address,
account: Address,
role: String,
expires_at: Option<u64>,
) -> Result<(), AccessError> {
admin.require_auth();
Self::require_role_manager(&env, &admin, &role)?;
if Self::is_blacklisted_internal(&env, &account) {
return Err(AccessError::Blacklisted);
}
if Self::has_role_internal(&env, &account, &role) {
return Err(AccessError::AlreadyHasRole);
}
let expiry_timestamp = expires_at.unwrap_or(u64::MAX);
// Set HasRole flag
env.storage()
.instance()
.set(&DataKey::HasRole(role.clone(), account.clone()), &true);
Self::record_role_name(&env, &role);
// Add to indexed member storage (append-only; stale entries filtered at read time)
if !env
.storage()
.instance()
.has(&DataKey::RoleMemberIndex(role.clone(), account.clone()))
{
let count: u32 = env
.storage()
.instance()
.get(&DataKey::RoleMemberCount(role.clone()))
.unwrap_or(0);
env.storage()
.instance()
.set(&DataKey::RoleMember(role.clone(), count), &account);
env.storage().instance().set(
&DataKey::RoleMemberIndex(role.clone(), account.clone()),
&count,
);
env.storage()
.instance()
.set(&DataKey::RoleMemberCount(role.clone()), &(count + 1));
}
// Add to AddressRoles list (if not already present)
let mut roles: Vec<String> = env
.storage()
.instance()
.get(&DataKey::AddressRoles(account.clone()))
.unwrap_or_else(|| Vec::new(&env));
if !roles.iter().any(|r| r == role) {
roles.push_back(role.clone());
}
env.storage()
.instance()
.set(&DataKey::AddressRoles(account.clone()), &roles);
// Set expiry timestamp
let key = DataKey::RoleExpiry(role.clone(), account.clone());
env.storage().instance().set(&key, &expiry_timestamp);
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ROLE_GRANTED),),
(account, role, expiry_timestamp),
);
Ok(())
}
/// Revoke a direct role grant from an address.
///
/// Only removes the direct grant. If the address inherits the role via
/// the hierarchy it will still pass `has_role` checks.
///
/// # Errors
/// * [`AccessError::Unauthorized`] -- caller is not super-admin or role admin.
/// * [`AccessError::RoleNotFound`] -- target does not hold the role directly.
pub fn revoke_role(
env: Env,
caller: Address,
role: String,
target: Address,
) -> Result<(), AccessError> {
caller.require_auth();
Self::require_role_manager(&env, &caller, &role)?;
// Check the raw storage key -- not has_role_internal -- so that expired
// roles (where has_role_internal returns false) can still be revoked
// to clean up storage.
let key = DataKey::HasRole(role.clone(), target.clone());
if !env.storage().instance().has(&key) {
return Err(AccessError::RoleNotFound);
}
env.storage().instance().remove(&key);
env.storage()
.instance()
.remove(&DataKey::RoleExpiry(role.clone(), target.clone()));
env.storage()
.instance()
.remove(&DataKey::RoleMemberIndex(role.clone(), target.clone()));
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ROLE_REVOKED),),
(role, target),
);
Ok(())
}
/// Check if an address has a role -- either directly or via the hierarchy.
///
/// Walks the role's ancestor chain. Returns `true` if the address holds
/// any role in the chain from `role` up to the root.
pub fn has_role(env: Env, role: String, target: Address) -> bool {
if Self::is_blacklisted_internal(&env, &target) {
return false;
}
Self::has_role_internal(&env, &target, &role)
}
/// Check if a role has expired for an address.
pub fn is_role_expired(env: Env, role: String, target: Address) -> bool {
if let Some(expires_at) = env
.storage()
.instance()
.get::<DataKey, u64>(&DataKey::RoleExpiry(role, target))
{
let current_timestamp = env.ledger().timestamp();
current_timestamp >= expires_at
} else {
false
}
}
/// Return the expiry timestamp for a role grant, or None if no expiry is set.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `role` - The role name.
/// * `target` - The address whose expiry to query.
///
/// # Returns
/// `Some(timestamp)` if an expiry exists, `None` otherwise.
pub fn get_role_expiry(env: Env, role: String, target: Address) -> Option<u64> {
env.storage()
.instance()
.get::<DataKey, u64>(&DataKey::RoleExpiry(role, target))
}
/// Set the parent role for a role (defines the hierarchy edge).
///
/// After this call, any address that holds `parent_role` (directly or
/// via inheritance) will also pass `has_role` checks for `role`.
///
/// Only the super-admin can modify the hierarchy.
///
/// # Errors
/// * [`AccessError::Unauthorized`] -- caller is not the super-admin.
/// * [`AccessError::HierarchyCycle`] -- setting this parent would create a cycle.
pub fn set_role_parent(
env: Env,
caller: Address,
role: String,
parent_role: String,
) -> Result<(), AccessError> {
caller.require_auth();
Self::require_super_admin(&env, &caller)?;
// Prevent cycles: parent_role must not be a descendant of role.
// Equivalently, role must not appear in parent_role's ancestor chain.
if Self::is_ancestor(&env, &parent_role, &role) {
return Err(AccessError::HierarchyCycle);
}
env.storage()
.instance()
.set(&DataKey::RoleParent(role.clone()), &parent_role);
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ROLE_PARENT_SET),),
(role, parent_role),
);
Ok(())
}
/// Remove the parent relationship for a role.
///
/// After this call, `role` becomes a root role with no parent.
/// Only the super-admin can modify the hierarchy.
///
/// # Errors
/// * [`AccessError::Unauthorized`] -- caller is not the super-admin.
pub fn remove_role_parent(env: Env, caller: Address, role: String) -> Result<(), AccessError> {
caller.require_auth();
Self::require_super_admin(&env, &caller)?;
env.storage()
.instance()
.remove(&DataKey::RoleParent(role.clone()));
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ROLE_PARENT_REMOVED),),
role,
);
Ok(())
}
/// Get the direct parent role of a role, if one is set.
pub fn get_role_parent(env: Env, role: String) -> Option<String> {
env.storage().instance().get(&DataKey::RoleParent(role))
}
/// Set the admin for a specific role (who can grant/revoke it).
///
/// # Errors
/// * [`AccessError::Unauthorized`] -- caller is not the super-admin.
/// * [`AccessError::Blacklisted`] -- the proposed admin is blacklisted.
pub fn set_role_admin(
env: Env,
caller: Address,
role: String,
admin: Address,
) -> Result<(), AccessError> {
caller.require_auth();
Self::require_super_admin(&env, &caller)?;
if Self::is_blacklisted_internal(&env, &admin) {
return Err(AccessError::Blacklisted);
}
env.storage()
.instance()
.set(&DataKey::RoleAdmin(role.clone()), &admin);
env.events()
.publish((Symbol::new(&env, "role_admin_set"),), (role, admin));
Ok(())
}
/// Returns the role admin for the given role, or None if none is set.
pub fn get_role_admin(env: Env, role: String) -> Option<Address> {
env.storage()
.instance()
.get::<DataKey, Address>(&DataKey::RoleAdmin(role))
}
/// Returns `true` if `addr` is the designated admin for `role`.
///
/// Convenience wrapper around [`Self::get_role_admin`] that avoids
/// callers having to unwrap an `Option` and compare addresses themselves.
pub fn is_role_admin(env: Env, role: String, addr: Address) -> bool {
env.storage()
.instance()
.get::<DataKey, Address>(&DataKey::RoleAdmin(role))
.map(|admin| admin == addr)
.unwrap_or(false)
}
/// Blacklist an address -- prevents it from being granted any role.
///
/// # Errors
/// * [`AccessError::Unauthorized`] -- caller is not the super-admin.
/// * [`AccessError::CannotBlacklistAdmin`] -- target is the super-admin.
pub fn blacklist(
env: Env,
caller: Address,
target: Address,
reason: Option<String>,
expires_at: Option<u64>,
) -> Result<(), AccessError> {
caller.require_auth();
Self::require_super_admin(&env, &caller)?;
let super_admin: Address = env
.storage()
.instance()
.get(&DataKey::SuperAdmin)
.ok_or(AccessError::NotInitialized)?;
if target == super_admin {
return Err(AccessError::CannotBlacklistAdmin);
}
if !env
.storage()
.instance()
.has(&DataKey::Blacklisted(target.clone()))
{
let c: u32 = env
.storage()
.instance()
.get(&DataKey::BlacklistCount)
.unwrap_or(0);
env.storage()
.instance()
.set(&DataKey::BlacklistCount, &(c + 1));
}
env.storage()
.instance()
.set(&DataKey::Blacklisted(target.clone()), &true);
if let Some(r) = reason {
env.storage()
.instance()
.set(&DataKey::BlacklistReason(target.clone()), &r);
}
if let Some(exp) = expires_at {
env.storage()
.instance()
.set(&DataKey::BlacklistExpiry(target.clone()), &exp);
}
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ADDRESS_BLACKLISTED),),
target,
);
Ok(())
}
/// Remove an address from the blacklist.
///
/// # Errors
/// * [`AccessError::Unauthorized`] -- caller is not the super-admin.
pub fn unblacklist(env: Env, caller: Address, target: Address) -> Result<(), AccessError> {
caller.require_auth();
Self::require_super_admin(&env, &caller)?;
if env
.storage()
.instance()
.has(&DataKey::Blacklisted(target.clone()))
{
let c: u32 = env
.storage()
.instance()
.get(&DataKey::BlacklistCount)
.unwrap_or(1);
env.storage()
.instance()
.set(&DataKey::BlacklistCount, &(c.saturating_sub(1)));
}
env.storage()
.instance()
.remove(&DataKey::Blacklisted(target.clone()));
env.storage()
.instance()
.remove(&DataKey::BlacklistReason(target.clone()));
env.storage()
.instance()
.remove(&DataKey::BlacklistExpiry(target.clone()));
env.events()
.publish((Symbol::new(&env, "address_unblacklisted"),), target);
Ok(())
}
/// Check if an address is blacklisted.
pub fn is_blacklisted(env: Env, target: Address) -> bool {
Self::is_blacklisted_internal(&env, &target)
}
/// Get paginated role members. Filters out revoked/expired entries.
pub fn get_role_members(env: Env, role: String, offset: u32, limit: u32) -> Vec<Address> {
if limit == 0 {
return Vec::new(&env);
}
let total: u32 = env
.storage()
.instance()
.get(&DataKey::RoleMemberCount(role.clone()))
.unwrap_or(0);
if offset >= total {
return Vec::new(&env);
}
let end = core::cmp::min(total, offset.saturating_add(limit));
let mut active_members = Vec::new(&env);
// Paginate over indexed members and filter out revoked/expired entries.
for i in offset..end {
if let Some(member) = env
.storage()
.instance()
.get::<DataKey, Address>(&DataKey::RoleMember(role.clone(), i))
{
if Self::has_role_internal(&env, &member, &role) {
active_members.push_back(member);
}
}
}
active_members
}
/// Get all roles for an address.
pub fn get_roles_for_address(env: Env, addr: Address) -> Vec<String> {
env.storage()
.instance()
.get(&DataKey::AddressRoles(addr))
.unwrap_or_else(|| Vec::new(&env))
}
/// Record a role name so it can be enumerated later via [`get_all_roles`].
fn record_role_name(env: &Env, role: &String) {
let key = DataKey::AllRoles;
let mut roles: Vec<String> = env.storage().instance().get(&key).unwrap_or_else(|| Vec::new(env));
if !roles.iter().any(|r| &r == role) {
roles.push_back(role.clone());
env.storage().instance().set(&key, &roles);
}
}
/// Return the number of indexed members ever added for `role`.
///
/// This is the storage-level member count (`RoleMemberCount`) and may
/// include entries that have since been revoked or expired; it is intended
/// for operational monitoring rather than exact active membership.
pub fn get_role_count(env: Env, role: String) -> u32 {
env.storage()
.instance()
.get(&DataKey::RoleMemberCount(role))
.unwrap_or(0)
}
/// Return the total number of distinct addresses currently stored on the
/// blacklist (including any entries whose expiry has not been garbage
/// collected).
pub fn get_blacklist_count(env: Env) -> u32 {
env.storage()
.instance()
.get(&DataKey::BlacklistCount)
.unwrap_or(0)
}
/// Return every role name that has ever been granted, for enumeration by
/// off-chain tooling (e.g. the metrics exporter).
pub fn get_all_roles(env: Env) -> Vec<String> {
env.storage()
.instance()
.get(&DataKey::AllRoles)
.unwrap_or_else(|| Vec::new(&env))
}
/// Transfer super-admin to a new address.
///
/// # Errors
/// * [`AccessError::Unauthorized`] -- caller is not the current super-admin.
pub fn transfer_super_admin(
env: Env,
current: Address,
new_admin: Address,
) -> Result<(), AccessError> {
current.require_auth();
Self::require_super_admin(&env, ¤t)?;
env.storage()
.instance()
.set(&DataKey::SuperAdmin, &new_admin);
env.events().publish(
(Symbol::new(&env, router_common::EVENT_ADMIN_TRANSFERRED),),
(current, new_admin),
);
Ok(())
}
/// Get current super-admin.
///
/// # Errors
/// * [`AccessError::NotInitialized`] -- contract not initialized.
pub fn super_admin(env: Env) -> Result<Address, AccessError> {
env.storage()
.instance()
.get(&DataKey::SuperAdmin)
.ok_or(AccessError::NotInitialized)
}
/// Force-expire a role grant, removing it from storage.
pub fn expire_role(
env: Env,
caller: Address,
role: String,
target: Address,
) -> Result<(), AccessError> {
caller.require_auth();
Self::require_super_admin(&env, &caller)?;
env.storage()
.instance()
.remove(&DataKey::RoleExpiry(role.clone(), target.clone()));
env.storage()
.instance()
.remove(&DataKey::HasRole(role.clone(), target.clone()));
env.storage()
.instance()
.remove(&DataKey::RoleMemberIndex(role.clone(), target.clone()));
env.events()
.publish((Symbol::new(&env, "role_expired"),), (role, target));
Ok(())
}
/// Grant a role to multiple accounts in one call.
///
/// Iterates `accounts` and calls the same logic as `grant_role` for each.
/// Returns a vector of per-account results so partial failures are visible.
///
/// # Errors
/// * [`AccessError::Unauthorized`] -- caller is not super-admin or role admin.
pub fn grant_role_batch(
env: Env,
admin: Address,
accounts: Vec<Address>,
role: String,
expires_at: Option<u64>,
) -> Result<Vec<Result<(), AccessError>>, AccessError> {
admin.require_auth();
Self::require_role_manager(&env, &admin, &role)?;
let mut results = Vec::new(&env);
for account in accounts.iter() {
results.push_back(Self::grant_role_internal(&env, &account, &role, expires_at));
}
Ok(results)
}
/// Revoke a role from multiple accounts in one call.
///
/// Calls the revoke logic for each target and returns `Ok(())` only
/// if all revocations succeed.
///
/// # Errors
/// * [`AccessError::Unauthorized`] -- caller is not super-admin or role admin.
/// * [`AccessError::RoleNotFound`] -- a target does not hold the role directly.
pub fn bulk_revoke_role(
env: Env,
caller: Address,
role: String,
targets: Vec<Address>,
) -> Result<(), AccessError> {
caller.require_auth();
Self::require_role_manager(&env, &caller, &role)?;
for target in targets.iter() {
Self::revoke_role_internal(&env, &role, &target)?;
}
Ok(())
}
/// Revoke a role from multiple accounts in one call.
///
/// Returns a vector of per-account results so partial failures are visible.
///
/// # Errors
/// * [`AccessError::Unauthorized`] -- caller is not super-admin or role admin.
pub fn revoke_role_batch(
env: Env,
caller: Address,
role: String,
targets: Vec<Address>,
) -> Result<Vec<Result<(), AccessError>>, AccessError> {
caller.require_auth();
Self::require_role_manager(&env, &caller, &role)?;
let mut results = Vec::new(&env);
for target in targets.iter() {
results.push_back(Self::revoke_role_internal(&env, &role, &target));
}
Ok(results)
}
// ── Helpers ───────────────────────────────────────────────────────────────
fn require_super_admin(env: &Env, caller: &Address) -> Result<(), AccessError> {
let admin: Address = env
.storage()
.instance()
.get(&DataKey::SuperAdmin)
.ok_or(AccessError::NotInitialized)?;
if &admin != caller {
return Err(AccessError::Unauthorized);
}
Ok(())
}
fn require_role_manager(env: &Env, caller: &Address, role: &String) -> Result<(), AccessError> {
if Self::is_blacklisted_internal(env, caller) {
return Err(AccessError::Blacklisted);
}
if let Some(admin) = env
.storage()
.instance()
.get::<DataKey, Address>(&DataKey::SuperAdmin)
{
if &admin == caller {
return Ok(());
}
}
if let Some(role_admin) = env
.storage()
.instance()
.get::<DataKey, Address>(&DataKey::RoleAdmin(role.clone()))
{
if &role_admin == caller {
return Ok(());
}
}
Err(AccessError::Unauthorized)
}
/// Returns true if `target` holds `role` directly (no hierarchy walk).
fn has_direct_role(env: &Env, role: &String, target: &Address) -> bool {
env.storage()
.instance()
.get::<DataKey, bool>(&DataKey::HasRole(role.clone(), target.clone()))
.unwrap_or(false)
}
/// Returns true if `account` holds `role` directly OR via the hierarchy.
///
/// Walks up the ancestor chain of `role`. At each level, checks whether
/// `account` has a direct grant for that ancestor. Also checks expiry.
/// Stops at depth `MAX_HIERARCHY_DEPTH` to guard against storage
/// inconsistencies.
fn has_role_internal(env: &Env, account: &Address, role: &String) -> bool {
if Self::is_blacklisted_internal(env, account) {
return false;
}
let mut current = role.clone();
let mut depth = 0u32;
loop {
if Self::has_direct_role(env, ¤t, account) {
// Check if role has expired
if let Some(expires_at) = env
.storage()
.instance()
.get::<DataKey, u64>(&DataKey::RoleExpiry(current.clone(), account.clone()))
{
if env.ledger().timestamp() >= expires_at {
return false;
}
}
return true;
}
match env
.storage()
.instance()
.get::<DataKey, String>(&DataKey::RoleParent(current))
{
Some(parent) => {
depth += 1;
if depth >= MAX_HIERARCHY_DEPTH {
return false;
}
current = parent;
}
None => return false,
}
}
}
/// Returns true if `ancestor` is an ancestor of `role` in the hierarchy.
/// Used by `set_role_parent` to detect cycles.
fn is_ancestor(env: &Env, role: &String, ancestor: &String) -> bool {
let mut current = role.clone();
let mut depth = 0u32;
loop {
if ¤t == ancestor {
return true;
}
match env
.storage()
.instance()
.get::<DataKey, String>(&DataKey::RoleParent(current))
{
Some(parent) => {
depth += 1;
if depth >= MAX_HIERARCHY_DEPTH {
return false;
}
current = parent;
}
None => return false,
}
}
}
/// Check if an address is blacklisted, with expiry support.
fn is_blacklisted_internal(env: &Env, target: &Address) -> bool {
let is_blacklisted = env
.storage()
.instance()
.get::<DataKey, bool>(&DataKey::Blacklisted(target.clone()))
.unwrap_or(false);
if !is_blacklisted {
return false;
}
// If an expiry is set and has passed, treat as not blacklisted and clean up
if let Some(expires_at) = env
.storage()
.instance()
.get::<DataKey, u64>(&DataKey::BlacklistExpiry(target.clone()))
{
let current_timestamp = env.ledger().timestamp();
if current_timestamp >= expires_at {
// Expired: remove stored blacklist data
env.storage()
.instance()
.remove(&DataKey::Blacklisted(target.clone()));
env.storage()
.instance()
.remove(&DataKey::BlacklistExpiry(target.clone()));
env.storage()
.instance()
.remove(&DataKey::BlacklistReason(target.clone()));
return false;
}
}
true
}
/// Internal helper used by `grant_role_batch`.
fn grant_role_internal(
env: &Env,
account: &Address,
role: &String,
expires_at: Option<u64>,
) -> Result<(), AccessError> {
if Self::is_blacklisted_internal(env, account) {
return Err(AccessError::Blacklisted);
}
if Self::has_role_internal(env, account, role) {
return Err(AccessError::AlreadyHasRole);
}
let expiry_timestamp = expires_at.unwrap_or(u64::MAX);
env.storage()
.instance()
.set(&DataKey::HasRole(role.clone(), account.clone()), &true);
Self::record_role_name(env, role);
// Add to indexed member storage
if !env
.storage()
.instance()
.has(&DataKey::RoleMemberIndex(role.clone(), account.clone()))
{
let count: u32 = env
.storage()
.instance()
.get(&DataKey::RoleMemberCount(role.clone()))
.unwrap_or(0);
env.storage()
.instance()
.set(&DataKey::RoleMember(role.clone(), count), account);
env.storage().instance().set(
&DataKey::RoleMemberIndex(role.clone(), account.clone()),
&count,
);
env.storage()
.instance()
.set(&DataKey::RoleMemberCount(role.clone()), &(count + 1));
}
let mut roles: Vec<String> = env
.storage()
.instance()
.get(&DataKey::AddressRoles(account.clone()))
.unwrap_or_else(|| Vec::new(env));
if !roles.iter().any(|r| r == *role) {
roles.push_back(role.clone());
}
env.storage()
.instance()
.set(&DataKey::AddressRoles(account.clone()), &roles);
env.storage().instance().set(
&DataKey::RoleExpiry(role.clone(), account.clone()),
&expiry_timestamp,
);
env.events().publish(
(Symbol::new(env, router_common::EVENT_ROLE_GRANTED),),
(account.clone(), role.clone(), expiry_timestamp),
);
Ok(())
}
/// Internal helper used by `revoke_role_batch`.
fn revoke_role_internal(env: &Env, role: &String, target: &Address) -> Result<(), AccessError> {
let key = DataKey::HasRole(role.clone(), target.clone());
if !env.storage().instance().has(&key) {
return Err(AccessError::RoleNotFound);
}
env.storage().instance().remove(&key);
env.storage()
.instance()
.remove(&DataKey::RoleExpiry(role.clone(), target.clone()));
env.storage()
.instance()
.remove(&DataKey::RoleMemberIndex(role.clone(), target.clone()));
env.events().publish(
(Symbol::new(env, router_common::EVENT_ROLE_REVOKED),),
(role.clone(), target.clone()),
);
Ok(())
}
}
// ── Tests ─────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
extern crate std;
use super::*;
use soroban_sdk::{
testutils::{Address as _, Events, Ledger},
Env, IntoVal, Symbol,
};
fn setup() -> (Env, Address, RouterAccessClient<'static>) {
let env = Env::default();
env.mock_all_auths();
let contract_id = env.register_contract(None, RouterAccess);
let client = RouterAccessClient::new(&env, &contract_id);
let admin = Address::generate(&env);
client.initialize(&admin);
(env, admin, client)
}
#[test]
fn test_expired_role_not_recognized() {
let (env, admin, client) = setup();
let role = String::from_str(&env, "operator");
let user = Address::generate(&env);
let expires_at = env.ledger().timestamp() + 10;
client.grant_role(&admin, &user, &role, &Some(expires_at));
env.ledger().set_timestamp(expires_at + 10);
assert!(!client.has_role(&role, &user));
}
#[test]
fn test_role_expires_correctly_with_timestamp() {
let (env, admin, client) = setup();
let role = String::from_str(&env, "operator");
let user = Address::generate(&env);
let expires_at = env.ledger().timestamp() + 1;
client.grant_role(&admin, &user, &role, &Some(expires_at));
env.ledger().set_timestamp(expires_at + 4);
assert!(!client.has_role(&role, &user));
}
#[test]
fn test_set_role_admin_emits_event() {
let (env, admin, client) = setup();
let role = String::from_str(&env, "operator");
let new_role_admin = Address::generate(&env);
client.set_role_admin(&admin, &role, &new_role_admin);
let events = env.events().all();
let last = events.last().unwrap();
let topic: Symbol = last.1.get(0).unwrap().into_val(&env);
assert_eq!(topic, Symbol::new(&env, "role_admin_set"));
let (emitted_role, emitted_admin): (String, Address) = last.2.into_val(&env);
assert_eq!(emitted_role, role);
assert_eq!(emitted_admin, new_role_admin);
}
#[test]
fn test_set_role_admin_rejects_blacklisted_address() {
let (env, admin, client) = setup();
let role = String::from_str(&env, "operator");
let blacklisted_addr = Address::generate(&env);
// Blacklist the address
client.blacklist(&admin, &blacklisted_addr, &None::<String>, &None);
// Try to set blacklisted address as role admin
let result = client.try_set_role_admin(&admin, &role, &blacklisted_addr);
assert_eq!(result, Err(Ok(AccessError::Blacklisted)));
}
#[test]
fn test_set_role_admin_valid_address_succeeds() {
let (env, admin, client) = setup();
let role = String::from_str(&env, "operator");