Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/windows-lifecycle-handoff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tracedecay": patch
---

Secure Windows update lifecycle handoff without trusting stale owner sidecars, and restore platform-neutral migration and post-update test coverage on Windows.
6 changes: 6 additions & 0 deletions src/daemon/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,9 @@ fn refresh_installed_service_with_state(
spec: &DaemonServiceSpec,
previous_state: Option<DaemonServiceState>,
) -> Result<Option<PathBuf>> {
if !cfg!(any(target_os = "linux", target_os = "macos")) {
return Ok(None);
}
let service_path = service_unit_path()?;
if !service_path.exists() {
return Ok(None);
Expand All @@ -372,6 +375,9 @@ fn refresh_installed_service_with_state(

#[doc(hidden)]
pub fn quiesce_installed_service_under_lease() -> Result<DaemonServiceState> {
if !cfg!(any(target_os = "linux", target_os = "macos")) {
return Ok(DaemonServiceState::Missing);
}
let service_path = service_unit_path()?;
if !service_path.exists() {
if daemon_reachable() {
Expand Down
149 changes: 136 additions & 13 deletions src/lifecycle_lease.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,19 +199,29 @@ fn acquire_exclusive_or_inherited_at(
Ok(()) => own_exclusive(file, path, operation),
Err(error) if is_lock_contended(&error) => {
let owner = read_owner(&mut file, path);
if let Some(token) = inherited.filter(|token| {
owner.as_deref().and_then(|line| line.split('\t').next()) == Some(token.as_str())
}) {
register_process_token(&token);
Ok(LifecycleLease {
hold: LeaseHold::Inherited,
token: Some(token),
lock_path: path.to_path_buf(),
exclusive: true,
})
} else {
#[cfg(windows)]
{
let _ = inherited;
Err(busy_error(operation, owner.as_deref()))
}
#[cfg(not(windows))]
{
if let Some(token) = inherited.filter(|token| {
owner
.as_deref()
.is_some_and(|owner| live_owner_matches(owner, token))
}) {
register_process_token(&token);
Ok(LifecycleLease {
hold: LeaseHold::Inherited,
token: Some(token),
lock_path: path.to_path_buf(),
exclusive: true,
})
} else {
Err(busy_error(operation, owner.as_deref()))
}
}
}
Err(error) => Err(lock_error(path, operation, &error)),
}
Expand Down Expand Up @@ -287,7 +297,14 @@ fn try_acquire_shared_at(path: &Path, operation: &str) -> Result<SharedLeaseAtte

fn own_exclusive(mut file: File, path: &Path, operation: &str) -> Result<LifecycleLease> {
let token = lease_token();
let owner = format!("{token}\t{operation}\t{}\n", std::process::id());
let pid = std::process::id();
#[cfg(not(windows))]
let owner = process_start_time(pid).map_or_else(
|| format!("{token}\t{operation}\t{pid}\n"),
|started_at| format!("{token}\t{operation}\t{pid}\t{started_at}\n"),
);
#[cfg(windows)]
let owner = format!("{token}\t{operation}\t{pid}\n");
file.set_len(0).map_err(|error| owner_write_error(&error))?;
file.seek(SeekFrom::Start(0))
.map_err(|error| owner_write_error(&error))?;
Expand Down Expand Up @@ -329,6 +346,32 @@ fn process_owns_token(token: &str) -> bool {
.any(|candidate| candidate == token)
}

#[cfg(not(windows))]
fn live_owner_matches(owner: &str, inherited_token: &str) -> bool {
let mut fields = owner.split('\t');
if fields.next() != Some(inherited_token) {
return false;
}
let _operation = fields.next();
let Some(pid) = fields.next().and_then(|pid| pid.parse::<u32>().ok()) else {
return false;
};
let Some(live_start_time) = process_start_time(pid) else {
return false;
};
fields
.next()
.is_none_or(|recorded| recorded.parse::<u64>().ok() == Some(live_start_time))
}

#[cfg(not(windows))]
fn process_start_time(pid: u32) -> Option<u64> {
let pid = sysinfo::Pid::from_u32(pid);
let mut system = sysinfo::System::new();
system.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
system.process(pid).map(sysinfo::Process::start_time)
}

fn open_lock_file(path: &Path) -> Result<File> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|error| lock_error(path, "open", &error))?;
Expand Down Expand Up @@ -540,7 +583,12 @@ mod tests {
let parent = acquire_exclusive_at(&path, "update").unwrap();
let token = parent.token().unwrap().to_string();

acquire_exclusive_or_inherited_at(&path, "post-update", Some(token)).unwrap();
let matching = acquire_exclusive_or_inherited_at(&path, "post-update", Some(token));
#[cfg(not(windows))]
matching.unwrap();
#[cfg(windows)]
assert!(matching.unwrap_err().to_string().contains("update"));

let error = acquire_exclusive_or_inherited_at(
&path,
"post-update",
Expand All @@ -550,4 +598,79 @@ mod tests {

assert!(error.to_string().contains("update"));
}

#[test]
fn post_update_child_rejects_a_stale_owner_token_from_a_dead_process() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("lifecycle.lock");
let mut external = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&path)
.unwrap();
fs2::FileExt::try_lock_exclusive(&external).unwrap();
let stale_token = "stale-owner-token";
writeln!(external, "{stale_token}\tupdate\t{}", u32::MAX).unwrap();
external.flush().unwrap();

let error =
acquire_exclusive_or_inherited_at(&path, "post-update", Some(stale_token.to_string()))
.unwrap_err();

assert!(error.to_string().contains("update"));
}

#[test]
fn post_update_child_rejects_a_reused_pid_with_the_wrong_process_start() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("lifecycle.lock");
let mut external = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&path)
.unwrap();
fs2::FileExt::try_lock_exclusive(&external).unwrap();
let stale_token = "stale-owner-token";
writeln!(external, "{stale_token}\tupdate\t{}\t0", std::process::id()).unwrap();
external.flush().unwrap();

let error =
acquire_exclusive_or_inherited_at(&path, "post-update", Some(stale_token.to_string()))
.unwrap_err();

assert!(error.to_string().contains("update"));
}

#[cfg(windows)]
#[test]
fn post_update_child_never_trusts_a_matching_windows_sidecar_token() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("lifecycle.lock");
let mut external = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&path)
.unwrap();
fs2::FileExt::try_lock_exclusive(&external).unwrap();
let token = "matching-live-token";
writeln!(external, "{token}\tupdate\t{}", std::process::id()).unwrap();
external.flush().unwrap();
std::fs::write(
super::owner_sidecar_path(&path),
format!("{token}\tupdate\t{}\n", std::process::id()),
)
.unwrap();

let error =
acquire_exclusive_or_inherited_at(&path, "post-update", Some(token.to_string()))
.unwrap_err();

assert!(error.to_string().contains("update"));
}
}
23 changes: 19 additions & 4 deletions src/migrate/consolidate/files.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::collections::BTreeMap;
use std::fs::{self, File};
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read};
use std::path::{Path, PathBuf};

Expand Down Expand Up @@ -93,19 +93,34 @@ pub(super) fn copy_file_atomic(source: &Path, target: &Path) -> Result<()> {
.ok_or_else(|| config_error("artifact target has no parent"))?;
fs::create_dir_all(parent).map_err(io_error)?;
let temp = target.with_extension(format!("tmp-{}", std::process::id()));
fs::copy(source, &temp).map_err(io_error)?;
File::open(&temp)
.and_then(|file| file.sync_all())
match fs::remove_file(&temp) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(io_error(error)),
}
let mut input = File::open(source).map_err(io_error)?;
let mut output = OpenOptions::new()
.write(true)
.create_new(true)
.open(&temp)
.map_err(io_error)?;
io::copy(&mut input, &mut output).map_err(io_error)?;
fs::set_permissions(&temp, fs::metadata(source).map_err(io_error)?.permissions())
.map_err(io_error)?;
output.sync_all().map_err(io_error)?;
drop(output);
fs::rename(&temp, target).map_err(io_error)?;
sync_parent_directory(parent)?;
Ok(())
}

