revault_vault_api 0.0.5

reVault API for creating and managing vaults
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
use std::io;
use std::thread;

#[cfg(windows)]
use std::sync::mpsc::Sender;
#[cfg(any(windows, test))]
use std::sync::mpsc::{self, Receiver};

#[cfg(unix)]
type SleepHandler = Box<dyn FnMut(SleepEvent) + Send>;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum SleepEvent {
    SuspendRequested,
    Resumed,
}

pub(crate) struct SleepWatcher {
    #[cfg(any(windows, test))]
    receiver: Receiver<SleepEvent>,
}

pub(crate) struct SleepInhibitor {
    _inner: platform::SleepInhibitor,
}

/// Platform sleep/suspend capabilities used by the lockbox session agent.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AgentSleepSupport {
    /// True when the agent can receive suspend/resume notifications.
    pub suspend_notifications: bool,
    /// True when active secret operations can request temporary sleep inhibition.
    pub sleep_inhibition: bool,
}

impl AgentSleepSupport {
    /// True when all sleep/suspend management features are available.
    pub fn supported(self) -> bool {
        self.suspend_notifications && self.sleep_inhibition
    }
}

/// Returns sleep/suspend capabilities compiled for the current platform.
pub fn agent_sleep_support() -> AgentSleepSupport {
    platform::agent_sleep_support()
}

impl SleepInhibitor {
    pub(crate) fn acquire_active(reason: &str) -> io::Result<Self> {
        platform::SleepInhibitor::acquire_active(reason).map(|inner| Self { _inner: inner })
    }
}

impl SleepWatcher {
    #[cfg(windows)]
    pub(crate) fn start() -> io::Result<Self> {
        let (sender, receiver) = mpsc::channel();
        platform::spawn(sender)?;
        Ok(Self { receiver })
    }

    #[cfg(unix)]
    pub(crate) fn start_handler(
        handler: impl FnMut(SleepEvent) + Send + 'static,
    ) -> io::Result<()> {
        platform::spawn_handler(Box::new(handler))
    }

    #[cfg(all(test, unix))]
    pub(crate) fn drain(&self) -> Vec<SleepEvent> {
        let mut events = Vec::new();
        while let Ok(event) = self.receiver.try_recv() {
            events.push(event);
        }
        events
    }

    #[cfg(windows)]
    pub(crate) fn recv(&self) -> Result<SleepEvent, mpsc::RecvError> {
        self.receiver.recv()
    }

    #[cfg(all(test, unix))]
    pub(crate) fn from_events(events: impl IntoIterator<Item = SleepEvent>) -> Self {
        let (sender, receiver) = mpsc::channel();
        for event in events {
            let _ = sender.send(event);
        }
        Self { receiver }
    }
}

#[cfg(target_os = "linux")]
mod platform {
    use super::*;
    use dbus::arg::OwnedFd;
    use dbus::blocking::Connection;
    use dbus::blocking::Proxy;
    use dbus::message::MatchRule;
    use std::time::Duration;

    pub(super) fn spawn_handler(handler: SleepHandler) -> io::Result<()> {
        let connection =
            Connection::new_system().map_err(|err| io::Error::other(err.to_string()))?;
        let mut inhibitor = acquire_sleep_inhibitor(&connection).ok();
        let rule = MatchRule::new_signal("org.freedesktop.login1.Manager", "PrepareForSleep")
            .with_sender("org.freedesktop.login1")
            .with_path("/org/freedesktop/login1");
        let mut handler = handler;
        connection
            .add_match(rule, move |(sleeping,): (bool,), connection, _| {
                let event = if sleeping {
                    SleepEvent::SuspendRequested
                } else {
                    SleepEvent::Resumed
                };
                handler(event);
                if sleeping {
                    drop(inhibitor.take());
                } else {
                    inhibitor = acquire_sleep_inhibitor(connection).ok();
                }
                true
            })
            .map_err(|err| io::Error::other(err.to_string()))?;
        thread::Builder::new()
            .name("lockbox-sleep-watcher".to_string())
            .spawn(move || watch_logind(connection))
            .map(|_| ())
    }

    pub(super) fn agent_sleep_support() -> AgentSleepSupport {
        AgentSleepSupport {
            suspend_notifications: true,
            sleep_inhibition: true,
        }
    }

