did-hosting-common 0.10.0

DID Hosting Common, Common methods and structs related to WebVH Content
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
//! `acl/change-role/0.1` handler — record a role transition with an
//! optimistic-concurrency check against the subject's prior role.
//!
//! Spec contract (from `specs/acl/change-role/0.1/spec.md`):
//!
//! * State-checked: maintainer rejects with `acl/change-role:state_mismatch`
//!   when the subject's current role does not match `payload.fromRole`.
//! * Role-vocabulary check: returns `acl/change-role:role_not_recognized`
//!   when either `fromRole` or `toRole` lies outside `admin/owner/service`.
//! * Self-promotion (issuer == subject, `toRole` strictly greater than
//!   `fromRole`) is forbidden by maintainer policy — flagged with
//!   `permission_denied`.
//! * Last-authority guard: a change that demotes the only Admin is
//!   rejected with `acl/change-role:last_authority_protected` — a
//!   maintainer-minted extended code (SPEC.md §8.5) pinned to this
//!   spec's slug so clients dispatching on `payload.code` don't have
//!   to cross slugs.

use serde_json::json;
use trust_tasks_rs::{
    ErrorPayload, ErrorResponse, Payload, ProofPolicy, ProofVerifier, ResolvedParties,
    StandardCode, TransportHandler, TrustTask, specs::acl::change_role::v0_1 as change_role,
};

use crate::server::acl::{self, AclEntry, Role};
use crate::server::trust_tasks::{
    DispatchOutcome, TrustTaskContext, entry::SpecAclEntry, reject_with, run_pipeline,
};

const ERR_STATE_MISMATCH: &str = "state_mismatch";
const ERR_ROLE_NOT_RECOGNIZED: &str = "role_not_recognized";
const ERR_LAST_AUTHORITY: &str = "last_authority_protected";

/// Run the framework pipeline + business logic for an inbound
/// `acl/change-role/0.1` request.
pub async fn handle<V>(
    ctx: &TrustTaskContext<'_>,
    transport: &(impl TransportHandler + Sync),
    policy: ProofPolicy<'_, V>,
    doc: TrustTask<change_role::Payload>,
) -> DispatchOutcome
where
    V: ProofVerifier + ?Sized,
{
    let acl_ks = ctx.acl_ks.clone();
    let acl_locks = ctx.acl_locks.clone();
    run_pipeline(
        transport,
        policy,
        doc,
        ctx.my_vid,
        move |doc, parties| async move {
            // Serialise every ACL mutation through one global lock so
            // the read-then-write critical section is race-free
            // across concurrent admins. See `ACL_WRITE_LOCK_KEY` for
            // why per-subject locking is insufficient.
            let _guard = acl_locks
                .guard(crate::server::trust_tasks::ACL_WRITE_LOCK_KEY)
                .await;
            handle_inner(&acl_ks, doc, &parties).await
        },
    )
    .await
}

