#[cfg(target_os = "windows")]
use serde::{Deserialize, Serialize};
use std::fmt;
use super::consent_prompt::{prompt_for_locale, ConsentPrompt};
#[cfg(target_os = "windows")]
const CONSENT_SCHEMA_VERSION: u32 = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConsentState {
Granted,
Denied,
Undetermined,
NotApplicable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConsentStatusReason {
NoRecord,
StoreUnreadable,
StoreMalformed,
ConsentSchemaUnsupported,
PromptVersionMissing,
PromptVersionUnsupported,
NotApplicable,
}
impl ConsentStatusReason {
pub fn as_str(&self) -> &'static str {
match self {
Self::NoRecord => "no-record",
Self::StoreUnreadable => "store-unreadable",
Self::StoreMalformed => "store-malformed",
Self::ConsentSchemaUnsupported => "consent-schema-unsupported",
Self::PromptVersionMissing => "prompt-version-missing",
Self::PromptVersionUnsupported => "prompt-version-unsupported",
Self::NotApplicable => "not-applicable",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConsentStatus {
pub stored_state: ConsentState,
pub effective_state: ConsentState,
pub reason: Option<ConsentStatusReason>,
}
impl ConsentStatus {
pub fn needs_prompt(&self) -> bool {
matches!(self.effective_state, ConsentState::Undetermined)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConsentDecision {
Yes,
No,
Dismissed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConsentActionResult {
Granted,
Denied,
Dismissed,
Withdrawn,
AlreadyGranted,
PolicyBlocked,
NotApplicable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConsentActionOutcome {
pub result: ConsentActionResult,
pub status: ConsentStatus,
pub policy: super::policy::PolicyState,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConsentActionError {
Presenter(String),
Persist(String),
}
impl fmt::Display for ConsentActionError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Presenter(message) => write!(formatter, "consent presenter failed: {message}"),
Self::Persist(message) => write!(formatter, "failed to persist consent: {message}"),
}
}
}
impl std::error::Error for ConsentActionError {}
impl ConsentState {
pub fn as_str(&self) -> &'static str {
match self {
ConsentState::Granted => "granted",
ConsentState::Denied => "denied",
ConsentState::Undetermined => "undetermined",
ConsentState::NotApplicable => "not-applicable",
}
}
pub fn allows_collection(&self) -> bool {
matches!(self, ConsentState::Granted)
}
pub fn needs_prompt(&self) -> bool {
matches!(self, ConsentState::Undetermined)
}
}
pub fn needs_consent_prompt() -> bool {
if super::policy::is_blocked_by_policy() {
return false;
}
get_consent().needs_prompt()
}
#[cfg(target_os = "windows")]
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ConsentRecord {
#[serde(rename = "schemaVersion")]
schema_version: u32,
consent: String,
#[serde(default)]
source: String,
#[serde(rename = "promptedMxcVersion", default)]
prompted_mxc_version: String,
#[serde(rename = "promptResourceVersion", default)]
prompt_resource_version: Option<u32>,
#[serde(rename = "promptLocale", default)]
prompt_locale: String,
#[serde(rename = "updatedAtEpoch", default)]
updated_at_epoch: u64,
#[serde(default)]
revision: u64,
}
pub fn get_consent() -> ConsentState {
get_status().effective_state
}
pub fn get_status() -> ConsentStatus {
platform::read_status()
}
pub(crate) fn local_app_data_dir() -> Option<std::path::PathBuf> {
platform::local_app_data_dir()
}
#[cfg(test)]
pub(crate) fn set_consent(granted: bool, source: &str) -> Result<(), String> {
platform::with_store_lock(|| platform::write(granted, source))
}
pub fn request_consent<F>(
locale: Option<&str>,
presenter: F,
) -> Result<ConsentActionOutcome, ConsentActionError>
where
F: FnOnce(&ConsentPrompt) -> Result<ConsentDecision, String>,
{
let (prompt, policy, status, revision) = match consent_preflight(locale) {
ConsentPreflight::Complete(outcome) => return Ok(outcome),
ConsentPreflight::Failed(error) => return Err(ConsentActionError::Persist(error)),
ConsentPreflight::Present {
prompt,
policy,
status,
revision,
} => (prompt, policy, status, revision),
};
let decision = presenter(prompt).map_err(ConsentActionError::Presenter)?;
persist_presented_decision(decision, prompt, policy, status, revision)
}
pub async fn request_consent_async<F, Fut>(
locale: Option<&str>,
presenter: F,
) -> Result<ConsentActionOutcome, ConsentActionError>
where
F: FnOnce(&ConsentPrompt) -> Fut,
Fut: std::future::Future<Output = Result<ConsentDecision, String>>,
{
let locale = locale.map(str::to_owned);
match BlockingTask::spawn(move || consent_preflight(locale.as_deref())).await {
ConsentPreflight::Complete(outcome) => Ok(outcome),
ConsentPreflight::Failed(error) => Err(ConsentActionError::Persist(error)),
ConsentPreflight::Present {
prompt,
policy,
status,
revision,
} => {
let decision = presenter(prompt)
.await
.map_err(ConsentActionError::Presenter)?;
BlockingTask::spawn(move || {
persist_presented_decision(decision, prompt, policy, status, revision)
})
.await
}
}
}
struct BlockingTask<T> {
shared: std::sync::Arc<BlockingTaskState<T>>,
}
struct BlockingTaskState<T> {
result: std::sync::Mutex<Option<std::thread::Result<T>>>,
waker: std::sync::Mutex<Option<std::task::Waker>>,
}
impl<T: Send + 'static> BlockingTask<T> {
fn spawn(operation: impl FnOnce() -> T + Send + 'static) -> Self {
let shared = std::sync::Arc::new(BlockingTaskState {
result: std::sync::Mutex::new(None),
waker: std::sync::Mutex::new(None),
});
let worker = std::sync::Arc::clone(&shared);
std::thread::spawn(move || {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(operation));
*worker.result.lock().unwrap_or_else(|e| e.into_inner()) = Some(result);
if let Some(waker) = worker
.waker
.lock()
.unwrap_or_else(|e| e.into_inner())
.take()
{
waker.wake();
}
});
Self { shared }
}
}
impl<T> std::future::Future for BlockingTask<T> {
type Output = T;
fn poll(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
if let Some(result) = self
.shared
.result
.lock()
.unwrap_or_else(|e| e.into_inner())
.take()
{
return std::task::Poll::Ready(match result {
Ok(value) => value,
Err(payload) => std::panic::resume_unwind(payload),
});
}
*self.shared.waker.lock().unwrap_or_else(|e| e.into_inner()) = Some(cx.waker().clone());
match self
.shared
.result
.lock()
.unwrap_or_else(|e| e.into_inner())
.take()
{
Some(result) => {
self.shared
.waker
.lock()
.unwrap_or_else(|e| e.into_inner())
.take();
std::task::Poll::Ready(match result {
Ok(value) => value,
Err(payload) => std::panic::resume_unwind(payload),
})
}
None => std::task::Poll::Pending,
}
}
}
enum ConsentPreflight {
Complete(ConsentActionOutcome),
Failed(String),
Present {
prompt: &'static ConsentPrompt,
policy: super::policy::PolicyState,
status: ConsentStatus,
revision: Option<u64>,
},
}
fn consent_preflight(locale: Option<&str>) -> ConsentPreflight {
let policy = super::policy::get_policy();
let (status, revision) = match platform::with_store_lock(|| {
let status = platform::read_status_unlocked();
let revision = platform::read_revision_unlocked()?;
Ok((status, revision))
}) {
Ok(snapshot) => snapshot,
Err(error) => return ConsentPreflight::Failed(error),
};
if status.effective_state == ConsentState::NotApplicable {
return ConsentPreflight::Complete(ConsentActionOutcome {
result: ConsentActionResult::NotApplicable,
status,
policy,
});
}
if !policy.allows_collection() {
return ConsentPreflight::Complete(ConsentActionOutcome {
result: ConsentActionResult::PolicyBlocked,
status,
policy,
});
}
if status.effective_state == ConsentState::Granted {
return ConsentPreflight::Complete(ConsentActionOutcome {
result: ConsentActionResult::AlreadyGranted,
status,
policy,
});
}
let prompt = prompt_for_locale(locale);
ConsentPreflight::Present {
prompt,
policy,
status,
revision,
}
}
fn persist_presented_decision(
decision: ConsentDecision,
prompt: &ConsentPrompt,
policy: super::policy::PolicyState,
status: ConsentStatus,
revision: Option<u64>,
) -> Result<ConsentActionOutcome, ConsentActionError> {
platform::with_store_lock(|| {
let current_policy = super::policy::get_policy();
let current_status = platform::read_status_unlocked();
let current_revision = platform::read_revision_unlocked()?;
if current_status.effective_state == ConsentState::NotApplicable {
return Ok(ConsentActionOutcome {
result: ConsentActionResult::NotApplicable,
status: current_status,
policy: current_policy,
});
}
if !current_policy.allows_collection() {
return Ok(ConsentActionOutcome {
result: ConsentActionResult::PolicyBlocked,
status: current_status,
policy: current_policy,
});
}
if current_status.effective_state == ConsentState::Granted
&& !matches!(decision, ConsentDecision::No)
{
return Ok(ConsentActionOutcome {
result: ConsentActionResult::AlreadyGranted,
status: current_status,
policy: current_policy,
});
}
let is_concurrent_grant_being_withdrawn = matches!(decision, ConsentDecision::No)
&& current_status.effective_state == ConsentState::Granted
&& status.effective_state != ConsentState::Granted;
if current_policy != policy
|| ((current_status.effective_state != status.effective_state
|| current_revision != revision)
&& !is_concurrent_grant_being_withdrawn)
{
return Err(
"consent state changed while the presenter was open; no decision was written"
.to_string(),
);
}
match decision {
ConsentDecision::Yes => {
platform::write_presented(true, "prompt", prompt)?;
Ok(ConsentActionOutcome {
result: ConsentActionResult::Granted,
status: platform::read_status_unlocked(),
policy: current_policy,
})
}
ConsentDecision::No => {
platform::write_presented(false, "prompt", prompt)?;
Ok(ConsentActionOutcome {
result: ConsentActionResult::Denied,
status: platform::read_status_unlocked(),
policy: current_policy,
})
}
ConsentDecision::Dismissed => Ok(ConsentActionOutcome {
result: ConsentActionResult::Dismissed,
status: current_status,
policy: current_policy,
}),
}
})
.map_err(ConsentActionError::Persist)
}
pub fn withdraw_consent() -> Result<ConsentActionOutcome, ConsentActionError> {
#[cfg(not(target_os = "windows"))]
{
let current_status = get_status();
Ok(ConsentActionOutcome {
result: ConsentActionResult::NotApplicable,
status: current_status,
policy: super::policy::get_policy(),
})
}
#[cfg(target_os = "windows")]
{
platform::with_store_lock(|| {
platform::begin_withdrawal()?;
platform::write(false, "withdrawal")?;
platform::finish_withdrawal()?;
Ok(ConsentActionOutcome {
result: ConsentActionResult::Withdrawn,
status: platform::read_status_unlocked(),
policy: super::policy::get_policy(),
})
})
.map_err(ConsentActionError::Persist)
}
}
#[cfg(target_os = "windows")]
fn now_epoch_seconds() -> u64 {
use std::time::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
#[cfg(target_os = "windows")]
mod platform {
use super::{
now_epoch_seconds, ConsentRecord, ConsentState, ConsentStatus, ConsentStatusReason,
CONSENT_SCHEMA_VERSION,
};
use crate::mxc_common::telemetry::consent_prompt::{CONSENT_RESOURCE_VERSION, FALLBACK_LOCALE};
use crate::mxc_common::telemetry::FailureReporter;
use std::fs;
use std::io::{Read, Write};
use std::os::windows::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::time::Duration;
const IO_RETRY_ATTEMPTS: u32 = 5;
#[cfg(test)]
const IO_RETRY_DELAY: Duration = Duration::ZERO;
#[cfg(not(test))]
const IO_RETRY_DELAY: Duration = Duration::from_millis(20);
const ERROR_SHARING_VIOLATION: i32 = 32;
const ERROR_LOCK_VIOLATION: i32 = 33;
const MAX_CONSENT_FILE_BYTES: u64 = 16 * 1024;
const WITHDRAWAL_PENDING_FILE: &str = "telemetry-consent.withdrawal-pending";
const CONSENT_LOCK_FILE: &str = "telemetry-consent.lock";
const WITHDRAWAL_MARKER_STALE_AFTER: Duration = Duration::from_secs(5);
fn report_consent_store_failure(signature: String) {
static FAILURES: OnceLock<FailureReporter> = OnceLock::new();
FAILURES
.get_or_init(FailureReporter::default)
.report(signature, |detail| {
let stderr = std::io::stderr();
let mut handle = stderr.lock();
let _ = writeln!(
handle,
"mxc: telemetry consent store failure ({detail}); \
treating consent as undetermined"
);
let _ = handle.flush();
});
}
fn known_folder_local_app_data() -> Option<PathBuf> {
static CACHED: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
cache_successful_resolution(&CACHED, resolve_known_folder_local_app_data)
}
fn cache_successful_resolution(
cache: &std::sync::OnceLock<PathBuf>,
resolver: impl FnOnce() -> Option<PathBuf>,
) -> Option<PathBuf> {
if let Some(cached) = cache.get() {
return Some(cached.clone());
}
let resolved = resolver()?;
let _ = cache.set(resolved.clone());
Some(resolved)
}
fn process_token() -> Option<crate::mxc_common::process_util::OwnedHandle> {
use windows::Win32::Foundation::HANDLE;
use windows::Win32::Security::{TOKEN_IMPERSONATE, TOKEN_QUERY};
use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
let mut token = HANDLE::default();
unsafe {
OpenProcessToken(
GetCurrentProcess(),
TOKEN_QUERY | TOKEN_IMPERSONATE,
&mut token,
)
}
.ok()?;
Some(crate::mxc_common::process_util::OwnedHandle::new(token))
}
fn resolve_known_folder_local_app_data() -> Option<PathBuf> {
use crate::mxc_common::string_util::CoTaskMemPWSTR;
use windows::Win32::UI::Shell::{
FOLDERID_LocalAppData, SHGetKnownFolderPath, KF_FLAG_DEFAULT,
};
let token = process_token()?;
let pwstr = unsafe {
SHGetKnownFolderPath(&FOLDERID_LocalAppData, KF_FLAG_DEFAULT, Some(token.get()))
}
.ok()?;
let owned = CoTaskMemPWSTR::new(pwstr.0);
let resolved = owned.to_string_lossy();
if resolved.is_empty() {
None
} else {
Some(PathBuf::from(resolved))
}
}
#[cfg(any(test, all(feature = "test-support", debug_assertions)))]
fn debug_local_app_data_override() -> Option<PathBuf> {
crate::mxc_common::telemetry::consent::test_support::current_local_app_data_override()
.or_else(
crate::mxc_common::telemetry::consent::test_support::inherited_local_app_data_override,
)
}
pub(super) fn local_app_data_dir() -> Option<PathBuf> {
#[cfg(any(test, all(feature = "test-support", debug_assertions)))]
if let Some(over) = debug_local_app_data_override() {
return Some(over);
}
known_folder_local_app_data()
}
pub(super) fn with_store_lock<T>(
operation: impl FnOnce() -> Result<T, String>,
) -> Result<T, String> {
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use windows::Win32::Foundation::HANDLE;
use windows::Win32::Storage::FileSystem::{
LockFileEx, FILE_SHARE_READ, FILE_SHARE_WRITE, LOCKFILE_EXCLUSIVE_LOCK,
};
use windows::Win32::System::IO::OVERLAPPED;
let path = consent_file_path().ok_or_else(|| {
"could not resolve %LocalAppData%; cannot lock telemetry consent".to_string()
})?;
let dir = path
.parent()
.ok_or_else(|| "invalid telemetry consent path".to_string())?;
fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
let lock_path = dir.join(CONSENT_LOCK_FILE);
let mut options = fs::OpenOptions::new();
options
.read(true)
.write(true)
.create(true)
.share_mode(FILE_SHARE_READ.0 | FILE_SHARE_WRITE.0);
let file = with_io_retry(|| options.open(&lock_path))
.map_err(|error| format!("failed to open telemetry consent lock: {error}"))?;
let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
unsafe {
LockFileEx(
HANDLE(file.as_raw_handle()),
LOCKFILE_EXCLUSIVE_LOCK,
None,
u32::MAX,
u32::MAX,
&mut overlapped,
)
}
.map_err(|error| format!("failed to lock telemetry consent: {error}"))?;
let _lock = file;
operation()
}
#[cfg(test)]
pub(super) fn known_folder_local_app_data_for_test() -> Option<PathBuf> {
known_folder_local_app_data()
}
#[cfg(test)]
pub(super) fn local_app_data_dir_for_test() -> Option<PathBuf> {
local_app_data_dir()
}
#[cfg(test)]
pub(super) fn cache_successful_resolution_for_test(
cache: &std::sync::OnceLock<PathBuf>,
resolver: impl FnOnce() -> Option<PathBuf>,
) -> Option<PathBuf> {
cache_successful_resolution(cache, resolver)
}
fn consent_file_path() -> Option<PathBuf> {
local_app_data_dir().map(|dir| dir.join("mxc").join("telemetry-consent.json"))
}
fn is_transient_io_error(e: &std::io::Error) -> bool {
if matches!(
e.raw_os_error(),
Some(ERROR_SHARING_VIOLATION) | Some(ERROR_LOCK_VIOLATION)
) {
return true;
}
matches!(
e.kind(),
std::io::ErrorKind::PermissionDenied | std::io::ErrorKind::Interrupted
)
}
fn with_io_retry<T>(mut op: impl FnMut() -> std::io::Result<T>) -> std::io::Result<T> {
let mut attempt = 0;
loop {
match op() {
Ok(v) => return Ok(v),
Err(e) if attempt + 1 < IO_RETRY_ATTEMPTS && is_transient_io_error(&e) => {
attempt += 1;
std::thread::sleep(IO_RETRY_DELAY);
}
Err(e) => return Err(e),
}
}
}
#[cfg(test)]
pub(super) fn with_io_retry_for_test<T>(
op: impl FnMut() -> std::io::Result<T>,
) -> std::io::Result<T> {
with_io_retry(op)
}
#[cfg(test)]
pub(super) fn transient_io_error_for_test() -> std::io::Error {
std::io::Error::from_raw_os_error(ERROR_SHARING_VIOLATION)
}
#[cfg(test)]
pub(super) const IO_RETRY_ATTEMPTS_FOR_TEST: u32 = IO_RETRY_ATTEMPTS;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum WithdrawalMarkerState {
Absent,
Pending,
Stale,
}
fn withdrawal_marker_state(marker: &Path) -> std::io::Result<WithdrawalMarkerState> {
match with_io_retry(|| fs::metadata(marker)) {
Ok(metadata) => {
let is_stale = metadata
.modified()
.ok()
.and_then(|modified| std::time::SystemTime::now().duration_since(modified).ok())
.is_some_and(|age| age >= WITHDRAWAL_MARKER_STALE_AFTER);
Ok(if is_stale {
WithdrawalMarkerState::Stale
} else {
WithdrawalMarkerState::Pending
})
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
Ok(WithdrawalMarkerState::Absent)
}
Err(error) => Err(error),
}
}
#[cfg(test)]
pub(super) fn read_status_unlocked_with_marker_for_test(
marker_state: std::io::Result<WithdrawalMarkerState>,
) -> ConsentStatus {
read_status_unlocked_inner(
|_| marker_state,
recover_stale_withdrawal_marker,
report_consent_store_failure,
)
}
#[cfg(test)]
pub(super) fn read_status_unlocked_with_reporter_for_test(
marker_state: std::io::Result<WithdrawalMarkerState>,
report: impl FnMut(String),
) -> ConsentStatus {
read_status_unlocked_inner(|_| marker_state, recover_stale_withdrawal_marker, report)
}
pub(super) fn read_status() -> ConsentStatus {
match with_store_lock(|| Ok(read_status_unlocked())) {
Ok(status) => status,
Err(error) => {
report_consent_store_failure(format!("lock consent store: {error}"));
unreadable_status()
}
}
}
pub(super) fn read_status_unlocked() -> ConsentStatus {
read_status_unlocked_inner(
withdrawal_marker_state,
recover_stale_withdrawal_marker,
report_consent_store_failure,
)
}
pub(super) fn read_revision_unlocked() -> Result<Option<u64>, String> {
let Some(path) = consent_file_path() else {
return Ok(None);
};
Ok(read_record(&path)?.map(|record| record.revision))
}
fn read_status_unlocked_inner(
marker_check: impl FnOnce(&Path) -> std::io::Result<WithdrawalMarkerState>,
recover_stale: impl FnOnce(&Path, &Path) -> Result<(), String>,
mut report: impl FnMut(String),
) -> ConsentStatus {
fn no_record_status() -> ConsentStatus {
ConsentStatus {
stored_state: ConsentState::Undetermined,
effective_state: ConsentState::Undetermined,
reason: Some(ConsentStatusReason::NoRecord),
}
}
let Some(path) = consent_file_path() else {
report("resolve consent store path".to_string());
return unreadable_status();
};
let Some(dir) = path.parent() else {
report("resolve consent store parent directory".to_string());
return unreadable_status();
};
let marker_path = dir.join(WITHDRAWAL_PENDING_FILE);
match marker_check(&marker_path) {
Ok(WithdrawalMarkerState::Absent) => {}
Ok(WithdrawalMarkerState::Pending) => {
return unreadable_status();
}
Err(error) => {
report(format!(
"inspect withdrawal marker: kind={:?}, os_error={:?}, error={error}",
error.kind(),
error.raw_os_error()
));
return unreadable_status();
}
Ok(WithdrawalMarkerState::Stale) => {
if let Err(error) = recover_stale(&path, &marker_path) {
report(format!("recover stale withdrawal marker: {error}"));
return unreadable_status();
}
}
}
let data = match with_io_retry(|| read_bounded(&path)) {
Ok(data) => data,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return no_record_status();
}
Err(error) => {
report(format!(
"read consent record: kind={:?}, os_error={:?}, error={error}",
error.kind(),
error.raw_os_error()
));
return unreadable_status();
}
};
let record = match serde_json::from_str::<ConsentRecord>(&data) {
Ok(record) => record,
Err(error) => {
report(format!("parse consent record: {error}"));
return malformed_status();
}
};
let stored_state = match record.consent.as_str() {
"granted" => ConsentState::Granted,
"denied" => ConsentState::Denied,
_ => {
report("validate consent record: unrecognized consent value".to_string());
return malformed_status();
}
};
if stored_state == ConsentState::Denied {
return ConsentStatus {
stored_state,
effective_state: ConsentState::Denied,
reason: None,
};
}
if record.schema_version != CONSENT_SCHEMA_VERSION {
return ConsentStatus {
stored_state,
effective_state: ConsentState::Undetermined,
reason: Some(if record.prompt_resource_version.is_none() {
ConsentStatusReason::PromptVersionMissing
} else {
ConsentStatusReason::ConsentSchemaUnsupported
}),
};
}
match record.prompt_resource_version {
Some(CONSENT_RESOURCE_VERSION) if record.prompt_locale == FALLBACK_LOCALE => {
ConsentStatus {
stored_state,
effective_state: ConsentState::Granted,
reason: None,
}
}
Some(CONSENT_RESOURCE_VERSION) => {
report("validate consent record: unsupported prompt locale".to_string());
ConsentStatus {
stored_state,
effective_state: ConsentState::Undetermined,
reason: Some(ConsentStatusReason::PromptVersionUnsupported),
}
}
None => ConsentStatus {
stored_state,
effective_state: ConsentState::Undetermined,
reason: Some(ConsentStatusReason::PromptVersionMissing),
},
Some(_) => ConsentStatus {
stored_state,
effective_state: ConsentState::Undetermined,
reason: Some(ConsentStatusReason::PromptVersionUnsupported),
},
}
}
fn unreadable_status() -> ConsentStatus {
ConsentStatus {
stored_state: ConsentState::Undetermined,
effective_state: ConsentState::Undetermined,
reason: Some(ConsentStatusReason::StoreUnreadable),
}
}
fn malformed_status() -> ConsentStatus {
ConsentStatus {
stored_state: ConsentState::Undetermined,
effective_state: ConsentState::Undetermined,
reason: Some(ConsentStatusReason::StoreMalformed),
}
}
fn read_bounded(path: &Path) -> std::io::Result<String> {
let file = fs::File::open(path)?;
let mut bytes = Vec::new();
file.take(MAX_CONSENT_FILE_BYTES + 1)
.read_to_end(&mut bytes)?;
if bytes.len() as u64 > MAX_CONSENT_FILE_BYTES {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"telemetry consent file exceeds the supported size",
));
}
String::from_utf8(bytes)
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
}
fn read_record(path: &Path) -> Result<Option<ConsentRecord>, String> {
let data = match with_io_retry(|| read_bounded(path)) {
Ok(data) => data,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => {
return Err(format!(
"failed to read telemetry consent record revision: {error}"
));
}
};
Ok(serde_json::from_str(&data).ok())
}
fn recover_stale_withdrawal_marker(_path: &Path, marker: &Path) -> Result<(), String> {
match withdrawal_marker_state(marker)
.map_err(|e| format!("failed to inspect stale withdrawal marker: {e}"))?
{
WithdrawalMarkerState::Absent => Ok(()),
WithdrawalMarkerState::Pending | WithdrawalMarkerState::Stale => write_record(
false,
"withdrawal-recovery",
Some(CONSENT_RESOURCE_VERSION),
FALLBACK_LOCALE,
),
}
}
fn remove_best_effort(path: &Path) {
let _ = fs::remove_file(path);
}
pub(super) fn write(granted: bool, source: &str) -> Result<(), String> {
write_record(
granted,
source,
Some(CONSENT_RESOURCE_VERSION),
FALLBACK_LOCALE,
)
}
pub(super) fn write_presented(
granted: bool,
source: &str,
prompt: &crate::mxc_common::telemetry::consent_prompt::ConsentPrompt,
) -> Result<(), String> {
write_record(
granted,
source,
Some(prompt.resource_version),
prompt.locale,
)
}
pub(super) fn begin_withdrawal() -> Result<(), String> {
let path = consent_file_path().ok_or_else(|| {
"could not resolve %LocalAppData%; cannot persist telemetry consent".to_string()
})?;
let dir = path
.parent()
.ok_or_else(|| "invalid telemetry consent path".to_string())?;
fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
let marker = dir.join(WITHDRAWAL_PENDING_FILE);
with_io_retry(|| {
let mut file = fs::File::create(&marker)?;
file.write_all(b"pending")?;
file.sync_all()
})
.map_err(|e| format!("failed to durably mark withdrawal pending: {e}"))
}
pub(super) fn finish_withdrawal() -> Result<(), String> {
let path = consent_file_path().ok_or_else(|| {
"could not resolve %LocalAppData%; cannot persist telemetry consent".to_string()
})?;
clear_withdrawal_marker(&path)
}
fn write_record(
granted: bool,
source: &str,
prompt_resource_version: Option<u32>,
prompt_locale: &str,
) -> Result<(), String> {
let path = consent_file_path().ok_or_else(|| {
"could not resolve %LocalAppData%; cannot persist telemetry consent".to_string()
})?;
let dir = path
.parent()
.ok_or_else(|| "invalid telemetry consent path".to_string())?;
fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
let revision = read_record(&path)?
.map_or(0, |record| record.revision)
.checked_add(1)
.ok_or_else(|| "telemetry consent record revision is exhausted".to_string())?;
let record = ConsentRecord {
schema_version: CONSENT_SCHEMA_VERSION,
consent: if granted { "granted" } else { "denied" }.to_string(),
source: source.to_string(),
prompted_mxc_version: crate::mxc_common::telemetry::version().to_string(),
prompt_resource_version,
prompt_locale: prompt_locale.to_string(),
updated_at_epoch: now_epoch_seconds(),
revision,
};
let json = serde_json::to_string_pretty(&record)
.map_err(|e| format!("failed to serialize telemetry consent record: {e}"))?;
let unique = format!("{}-{:x}", std::process::id(), random_suffix());
let tmp_path = path.with_extension(format!("json.{unique}.tmp"));
if let Err(e) = with_io_retry(|| {
let mut file = fs::File::create(&tmp_path)?;
file.write_all(json.as_bytes())?;
file.sync_all()
}) {
remove_best_effort(&tmp_path);
return Err(format!("failed to write {}: {e}", tmp_path.display()));
}
if let Err(e) = with_io_retry(|| replace_file_write_through(&tmp_path, &path)) {
remove_best_effort(&tmp_path);
return Err(format!("failed to finalize {}: {e}", path.display()));
}
clear_withdrawal_marker(&path)
}
pub(super) fn replace_file_write_through(
source: &Path,
destination: &Path,
) -> std::io::Result<()> {
use windows::core::PCWSTR;
use windows::Win32::Storage::FileSystem::{
MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,
};
let source: Vec<u16> = source.as_os_str().encode_wide().chain(Some(0)).collect();
let destination: Vec<u16> = destination
.as_os_str()
.encode_wide()
.chain(Some(0))
.collect();
unsafe {
MoveFileExW(
PCWSTR(source.as_ptr()),
PCWSTR(destination.as_ptr()),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
)
}
.map_err(windows_error_to_io)
}
fn windows_error_to_io(error: windows::core::Error) -> std::io::Error {
let hresult = error.code().0 as u32;
let raw_error = if hresult & 0xffff_0000 == 0x8007_0000 {
(hresult & 0xffff) as i32
} else {
hresult as i32
};
std::io::Error::from_raw_os_error(raw_error)
}
fn clear_withdrawal_marker(path: &Path) -> Result<(), String> {
let dir = path
.parent()
.ok_or_else(|| "invalid telemetry consent path".to_string())?;
match with_io_retry(|| fs::remove_file(dir.join(WITHDRAWAL_PENDING_FILE))) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(format!("failed to clear withdrawal marker: {e}")),
}
}
fn random_suffix() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_SUFFIX: AtomicU64 = AtomicU64::new(0);
NEXT_SUFFIX.fetch_add(1, Ordering::Relaxed)
}
}
#[cfg(not(target_os = "windows"))]
mod platform {
use super::{ConsentState, ConsentStatus, ConsentStatusReason};
use std::path::PathBuf;
pub(super) fn with_store_lock<T>(
operation: impl FnOnce() -> Result<T, String>,
) -> Result<T, String> {
operation()
}
pub(super) fn read_status() -> ConsentStatus {
ConsentStatus {
stored_state: ConsentState::NotApplicable,
effective_state: ConsentState::NotApplicable,
reason: Some(ConsentStatusReason::NotApplicable),
}
}
pub(super) fn local_app_data_dir() -> Option<PathBuf> {
None
}
pub(super) fn read_status_unlocked() -> ConsentStatus {
read_status()
}
pub(super) fn read_revision_unlocked() -> Result<Option<u64>, String> {
Ok(None)
}
#[cfg(test)]
pub(super) fn write(_granted: bool, _source: &str) -> Result<(), String> {
Err("telemetry is Windows-only; consent is not applicable on this platform".to_string())
}
pub(super) fn write_presented(
_granted: bool,
_source: &str,
_prompt: &crate::mxc_common::telemetry::consent_prompt::ConsentPrompt,
) -> Result<(), String> {
Err("telemetry is Windows-only; consent is not applicable on this platform".to_string())
}
}
#[cfg(any(test, all(feature = "test-support", debug_assertions)))]
pub mod test_support {
use std::path::Path;
#[cfg(target_os = "windows")]
use std::path::PathBuf;
use std::sync::{Mutex, MutexGuard};
#[cfg(target_os = "windows")]
const LOCAL_APPDATA_OVERRIDE_ENV: &str = "MXC_TEST_LOCALAPPDATA_OVERRIDE";
#[cfg(target_os = "windows")]
const LOCAL_APPDATA_OVERRIDE_OWNER_ENV: &str = "MXC_TEST_LOCALAPPDATA_OVERRIDE_OWNER_PID";
pub(crate) static ENV_LOCK: Mutex<()> = Mutex::new(());
#[cfg(target_os = "windows")]
static LOCAL_APP_DATA_OVERRIDE: Mutex<Option<PathBuf>> = Mutex::new(None);
pub struct LocalAppDataGuard {
_lock: MutexGuard<'static, ()>,
#[cfg(target_os = "windows")]
previous_override: Option<PathBuf>,
}
impl LocalAppDataGuard {
#[cfg(target_os = "windows")]
pub fn set(path: &Path) -> Self {
let lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let previous_override = LOCAL_APP_DATA_OVERRIDE
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
*LOCAL_APP_DATA_OVERRIDE
.lock()
.unwrap_or_else(|e| e.into_inner()) = Some(path.to_path_buf());
Self {
_lock: lock,
previous_override,
}
}
#[cfg(not(target_os = "windows"))]
pub fn set(_path: &Path) -> Self {
let lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
Self { _lock: lock }
}
}
#[cfg(all(
target_os = "windows",
any(test, all(feature = "test-support", debug_assertions))
))]
pub(crate) fn current_local_app_data_override() -> Option<PathBuf> {
LOCAL_APP_DATA_OVERRIDE
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
#[cfg(all(
target_os = "windows",
any(test, all(feature = "test-support", debug_assertions))
))]
pub(crate) fn inherited_local_app_data_override() -> Option<PathBuf> {
let path = std::env::var_os(LOCAL_APPDATA_OVERRIDE_ENV)
.filter(|value| !value.is_empty())
.map(PathBuf::from)?;
scoped_local_app_data_override(
path,
std::env::var_os(LOCAL_APPDATA_OVERRIDE_OWNER_ENV),
direct_parent_process_id(),
)
}
#[cfg(all(
target_os = "windows",
any(test, all(feature = "test-support", debug_assertions))
))]
fn scoped_local_app_data_override(
path: PathBuf,
owner: Option<std::ffi::OsString>,
parent_process_id: Option<u32>,
) -> Option<PathBuf> {
let owner = owner?.to_str()?.parse::<u32>().ok()?;
(Some(owner) == parent_process_id).then_some(path)
}
#[cfg(all(
target_os = "windows",
any(test, all(feature = "test-support", debug_assertions))
))]
fn direct_parent_process_id() -> Option<u32> {
use windows::Win32::Foundation::CloseHandle;
use windows::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
TH32CS_SNAPPROCESS,
};
let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }.ok()?;
let mut entry = PROCESSENTRY32W {
dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32,
..Default::default()
};
let mut parent = None;
unsafe {
if Process32FirstW(snapshot, &mut entry).is_ok() {
loop {
if entry.th32ProcessID == std::process::id() {
parent = Some(entry.th32ParentProcessID);
break;
}
if Process32NextW(snapshot, &mut entry).is_err() {
break;
}
}
}
let _ = CloseHandle(snapshot);
}
parent
}
#[cfg(all(target_os = "windows", test))]
pub(crate) fn apply_inherited_override(command: &mut std::process::Command, path: &Path) {
command.env(LOCAL_APPDATA_OVERRIDE_ENV, path).env(
LOCAL_APPDATA_OVERRIDE_OWNER_ENV,
std::process::id().to_string(),
);
}
#[cfg(target_os = "windows")]
impl Drop for LocalAppDataGuard {
fn drop(&mut self) {
*LOCAL_APP_DATA_OVERRIDE
.lock()
.unwrap_or_else(|e| e.into_inner()) = self.previous_override.clone();
}
}
#[cfg(all(target_os = "windows", test))]
mod tests {
use super::scoped_local_app_data_override;
use std::path::PathBuf;
#[test]
fn inherited_override_requires_direct_parent_owner() {
let path = PathBuf::from("isolated");
assert_eq!(
scoped_local_app_data_override(path.clone(), Some("41".into()), Some(41)),
Some(path.clone())
);
assert_eq!(
scoped_local_app_data_override(path.clone(), Some("42".into()), Some(41)),
None
);
assert_eq!(
scoped_local_app_data_override(path.clone(), Some("invalid".into()), Some(41)),
None
);
assert_eq!(scoped_local_app_data_override(path, None, Some(41)), None);
}
}
}
#[cfg(test)]
mod tests {
use super::test_support::LocalAppDataGuard;
use super::*;
fn block_on<F: std::future::Future>(future: F) -> F::Output {
fn raw_waker() -> std::task::RawWaker {
fn clone(_: *const ()) -> std::task::RawWaker {
raw_waker()
}
fn wake(_: *const ()) {}
fn wake_by_ref(_: *const ()) {}
fn drop(_: *const ()) {}
std::task::RawWaker::new(
std::ptr::null(),
&std::task::RawWakerVTable::new(clone, wake, wake_by_ref, drop),
)
}
let waker = unsafe { std::task::Waker::from_raw(raw_waker()) };
let mut future = std::pin::pin!(future);
let mut context = std::task::Context::from_waker(&waker);
loop {
match future.as_mut().poll(&mut context) {
std::task::Poll::Ready(result) => return result,
std::task::Poll::Pending => std::thread::sleep(std::time::Duration::from_millis(1)),
}
}
}
#[test]
fn blocking_task_propagates_worker_panic_without_hanging() {
struct SignalWaker(std::sync::mpsc::Sender<()>);
impl std::task::Wake for SignalWaker {
fn wake(self: std::sync::Arc<Self>) {
let _ = self.0.send(());
}
fn wake_by_ref(self: &std::sync::Arc<Self>) {
let _ = self.0.send(());
}
}
let (sender, receiver) = std::sync::mpsc::channel();
let waker = std::task::Waker::from(std::sync::Arc::new(SignalWaker(sender)));
let mut context = std::task::Context::from_waker(&waker);
let mut task = std::pin::pin!(BlockingTask::spawn(|| -> () { panic!("worker panic") }));
let propagated = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if std::future::Future::poll(task.as_mut(), &mut context).is_pending() {
receiver
.recv_timeout(std::time::Duration::from_secs(10))
.expect("blocking task did not wake after its worker panicked");
let _ = std::future::Future::poll(task.as_mut(), &mut context);
}
}))
.is_err();
assert!(
propagated,
"blocking task did not propagate its worker panic"
);
}
#[test]
fn consent_state_as_str_is_stable() {
assert_eq!(ConsentState::Granted.as_str(), "granted");
assert_eq!(ConsentState::Denied.as_str(), "denied");
assert_eq!(ConsentState::Undetermined.as_str(), "undetermined");
assert_eq!(ConsentState::NotApplicable.as_str(), "not-applicable");
}
#[test]
fn only_granted_allows_collection() {
assert!(ConsentState::Granted.allows_collection());
assert!(!ConsentState::Denied.allows_collection());
assert!(!ConsentState::Undetermined.allows_collection());
assert!(!ConsentState::NotApplicable.allows_collection());
}
#[test]
fn only_undetermined_needs_prompt() {
assert!(ConsentState::Undetermined.needs_prompt());
assert!(!ConsentState::Granted.needs_prompt());
assert!(!ConsentState::Denied.needs_prompt());
assert!(!ConsentState::NotApplicable.needs_prompt());
}
#[cfg(target_os = "windows")]
#[test]
fn now_epoch_seconds_is_plausible() {
let secs = now_epoch_seconds();
assert!(secs > 1_700_000_000, "epoch seconds too small: {secs}");
assert!(secs < 4_000_000_000, "epoch seconds too large: {secs}");
}
#[cfg(not(target_os = "windows"))]
#[test]
fn non_windows_is_always_not_applicable_and_write_fails() {
let _guard = LocalAppDataGuard::set(std::path::Path::new("unused"));
assert_eq!(get_consent(), ConsentState::NotApplicable);
assert_eq!(
request_consent(None, |_| panic!("non-Windows consent must not present"))
.unwrap()
.result,
ConsentActionResult::NotApplicable
);
assert_eq!(
block_on(request_consent_async(None, |_| async {
panic!("non-Windows async consent must not present")
}))
.unwrap()
.result,
ConsentActionResult::NotApplicable
);
assert_eq!(
withdraw_consent().unwrap().result,
ConsentActionResult::NotApplicable
);
assert!(set_consent(true, "cli").is_err());
assert!(set_consent(false, "cli").is_err());
assert!(
!needs_consent_prompt(),
"must never ask for consent where nothing is collected"
);
}
#[cfg(target_os = "windows")]
mod windows_tests {
use super::{block_on, LocalAppDataGuard};
use crate::mxc_common::telemetry::consent::{
get_consent, get_status, needs_consent_prompt, platform, request_consent,
request_consent_async, set_consent, withdraw_consent, ConsentActionError,
ConsentActionResult, ConsentDecision, ConsentState, ConsentStatusReason,
};
fn age_withdrawal_marker(store_root: &std::path::Path) {
let marker = store_root
.join("mxc")
.join("telemetry-consent.withdrawal-pending");
let file = std::fs::OpenOptions::new()
.write(true)
.open(&marker)
.expect("open withdrawal marker");
let stale_time = std::time::SystemTime::now() - std::time::Duration::from_secs(10);
file.set_times(std::fs::FileTimes::new().set_modified(stale_time))
.expect("age withdrawal marker");
}
#[test]
fn needs_consent_prompt_tracks_the_store() {
let tmp = tempfile::tempdir().unwrap();
let _env =
crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
assert!(needs_consent_prompt(), "fresh store must prompt");
set_consent(false, "prompt").unwrap();
assert!(
!needs_consent_prompt(),
"a recorded denial must not re-prompt"
);
set_consent(true, "settings-toggle").unwrap();
assert!(
!needs_consent_prompt(),
"a recorded grant must not re-prompt"
);
}
#[test]
fn needs_consent_prompt_is_suppressed_by_blocking_policy() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(0);
assert!(
!needs_consent_prompt(),
"a blocking policy must suppress a meaningless prompt"
);
}
#[test]
fn fresh_store_is_undetermined() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
assert_eq!(get_consent(), ConsentState::Undetermined);
}
#[test]
fn store_lock_file_persists_when_released() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
let lock_path = tmp.path().join("mxc").join("telemetry-consent.lock");
platform::with_store_lock(|| {
assert!(lock_path.exists(), "lock file must exist while held");
Ok(())
})
.expect("acquire store lock");
assert!(
lock_path.exists(),
"lock ownership must not depend on deleting the lock file"
);
}
#[test]
fn preexisting_unlocked_store_lock_file_can_be_reused() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
let dir = tmp.path().join("mxc");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("telemetry-consent.lock"), []).unwrap();
set_consent(true, "cli").expect("pre-existing lock file must not block consent writes");
assert_eq!(get_consent(), ConsentState::Granted);
}
#[test]
fn grant_then_read_round_trips() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
set_consent(true, "cli").expect("grant should succeed");
assert_eq!(get_consent(), ConsentState::Granted);
}
#[test]
fn deny_then_read_round_trips() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
set_consent(false, "cli").expect("deny should succeed");
assert_eq!(get_consent(), ConsentState::Denied);
}
#[test]
fn consent_can_be_flipped_repeatedly() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
set_consent(true, "prompt").unwrap();
assert_eq!(get_consent(), ConsentState::Granted);
set_consent(false, "settings-toggle").unwrap();
assert_eq!(get_consent(), ConsentState::Denied);
set_consent(true, "settings-toggle").unwrap();
assert_eq!(get_consent(), ConsentState::Granted);
}
#[test]
fn presenter_yes_persists_a_current_version_grant() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
let outcome = request_consent(Some("en-US"), |prompt| {
assert_eq!(
prompt.resource_version,
crate::mxc_common::telemetry::consent_prompt::CONSENT_RESOURCE_VERSION
);
assert_eq!(prompt.locale, "en-US");
Ok(ConsentDecision::Yes)
})
.expect("consent request");
assert_eq!(outcome.result, ConsentActionResult::Granted);
assert_eq!(outcome.status.stored_state, ConsentState::Granted);
assert_eq!(outcome.status.effective_state, ConsentState::Granted);
assert_eq!(outcome.status.reason, None);
}
#[test]
fn async_presenter_yes_persists_a_current_version_grant() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
let outcome = block_on(request_consent_async(Some("en-US"), |prompt| {
assert_eq!(
prompt.resource_version,
crate::mxc_common::telemetry::consent_prompt::CONSENT_RESOURCE_VERSION
);
assert_eq!(prompt.locale, "en-US");
async { Ok(ConsentDecision::Yes) }
}))
.expect("async consent request");
assert_eq!(outcome.result, ConsentActionResult::Granted);
assert_eq!(outcome.status.stored_state, ConsentState::Granted);
assert_eq!(outcome.status.effective_state, ConsentState::Granted);
assert_eq!(outcome.status.reason, None);
}
#[test]
fn async_presenter_no_persists_a_denial() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
let outcome = block_on(request_consent_async(None, |_| async {
Ok(ConsentDecision::No)
}))
.expect("async denial");
assert_eq!(outcome.result, ConsentActionResult::Denied);
assert_eq!(get_consent(), ConsentState::Denied);
}
#[test]
fn async_dismissal_preserves_the_prior_state() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
set_consent(false, "prompt").unwrap();
let outcome = block_on(request_consent_async(None, |_| async {
Ok(ConsentDecision::Dismissed)
}))
.expect("async dismissal");
assert_eq!(outcome.result, ConsentActionResult::Dismissed);
assert_eq!(get_consent(), ConsentState::Denied);
}
#[test]
fn async_presenter_error_preserves_the_prior_state() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
set_consent(false, "prompt").unwrap();
let error = block_on(request_consent_async(None, |_| async {
Err("host UI failed".to_string())
}))
.expect_err("async presenter failure");
assert_eq!(
error,
ConsentActionError::Presenter("host UI failed".to_string())
);
assert_eq!(get_consent(), ConsentState::Denied);
}
#[test]
fn async_policy_block_skips_the_presenter() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(0);
let outcome = block_on(request_consent_async(None, |_| async {
panic!("blocked policy must not present")
}))
.expect("blocked result");
assert_eq!(outcome.result, ConsentActionResult::PolicyBlocked);
}
#[test]
fn policy_change_while_presenter_is_open_blocks_stale_grant() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
let outcome = request_consent(Some("en-US"), |_| {
env.set_policy_value(0);
Ok(ConsentDecision::Yes)
})
.expect("policy change should produce a typed outcome");
assert_eq!(outcome.result, ConsentActionResult::PolicyBlocked);
assert_eq!(outcome.status.effective_state, ConsentState::Undetermined);
assert_eq!(get_consent(), ConsentState::Undetermined);
}
#[test]
fn consent_change_while_presenter_is_open_rejects_stale_decision() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
let error = request_consent(Some("en-US"), |_| {
set_consent(false, "concurrent-withdrawal").unwrap();
Ok(ConsentDecision::Yes)
})
.expect_err("stale presenter decision must not overwrite a newer denial");
assert_eq!(
error,
ConsentActionError::Persist(
"consent state changed while the presenter was open; no decision was written"
.to_string()
)
);
assert_eq!(get_consent(), ConsentState::Denied);
}
#[test]
fn same_state_change_while_presenter_is_open_rejects_stale_decision() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
set_consent(false, "initial-denial").unwrap();
let error = request_consent(Some("en-US"), |_| {
set_consent(false, "concurrent-withdrawal").unwrap();
Ok(ConsentDecision::Yes)
})
.expect_err("stale presenter decision must not overwrite a newer denial");
assert_eq!(
error,
ConsentActionError::Persist(
"consent state changed while the presenter was open; no decision was written"
.to_string()
)
);
assert_eq!(get_consent(), ConsentState::Denied);
let record =
std::fs::read_to_string(tmp.path().join("mxc").join("telemetry-consent.json"))
.unwrap();
assert!(record.contains(r#""source": "concurrent-withdrawal""#));
}
#[test]
fn explicit_denial_withdraws_a_concurrent_grant() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
let outcome = request_consent(Some("en-US"), |_| {
set_consent(true, "concurrent-grant").unwrap();
Ok(ConsentDecision::No)
})
.expect("explicit denial should be persisted");
assert_eq!(outcome.result, ConsentActionResult::Denied);
assert_eq!(get_consent(), ConsentState::Denied);
}
#[test]
fn explicit_request_can_replace_a_prior_denial() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
set_consent(false, "prompt").unwrap();
let outcome = request_consent(None, |_| Ok(ConsentDecision::Yes)).unwrap();
assert_eq!(outcome.result, ConsentActionResult::Granted);
assert_eq!(get_consent(), ConsentState::Granted);
}
#[test]
fn dismissed_or_failed_presenter_does_not_rewrite_prior_state() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
set_consent(false, "prompt").unwrap();
let dismissed =
request_consent(None, |_| Ok(ConsentDecision::Dismissed)).expect("dismissal");
assert_eq!(dismissed.result, ConsentActionResult::Dismissed);
assert_eq!(get_consent(), ConsentState::Denied);
let error = request_consent(None, |_| Err("host UI failed".to_string()))
.expect_err("presenter failure");
assert_eq!(
error,
ConsentActionError::Presenter("host UI failed".to_string())
);
assert_eq!(get_consent(), ConsentState::Denied);
}
#[test]
fn policy_block_and_current_grant_skip_the_presenter() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(0);
let blocked = request_consent(None, |_| panic!("blocked policy must not present"))
.expect("blocked result");
assert_eq!(blocked.result, ConsentActionResult::PolicyBlocked);
env.set_policy_value(3);
set_consent(true, "prompt").unwrap();
let granted = request_consent(None, |_| panic!("current grant must not re-present"))
.expect("already granted result");
assert_eq!(granted.result, ConsentActionResult::AlreadyGranted);
}
#[test]
fn withdrawal_is_idempotent_and_ignores_blocking_policy() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
set_consent(true, "prompt").unwrap();
env.set_policy_value(0);
for _ in 0..2 {
let outcome = withdraw_consent().expect("withdrawal");
assert_eq!(outcome.result, ConsentActionResult::Withdrawn);
assert_eq!(outcome.status.effective_state, ConsentState::Denied);
}
}
#[test]
fn withdrawal_reports_the_current_policy_after_waiting_for_the_store_lock() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
set_consent(true, "prompt").unwrap();
let outcome = std::thread::scope(|scope| {
let handle = platform::with_store_lock(|| {
let handle = scope.spawn(|| withdraw_consent().expect("withdrawal"));
env.set_policy_value(0);
Ok(handle)
})
.expect("store lock");
handle.join().unwrap()
});
assert_eq!(outcome.result, ConsentActionResult::Withdrawn);
assert_eq!(outcome.status.effective_state, ConsentState::Denied);
assert_eq!(
outcome.policy,
crate::mxc_common::telemetry::PolicyState::Blocked
);
}
#[test]
fn consent_read_waits_for_the_store_lock() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
set_consent(true, "prompt").unwrap();
let (started_tx, started_rx) = std::sync::mpsc::channel();
let (status_tx, status_rx) = std::sync::mpsc::channel();
std::thread::scope(|scope| {
let read_handle = platform::with_store_lock(|| {
let handle = scope.spawn(move || {
started_tx.send(()).expect("send reader start");
status_tx.send(get_status()).expect("send consent status");
});
started_rx.recv().expect("reader start");
assert!(
status_rx
.recv_timeout(std::time::Duration::from_millis(100))
.is_err(),
"consent read must wait while a writer owns the store lock"
);
Ok(handle)
})
.expect("store lock");
read_handle.join().unwrap();
});
let status = status_rx.recv().expect("consent status after lock release");
assert_eq!(status.effective_state, ConsentState::Granted);
}
#[test]
fn store_lock_waits_beyond_the_previous_retry_budget() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
let (started_tx, started_rx) = std::sync::mpsc::channel();
let (result_tx, result_rx) = std::sync::mpsc::channel();
std::thread::scope(|scope| {
platform::with_store_lock(|| {
scope.spawn(move || {
started_tx.send(()).expect("send writer start");
result_tx
.send(set_consent(true, "cli"))
.expect("send writer result");
});
started_rx.recv().expect("writer start");
assert!(
result_rx
.recv_timeout(std::time::Duration::from_millis(1_100))
.is_err(),
"the waiting writer must not exhaust a retry budget"
);
Ok(())
})
.expect("store lock");
});
result_rx
.recv()
.expect("writer result after lock release")
.expect("waiting writer must acquire the released lock");
assert_eq!(get_consent(), ConsentState::Granted);
}
#[test]
fn corrupt_file_is_undetermined_not_granted() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
let dir = tmp.path().join("mxc");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("telemetry-consent.json"), "not json at all").unwrap();
assert_eq!(get_consent(), ConsentState::Undetermined);
}
#[test]
fn oversized_file_is_rejected_without_unbounded_read() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
let dir = tmp.path().join("mxc");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("telemetry-consent.json"),
vec![b'x'; 16 * 1024 + 1],
)
.unwrap();
let status = get_status();
assert_eq!(status.effective_state, ConsentState::Undetermined);
assert_eq!(status.reason, Some(ConsentStatusReason::StoreUnreadable));
}
#[test]
fn pending_withdrawal_marker_fails_closed() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
platform::begin_withdrawal().unwrap();
let status = get_status();
assert_eq!(status.effective_state, ConsentState::Undetermined);
assert_eq!(status.reason, Some(ConsentStatusReason::StoreUnreadable));
}
#[test]
fn pending_withdrawal_marker_metadata_errors_fail_closed() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
set_consent(true, "prompt").unwrap();
let status =
platform::read_status_unlocked_with_marker_for_test(Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"marker temporarily unreadable",
)));
assert_eq!(status.stored_state, ConsentState::Undetermined);
assert_eq!(status.effective_state, ConsentState::Undetermined);
assert_eq!(status.reason, Some(ConsentStatusReason::StoreUnreadable));
}
#[test]
fn swallowed_store_failures_are_reported() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
let reports = std::sync::Mutex::new(Vec::new());
let status = platform::read_status_unlocked_with_reporter_for_test(
Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"marker temporarily unreadable",
)),
|message| {
reports
.lock()
.unwrap_or_else(|error| error.into_inner())
.push(message);
},
);
assert_eq!(status.reason, Some(ConsentStatusReason::StoreUnreadable));
assert_eq!(
reports
.lock()
.unwrap_or_else(|error| error.into_inner())
.as_slice(),
[
"inspect withdrawal marker: kind=PermissionDenied, os_error=None, error=marker temporarily unreadable"
]
);
}
#[test]
fn malformed_store_is_reported() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
let dir = tmp.path().join("mxc");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("telemetry-consent.json"), "not json at all").unwrap();
let reports = std::sync::Mutex::new(Vec::new());
let status = platform::read_status_unlocked_with_reporter_for_test(
Ok(platform::WithdrawalMarkerState::Absent),
|message| {
reports
.lock()
.unwrap_or_else(|error| error.into_inner())
.push(message);
},
);
assert_eq!(status.reason, Some(ConsentStatusReason::StoreMalformed));
assert!(
reports
.lock()
.unwrap_or_else(|error| error.into_inner())
.iter()
.any(|message| message.starts_with("parse consent record:")),
"malformed consent must produce a diagnostic"
);
}
#[test]
fn successful_grant_repairs_a_stale_withdrawal_marker() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
platform::begin_withdrawal().unwrap();
let outcome = request_consent(None, |_| Ok(ConsentDecision::Yes)).unwrap();
assert_eq!(outcome.result, ConsentActionResult::Granted);
assert_eq!(outcome.status.effective_state, ConsentState::Granted);
assert_eq!(get_consent(), ConsentState::Granted);
}
#[test]
fn stale_withdrawal_marker_recovers_to_denied() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
set_consent(true, "prompt").unwrap();
platform::begin_withdrawal().unwrap();
age_withdrawal_marker(tmp.path());
let status = get_status();
assert_eq!(status.stored_state, ConsentState::Denied);
assert_eq!(status.effective_state, ConsentState::Denied);
assert_eq!(status.reason, None);
assert_eq!(get_consent(), ConsentState::Denied);
let record =
std::fs::read_to_string(tmp.path().join("mxc").join("telemetry-consent.json"))
.unwrap();
assert!(record.contains(r#""source": "withdrawal-recovery""#));
assert!(
!tmp.path()
.join("mxc")
.join("telemetry-consent.withdrawal-pending")
.exists(),
"recovery must clear the stale withdrawal marker"
);
}
#[test]
fn stale_withdrawal_marker_on_denied_record_is_cleared() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
set_consent(false, "cli").unwrap();
platform::begin_withdrawal().unwrap();
age_withdrawal_marker(tmp.path());
let status = get_status();
assert_eq!(status.stored_state, ConsentState::Denied);
assert_eq!(status.effective_state, ConsentState::Denied);
assert_eq!(status.reason, None);
assert!(
!tmp.path()
.join("mxc")
.join("telemetry-consent.withdrawal-pending")
.exists(),
"recovery must eventually clear a leftover withdrawal marker"
);
}
#[test]
fn stale_withdrawal_recovery_is_serialized_with_concurrent_writers() {
let tmp = tempfile::tempdir().unwrap();
let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
env.set_policy_value(3);
set_consent(true, "prompt").unwrap();
platform::begin_withdrawal().unwrap();
age_withdrawal_marker(tmp.path());
std::thread::scope(|scope| {
let (reader, writer) = platform::with_store_lock(|| {
let (reader_started_tx, reader_started_rx) = std::sync::mpsc::channel();
let (writer_started_tx, writer_started_rx) = std::sync::mpsc::channel();
let reader = scope.spawn(move || {
reader_started_tx.send(()).unwrap();
get_status()
});
let writer = scope.spawn(move || {
writer_started_tx.send(()).unwrap();
withdraw_consent().map(|_| ())
});
reader_started_rx.recv().unwrap();
writer_started_rx.recv().unwrap();
assert!(
!reader.is_finished() && !writer.is_finished(),
"recovery and writer must wait for the store lock"
);
Ok((reader, writer))
})
.unwrap();
let reader_status = reader.join().unwrap();
writer.join().unwrap().unwrap();
assert_eq!(reader_status.effective_state, ConsentState::Denied);
assert_eq!(get_consent(), ConsentState::Denied);
assert!(!tmp
.path()
.join("mxc")
.join("telemetry-consent.withdrawal-pending")
.exists());
});
}
#[test]
fn unsupported_schema_grant_is_undetermined() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
let dir = tmp.path().join("mxc");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("telemetry-consent.json"),
r#"{"schemaVersion":999,"consent":"granted"}"#,
)
.unwrap();
assert_eq!(get_consent(), ConsentState::Undetermined);
}
#[test]
fn unsupported_schema_denial_remains_denied() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
let dir = tmp.path().join("mxc");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("telemetry-consent.json"),
r#"{"schemaVersion":999,"consent":"denied"}"#,
)
.unwrap();
let status = get_status();
assert_eq!(status.stored_state, ConsentState::Denied);
assert_eq!(status.effective_state, ConsentState::Denied);
assert_eq!(status.reason, None);
}
#[test]
fn unsupported_grant_schema_reports_a_typed_reason() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
let dir = tmp.path().join("mxc");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("telemetry-consent.json"),
r#"{"schemaVersion":999,"consent":"granted","promptResourceVersion":1,"promptLocale":"en-US"}"#,
)
.unwrap();
let status = get_status();
assert_eq!(status.stored_state, ConsentState::Granted);
assert_eq!(status.effective_state, ConsentState::Undetermined);
assert_eq!(
status.reason,
Some(ConsentStatusReason::ConsentSchemaUnsupported)
);
}
#[test]
fn unsupported_prompt_version_reports_a_typed_reason() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
let dir = tmp.path().join("mxc");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("telemetry-consent.json"),
r#"{"schemaVersion":2,"consent":"granted","promptResourceVersion":999,"promptLocale":"en-US"}"#,
)
.unwrap();
let status = get_status();
assert_eq!(status.stored_state, ConsentState::Granted);
assert_eq!(status.effective_state, ConsentState::Undetermined);
assert_eq!(
status.reason,
Some(ConsentStatusReason::PromptVersionUnsupported)
);
}
#[test]
fn unsupported_prompt_locale_cannot_authorize_collection() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
let dir = tmp.path().join("mxc");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("telemetry-consent.json"),
r#"{"schemaVersion":2,"consent":"granted","promptResourceVersion":1,"promptLocale":"fr-FR"}"#,
)
.unwrap();
let status = get_status();
assert_eq!(status.stored_state, ConsentState::Granted);
assert_eq!(status.effective_state, ConsentState::Undetermined);
assert_eq!(
status.reason,
Some(ConsentStatusReason::PromptVersionUnsupported)
);
}
#[test]
fn write_through_replace_handles_new_and_existing_records() {
let tmp = tempfile::tempdir().unwrap();
let destination = tmp.path().join("telemetry-consent.json");
for contents in ["first", "replacement"] {
let source = tmp.path().join(format!("{contents}.tmp"));
std::fs::write(&source, contents).unwrap();
platform::replace_file_write_through(&source, &destination).unwrap();
assert_eq!(std::fs::read_to_string(&destination).unwrap(), contents);
assert!(!source.exists());
}
}
#[test]
fn concurrent_grant_revoke_never_corrupts_the_store() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
for iteration in 0..10 {
let results: Vec<Result<(), String>> = std::thread::scope(|scope| {
let handles: Vec<_> = (0..16)
.map(|i| scope.spawn(move || set_consent(i % 2 == 0, "cli")))
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
for (writer, result) in results.iter().enumerate() {
assert!(
result.is_ok(),
"iteration {iteration}, concurrent writer {writer} failed: {result:?}"
);
}
let state = get_consent();
assert!(matches!(
state,
ConsentState::Granted | ConsentState::Denied
));
}
}
#[test]
fn legacy_records_preserve_provenance_but_require_reconsent_for_grants() {
for (stored, effective, reason) in [
(
"granted",
ConsentState::Undetermined,
Some(ConsentStatusReason::PromptVersionMissing),
),
("denied", ConsentState::Denied, None),
] {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
let dir = tmp.path().join("mxc");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join("telemetry-consent.json"),
format!(
r#"{{"schemaVersion":1,"consent":"{stored}","source":"prompt","promptedMxcVersion":"0.7.0","updatedAtUtc":"2026-01-02T03:04:05Z"}}"#
),
)
.unwrap();
let status = get_status();
assert_eq!(
status.stored_state,
if stored == "granted" {
ConsentState::Granted
} else {
ConsentState::Denied
}
);
assert_eq!(status.effective_state, effective);
assert_eq!(status.reason, reason);
}
}
#[test]
fn io_retry_retries_transient_errors_then_succeeds() {
use crate::mxc_common::telemetry::consent::platform;
let mut calls = 0;
let result = platform::with_io_retry_for_test(|| {
calls += 1;
if calls < 3 {
Err(platform::transient_io_error_for_test())
} else {
Ok(calls)
}
});
assert_eq!(result.unwrap(), 3);
assert_eq!(calls, 3);
}
#[test]
fn io_retry_gives_up_after_the_attempt_budget() {
use crate::mxc_common::telemetry::consent::platform;
let mut calls = 0;
let result = platform::with_io_retry_for_test(|| {
calls += 1;
Err::<(), _>(platform::transient_io_error_for_test())
});
assert!(result.is_err());
assert_eq!(calls, platform::IO_RETRY_ATTEMPTS_FOR_TEST);
}
#[test]
fn io_retry_does_not_retry_not_found() {
use crate::mxc_common::telemetry::consent::platform;
let mut calls = 0;
let result = platform::with_io_retry_for_test(|| {
calls += 1;
Err::<(), _>(std::io::Error::new(
std::io::ErrorKind::NotFound,
"no consent file",
))
});
assert!(result.is_err());
assert_eq!(calls, 1, "NotFound must not be retried");
}
#[test]
fn missing_local_app_data_resolution_falls_back_to_real_known_folder() {
let resolved =
crate::mxc_common::telemetry::consent::platform::known_folder_local_app_data_for_test();
assert!(
resolved.is_some(),
"known-folder API should resolve a real path"
);
}
#[test]
fn local_app_data_override_reaches_child_processes() {
let tmp = tempfile::tempdir().unwrap();
let _guard = LocalAppDataGuard::set(tmp.path());
let mut command = std::process::Command::new(std::env::current_exe().unwrap());
super::super::test_support::apply_inherited_override(&mut command, tmp.path());
let status = command
.arg("child_process_local_app_data_override_probe")
.arg("--nocapture")
.env("MXC_CHILD_OVERRIDE_PROBE", tmp.path())
.status()
.expect("spawn child test probe");
assert!(status.success(), "child probe failed: {status}");
}
#[test]
fn child_process_local_app_data_override_probe() {
let Some(expected) = std::env::var_os("MXC_CHILD_OVERRIDE_PROBE") else {
return;
};
assert_eq!(
platform::local_app_data_dir_for_test(),
Some(std::path::PathBuf::from(expected))
);
assert_eq!(get_status().reason, Some(ConsentStatusReason::NoRecord));
}
#[test]
fn known_folder_resolution_only_caches_successful_results() {
let cache = std::sync::OnceLock::new();
let mut calls = 0;
assert_eq!(
platform::cache_successful_resolution_for_test(&cache, || {
calls += 1;
None
}),
None
);
assert_eq!(
platform::cache_successful_resolution_for_test(&cache, || {
calls += 1;
Some(std::path::PathBuf::from(r"C:\Users\test\AppData\Local"))
}),
Some(std::path::PathBuf::from(r"C:\Users\test\AppData\Local"))
);
assert_eq!(
platform::cache_successful_resolution_for_test(&cache, || {
calls += 1;
Some(std::path::PathBuf::from(r"C:\Users\test\AppData\Roaming"))
}),
Some(std::path::PathBuf::from(r"C:\Users\test\AppData\Local"))
);
assert_eq!(calls, 2, "a failed lookup must not be cached forever");
}
}
}