    pub(super) struct SleepInhibitor {
        _fd: OwnedFd,
    }

    impl SleepInhibitor {
        pub(super) fn acquire_active(reason: &str) -> io::Result<Self> {
            let connection =
                Connection::new_system().map_err(|err| io::Error::other(err.to_string()))?;
            acquire_logind_inhibitor(&connection, reason, "block")
                .map(|fd| Self { _fd: fd })
                .map_err(|err| io::Error::other(err.to_string()))
        }
    }

    fn watch_logind(connection: Connection) {
        loop {
            if connection.process(Duration::from_secs(60)).is_err() {
                return;
            }
        }
    }

    fn acquire_sleep_inhibitor(connection: &Connection) -> Result<OwnedFd, dbus::Error> {
        acquire_logind_inhibitor(
            connection,
            "Clear cached lockbox keys before system sleep",
            "delay",
        )
    }

    fn acquire_logind_inhibitor(
        connection: &Connection,
        reason: &str,
        mode: &str,
    ) -> Result<OwnedFd, dbus::Error> {
        let proxy = Proxy::new(
            "org.freedesktop.login1",
            "/org/freedesktop/login1",
            Duration::from_secs(5),
            connection,
        );
        let (fd,): (OwnedFd,) = proxy.method_call(
            "org.freedesktop.login1.Manager",
            "Inhibit",
            ("sleep", "lockbox", reason, mode),
        )?;
        Ok(fd)
    }
}

#[cfg(target_os = "macos")]
mod platform {
    use super::*;
    use objc2_core_foundation::{kCFRunLoopDefaultMode, CFRunLoop};
    use objc2_io_kit::{
        io_connect_t, io_object_t, io_service_t, kIOMessageCanSystemSleep,
        kIOMessageSystemHasPoweredOn, kIOMessageSystemWillSleep, IOAllowPowerChange,
        IONotificationPort, IONotificationPortRef, IORegisterForSystemPower,
    };
    use std::ffi::{c_char, c_void, CString};
    use std::ptr::null_mut;
    use std::sync::Mutex;

    struct CallbackContext {
        handler: Mutex<SleepHandler>,
        root_port: io_connect_t,
    }

    pub(super) fn spawn_handler(handler: SleepHandler) -> io::Result<()> {
        thread::Builder::new()
            .name("lockbox-sleep-watcher".to_string())
            .spawn(move || watch_iokit(handler))
            .map(|_| ())
    }

    pub(super) fn agent_sleep_support() -> AgentSleepSupport {
        AgentSleepSupport {
            suspend_notifications: true,
            sleep_inhibition: true,
        }
    }

    pub(super) struct SleepInhibitor {
        assertion_id: u32,
    }

    impl SleepInhibitor {
        pub(super) fn acquire_active(reason: &str) -> io::Result<Self> {
            let assertion_type = CfString::new("NoIdleSleepAssertion")?;
            let reason = CfString::new(reason)?;
            let mut assertion_id = 0u32;
            // SAFETY: The CFString references are valid for the duration of
            // this call and `assertion_id` is a writable out pointer.
            let result = unsafe {
                IOPMAssertionCreateWithName(
                    assertion_type.as_raw(),
                    K_IOPM_ASSERTION_LEVEL_ON,
                    reason.as_raw(),
                    &mut assertion_id,
                )
            };
            if result == 0 {
                Ok(Self { assertion_id })
            } else {
                Err(io::Error::from_raw_os_error(result))
            }
        }
    }

    impl Drop for SleepInhibitor {
        fn drop(&mut self) {
            // SAFETY: `assertion_id` was returned by
            // `IOPMAssertionCreateWithName` and is released exactly once.
            unsafe {
                IOPMAssertionRelease(self.assertion_id);
            }
        }
    }

    struct CfString {
        raw: *const c_void,
    }

    impl CfString {
        fn new(value: &str) -> io::Result<Self> {
            let value = CString::new(value).map_err(|_| {
                io::Error::new(io::ErrorKind::InvalidInput, "string contains NUL byte")
            })?;
            // SAFETY: `value` is a valid NUL-terminated C string and the
            // returned object is owned by this wrapper.
            let raw = unsafe {
                CFStringCreateWithCString(
                    std::ptr::null(),
                    value.as_ptr(),
                    K_CF_STRING_ENCODING_UTF8,
                )
            };
            if raw.is_null() {
                Err(io::Error::other("failed to allocate CFString"))
            } else {
                Ok(Self { raw })
            }
        }