async fn handle_inner(
    acl_ks: &crate::server::store::KeyspaceHandle,
    doc: TrustTask<change_role::Payload>,
    parties: &ResolvedParties,
) -> Result<TrustTask<change_role::Response>, ErrorResponse> {
    // ─── 1. Authorise: caller must be Admin. ──────────────────────
    let caller = parties.issuer.as_deref().ok_or_else(|| {
        reject_with(
            &doc,
            ErrorPayload::new(StandardCode::PermissionDenied)
                .with_message("inbound document has no in-band or transport-derived issuer"),
        )
    })?;
    match acl::check_acl(acl_ks, caller).await {
        Ok(Role::Admin) => {}
        Ok(_) => {
            return Err(reject_with(
                &doc,
                ErrorPayload::new(StandardCode::PermissionDenied)
                    .with_message("only Admin callers may emit acl/change-role/0.1"),
            ));
        }
        Err(_) => {
            return Err(reject_with(
                &doc,
                ErrorPayload::new(StandardCode::PermissionDenied)
                    .with_message("caller is not present in the maintainer's ACL"),
            ));
        }
    }

    let from_role_str: String = (*doc.payload.from_role).clone();
    let to_role_str: String = (*doc.payload.to_role).clone();

    // ─── 2. Role-vocabulary check. ────────────────────────────────
    let from_role = parse_role(&from_role_str).map_err(|()| {
        reject_with(
            &doc,
            ErrorPayload::new(extended_code(ERR_ROLE_NOT_RECOGNIZED))
                .with_message(format!("fromRole {from_role_str:?} is not recognised"))
                .with_details(role_not_recognized_details(&from_role_str)),
        )
    })?;
    let to_role = parse_role(&to_role_str).map_err(|()| {
        reject_with(
            &doc,
            ErrorPayload::new(extended_code(ERR_ROLE_NOT_RECOGNIZED))
                .with_message(format!("toRole {to_role_str:?} is not recognised"))
                .with_details(role_not_recognized_details(&to_role_str)),
        )
    })?;

    // ─── 3. Self-promotion guard. ─────────────────────────────────
    if caller == doc.payload.subject && is_strict_promotion(&from_role, &to_role) {
        return Err(reject_with(
            &doc,
            ErrorPayload::new(StandardCode::PermissionDenied)
                .with_message("self-promotion to a more privileged role is forbidden"),
        ));
    }

    // ─── 4. Load the subject's current entry + state-check. ───────
    let existing = acl::get_acl_entry(acl_ks, &doc.payload.subject)
        .await
        .map_err(|e| internal(&doc, e))?;
    let mut entry = match existing {
        Some(e) => e,
        None => {
            // Spec doesn't define a dedicated code for "subject absent
            // on a change-role"; the closest is state_mismatch — the
            // subject's "current role" is "absent" which doesn't match
            // any fromRole the producer could supply.
            return Err(reject_with(
                &doc,
                ErrorPayload::new(extended_code(ERR_STATE_MISMATCH))
                    .with_message(format!(
                        "subject {} is not in the maintainer's ACL",
                        doc.payload.subject
                    ))
                    .with_details(json!({ "currentRole": null })),
            ));
        }
    };

    if entry.role != from_role {
        return Err(reject_with(
            &doc,
            ErrorPayload::new(extended_code(ERR_STATE_MISMATCH))
                .with_message(format!(
                    "subject's current role is {:?}, not {:?}",
                    entry.role.to_string(),
                    from_role.to_string()
                ))
                .with_details(json!({ "currentRole": entry.role.to_string() })),
        ));
    }

    // ─── 5. Idempotent no-op. ─────────────────────────────────────
    if from_role == to_role {
        // Same-role transition is a no-op; spec doesn't forbid it
        // explicitly but a maintainer that complies with the state-
        // check has already proven the entry is in the requested
        // state. Return the entry unchanged.
        let resp = build_response(&doc, &entry);
        return Ok(resp);
    }

    // ─── 6. Last-authority guard. ────────────────────────────────
    // A demote that removes the only Admin would empty the privileged
    // set. The spec's `change-role/0.1` doesn't enumerate this error
    // code, but §8.5 permits a consumer to mint its own slug-
    // namespaced code — `acl/change-role:last_authority_protected`
    // keeps the slug aligned with the request's `type` URI so a
    // client dispatching on `payload.code` doesn't cross spec slugs.
    if matches!(from_role, Role::Admin) && !matches!(to_role, Role::Admin) {
        let all = acl::list_acl_entries(acl_ks)
            .await
            .map_err(|e| internal(&doc, e))?;
        let other_admins: Vec<String> = all
            .iter()
            .filter(|e| matches!(e.role, Role::Admin) && e.did != doc.payload.subject)
            .map(|e| e.did.clone())
            .collect();
        if other_admins.is_empty() {
            return Err(reject_with(
                &doc,
                ErrorPayload::new(extended_code(ERR_LAST_AUTHORITY))
                    .with_message(
                        "this role change would leave the maintainer with no Admin entries",
                    )
                    .with_details(json!({
                        "protectedRole": "admin",
                        "remainingHolders": other_admins,
                    })),
            ));
        }
    }

    // ─── 7. Apply the transition. ────────────────────────────────
    // A `MetricsReader`'s domain scope is never consulted (it reads counters
    // only), so it is `All` by default — and carrying that over would make the
    // promoted entry, an Owner say, an Owner on every domain. Leaving the role
    // resets the scope to no domains instead; the operator grants the scope
    // the new role should have with `acl/grant` (the console's role edit does
    // exactly that, right after this task). Other roles keep their scope: for
    // Admin and Service `All` is a real grant, and changing role widens
    // nothing.
    if entry.role == Role::MetricsReader {
        entry.domains = crate::server::domain::DomainScope::Allowed { domains: vec![] };
    }
    entry.role = to_role;
    acl::store_acl_entry(acl_ks, &entry)
        .await
        .map_err(|e| internal(&doc, e))?;

    Ok(build_response(&doc, &entry))
}

