rsbinder 0.12.0

Pure-Rust Binder IPC for Linux, Android, and macOS — kernel binder plus a libbinder-compatible RPC (binder-over-socket) transport.
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
// Copyright 2022 Jeff Kim <hiking90@gmail.com>
// SPDX-License-Identifier: Apache-2.0

//! Client stub for Android's `PermissionManagerService`
//! (`android.os.IPermissionController`).
//!
//! rsbinder provides the **client side only** — the server lives in
//! Android's `system_server`. Consumers acquire a proxy via
//! [`crate::hub::try_get_service`]`("permission")` then cast through
//! [`crate::permission_controller::IPermissionController`].
//!
//! The wire descriptor is `"android.os.IPermissionController"`, generated
//! from `aidl/permission/android/os/IPermissionController.aidl` (vendored
//! verbatim from AOSP `frameworks/base/core/java/android/os/`). The
//! descriptor is stable across Android 10–16; rsbinder ships a single
//! AIDL (unlike `IServiceManager`, which is per-version).
//!
//! On non-Android targets (Linux + binderfs without an Android
//! userspace, or macOS), `system_server` does not exist — the helpers
//! still compile but nothing registers a `"permission"` service:
//! [`crate::hub::try_get_service`] returns `Ok(None)` where a service
//! manager is reachable but holds no such entry, and `Err` (or, with no
//! kernel binder at all, a `ProcessState` panic) where no service
//! manager is reachable. With no
//! [`crate::permission_controller::PermissionAuthority`] installed, the
//! [`crate::permission_controller::check_permission`] convenience
//! returns `false` (fail-closed) on each path it can take **as long as
//! nothing is registered under that name**: a parcel that
//! does not use kernel marshalling is denied by the marshalling-mode gate
//! before the lookup is reached, a kernel-marshalling parcel outside a
//! transaction is denied by the `is_handling_transaction` gate, and a
//! lookup that yields `Ok(None)` or `Err` denies as well. The Linux
//! `hub` is a general-purpose service manager: a process allowed to
//! register can [`crate::hub::add_service`] a binder under the name
//! `"permission"`, and if its descriptor matches, the lookup
//! succeeds and `check_permission` returns that service's answer
//! verbatim — `true` included.
//!
//! The lookup is not repeated per check. A controller that answered once
//! is kept and asked directly until a call to it fails, as AOSP libbinder
//! keeps `gPermissionController`. Until then, re-registering `"permission"`
//! under another binder or restarting the service manager does not change
//! which process answers, and the kept strong reference counts as a client
//! of the registered service, so its `tryUnregisterService` is refused.
//!
//! With nothing registered under that name, the `ProcessState` panic is
//! the one outcome that is not a `false`.
//! Reaching it takes a kernel-marshalling parcel *and* an in-flight
//! transaction *and* a process with no kernel binder — a combination only
//! an RPC dispatch handed some parcel other than its own inbound one can
//! produce, since `is_handling_transaction` is otherwise false there.
//! Generated `@EnforcePermission` code always passes the inbound RPC
//! parcel, which stops at the first gate, so this is reachable only from
//! a hand-written handler.

include!(concat!(env!("OUT_DIR"), "/permission_controller.rs"));

pub use android::os::IPermissionController::{
    BnPermissionController, BpPermissionController, IPermissionController,
    IPermissionControllerDefault, IPermissionControllerDefaultRef,
};

#[cfg(feature = "async")]
pub use android::os::IPermissionController::{
    IPermissionControllerAsync, IPermissionControllerAsyncService,
};

use std::sync::{Arc, Mutex, PoisonError, RwLock};

use crate::error::Result;
use crate::{hub, Caller, FromIBinder, Parcel, Strong};

/// Service name registered by Android's `PermissionManagerService`. Used
/// as the key for [`crate::hub::try_get_service`].
pub const SERVICE_NAME: &str = "permission";

