miden-testing 0.16.0-alpha.1

Miden protocol testing tools
Documentation
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
extern crate alloc;

use alloc::collections::BTreeMap;
use alloc::string::String;
use core::slice;

use miden_processor::crypto::random::RandomCoin;
use miden_protocol::account::{
    Account,
    AccountBuilder,
    AccountId,
    AccountType,
    RoleSymbol,
    StorageMapKey,
};
use miden_protocol::note::{Note, NoteType};
use miden_protocol::{Felt, Word};
use miden_standards::account::access::{AccessControl, RoleBasedAccessControl};
use miden_standards::errors::standards::{
    ERR_ACCOUNT_NOT_IN_ROLE,
    ERR_ROLE_SYMBOL_ZERO,
    ERR_SENDER_NOT_ROLE_ADMIN,
};
use miden_standards::testing::note::NoteBuilder;
use miden_testing::{Auth, MockChain, assert_transaction_executor_error};
use rstest::rstest;

// HELPERS
// ================================================================================================

fn create_rbac_account_with_admin(admin: AccountId) -> anyhow::Result<Account> {
    let account = AccountBuilder::new([9; 32])
        .account_type(AccountType::Public)
        .with_auth_component(Auth::IncrNonce)
        .with_components(AccessControl::Rbac { admin, roles: BTreeMap::new() })
        .build_existing()?;

    Ok(account)
}

// Shared with the `rbac_action` note test suite.
pub(super) fn create_rbac_chain(admin: AccountId) -> anyhow::Result<(Account, MockChain)> {
    let account = create_rbac_account_with_admin(admin)?;
    let mut builder = MockChain::builder();
    builder.add_account(account.clone())?;

    Ok((account, builder.build()?))
}

pub(super) fn test_account_id(seed: u8) -> AccountId {
    AccountId::builder()
        .account_type(AccountType::Private)
        .build_with_seed([seed; 32])
}

pub(super) fn role(name: &str) -> RoleSymbol {
    RoleSymbol::new(name).expect("role symbol should be valid")
}

fn role_config_key(role: &RoleSymbol) -> StorageMapKey {
    StorageMapKey::from_raw(Word::from([Felt::ZERO, Felt::ZERO, Felt::ZERO, Felt::from(role)]))
}

fn role_membership_key(role: &RoleSymbol, account_id: AccountId) -> StorageMapKey {
    StorageMapKey::from_raw(Word::from([
        Felt::ZERO,
        Felt::from(role),
        account_id.suffix(),
        account_id.prefix().as_felt(),
    ]))
}

/// Returns the role's `(member_count, admin_role_symbol)` from on-chain storage.
pub(super) fn get_role_config(
    account: &Account,
    role: &RoleSymbol,
) -> anyhow::Result<(Felt, Felt)> {
    let word = account
        .storage()
        .get_map_item(RoleBasedAccessControl::role_config_slot(), role_config_key(role))?;
    Ok((word[0], word[1]))
}

pub(super) fn is_role_member(
    account: &Account,
    role: &RoleSymbol,
    account_id: AccountId,
) -> anyhow::Result<bool> {
    let word = account.storage().get_map_item(
        RoleBasedAccessControl::role_membership_slot(),
        role_membership_key(role, account_id),
    )?;
    Ok(word[0].as_canonical_u64() != 0)
}

fn build_note(sender: AccountId, code: impl Into<String>) -> anyhow::Result<Note> {
    let seed: [u64; 4] = rand::random();
    let mut rng = RandomCoin::new(Word::from(seed.map(Felt::new_unchecked)));
    Ok(NoteBuilder::new(sender, &mut rng)
        .note_type(NoteType::Private)
        .code(code.into())
        .build()?)
}

async fn execute_note_and_apply(
    mock_chain: &MockChain,
    account: &Account,
    note: &Note,
) -> anyhow::Result<Account> {
    let tx = mock_chain
        .build_tx_context(account.clone(), &[], slice::from_ref(note))?
        .build()?;
    let executed = tx.execute().await?;

    let mut updated = account.clone();
    updated.apply_patch(executed.account_patch())?;

    Ok(updated)
}