        fn as_raw(&self) -> *const c_void {
            self.raw
        }
    }

    impl Drop for CfString {
        fn drop(&mut self) {
            // SAFETY: `raw` is a Core Foundation object owned by this wrapper.
            unsafe {
                CFRelease(self.raw);
            }
        }
    }

    const K_CF_STRING_ENCODING_UTF8: u32 = 0x0800_0100;
    const K_IOPM_ASSERTION_LEVEL_ON: u32 = 255;

    #[link(name = "CoreFoundation", kind = "framework")]
    extern "C" {
        fn CFStringCreateWithCString(
            alloc: *const c_void,
            c_str: *const c_char,
            encoding: u32,
        ) -> *const c_void;
        fn CFRelease(cf: *const c_void);
    }

    #[link(name = "IOKit", kind = "framework")]
    extern "C" {
        fn IOPMAssertionCreateWithName(
            assertion_type: *const c_void,
            level: u32,
            reason: *const c_void,
            assertion_id: *mut u32,
        ) -> i32;
        fn IOPMAssertionRelease(assertion_id: u32) -> i32;
    }

    fn watch_iokit(handler: SleepHandler) {
        let mut notification_port: IONotificationPortRef = null_mut();
        let mut notifier: io_object_t = 0;
        let context = Box::new(CallbackContext {
            handler: Mutex::new(handler),
            root_port: 0,
        });
        let context_ptr = Box::into_raw(context);
        // SAFETY: `context_ptr`, `notification_port`, and `notifier` are valid
        // for this registration call. The watcher thread runs the Core
        // Foundation loop for the process lifetime of the agent.
        let root_port = unsafe {
            IORegisterForSystemPower(
                context_ptr.cast::<c_void>(),
                &mut notification_port,
                Some(sleep_callback),
                &mut notifier,
            )
        };
        if root_port == 0 || notification_port.is_null() {
            // SAFETY: Reclaims the boxed context when registration failed.
            unsafe {
                drop(Box::from_raw(context_ptr));
            }
            return;
        }
        // SAFETY: The context allocation remains owned by this thread for as
        // long as the run loop is active.
        unsafe {
            (*context_ptr).root_port = root_port;
        }
        // SAFETY: `notification_port` was returned by IOKit and produces a
        // valid run-loop source while the notification port remains alive.
        let Some(source) = (unsafe { IONotificationPort::run_loop_source(notification_port) })
        else {
            return;
        };
        let Some(run_loop) = CFRunLoop::current() else {
            return;
        };
        // SAFETY: Core Foundation provides this global run-loop mode constant
        // for process-wide read-only use.
        let default_mode = unsafe { kCFRunLoopDefaultMode };
        run_loop.add_source(Some(&source), default_mode);
        CFRunLoop::run();
    }

    unsafe extern "C-unwind" fn sleep_callback(
        refcon: *mut c_void,
        _service: io_service_t,
        message_type: u32,
        message_argument: *mut c_void,
    ) {
        // SAFETY: `refcon` is the `CallbackContext` pointer registered with
        // `IORegisterForSystemPower`; it remains allocated while this callback
        // can be invoked by the watcher run loop.
        let context = unsafe { &*(refcon.cast::<CallbackContext>()) };
        match message_type {
            event if event == kIOMessageCanSystemSleep => {
                IOAllowPowerChange(context.root_port, message_argument as isize);
            }
            event if event == kIOMessageSystemWillSleep => {
                if let Ok(mut handler) = context.handler.lock() {
                    handler(SleepEvent::SuspendRequested);
                }
                IOAllowPowerChange(context.root_port, message_argument as isize);
            }
            event if event == kIOMessageSystemHasPoweredOn => {
                if let Ok(mut handler) = context.handler.lock() {
                    handler(SleepEvent::Resumed);
                }
            }
            _ => {}
        }
    }
}