fn parse_role(s: &str) -> Result<Role, ()> {
    s.parse::<Role>().map_err(|_| ())
}

fn role_not_recognized_details(offending: &str) -> serde_json::Value {
    json!({
        "offendingRole": offending,
        "knownRoles": ["admin", "owner", "service", "metricsReader"],
    })
}

/// Strict role ordering for the self-promotion guard. We define a
/// total order: `MetricsReader < Service < Owner < Admin`. Self-promotion
/// to a strictly greater role is forbidden. `MetricsReader` ranks lowest —
/// a read-only metrics credential can never self-promote into anything.
fn is_strict_promotion(from: &Role, to: &Role) -> bool {
    role_rank(to) > role_rank(from)
}

fn role_rank(r: &Role) -> u8 {
    match r {
        Role::MetricsReader => 0,
        Role::Service => 1,
        Role::Owner => 2,
        Role::Admin => 3,
    }
}

fn build_response(
    request: &TrustTask<change_role::Payload>,
    local: &AclEntry,
) -> TrustTask<change_role::Response> {
    let neutral = SpecAclEntry::from_local(local);
    let value = serde_json::to_value(&neutral).expect("SpecAclEntry serialises");
    let spec_entry: change_role::AclEntry =
        serde_json::from_value(value).expect("change_role::AclEntry from SpecAclEntry value");
    // The generated payload types are `#[non_exhaustive]` from trust-tasks
    // 0.17 on: built through the generated builder, whose `try_into` can only
    // fail on a field left unset.
    let payload: change_role::Response = change_role::Response::builder()
        .entry(spec_entry)
        .try_into()
        .expect("change-role response has every required field set");
    let id = format!("urn:uuid:{}", uuid::Uuid::new_v4());
    request.respond_with(id, payload)
}

fn extended_code(local: &str) -> trust_tasks_rs::TrustTaskCode {
    change_role::Payload::extended_code(local.to_string())
}