fn sync_file_and_parent(path: &Path) -> Result<()> {
#[cfg(unix)]
File::open(path)
.and_then(|file| file.sync_all())
.map_err(io_error)?;
#[cfg(not(unix))]
let _ = path;
let parent = path
.parent()
.ok_or_else(|| config_error("artifact target has no parent"))?;
Expand Down
13 changes: 13 additions & 0 deletions src/migrate/consolidate/sqlite/inspect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,19 @@ pub(in crate::migrate::consolidate) async fn extend_graph_identities(
Ok(())
}

#[cfg(all(test, windows))]
pub(in crate::migrate::consolidate) async fn acquire_offline_guards(
paths: &[PathBuf],
) -> Result<OfflineDatabaseGuards> {
// Windows byte-range locks prevent the same process from copying a file
// after BEGIN IMMEDIATE. Production consolidation already fails closed on
// Windows because open-holder discovery is unsupported; unit fixtures use
// isolated stores and exercise the remaining migration semantics here.
let _ = paths;
Ok(OfflineDatabaseGuards { _holds: Vec::new() })
}

#[cfg(not(all(test, windows)))]
pub(in crate::migrate::consolidate) async fn acquire_offline_guards(
paths: &[PathBuf],
) -> Result<OfflineDatabaseGuards> {
Expand Down
Loading
Loading