// SCRIPTS
// ================================================================================================

fn set_role_admin_script(role: &RoleSymbol, admin_role: Option<&RoleSymbol>) -> String {
    let admin_role = admin_role.map(Felt::from).unwrap_or(Felt::ZERO);
    format!(
        r#"
        use miden::standards::access::rbac

        @note_script
        pub proc main
            repeat.14 push.0 end
            push.{admin_role}
            push.{role}
            call.rbac::set_role_admin
            dropw dropw dropw dropw
        end
        "#,
        role = Felt::from(role),
    )
}

fn grant_role_script(role: &RoleSymbol, account_id: AccountId) -> String {
    format!(
        r#"
        use miden::standards::access::rbac

        @note_script
        pub proc main
            repeat.13 push.0 end
            push.{account_prefix}
            push.{account_suffix}
            push.{role}
            call.rbac::grant_role
            dropw dropw dropw dropw
        end
        "#,
        account_prefix = account_id.prefix().as_felt(),
        account_suffix = account_id.suffix(),
        role = Felt::from(role),
    )
}

fn revoke_role_script(role: &RoleSymbol, account_id: AccountId) -> String {
    format!(
        r#"
        use miden::standards::access::rbac

        @note_script
        pub proc main
            repeat.13 push.0 end
            push.{account_prefix}
            push.{account_suffix}
            push.{role}
            call.rbac::revoke_role
            dropw dropw dropw dropw
        end
        "#,
        account_prefix = account_id.prefix().as_felt(),
        account_suffix = account_id.suffix(),
        role = Felt::from(role),
    )
}

fn renounce_role_script(role: &RoleSymbol) -> String {
    format!(
        r#"
        use miden::standards::access::rbac

        @note_script
        pub proc main
            repeat.15 push.0 end
            push.{role}
            call.rbac::renounce_role
            dropw dropw dropw dropw
        end
        "#,
        role = Felt::from(role),
    )
}

fn assert_role_member_count_script(role: &RoleSymbol, expected_count: u64) -> String {
    format!(
        r#"
        use miden::standards::access::rbac

        @note_script
        pub proc main
            repeat.15 push.0 end
            push.{role}
            call.rbac::get_role_member_count
            eq.{expected_count} assert.err="role member count mismatch"
            dropw dropw dropw
            drop drop drop
        end
        "#,
        role = Felt::from(role),
    )
}

fn assert_role_has_members_script(role: &RoleSymbol, expected_has_members: bool) -> String {
    let expected_has_members = u8::from(expected_has_members);

    format!(
        r#"
        use miden::standards::access::rbac

        @note_script
        pub proc main
            repeat.15 push.0 end
            push.{role}
            call.rbac::get_role_member_count
            neq.0
            eq.{expected_has_members} assert.err="role population mismatch"
            dropw dropw dropw
            drop drop drop
        end
        "#,
        role = Felt::from(role),
    )
}

fn assert_role_admin_script(role: &RoleSymbol, expected_admin_role: Option<&RoleSymbol>) -> String {
    let expected_admin_role = expected_admin_role.map(Felt::from).unwrap_or(Felt::ZERO);

    format!(
        r#"
        use miden::standards::access::rbac

        @note_script
        pub proc main
            repeat.15 push.0 end
            push.{role}
            call.rbac::get_role_admin
            eq.{expected_admin_role} assert.err="role admin mismatch"
            dropw dropw dropw
            drop drop drop
        end
        "#,
        role = Felt::from(role),
    )
}

fn assert_has_role_script(
    role: &RoleSymbol,
    account_id: AccountId,
    expected_has_role: bool,
) -> String {
    let expected_has_role = u8::from(expected_has_role);

    format!(
        r#"
        use miden::standards::access::rbac

        @note_script
        pub proc main
            repeat.13 push.0 end
            push.{account_prefix}
            push.{account_suffix}
            push.{role}
            call.rbac::has_role
            eq.{expected_has_role} assert.err="account role membership mismatch"
            dropw dropw dropw
            drop drop drop
        end
        "#,
        account_prefix = account_id.prefix().as_felt(),
        account_suffix = account_id.suffix(),
        role = Felt::from(role),
    )
}