fn internal<P>(doc: &TrustTask<P>, err: impl std::fmt::Display) -> ErrorResponse {
    tracing::error!(error = %err, "acl/change-role internal failure");
    reject_with(
        doc,
        ErrorPayload::new(StandardCode::InternalError)
            .with_message("the maintainer encountered an internal failure"),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use trust_tasks_rs::{Payload, VerificationError, handlers::InMemoryHandler};

    use crate::server::config::StoreConfig;
    use crate::server::domain::DomainScope;
    use crate::server::store::{KS_ACL, Store};
    use crate::server::trust_tasks::TrustTaskContext;

    const SERVICE_DID: &str = "did:web:maintainer.example";
    const ADMIN_DID: &str = "did:web:admin.example";
    const SECOND_ADMIN: &str = "did:web:admin2.example";
    const ALICE_DID: &str = "did:web:alice.example";

    struct PanickingVerifier;
    #[async_trait::async_trait]
    impl ProofVerifier for PanickingVerifier {
        async fn verify<P>(&self, _doc: &TrustTask<P>) -> Result<(), VerificationError>
        where
            P: serde::Serialize + Send + Sync,
        {
            panic!("verifier called under RejectIfPresent policy");
        }
    }
    /// Default test policy: `AcceptUnverified`. `acl/change-role/0.1`
    /// is REQUIRED — `request()` attaches a stub proof so the
    /// framework's IS_PROOF_REQUIRED gate passes; the unverified
    /// policy then accepts it without invoking any verifier.
    fn no_verifier() -> ProofPolicy<'static, PanickingVerifier> {
        ProofPolicy::AcceptUnverified
    }

    /// Stub proof so the IS_PROOF_REQUIRED gate accepts the request
    /// under `ProofPolicy::AcceptUnverified`.
    fn add_stub_proof(doc: &mut TrustTask<change_role::Payload>) {
        doc.proof = Some(trust_tasks_rs::Proof {
            proof_type: "DataIntegrityProof".into(),
            cryptosuite: "eddsa-jcs-2022".into(),
            verification_method: "did:web:admin.example#key-1".into(),
            created: chrono::Utc::now(),
            proof_purpose: "authentication".into(),
            proof_value: "z-stub".into(),
            extra: Default::default(),
        });
    }

    async fn harness() -> (Store, crate::server::store::KeyspaceHandle) {
        let dir = tempfile::tempdir().expect("tempdir");
        let cfg = StoreConfig {
            data_dir: dir.path().to_path_buf(),
            ..StoreConfig::default()
        };
        std::mem::forget(dir);
        let store = Store::open(&cfg).await.expect("open fjall");
        let acl_ks = store.keyspace(KS_ACL).expect("acl keyspace");
        acl::store_acl_entry(
            &acl_ks,
            &AclEntry {
                did: ADMIN_DID.into(),
                role: Role::Admin,
                label: None,
                created_at: 1_700_000_000,
                max_total_size: None,
                max_did_count: None,
                domains: DomainScope::All,
            },
        )
        .await
        .unwrap();
        (store, acl_ks)
    }

    fn ctx<'a>(
        acl_ks: &'a crate::server::store::KeyspaceHandle,
        acl_locks: &'a crate::server::path_locks::PathLocks,
    ) -> TrustTaskContext<'a> {
        TrustTaskContext {
            acl_ks,
            acl_locks,
            my_vid: SERVICE_DID,
        }
    }

    fn transport(peer: &str) -> InMemoryHandler {
        InMemoryHandler::new()
            .with_local(SERVICE_DID.to_string())
            .with_peer(peer.to_string())
    }

    async fn seed(ks: &crate::server::store::KeyspaceHandle, did: &str, role: Role) {
        acl::store_acl_entry(
            ks,
            &AclEntry {
                did: did.into(),
                role,
                label: None,
                created_at: 1_700_000_000,
                max_total_size: None,
                max_did_count: None,
                domains: DomainScope::All,
            },
        )
        .await
        .unwrap();
    }

    fn request(
        issuer_did: &str,
        subject: &str,
        from: &str,
        to: &str,
    ) -> TrustTask<change_role::Payload> {
        let from_role: change_role::PayloadFromRole =
            from.to_string().try_into().expect("fromRole non-empty");
        let to_role: change_role::PayloadToRole =
            to.to_string().try_into().expect("toRole non-empty");
        let payload: change_role::Payload = change_role::Payload::builder()
            .from_role(from_role)
            .reason(Some(
                "test"
                    .parse::<change_role::PayloadReason>()
                    .expect("reason"),
            ))
            .subject(subject)
            .to_role(to_role)
            .try_into()
            .expect("test change-role payload is well formed");
        let mut doc = TrustTask::for_payload(format!("urn:uuid:{}", uuid::Uuid::new_v4()), payload);
        doc.issuer = Some(issuer_did.into());
        doc.recipient = Some(SERVICE_DID.into());
        doc.issued_at = Some(chrono::Utc::now());
        add_stub_proof(&mut doc);
        doc
    }

    #[tokio::test]
    async fn successful_role_transition_persists() {
        let (_s, acl_ks) = harness().await;
        let acl_locks = crate::server::path_locks::PathLocks::new();
        seed(&acl_ks, ALICE_DID, Role::Owner).await;
        let outcome = handle(
            &ctx(&acl_ks, &acl_locks),
            &transport(ADMIN_DID),
            no_verifier(),
            request(ADMIN_DID, ALICE_DID, "owner", "service"),
        )
        .await;
        let resp = match outcome {
            DispatchOutcome::Handled(d) => d,
            other => panic!("expected Handled, got {other:?}"),
        };
        assert_eq!(
            resp.type_uri.to_string(),
            format!("{}#response", change_role::Payload::TYPE_URI)
        );
        assert_eq!(resp.payload["entry"]["role"], "service");
        let updated = acl::get_acl_entry(&acl_ks, ALICE_DID)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(updated.role, Role::Service);
    }

    #[tokio::test]
    async fn state_mismatch_when_fromrole_wrong() {
        let (_s, acl_ks) = harness().await;
        let acl_locks = crate::server::path_locks::PathLocks::new();
        seed(&acl_ks, ALICE_DID, Role::Owner).await;
        // Caller claims Alice was a `service` but she's an `owner`.
        let outcome = handle(
            &ctx(&acl_ks, &acl_locks),
            &transport(ADMIN_DID),
            no_verifier(),
            request(ADMIN_DID, ALICE_DID, "service", "admin"),
        )
        .await;
        let err = match outcome {
            DispatchOutcome::Rejected(e) => e,
            other => panic!("expected Rejected, got {other:?}"),
        };
        assert_eq!(err.payload.code, extended_code(ERR_STATE_MISMATCH));
        assert_eq!(err.payload.details.unwrap()["currentRole"], "owner");
        // Storage unchanged.
        assert_eq!(
            acl::get_acl_entry(&acl_ks, ALICE_DID)
                .await
                .unwrap()
                .unwrap()
                .role,
            Role::Owner
        );
    }

    #[tokio::test]
    async fn unknown_role_string_rejected() {
        let (_s, acl_ks) = harness().await;
        let acl_locks = crate::server::path_locks::PathLocks::new();
        seed(&acl_ks, ALICE_DID, Role::Owner).await;
        let outcome = handle(
            &ctx(&acl_ks, &acl_locks),
            &transport(ADMIN_DID),
            no_verifier(),
            request(ADMIN_DID, ALICE_DID, "owner", "superuser"),
        )
        .await;
        let err = match outcome {
            DispatchOutcome::Rejected(e) => e,
            other => panic!("expected Rejected, got {other:?}"),
        };
        assert_eq!(err.payload.code, extended_code(ERR_ROLE_NOT_RECOGNIZED));
        let details = err.payload.details.unwrap();
        assert_eq!(details["offendingRole"], "superuser");
        assert_eq!(
            details["knownRoles"],
            json!(["admin", "owner", "service", "metricsReader"])
        );
    }

    /// A MetricsReader's unused all-domains scope does not survive a role
    /// change: promoted to Owner, it holds no domain until a grant gives it
    /// one, rather than every domain.
    #[tokio::test]
    async fn leaving_metrics_reader_resets_the_scope_to_no_domains() {
        let (_s, acl_ks) = harness().await;
        let acl_locks = crate::server::path_locks::PathLocks::new();
        seed(&acl_ks, ALICE_DID, Role::MetricsReader).await;
        let outcome = handle(
            &ctx(&acl_ks, &acl_locks),
            &transport(ADMIN_DID),
            no_verifier(),
            request(ADMIN_DID, ALICE_DID, "metricsReader", "owner"),
        )
        .await;
        assert!(matches!(outcome, DispatchOutcome::Handled(_)));
        let entry = acl::get_acl_entry(&acl_ks, ALICE_DID)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(entry.role, Role::Owner);
        assert_eq!(entry.domains, DomainScope::Allowed { domains: vec![] });
        assert!(!entry.domains.allows("example.com"));
    }

    /// `is_strict_promotion` is the gate for the self-promotion
    /// refusal. Admin is the top of the 4-role enum, so an
    /// end-to-end "self-promotes from Admin → ??" test is
    /// unreachable today; this unit test is what catches a
    /// regression in the predicate if a future role landing
    /// reorders the rank.
    #[test]
    fn role_rank_unit() {
        // Total order: MetricsReader < Service < Owner < Admin.
        assert!(role_rank(&Role::MetricsReader) < role_rank(&Role::Service));
        assert!(role_rank(&Role::Service) < role_rank(&Role::Owner));
        assert!(role_rank(&Role::Owner) < role_rank(&Role::Admin));
        assert!(is_strict_promotion(&Role::Owner, &Role::Admin));
        assert!(is_strict_promotion(&Role::Service, &Role::Owner));
        // A read-only metrics credential can never self-promote.
        assert!(is_strict_promotion(&Role::MetricsReader, &Role::Service));
        assert!(is_strict_promotion(&Role::MetricsReader, &Role::Admin));
        assert!(!is_strict_promotion(&Role::Owner, &Role::Owner));
        assert!(!is_strict_promotion(&Role::Admin, &Role::Owner));
        assert!(!is_strict_promotion(
            &Role::MetricsReader,
            &Role::MetricsReader
        ));
    }

    #[tokio::test]
    async fn last_authority_blocks_admin_demote() {
        let (_s, acl_ks) = harness().await;
        let acl_locks = crate::server::path_locks::PathLocks::new();
        // ADMIN_DID is the only admin. Demote → reject.
        let outcome = handle(
            &ctx(&acl_ks, &acl_locks),
            &transport(ADMIN_DID),
            no_verifier(),
            request(ADMIN_DID, ADMIN_DID, "admin", "owner"),
        )
        .await;
        let err = match outcome {
            DispatchOutcome::Rejected(e) => e,
            other => panic!("expected Rejected, got {other:?}"),
        };
        assert_eq!(err.payload.code, extended_code(ERR_LAST_AUTHORITY));
        assert_eq!(
            acl::get_acl_entry(&acl_ks, ADMIN_DID)
                .await
                .unwrap()
                .unwrap()
                .role,
            Role::Admin
        );
    }

    #[tokio::test]
    async fn admin_demote_allowed_when_another_admin_exists() {
        let (_s, acl_ks) = harness().await;
        let acl_locks = crate::server::path_locks::PathLocks::new();
        seed(&acl_ks, SECOND_ADMIN, Role::Admin).await;
        let outcome = handle(
            &ctx(&acl_ks, &acl_locks),
            &transport(SECOND_ADMIN),
            no_verifier(),
            request(SECOND_ADMIN, ADMIN_DID, "admin", "owner"),
        )
        .await;
        assert!(matches!(outcome, DispatchOutcome::Handled(_)));
        assert_eq!(
            acl::get_acl_entry(&acl_ks, ADMIN_DID)
                .await
                .unwrap()
                .unwrap()
                .role,
            Role::Owner
        );
    }

    #[tokio::test]
    async fn non_admin_caller_rejected() {
        let (_s, acl_ks) = harness().await;
        let acl_locks = crate::server::path_locks::PathLocks::new();
        seed(&acl_ks, ALICE_DID, Role::Owner).await;
        let outcome = handle(
            &ctx(&acl_ks, &acl_locks),
            &transport(ALICE_DID),
            no_verifier(),
            request(ALICE_DID, ALICE_DID, "owner", "service"),
        )
        .await;
        let err = match outcome {
            DispatchOutcome::Rejected(e) => e,
            other => panic!("expected Rejected, got {other:?}"),
        };
        assert_eq!(
            err.payload.code,
            trust_tasks_rs::TrustTaskCode::Standard(StandardCode::PermissionDenied)
        );
    }

    #[tokio::test]
    async fn missing_subject_returns_state_mismatch_with_null() {
        let (_s, acl_ks) = harness().await;
        let acl_locks = crate::server::path_locks::PathLocks::new();
        let outcome = handle(
            &ctx(&acl_ks, &acl_locks),
            &transport(ADMIN_DID),
            no_verifier(),
            request(ADMIN_DID, "did:web:nobody.example", "owner", "service"),
        )
        .await;
        let err = match outcome {
            DispatchOutcome::Rejected(e) => e,
            other => panic!("expected Rejected, got {other:?}"),
        };
        assert_eq!(err.payload.code, extended_code(ERR_STATE_MISMATCH));
        assert_eq!(
            err.payload.details.unwrap()["currentRole"],
            serde_json::Value::Null
        );
    }

    #[tokio::test]
    async fn same_role_is_idempotent_noop() {
        let (_s, acl_ks) = harness().await;
        let acl_locks = crate::server::path_locks::PathLocks::new();
        seed(&acl_ks, ALICE_DID, Role::Owner).await;
        let outcome = handle(
            &ctx(&acl_ks, &acl_locks),
            &transport(ADMIN_DID),
            no_verifier(),
            request(ADMIN_DID, ALICE_DID, "owner", "owner"),
        )
        .await;
        assert!(matches!(outcome, DispatchOutcome::Handled(_)));
        // Entry unchanged.
        assert_eq!(
            acl::get_acl_entry(&acl_ks, ALICE_DID)
                .await
                .unwrap()
                .unwrap()
                .role,
            Role::Owner
        );
    }
}