/// An injectable, **transport-aware** authorization policy (Plan 2-16
/// Phase C). When one is installed via [`set_permission_authority`], it
/// **owns the decision whenever a caller is in flight** for every
/// generated `@EnforcePermission` check ([`check_permission`]) — across
/// kernel binder *and* RPC — and receives the transport-tagged [`Caller`]
/// so it can apply the right rule per transport (Android permission for
/// [`Caller::Kernel`]; a uid ACL, TLS-certificate allowlist, or token
/// scope for `Caller::Rpc`). With no transaction in flight
/// ([`crate::calling_caller`] returns `None`) the check fails closed
/// without consulting it, so an authority never sees an in-process call
/// and cannot log or allow one.
///
/// The core crate ships only this **slot**, never a policy: token/JWT
/// formats, certificate→permission tables, and uid→permission maps are
/// deployment concerns. With **no** authority installed, [`check_permission`]
/// keeps its safe default — kernel → `PermissionManagerService`, RPC →
/// deny (Plan 2-16 Phase A).
pub trait PermissionAuthority: Send + Sync {
    /// Return `true` to grant `permission` to `caller`. Implementations
    /// should fail closed for callers/transports they do not recognize.
    fn check(&self, permission: &str, caller: &Caller) -> bool;
}

/// Injected authority (`None` = default); a `RwLock`, not `OnceLock`, so it can be replaced.
static AUTHORITY: RwLock<Option<Arc<dyn PermissionAuthority>>> = RwLock::new(None);

/// Install the process-wide [`PermissionAuthority`]; subsequent
/// [`check_permission`] calls delegate the whole decision to it. Replaces
/// any previously installed authority.
pub fn set_permission_authority(authority: Arc<dyn PermissionAuthority>) {
    *AUTHORITY.write().expect("permission authority poisoned") = Some(authority);
}

/// Remove any installed [`PermissionAuthority`], restoring the built-in
/// default (kernel → PMS, RPC → deny).
pub fn clear_permission_authority() {
    *AUTHORITY.write().expect("permission authority poisoned") = None;
}

/// Acquire a `BpPermissionController` proxy for the system-wide
/// `permission` service, mirroring AOSP
/// `defaultServiceManager()->getService(String16("permission"))` +
/// `interface_cast<IPermissionController>(binder)`.
///
/// Returns `Err(StatusCode::NameNotFound)` when the service manager has
/// no `"permission"` entry — typically on non-Android Linux where
/// `system_server` is not running. On Android 11+ a service manager that
/// cannot be reached at all surfaces as its own transport error
/// (`DeadObject`, `FailedTransaction`, …) rather than `NameNotFound`, so
/// a caller that branches on `NameNotFound` to mean "no permission
/// service" must handle those separately. **Not on Android 10**: the
/// legacy C service manager cannot tell a not-found reply from a
/// transport failure and reports both as not-registered, so an
/// unreachable service manager arrives as `NameNotFound` there — but
/// only once the service manager proxy has been built; a first lookup
/// with no reachable service manager still fails inside `hub::default()`
/// with its own transport error. A descriptor mismatch propagates from
/// the `FromIBinder` cast.
///
/// This is a thin wrapper; consumers needing custom error mapping or
/// caching should call [`crate::hub::try_get_service`] directly.
///
/// # Panics
///
/// Panics if kernel binder was never initialized in this process: the
/// lookup reaches `ProcessState::as_self`.
pub fn default() -> Result<Strong<dyn IPermissionController>> {
    // Single-shot on purpose: a permission check must not block.
    let binder = hub::try_get_service(SERVICE_NAME)?.ok_or(crate::StatusCode::NameNotFound)?;
    <dyn IPermissionController>::try_from(binder)
}