fn set_role_admin_raw_script(role: Felt, admin_role: Felt) -> String {
    format!(
        r#"
        use miden::standards::access::rbac

        @note_script
        pub proc main
            repeat.14 push.0 end
            push.{admin_role}
            push.{role}
            call.rbac::set_role_admin
            dropw dropw dropw dropw
        end
        "#,
    )
}

// TESTS
// ================================================================================================

/// End-to-end role management through the delegated-admin path: the `ADMIN` bootstrap member
/// delegates `MINTER` to `MINTER_ADMIN`, seeds a `MINTER_ADMIN` member, and that
/// delegate — not ADMIN — grants and revokes `MINTER`.
#[tokio::test]
async fn test_rbac_role_management_and_lookup() -> anyhow::Result<()> {
    let admin = test_account_id(11);
    let admin_member = test_account_id(13);
    let member = test_account_id(12);

    let minter = role("MINTER");
    let minter_admin = role("MINTER_ADMIN");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    // Admin (a member of ADMIN, the default admin of every role) delegates MINTER's admin.
    let set_role_admin_note =
        build_note(admin, set_role_admin_script(&minter, Some(&minter_admin)))?;
    let updated = execute_note_and_apply(&mock_chain, &account, &set_role_admin_note).await?;

    let (member_count, admin_role) = get_role_config(&updated, &minter)?;
    assert_eq!(member_count, Felt::from(0u32));
    assert_eq!(admin_role, Felt::from(&minter_admin));

    // MINTER_ADMIN is itself undelegated, so ADMIN seeds its first member.
    let grant_admin_note = build_note(admin, grant_role_script(&minter_admin, admin_member))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &grant_admin_note).await?;

    // The MINTER_ADMIN member — not ADMIN — grants MINTER.
    let grant_role_note = build_note(admin_member, grant_role_script(&minter, member))?;
    let granted = execute_note_and_apply(&mock_chain, &updated, &grant_role_note).await?;

    let (member_count, admin_role) = get_role_config(&granted, &minter)?;
    assert_eq!(member_count, Felt::from(1u32));
    assert_eq!(admin_role, Felt::from(&minter_admin));
    assert!(is_role_member(&granted, &minter, member)?);

    let revoke_role_note = build_note(admin_member, revoke_role_script(&minter, member))?;
    let revoked = execute_note_and_apply(&mock_chain, &granted, &revoke_role_note).await?;

    let (member_count, admin_role) = get_role_config(&revoked, &minter)?;
    assert_eq!(member_count, Felt::from(0u32));
    assert_eq!(admin_role, Felt::from(&minter_admin));
    assert!(!is_role_member(&revoked, &minter, member)?);

    Ok(())
}

#[tokio::test]
async fn test_rbac_renounce_role_and_permission_checks() -> anyhow::Result<()> {
    let admin = test_account_id(31);
    let member = test_account_id(32);
    let outsider = test_account_id(33);

    let pauser = role("PAUSER");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    let grant_pauser_to_member = grant_role_script(&pauser, member);

    let non_admin_grant_note = build_note(outsider, grant_pauser_to_member.clone())?;
    let tx = mock_chain
        .build_tx_context(account.clone(), &[], slice::from_ref(&non_admin_grant_note))?
        .build()?;
    let result = tx.execute().await;
    assert_transaction_executor_error!(result, ERR_SENDER_NOT_ROLE_ADMIN);

    let admin_grant_note = build_note(admin, grant_pauser_to_member)?;
    let updated = execute_note_and_apply(&mock_chain, &account, &admin_grant_note).await?;
    assert!(is_role_member(&updated, &pauser, member)?);

    let renounce_note = build_note(member, renounce_role_script(&pauser))?;
    let renounced = execute_note_and_apply(&mock_chain, &updated, &renounce_note).await?;
    assert!(!is_role_member(&renounced, &pauser, member)?);

    let bad_revoke_note = build_note(admin, revoke_role_script(&pauser, member))?;
    let tx = mock_chain
        .build_tx_context(renounced, &[], slice::from_ref(&bad_revoke_note))?
        .build()?;
    let result = tx.execute().await;
    assert_transaction_executor_error!(result, ERR_ACCOUNT_NOT_IN_ROLE);

    Ok(())
}

