use std::{
future::Future,
pin::Pin,
sync::{Arc, OnceLock},
task::{Context, Poll, Waker},
};
use cranpose_core::ProcessIds;
use parking_lot::Mutex;
use crate::{
LifecycleObserver, LifecycleState, current_lifecycle_state, observe_lifecycle,
registry::ServiceRegistry,
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum DeviceAuthAvailability {
#[default]
Unsupported,
NoScreenLock,
Credential,
Biometric,
}
impl DeviceAuthAvailability {
pub const fn can_authenticate(self) -> bool {
matches!(self, Self::Credential | Self::Biometric)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DeviceAuthOutcome {
Unlocked,
Cancelled,
Failed,
Unavailable,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DeviceAuthRequest(u64);
impl DeviceAuthRequest {
pub const fn id(self) -> u64 {
self.0
}
pub const fn from_id(id: u64) -> Self {
Self(id)
}
}
pub trait DeviceAuthenticator: Send + Sync {
fn availability(&self) -> DeviceAuthAvailability;
fn authenticate(&self, request: DeviceAuthRequest, reason: &str);
}
static PLATFORM: ServiceRegistry<dyn DeviceAuthenticator> = ServiceRegistry::new();
static NEXT_REQUEST: ProcessIds = ProcessIds::starting_at(1);
#[derive(Default)]
struct Answer {
outcome: Option<DeviceAuthOutcome>,
wakers: Vec<Waker>,
}
impl Answer {
fn ready(outcome: DeviceAuthOutcome) -> Arc<Mutex<Self>> {
Arc::new(Mutex::new(Self {
outcome: Some(outcome),
wakers: Vec::new(),
}))
}
}
struct Open {
request: DeviceAuthRequest,
answer: Arc<Mutex<Answer>>,
waiting: Option<String>,
}
static OPEN: Mutex<Option<Open>> = Mutex::new(None);
static FOREGROUND: OnceLock<LifecycleObserver> = OnceLock::new();
pub fn set_platform_device_authenticator(authenticator: Option<Arc<dyn DeviceAuthenticator>>) {
match authenticator {
Some(authenticator) => PLATFORM.set(authenticator),
None => {
PLATFORM.clear();
let open = OPEN.lock().as_ref().map(|open| open.request);
if let Some(request) = open {
finish_device_auth(request, DeviceAuthOutcome::Unavailable);
}
}
}
}
pub fn device_auth_availability() -> DeviceAuthAvailability {
PLATFORM
.get()
.map_or(DeviceAuthAvailability::Unsupported, |platform| {
platform.availability()
})
}
pub fn authenticate_device_owner(reason: &str) -> DeviceAuthFuture {
if PLATFORM.get().is_none() {
return DeviceAuthFuture::ready(DeviceAuthOutcome::Unavailable);
}
if reason.trim().is_empty() {
log::warn!("cranpose: a device unlock was asked with no reason to show");
return DeviceAuthFuture::ready(DeviceAuthOutcome::Failed);
}
let mut open = OPEN.lock();
if let Some(open) = open.as_ref() {
return DeviceAuthFuture {
answer: Arc::clone(&open.answer),
};
}
let answer = Arc::new(Mutex::new(Answer::default()));
*open = Some(Open {
request: DeviceAuthRequest(NEXT_REQUEST.next()),
answer: Arc::clone(&answer),
waiting: Some(reason.to_owned()),
});
drop(open);
FOREGROUND.get_or_init(|| {
observe_lifecycle(|event| {
if event.to == LifecycleState::Resumed {
show_waiting();
}
})
});
if current_lifecycle_state() == LifecycleState::Resumed {
show_waiting();
}
DeviceAuthFuture { answer }
}
fn show_waiting() {
let waiting = {
let mut open = OPEN.lock();
match open.as_mut() {
Some(prompt) if prompt.waiting.is_some() && Arc::strong_count(&prompt.answer) == 1 => {
*open = None;
None
}
Some(prompt) => prompt.waiting.take().map(|reason| (prompt.request, reason)),
None => None,
}
};
let Some((request, reason)) = waiting else {
return;
};
match PLATFORM.get() {
Some(platform) => platform.authenticate(request, &reason),
None => finish_device_auth(request, DeviceAuthOutcome::Unavailable),
}
}
pub fn finish_device_auth(request: DeviceAuthRequest, outcome: DeviceAuthOutcome) {
let answer = {
let mut open = OPEN.lock();
match open.as_ref() {
Some(prompt) if prompt.request == request => open.take().map(|prompt| prompt.answer),
_ => None,
}
};
let Some(answer) = answer else {
log::debug!("cranpose: a device unlock answer came for a closed prompt");
return;
};
let wakers = {
let mut answer = answer.lock();
answer.outcome = Some(outcome);
std::mem::take(&mut answer.wakers)
};
for waker in wakers {
waker.wake();
}
}
#[must_use = "the outcome says whether the owner unlocked"]
pub struct DeviceAuthFuture {
answer: Arc<Mutex<Answer>>,
}
impl DeviceAuthFuture {
fn ready(outcome: DeviceAuthOutcome) -> Self {
Self {
answer: Answer::ready(outcome),
}
}
}
impl std::fmt::Debug for DeviceAuthFuture {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("DeviceAuthFuture")
.field("outcome", &self.answer.lock().outcome)
.finish()
}
}
impl Future for DeviceAuthFuture {
type Output = DeviceAuthOutcome;
fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<DeviceAuthOutcome> {
let mut answer = self.answer.lock();
if let Some(outcome) = answer.outcome {
return Poll::Ready(outcome);
}
let waker = context.waker();
if !answer.wakers.iter().any(|known| known.will_wake(waker)) {
answer.wakers.push(waker.clone());
}
Poll::Pending
}
}
#[expect(non_snake_case, reason = "names follow Compose's casing")]
#[track_caller]
pub fn rememberDeviceAuthAvailability() -> DeviceAuthAvailability {
let lifecycle = crate::rememberLifecycleState().get();
cranpose_core::rememberKeyed(lifecycle, |_| device_auth_availability())
}
#[cfg(test)]
#[path = "tests/device_auth_tests.rs"]
mod tests;