/// Convenience: ask `system_server`'s `PermissionManagerService` whether
/// the current binder *caller* (as reported by
/// [`crate::get_calling_uid`] / [`crate::get_calling_pid`]) holds
/// `permission_name`.
///
/// This is the runtime backing the generated `@EnforcePermission` deny
/// block; `reader` is the inbound transaction parcel held by
/// `on_transact`, used to detect the transport (see *RPC fail-closed*).
///
/// Intended for server-side use inside a [`crate::Transactable::transact`]
/// dispatch, mirroring AOSP `IPCThreadState::self()->getCallingUid()` +
/// `IPermissionController::checkPermission(...)`.
///
/// # RPC fail-closed (`@EnforcePermission` is kernel-only) — Plan 2-16 Phase A
///
/// `@EnforcePermission` has **no meaning over the RPC transport**: AOSP's
/// RPC stack carries no Android permission concept, and an RPC peer's uid
/// is a different namespace from the one `PermissionManagerService`
/// arbitrates. RPC dispatch does stamp the peer (Plan 2-16 Phase B), so
/// [`crate::get_calling_uid`] answers — which is the problem, not the
/// remedy: a Unix RPC peer running as root reads its real uid `0`, and
/// PMS *unconditionally grants* root, so every guarded method would
/// become a **silent grant to any RPC peer that runs as root**; a peer on
/// a transport that carries no uid (`Vsock`, TLS `Certificate`,
/// `Anonymous`) reads the `u32::MAX` sentinel, which PMS knows nothing
/// about. To prevent this, a `reader` that does not use kernel
/// marshalling ([`Parcel::is_kernel_backed`] is `false`) returns `false`
/// **before any uid read or PMS lookup**, regardless of process shape,
/// and emits a one-time `warn`. Gating on the marshalling mode rather
/// than on one named transport is what denies a mode added later by
/// default. The deny does not depend on what uid an RPC transport
/// carries — no uid makes an RPC parcel kernel-backed.
///
/// [`Parcel::is_kernel_backed`] answers only *which marshalling the
/// parcel uses* — it is **not** a statement that a live kernel
/// transaction vouched for the caller; a freshly constructed
/// [`Parcel::new`] reports `true` as well. Whether a transaction is in
/// flight is a second question, which this function asks separately via
/// [`crate::is_handling_transaction`]. Nesting is handled: while an RPC
/// dispatch is on the stack, a nested kernel `BR_TRANSACTION` dispatched
/// on the same thread hands the handler a kernel-marshalled `reader`, and
/// the outer RPC calling context is suspended for the duration of that
/// inner dispatch, so [`crate::get_calling_uid`] /
/// [`crate::get_calling_pid`] answer for the **kernel** caller. PMS is
/// therefore asked about the kernel caller's uid, not the suspended RPC
/// peer's.
///
/// The other direction is not symmetric. While a kernel dispatch calls out
/// over RPC, the peer's inbound dispatch is the innermost frame and its
/// calling context stays installed, so an RPC handler that passes a
/// kernel-marshalled parcel — a fresh [`Parcel::new`], or the outer kernel
/// `reader` it captured — gets past both gates above and PMS is asked about
/// the **RPC peer's** uid. A Unix peer running as root is granted
/// unconditionally there. Producing that combination takes a hand-written
/// handler that hands this function a parcel other than the one it was
/// dispatched with.
///
/// RPC services needing authorization must use transport-native means
/// (`PeerIdentity` + `RpcServer::set_authorizer`, or hand-rolled uid ACLs
/// via [`crate::get_calling_uid`] over Unix RPC).
///
/// # Fail-closed semantics
///
/// **With no [`PermissionAuthority`] installed**, returns `false` when:
/// - `reader` does not use kernel marshalling (see above) — a property of
///   the parcel, not of how the transaction was dispatched.
/// - The current thread is not handling a binder transaction (explicit
///   deny before uid/pid are read or PMS is consulted).
/// - The `permission` service is unreachable (`system_server` absent) —
///   the lookup error denies.
/// - The remote `checkPermission` call returns an error.
///
/// A reachable service that answers `true` grants, so this is fail-closed
/// against a *missing* permission service, not against a hostile one; see
/// the [module docs](crate::permission_controller) for what registering
/// under that name means on Linux.
///
/// This matches AOSP's "if in doubt, deny" posture for missing
/// PermissionManagerService — see Android `checkPermission` callers in
/// `frameworks/native/services/` for the same pattern.
///
/// The controller that answered the last check is kept process-wide and
/// asked directly next time, as AOSP libbinder's `checkPermission` keeps
/// `gPermissionController`, so a check costs one IPC instead of a service
/// manager lookup plus one. When the kept controller fails (its process
/// restarted), it is dropped and the same check goes once to a fresh
/// lookup. Unlike AOSP, a missing service is not waited for: the check
/// denies at once.
///
/// # Panics
///
/// Panics if the [`default()`] lookup is reached in a process where
/// kernel binder was never initialized (`ProcessState::as_self`). That
/// takes a kernel-marshalling `reader` *and* an in-flight transaction
/// *and* an uninitialized `ProcessState` — see the [module
/// docs](crate::permission_controller) for the one path that produces all
/// three. An installed [`PermissionAuthority`] returns before the lookup,
/// so it cannot panic here.
///
/// # Injected authority (Plan 2-16 Phase C)
///
/// If a [`PermissionAuthority`] is installed via
/// [`set_permission_authority`], it **replaces** the default decision for
/// every transport and receives the transport-tagged [`Caller`] — but
/// only while a transaction is in flight; with none
/// ([`crate::calling_caller`] returns `None`) the check fails closed
/// without consulting it. With no authority installed (the default), the
/// kernel→PMS / RPC→deny behavior applies unchanged.
pub fn check_permission(reader: &Parcel, permission_name: &str) -> bool {
    // Clone the Arc out so the read lock is released before the (re-entrant) policy runs.
    let authority = AUTHORITY
        .read()
        .expect("permission authority poisoned")
        .clone();
    if let Some(authority) = authority {
        // No caller (not in a transaction) ⇒ fail closed.
        return crate::calling_caller()
            .is_some_and(|caller| authority.check(permission_name, &caller));
    }

    // Deny before uid is read: an RPC uid is not a PMS uid (see rustdoc).
    if !reader.is_kernel_backed() {
        warn_enforce_permission_over_rpc();
        return false;
    }
    // Outside a transaction there is no caller: uid/pid would name this process itself.
    if !crate::is_handling_transaction() {
        return false;
    }
    let calling_pid = crate::get_calling_pid() as i32;
    let calling_uid = crate::get_calling_uid() as i32;
    ask_controller(&CONTROLLER, default, |pc| {
        pc.checkPermission(permission_name, calling_pid, calling_uid)
    })
}