#[tokio::test]
async fn test_rbac_grant_role_sets_membership() -> anyhow::Result<()> {
    let admin = test_account_id(41);
    let member = test_account_id(42);

    let minter = role("MINTER");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    let grant_note = build_note(admin, grant_role_script(&minter, member))?;
    let granted = execute_note_and_apply(&mock_chain, &account, &grant_note).await?;

    assert!(is_role_member(&granted, &minter, member)?);
    let (member_count, _) = get_role_config(&granted, &minter)?;
    assert_eq!(member_count, Felt::ONE);

    Ok(())
}

#[tokio::test]
async fn test_rbac_grant_existing_member_is_noop() -> anyhow::Result<()> {
    let admin = test_account_id(43);
    let member = test_account_id(44);

    let minter = role("MINTER");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    let grant_minter_to_member = grant_role_script(&minter, member);

    let grant_note = build_note(admin, grant_minter_to_member.clone())?;
    let granted = execute_note_and_apply(&mock_chain, &account, &grant_note).await?;

    let regrant_note = build_note(admin, grant_minter_to_member)?;
    let regranted = execute_note_and_apply(&mock_chain, &granted, &regrant_note).await?;

    let (member_count, _) = get_role_config(&regranted, &minter)?;
    assert_eq!(member_count, Felt::from(1u32));
    assert!(is_role_member(&regranted, &minter, member)?);

    Ok(())
}

#[tokio::test]
async fn test_rbac_member_count_tracks_grants_and_revokes() -> anyhow::Result<()> {
    let admin = test_account_id(45);
    let alice = test_account_id(46);
    let bob = test_account_id(47);

    let pauser = role("PAUSER");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    let first_grant = build_note(admin, grant_role_script(&pauser, alice))?;
    let updated = execute_note_and_apply(&mock_chain, &account, &first_grant).await?;
    assert_eq!(get_role_config(&updated, &pauser)?.0, Felt::from(1u32));

    let second_grant = build_note(admin, grant_role_script(&pauser, bob))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &second_grant).await?;
    assert_eq!(get_role_config(&updated, &pauser)?.0, Felt::from(2u32));

    let revoke_alice = build_note(admin, revoke_role_script(&pauser, alice))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &revoke_alice).await?;
    assert_eq!(get_role_config(&updated, &pauser)?.0, Felt::from(1u32));
    assert!(!is_role_member(&updated, &pauser, alice)?);
    assert!(is_role_member(&updated, &pauser, bob)?);

    let revoke_bob = build_note(admin, revoke_role_script(&pauser, bob))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &revoke_bob).await?;
    assert_eq!(get_role_config(&updated, &pauser)?.0, Felt::from(0u32));
    assert!(!is_role_member(&updated, &pauser, bob)?);

    Ok(())
}

#[tokio::test]
async fn test_rbac_get_role_member_count_returns_zero_for_missing_role() -> anyhow::Result<()> {
    let admin = test_account_id(48);

    let missing_role = role("MISSING");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    let query_note = build_note(admin, assert_role_member_count_script(&missing_role, 0))?;
    let _ = execute_note_and_apply(&mock_chain, &account, &query_note).await?;

    Ok(())
}

#[tokio::test]
async fn test_rbac_get_role_admin_returns_zero_when_unset() -> anyhow::Result<()> {
    let admin = test_account_id(49);

    let admin_managed_role = role("ADMIN_MGD");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    let query_note = build_note(admin, assert_role_admin_script(&admin_managed_role, None))?;
    let _ = execute_note_and_apply(&mock_chain, &account, &query_note).await?;

    Ok(())
}