#[cfg(windows)]
mod platform {
    use super::*;
    use std::ffi::c_void;
    use windows_sys::Win32::System::Power::{
        RegisterSuspendResumeNotification, SetThreadExecutionState,
        UnregisterSuspendResumeNotification, DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS, ES_CONTINUOUS,
        ES_SYSTEM_REQUIRED,
    };
    use windows_sys::Win32::UI::WindowsAndMessaging::{
        DEVICE_NOTIFY_CALLBACK, PBT_APMRESUMEAUTOMATIC, PBT_APMRESUMESUSPEND, PBT_APMSUSPEND,
    };

    pub(super) fn spawn(sender: Sender<SleepEvent>) -> io::Result<()> {
        thread::Builder::new()
            .name("lockbox-sleep-watcher".to_string())
            .spawn(move || watch_power_notifications(sender))
            .map(|_| ())
    }

    pub(super) fn agent_sleep_support() -> AgentSleepSupport {
        AgentSleepSupport {
            suspend_notifications: true,
            sleep_inhibition: true,
        }
    }

    pub(super) struct SleepInhibitor;

    impl SleepInhibitor {
        pub(super) fn acquire_active(_reason: &str) -> io::Result<Self> {
            // SAFETY: `SetThreadExecutionState` has no Rust-side memory
            // invariants and stores process/thread execution-state flags.
            let previous = unsafe { SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED) };
            if previous == 0 {
                Err(io::Error::last_os_error())
            } else {
                Ok(Self)
            }
        }
    }

    impl Drop for SleepInhibitor {
        fn drop(&mut self) {
            // SAFETY: Restores the continuous execution state flag when the
            // inhibitor guard is dropped.
            unsafe {
                SetThreadExecutionState(ES_CONTINUOUS);
            }
        }
    }

    fn watch_power_notifications(sender: Sender<SleepEvent>) {
        let sender = Box::new(sender);
        let context = Box::into_raw(sender);
        let mut params = DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS {
            Callback: Some(power_callback),
            Context: context.cast::<c_void>(),
        };
        // SAFETY: `params` points to a valid subscription record while the
        // watcher thread parks below. The callback context is a boxed Sender
        // that also lives for the process lifetime of the agent.
        let registration = unsafe {
            RegisterSuspendResumeNotification(
                (&mut params as *mut DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS).cast(),
                DEVICE_NOTIFY_CALLBACK,
            )
        };
        if registration == 0 {
            // SAFETY: Reclaims the boxed sender when registration failed.
            unsafe {
                drop(Box::from_raw(context));
            }
            return;
        }
        loop {
            thread::park();
        }
        // SAFETY: This cleanup is unreachable while the callback registration
        // is active. If the loop gains an exit path, `registration` and
        // `context` are still the owned values created above and must each be
        // released exactly once here.
        #[allow(unreachable_code)]
        unsafe {
            UnregisterSuspendResumeNotification(registration);
            drop(Box::from_raw(context));
        }
    }

    unsafe extern "system" fn power_callback(
        context: *const c_void,
        event_type: u32,
        _setting: *const c_void,
    ) -> u32 {
        if context.is_null() {
            return 0;
        }
        // SAFETY: `context` is the boxed `Sender<SleepEvent>` registered with
        // `RegisterSuspendResumeNotification` and remains allocated for the
        // lifetime of the notification callback.
        let sender = unsafe { &*(context.cast::<Sender<SleepEvent>>()) };
        match event_type {
            PBT_APMSUSPEND => {
                let _ = sender.send(SleepEvent::SuspendRequested);
            }
            PBT_APMRESUMESUSPEND | PBT_APMRESUMEAUTOMATIC => {
                let _ = sender.send(SleepEvent::Resumed);
            }
            _ => {}
        }
        0
    }
}

#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
mod platform {
    use super::*;

    pub(super) fn agent_sleep_support() -> AgentSleepSupport {
        AgentSleepSupport {
            suspend_notifications: false,
            sleep_inhibition: false,
        }
    }

    pub(super) struct SleepInhibitor;

    impl SleepInhibitor {
        pub(super) fn acquire_active(_reason: &str) -> io::Result<Self> {
            Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "sleep inhibition is not supported on this platform",
            ))
        }
    }

    #[cfg(unix)]
    pub(super) fn spawn_handler(_handler: SleepHandler) -> io::Result<()> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "sleep notifications are not supported on this platform",
        ))
    }
}