type ControllerSlot = Mutex<Option<Arc<Strong<dyn IPermissionController>>>>;

/// AOSP `gPermissionController`; see [`check_permission`].
static CONTROLLER: ControllerSlot = Mutex::new(None);

/// The lock is never held across an IPC.
fn ask_controller(
    slot: &ControllerSlot,
    lookup: impl FnOnce() -> Result<Strong<dyn IPermissionController>>,
    ask: impl Fn(&Strong<dyn IPermissionController>) -> crate::BinderResult<bool>,
) -> bool {
    let lock = || slot.lock().unwrap_or_else(PoisonError::into_inner);
    let cached = lock().clone();
    if let Some(pc) = cached {
        if let Ok(granted) = ask(&pc) {
            return granted;
        }
        let mut slot = lock();
        // Another thread may already have installed a fresh one; keep that.
        if slot.as_ref().is_some_and(|c| Arc::ptr_eq(c, &pc)) {
            *slot = None;
        }
    }
    let Ok(pc) = lookup() else {
        return false;
    };
    let Ok(granted) = ask(&pc) else {
        return false;
    };
    *lock() = Some(Arc::new(pc));
    granted
}

/// Warn once per process (not per interface) when `@EnforcePermission` first denies over RPC.
fn warn_enforce_permission_over_rpc() {
    use std::sync::Once;
    static WARNED: Once = Once::new();
    WARNED.call_once(|| {
        log::warn!(
            "@EnforcePermission is unsupported over RPC and denies every \
             guarded method (Plan 2-16 Phase A); use PeerIdentity / \
             set_authorizer or uid ACLs for RPC authorization"
        );
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A Unix RPC session's caps before fd-mode negotiation; incidental, but the guard takes it.
    #[cfg(feature = "rpc")]
    const UNIX_CAPS: crate::TransportCaps =
        crate::TransportCaps::TRUSTED_UID.union(crate::TransportCaps::SAME_HOST);

    /// AOSP wire descriptor; on a mismatch `system_server` rejects every interface token.
    #[test]
    fn test_descriptor_matches_aosp_wire() {
        // `descriptor()` needs `Self: Sized`; every concrete impl returns the same constant.
        assert_eq!(
            <BpPermissionController as IPermissionController>::descriptor(),
            "android.os.IPermissionController"
        );
    }

    /// system_server's `addService("permission", ...)`; drift makes `default()` `NameNotFound`.
    #[test]
    fn test_service_name_matches_system_server_registration() {
        assert_eq!(SERVICE_NAME, "permission");
    }

    /// Answers `checkPermission` with `grant`, or fails as a dead binder once `dead` is set.
    struct FakeController {
        grant: bool,
        dead: Arc<std::sync::atomic::AtomicBool>,
    }

    impl crate::Interface for FakeController {}

    impl IPermissionController for FakeController {
        fn checkPermission(&self, _: &str, _: i32, _: i32) -> crate::BinderResult<bool> {
            if self.dead.load(std::sync::atomic::Ordering::SeqCst) {
                return Err(crate::StatusCode::DeadObject.into());
            }
            Ok(self.grant)
        }
        fn noteOp(&self, _: &str, _: i32, _: &str) -> crate::BinderResult<i32> {
            Ok(0)
        }
        fn getPackagesForUid(&self, _: i32) -> crate::BinderResult<Vec<String>> {
            Ok(Vec::new())
        }
        fn isRuntimePermission(&self, _: &str) -> crate::BinderResult<bool> {
            Ok(false)
        }
        fn getPackageUid(&self, _: &str, _: i32) -> crate::BinderResult<i32> {
            Ok(0)
        }
    }

    fn fake(
        grant: bool,
    ) -> (
        Strong<dyn IPermissionController>,
        Arc<std::sync::atomic::AtomicBool>,
    ) {
        let dead = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let pc = BnPermissionController::new_binder(FakeController {
            grant,
            dead: dead.clone(),
        });
        (pc, dead)
    }

    /// Kept until it fails, then replaced by a lookup in the same call; failures are not cached.
    #[test]
    fn the_controller_is_cached_until_it_fails() {
        let ask = |pc: &Strong<dyn IPermissionController>| pc.checkPermission("p", 1, 2);
        let slot: ControllerSlot = Mutex::new(None);

        let (first, first_dead) = fake(true);
        assert!(ask_controller(&slot, || Ok(first), ask));
        assert!(
            ask_controller(&slot, || panic!("a cached controller needs no lookup"), ask),
            "the cached controller answers"
        );

        // `system_server` restarted: the cached proxy is dead, a lookup finds the new one.
        first_dead.store(true, std::sync::atomic::Ordering::SeqCst);
        let (second, _second_dead) = fake(false);
        let second_binder = second.as_binder();
        assert!(
            !ask_controller(&slot, || Ok(second), ask),
            "the fresh controller's answer, not a failure's deny"
        );
        let cached = slot
            .lock()
            .unwrap()
            .clone()
            .expect("the fresh controller is cached");
        assert!(cached.as_binder() == second_binder);

        // A fresh controller that fails is not cached, and the check denies.
        let slot: ControllerSlot = Mutex::new(None);
        let (broken, broken_dead) = fake(true);
        broken_dead.store(true, std::sync::atomic::Ordering::SeqCst);
        assert!(!ask_controller(&slot, || Ok(broken), ask));
        assert!(slot.lock().unwrap().is_none());
        // No controller at all denies.
        assert!(!ask_controller(
            &slot,
            || Err(crate::StatusCode::NameNotFound),
            ask
        ));
    }

    /// Plan 2-16 Phase A: an RPC parcel, or a kernel one outside a transaction, is denied pre-PMS.
    // `serial(authority)`: `AUTHORITY` is process-global and the delegation test sets it.
    #[cfg(feature = "rpc")]
    #[serial_test::serial(authority)]
    #[test]
    fn check_permission_denies_rpc_parcel() {
        use crate::rpc::transport::PeerIdentity;
        use crate::thread_state::RpcCallingGuard;
        use std::sync::Arc;

        let mut rpc_parcel = Parcel::new();
        rpc_parcel.set_for_rpc(true).unwrap();
        // In a simulated RPC transaction only the kernel-backing gate can produce the denial.
        let _g = RpcCallingGuard::install(
            Arc::new(PeerIdentity::Local { uid: 1000, pid: 7 }),
            UNIX_CAPS,
        );
        assert!(crate::is_handling_transaction());
        assert!(
            !check_permission(&rpc_parcel, "android.permission.INTERNET"),
            "RPC parcel must fail-closed regardless of uid/PMS"
        );

        // Dropping the guard first keeps `default()` (and its `ProcessState`) out of reach.
        drop(_g);
        let kernel_parcel = Parcel::new();
        assert!(kernel_parcel.is_kernel_backed());
        // Without this the denial could come from `default()` failing, not from the gate.
        assert!(!crate::is_handling_transaction());
        assert!(
            !check_permission(&kernel_parcel, "android.permission.INTERNET"),
            "outside a transaction the kernel path denies before PMS"
        );
    }

    /// Plan 2-16 Phase C: an installed authority grants a Unix-RPC uid what the default denies.
    #[cfg(feature = "rpc")]
    #[serial_test::serial(authority)]
    #[test]
    fn injected_authority_overrides_default_rpc_deny() {
        use crate::rpc::transport::PeerIdentity;
        use crate::thread_state::RpcCallingGuard;
        use crate::Caller;
        use std::sync::Arc;

        struct UidGrant {
            allow_uid: u32,
            permission: String,
        }
        impl PermissionAuthority for UidGrant {
            fn check(&self, permission: &str, caller: &Caller) -> bool {
                matches!(caller, Caller::Rpc(PeerIdentity::Local { uid, .. })
                    if *uid == self.allow_uid && permission == self.permission)
            }
        }

        set_permission_authority(Arc::new(UidGrant {
            allow_uid: 1000,
            permission: "com.example.DO_THING".to_string(),
        }));

        let mut rpc_parcel = Parcel::new();
        rpc_parcel.set_for_rpc(true).unwrap();

        // RPC uid 1000: the authority grants its one permission and denies everything else.
        {
            let _g = RpcCallingGuard::install(
                Arc::new(PeerIdentity::Local { uid: 1000, pid: 7 }),
                UNIX_CAPS,
            );
            assert!(
                check_permission(&rpc_parcel, "com.example.DO_THING"),
                "authority must grant the allowed uid+permission over RPC"
            );
            assert!(
                !check_permission(&rpc_parcel, "com.example.OTHER"),
                "authority must deny an unknown permission"
            );
        }
        // Different uid ⇒ deny.
        {
            let _g = RpcCallingGuard::install(
                Arc::new(PeerIdentity::Local { uid: 2000, pid: 7 }),
                UNIX_CAPS,
            );
            assert!(
                !check_permission(&rpc_parcel, "com.example.DO_THING"),
                "authority must deny a non-allowed uid"
            );
        }
        // No in-flight transaction ⇒ no caller ⇒ fail closed.
        assert!(!check_permission(&rpc_parcel, "com.example.DO_THING"));

        // Restore the default so other tests see kernel-PMS / RPC-deny.
        clear_permission_authority();
        let _g = RpcCallingGuard::install(
            Arc::new(PeerIdentity::Local { uid: 1000, pid: 7 }),
            UNIX_CAPS,
        );
        assert!(
            !check_permission(&rpc_parcel, "com.example.DO_THING"),
            "after clear, the default RPC deny is restored"
        );
    }
}