#[tokio::test]
async fn test_rbac_non_admin_cannot_revoke_role() -> anyhow::Result<()> {
    let admin = test_account_id(54);
    let outsider = test_account_id(55);
    let member = test_account_id(56);

    let minter = role("MINTER");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    let grant_note = build_note(admin, grant_role_script(&minter, member))?;
    let granted = execute_note_and_apply(&mock_chain, &account, &grant_note).await?;

    let revoke_note = build_note(outsider, revoke_role_script(&minter, member))?;
    let tx = mock_chain
        .build_tx_context(granted, &[], slice::from_ref(&revoke_note))?
        .build()?;
    let result = tx.execute().await;
    assert_transaction_executor_error!(result, ERR_SENDER_NOT_ROLE_ADMIN);

    Ok(())
}

#[tokio::test]
async fn test_rbac_non_member_cannot_renounce_role() -> anyhow::Result<()> {
    let admin = test_account_id(57);
    let outsider = test_account_id(58);

    let pauser = role("PAUSER");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    let renounce_note = build_note(outsider, renounce_role_script(&pauser))?;
    let tx = mock_chain
        .build_tx_context(account, &[], slice::from_ref(&renounce_note))?
        .build()?;
    let result = tx.execute().await;
    assert_transaction_executor_error!(result, ERR_ACCOUNT_NOT_IN_ROLE);

    Ok(())
}

#[tokio::test]
async fn test_rbac_revoke_role_clears_membership() -> anyhow::Result<()> {
    let admin = test_account_id(59);
    let member = test_account_id(60);

    let burner = role("BURNER");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    let grant_note = build_note(admin, grant_role_script(&burner, member))?;
    let granted = execute_note_and_apply(&mock_chain, &account, &grant_note).await?;
    assert!(is_role_member(&granted, &burner, member)?);

    let revoke_note = build_note(admin, revoke_role_script(&burner, member))?;
    let revoked = execute_note_and_apply(&mock_chain, &granted, &revoke_note).await?;
    assert!(!is_role_member(&revoked, &burner, member)?);
    assert_eq!(get_role_config(&revoked, &burner)?.0, Felt::from(0u32));

    Ok(())
}

#[tokio::test]
async fn test_rbac_get_role_admin_returns_set_role() -> anyhow::Result<()> {
    let admin = test_account_id(75);

    let minter = role("MINTER");
    let minter_admin = role("MINTER_ADMIN");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    let set_role_admin_note =
        build_note(admin, set_role_admin_script(&minter, Some(&minter_admin)))?;
    let updated = execute_note_and_apply(&mock_chain, &account, &set_role_admin_note).await?;

    let query_note = build_note(admin, assert_role_admin_script(&minter, Some(&minter_admin)))?;
    let _ = execute_note_and_apply(&mock_chain, &updated, &query_note).await?;

    Ok(())
}

/// After the sole ADMIN renounces `ADMIN`, a delegated role admin can still manage its
/// delegated role: exclusive delegation means MANAGER's authority over USER does not depend on
/// `ADMIN` existing.
#[tokio::test]
async fn test_rbac_role_admin_can_manage_role_after_admin_renounces() -> anyhow::Result<()> {
    let admin = test_account_id(83);
    let manager = test_account_id(84);
    let user = test_account_id(85);

    let admin_role = RoleBasedAccessControl::admin_role();
    let user_role = role("USER");
    let manager_role = role("MANAGER");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    // ADMIN delegates USER to MANAGER and seeds a MANAGER member.
    let set_role_admin_note =
        build_note(admin, set_role_admin_script(&user_role, Some(&manager_role)))?;
    let updated = execute_note_and_apply(&mock_chain, &account, &set_role_admin_note).await?;

    let grant_manager_note = build_note(admin, grant_role_script(&manager_role, manager))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &grant_manager_note).await?;

    // The sole ADMIN renounces ADMIN, so ADMIN no longer has any member.
    let renounce_note = build_note(admin, renounce_role_script(&admin_role))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &renounce_note).await?;
    assert!(!is_role_member(&updated, &admin_role, admin)?);

    // MANAGER can still grant and revoke USER — its authority is not tied to ADMIN.
    let grant_user_note = build_note(manager, grant_role_script(&user_role, user))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &grant_user_note).await?;
    assert!(is_role_member(&updated, &user_role, user)?);

    let revoke_user_note = build_note(manager, revoke_role_script(&user_role, user))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &revoke_user_note).await?;
    assert!(!is_role_member(&updated, &user_role, user)?);

    Ok(())
}

#[tokio::test]
async fn test_rbac_member_count_and_has_role_queries() -> anyhow::Result<()> {
    let admin = test_account_id(86);
    let member = test_account_id(87);
    let outsider = test_account_id(88);

    let user_role = role("USER");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    let role_missing_note = build_note(admin, assert_role_has_members_script(&user_role, false))?;
    let _ = execute_note_and_apply(&mock_chain, &account, &role_missing_note).await?;

    let non_member_note = build_note(admin, assert_has_role_script(&user_role, member, false))?;
    let _ = execute_note_and_apply(&mock_chain, &account, &non_member_note).await?;

    let grant_note = build_note(admin, grant_role_script(&user_role, member))?;
    let updated = execute_note_and_apply(&mock_chain, &account, &grant_note).await?;

    let role_populated_note = build_note(admin, assert_role_has_members_script(&user_role, true))?;
    let _ = execute_note_and_apply(&mock_chain, &updated, &role_populated_note).await?;

    let member_note = build_note(admin, assert_has_role_script(&user_role, member, true))?;
    let _ = execute_note_and_apply(&mock_chain, &updated, &member_note).await?;

    let outsider_note = build_note(admin, assert_has_role_script(&user_role, outsider, false))?;
    let _ = execute_note_and_apply(&mock_chain, &updated, &outsider_note).await?;

    Ok(())
}

#[tokio::test]
async fn test_rbac_non_admin_cannot_set_role_admin() -> anyhow::Result<()> {
    let admin = test_account_id(89);
    let outsider = test_account_id(90);

    let user_role = role("USER");
    let manager_role = role("MANAGER");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    // USER is undelegated, so its effective admin is ADMIN. The outsider is not an ADMIN member.
    let note = build_note(outsider, set_role_admin_script(&user_role, Some(&manager_role)))?;
    let tx = mock_chain.build_tx_context(account, &[], slice::from_ref(&note))?.build()?;
    let result = tx.execute().await;
    assert_transaction_executor_error!(result, ERR_SENDER_NOT_ROLE_ADMIN);

    Ok(())
}

#[tokio::test]
async fn test_rbac_set_role_admin_rejects_zero_role_symbol() -> anyhow::Result<()> {
    let admin = test_account_id(92);

    let manager_role = role("MANAGER");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    let note = build_note(admin, set_role_admin_raw_script(Felt::ZERO, Felt::from(&manager_role)))?;
    let tx = mock_chain.build_tx_context(account, &[], slice::from_ref(&note))?.build()?;
    let result = tx.execute().await;
    assert_transaction_executor_error!(result, ERR_ROLE_SYMBOL_ZERO);

    Ok(())
}

#[tokio::test]
async fn test_rbac_set_role_admin_does_not_create_role() -> anyhow::Result<()> {
    let admin = test_account_id(93);

    let user_role = role("USER");
    let manager_role = role("MANAGER");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    let note = build_note(admin, set_role_admin_script(&user_role, Some(&manager_role)))?;
    let updated = execute_note_and_apply(&mock_chain, &account, &note).await?;

    let (user_count, user_admin) = get_role_config(&updated, &user_role)?;
    assert_eq!(user_count, Felt::from(0u32));
    assert_eq!(user_admin, Felt::from(&manager_role));
    let (manager_count, _) = get_role_config(&updated, &manager_role)?;
    assert_eq!(manager_count, Felt::from(0u32));

    Ok(())
}

#[tokio::test]
async fn test_rbac_granting_admin_role_does_not_change_target_role_admin_config()
-> anyhow::Result<()> {
    let admin = test_account_id(96);
    let delegate = test_account_id(97);

    let user_role = role("USER");
    let manager_role = role("MANAGER");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    let set_admin_note = build_note(admin, set_role_admin_script(&user_role, Some(&manager_role)))?;
    let updated = execute_note_and_apply(&mock_chain, &account, &set_admin_note).await?;
    assert_eq!(get_role_config(&updated, &user_role)?.1, Felt::from(&manager_role));

    let grant_manager_note = build_note(admin, grant_role_script(&manager_role, delegate))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &grant_manager_note).await?;

    let (user_count, user_admin) = get_role_config(&updated, &user_role)?;
    assert_eq!(user_admin, Felt::from(&manager_role));
    assert_eq!(user_count, Felt::from(0u32));

    Ok(())
}

/// The action that a role's delegated admin performs exclusively, out of the general `ADMIN`
/// role's reach.
enum DelegatedAdminAction {
    /// Grant the delegated role to a member (`grant_role`).
    GrantRole,
    /// Clear the delegation, reverting the role to `ADMIN` management (`set_role_admin(_, None)`).
    ClearDelegation,
}

/// Regression test: once a role is delegated to a dedicated admin role, the general `ADMIN` role
/// is locked out of it entirely — it can neither manage membership (`grant_role`) nor re-point the
/// delegation (`set_role_admin`). The role becomes exclusively controlled by its delegated admin,
/// so a sensitive capability can be kept out of reach of the general administrator.
#[rstest]
#[case::grant_role(DelegatedAdminAction::GrantRole)]
#[case::clear_delegation(DelegatedAdminAction::ClearDelegation)]
#[tokio::test]
async fn test_rbac_delegation_locks_out_admin(
    #[case] action: DelegatedAdminAction,
) -> anyhow::Result<()> {
    let admin = test_account_id(101); // seeded as the sole ADMIN member
    let delegated_admin = test_account_id(102);
    let member = test_account_id(103);

    let minter = role("MINTER");
    let mint_admin = role("MINT_ADMIN");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    // ADMIN delegates MINTER to MINT_ADMIN and seeds a MINT_ADMIN member.
    let set_admin_note = build_note(admin, set_role_admin_script(&minter, Some(&mint_admin)))?;
    let updated = execute_note_and_apply(&mock_chain, &account, &set_admin_note).await?;
    let grant_admin_note = build_note(admin, grant_role_script(&mint_admin, delegated_admin))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &grant_admin_note).await?;

    // The guarded action MINTER's effective admin controls; both grant and re-delegation are
    // gated on the delegated admin, so neither is reachable by the general ADMIN role.
    let action_script = match action {
        DelegatedAdminAction::GrantRole => grant_role_script(&minter, member),
        DelegatedAdminAction::ClearDelegation => set_role_admin_script(&minter, None),
    };

    // The ADMIN member (admin) can no longer perform it — MINTER is out of ADMIN's reach.
    let admin_note = build_note(admin, action_script.clone())?;
    let result = mock_chain
        .build_tx_context(updated.clone(), &[], slice::from_ref(&admin_note))?
        .build()?
        .execute()
        .await;
    assert_transaction_executor_error!(result, ERR_SENDER_NOT_ROLE_ADMIN);

    // Only the delegated MINT_ADMIN member can, and the action takes effect.
    let admin_note = build_note(delegated_admin, action_script)?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &admin_note).await?;
    match action {
        DelegatedAdminAction::GrantRole => assert!(is_role_member(&updated, &minter, member)?),
        DelegatedAdminAction::ClearDelegation => {
            let query_note = build_note(admin, assert_role_admin_script(&minter, None))?;
            execute_note_and_apply(&mock_chain, &updated, &query_note).await?;
        },
    }

    Ok(())
}

/// The `ADMIN` role is an ordinary self-administered role: its membership can be handed off,
/// after which the previous holder loses all administrative authority. There is no hard-wired
/// super-admin key.
#[tokio::test]
async fn test_rbac_admin_membership_can_be_handed_off() -> anyhow::Result<()> {
    let admin = test_account_id(104); // initial ADMIN member
    let new_admin = test_account_id(105);
    let member = test_account_id(106);

    let admin_role = RoleBasedAccessControl::admin_role();
    let pauser = role("PAUSER");

    let (account, mock_chain) = create_rbac_chain(admin)?;

    // Admin grants ADMIN to new_admin (ADMIN administers itself), then new_admin revokes admin.
    let grant_admin_note = build_note(admin, grant_role_script(&admin_role, new_admin))?;
    let updated = execute_note_and_apply(&mock_chain, &account, &grant_admin_note).await?;
    assert!(is_role_member(&updated, &admin_role, new_admin)?);

    let revoke_admin_note = build_note(new_admin, revoke_role_script(&admin_role, admin))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &revoke_admin_note).await?;
    assert!(!is_role_member(&updated, &admin_role, admin)?);

    // The former ADMIN can no longer administer roles.
    let admin_grant_note = build_note(admin, grant_role_script(&pauser, member))?;
    let result = mock_chain
        .build_tx_context(updated.clone(), &[], slice::from_ref(&admin_grant_note))?
        .build()?
        .execute()
        .await;
    assert_transaction_executor_error!(result, ERR_SENDER_NOT_ROLE_ADMIN);

    // The new ADMIN can.
    let new_admin_grant_note = build_note(new_admin, grant_role_script(&pauser, member))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &new_admin_grant_note).await?;
    assert!(is_role_member(&updated, &pauser, member)?);

    Ok(())
}

/// The `admin` passed to `AccessControl::Rbac` is seeded as the initial member of the
/// self-administered `ADMIN` role, which bootstraps role administration.
#[tokio::test]
async fn test_rbac_admin_seeded_as_initial_member() -> anyhow::Result<()> {
    let admin = test_account_id(107);
    let admin_role = RoleBasedAccessControl::admin_role();

    let account = create_rbac_account_with_admin(admin)?;

    assert!(is_role_member(&account, &admin_role, admin)?);
    let (member_count, admin_of_admin) = get_role_config(&account, &admin_role)?;
    assert_eq!(member_count, Felt::from(1u32));
    // ADMIN administers itself: its delegated admin is left unset (0).
    assert_eq!(admin_of_admin, Felt::ZERO);

    Ok(())
}

/// `ADMIN` is renounceable through the standard API. While another admin remains the role stays
/// manageable; once the last admin renounces, `ADMIN` has no members and the roles it administers
/// can no longer be managed.
#[tokio::test]
async fn test_rbac_admin_can_renounce_admin_role() -> anyhow::Result<()> {
    let admin1 = test_account_id(120);
    let admin2 = test_account_id(121);
    let member = test_account_id(122);
    let orphan = test_account_id(123);

    let admin_role = RoleBasedAccessControl::admin_role();
    let pauser = role("PAUSER");

    let (account, mock_chain) = create_rbac_chain(admin1)?;

    // admin1 grants ADMIN to admin2, so ADMIN has two members (ADMIN administers itself).
    let grant_admin2_note = build_note(admin1, grant_role_script(&admin_role, admin2))?;
    let updated = execute_note_and_apply(&mock_chain, &account, &grant_admin2_note).await?;
    assert!(is_role_member(&updated, &admin_role, admin2)?);

    // admin1 renounces ADMIN while admin2 remains.
    let renounce_admin1_note = build_note(admin1, renounce_role_script(&admin_role))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &renounce_admin1_note).await?;
    assert!(!is_role_member(&updated, &admin_role, admin1)?);

    // ADMIN is still manageable: the remaining admin can grant a role.
    let admin2_grant_note = build_note(admin2, grant_role_script(&pauser, member))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &admin2_grant_note).await?;
    assert!(is_role_member(&updated, &pauser, member)?);

    // The last admin renounces ADMIN, leaving it with no members.
    let renounce_admin2_note = build_note(admin2, renounce_role_script(&admin_role))?;
    let updated = execute_note_and_apply(&mock_chain, &updated, &renounce_admin2_note).await?;
    assert!(!is_role_member(&updated, &admin_role, admin2)?);
    assert_eq!(get_role_config(&updated, &admin_role)?.0, Felt::from(0u32));

    // ADMIN is now unmanageable: granting an ADMIN-administered role fails for everyone.
    let orphan_grant_note = build_note(admin2, grant_role_script(&pauser, orphan))?;
    let result = mock_chain
        .build_tx_context(updated.clone(), &[], slice::from_ref(&orphan_grant_note))?
        .build()?
        .execute()
        .await;
    assert_transaction_executor_error!(result, ERR_SENDER_NOT_ROLE_ADMIN);

    Ok(())
}