Files
rust-discovery/crates/agent-windows/src/update_state.rs
T

728 lines
27 KiB
Rust

//! Original update state witnesses, never key contents or recovery authority.
//! The local retained list and compatible-reader registry are protected files;
//! none of their paths, identities or qualification hashes come from a job.
use crate::{
helper_ipc::{self as ipc, FileIdentity, PinnedFile},
update_native::{Role, files},
update_trust::{Protected, TrustState},
};
use anyhow::{Result, ensure};
use rmm_agent_core::auth::Request;
use rmm_domain::{
agent_update::UpdateDelegation, agent_update_provisioning::ActivationEvidence, jobs::hash,
};
use rmm_updater_handoff::Handoff;
use serde::{Deserialize, Serialize};
use std::{
fs::{File, OpenOptions},
io::Write,
mem::zeroed,
os::windows::{
fs::OpenOptionsExt,
io::{AsRawHandle, FromRawHandle},
},
path::{Path, PathBuf},
ptr,
};
use uuid::Uuid;
use windows_sys::Win32::{Foundation::*, Storage::FileSystem::*};
pub const ROOT: &str = r"C:\ProgramData\RustDiscoveryUpdater";
const RETAINED: &str = r"C:\ProgramData\RustDiscoveryUpdater\retained-files.json";
const ATTEMPTS: &str = r"C:\ProgramData\RustDiscoveryUpdater\attempts";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Retention {
MutableDatabase,
ImmutableMetadata,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Spec {
pub path: PathBuf,
pub identity: FileIdentity,
pub retention: Retention,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Metadata {
pub bytes: u64,
pub created: u64,
pub modified: u64,
pub attributes: u32,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RetainedProof {
pub spec: Spec,
pub security_sha256: String,
pub immutable_metadata: Option<Metadata>,
}
struct Held {
file: File,
parents: Vec<File>,
proof: RetainedProof,
}
fn info(file: &File, dir: bool) -> Result<Metadata> {
let mut v: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
ensure!(
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut v) } != 0
&& v.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0
&& (v.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == dir
&& (dir || v.nNumberOfLinks == 1),
"UPDATE_RETAINED_FILE_TYPE"
);
Ok(Metadata {
bytes: (u64::from(v.nFileSizeHigh) << 32) | u64::from(v.nFileSizeLow),
created: (u64::from(v.ftCreationTime.dwHighDateTime) << 32)
| u64::from(v.ftCreationTime.dwLowDateTime),
modified: (u64::from(v.ftLastWriteTime.dwHighDateTime) << 32)
| u64::from(v.ftLastWriteTime.dwLowDateTime),
attributes: v.dwFileAttributes,
})
}
fn open_meta(path: &Path, dir: bool) -> Result<File> {
// Do not request FILE_READ_DATA, even for the retained private TLS key.
let h = unsafe {
CreateFileW(
ipc::wide(path).as_ptr(),
FILE_READ_ATTRIBUTES | READ_CONTROL,
FILE_SHARE_READ | FILE_SHARE_WRITE,
ptr::null(),
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT | if dir { FILE_FLAG_BACKUP_SEMANTICS } else { 0 },
ptr::null_mut(),
)
};
ensure!(h != INVALID_HANDLE_VALUE, "UPDATE_RETAINED_OPEN");
let file = unsafe { File::from_raw_handle(h) };
info(&file, dir)?;
Ok(file)
}
fn fixed_namespace(path: &Path) -> bool {
path.is_absolute()
&& !path.to_string_lossy().starts_with(r"\\")
&& !path.to_string_lossy().contains("..")
&& [
r"C:\ProgramData\RustDiscovery\state",
r"C:\ProgramData\RustDiscoverySystem\state",
r"C:\ProgramData\RustDiscoverySystem\agent-intents",
]
.iter()
.any(|root| path.starts_with(root))
&& !path.as_os_str().to_string_lossy().contains('\0')
}
fn protected_metadata(file: &File, path: &Path) -> Result<()> {
if path.starts_with(r"C:\ProgramData\RustDiscovery\state") {
crate::native::private_path(path, false)
} else {
let writer = if path.starts_with(r"C:\ProgramData\RustDiscoverySystem\agent-intents") {
crate::SERVICE_NAME
} else {
ipc::HELPER_SERVICE
};
ipc::check_acl(
file.as_raw_handle(),
&[],
&[ipc::service_sid(writer)?],
None,
)
}
}
impl Held {
fn open(spec: Spec) -> Result<Self> {
ensure!(
fixed_namespace(&spec.path),
"UPDATE_RETAINED_FIXED_NAMESPACE"
);
let mut parents = Vec::new();
for parent in spec.path.ancestors().skip(1) {
parents.push(open_meta(parent, true)?);
}
let file = open_meta(&spec.path, false)?;
ensure!(
ipc::file_identity(&file)? == spec.identity,
"UPDATE_RETAINED_FILE_IDENTITY"
);
protected_metadata(&file, &spec.path)?;
let metadata = info(&file, false)?;
let proof = RetainedProof {
security_sha256: files::security_sha256(&file)?,
immutable_metadata: (spec.retention == Retention::ImmutableMetadata)
.then_some(metadata),
spec,
};
let held = Self {
file,
parents,
proof,
};
held.verify()?;
Ok(held)
}
fn verify(&self) -> Result<()> {
for parent in &self.parents {
info(parent, true)?;
}
let named = open_meta(&self.proof.spec.path, false)?;
protected_metadata(&named, &self.proof.spec.path)?;
ensure!(
ipc::file_identity(&named)? == self.proof.spec.identity
&& ipc::file_identity(&self.file)? == self.proof.spec.identity
&& files::security_sha256(&named)? == self.proof.security_sha256
&& self
.proof
.immutable_metadata
.as_ref()
.is_none_or(|v| info(&named, false).is_ok_and(|actual| &actual == v)),
"UPDATE_RETAINED_CHANGED"
);
Ok(())
}
}
/// Held access to the two fixed, LocalService-created agent state files.
/// The agent's existing private ACL contract permits its LocalService file
/// owner; SYSTEM helper policy files continue to use the stricter PinnedFile.
/// This pins names and security, and does not grant an executor/update effect.
pub(crate) struct AgentStateFile {
pub(crate) file: File,
pub(crate) identity: FileIdentity,
held: Held,
}
impl AgentStateFile {
pub(crate) fn journal() -> Result<Self> {
Self::open(
Path::new(r"C:\ProgramData\RustDiscovery\state\telemetry.sqlite"),
false,
)
}
pub(crate) fn lock() -> Result<Self> {
Self::open(
Path::new(r"C:\ProgramData\RustDiscovery\state\agent.lock"),
true,
)
}
fn open(path: &Path, write: bool) -> Result<Self> {
crate::native::private_path(Path::new(r"C:\ProgramData\RustDiscovery\state"), true)?;
let file = OpenOptions::new()
.read(true)
.write(write)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
info(&file, false)?;
let identity = ipc::file_identity(&file)?;
let held = Held::open(Spec {
path: path.into(),
identity,
retention: Retention::MutableDatabase,
})?;
let result = Self {
file,
identity,
held,
};
result.check()?;
Ok(result)
}
pub(crate) fn check(&self) -> Result<()> {
self.held.verify()?;
info(&self.file, false)?;
ensure!(
ipc::file_identity(&self.file)? == self.identity
&& files::security_sha256(&self.file)? == self.held.proof.security_sha256,
"UPDATE_AGENT_STATE_CHANGED"
);
Ok(())
}
}
fn key_paths() -> Result<std::collections::BTreeSet<PathBuf>> {
let mut keys = std::collections::BTreeSet::new();
for entry in std::fs::read_dir(r"C:\ProgramData\RustDiscovery\state")? {
let entry = entry?;
let path = entry.path();
if path.extension().is_some_and(|v| v == "key") {
let name = path
.file_name()
.and_then(|v| v.to_str())
.ok_or_else(|| anyhow::anyhow!("UPDATE_RETAINED_KEY_NAME"))?;
ensure!(
name == "device.key"
|| name
.strip_prefix("device-")
.and_then(|v| v.strip_suffix(".key"))
.is_some_and(|v| Uuid::parse_str(v).is_ok_and(|id| id.to_string() == v)),
"UPDATE_RETAINED_KEY_NAME"
);
ensure!(
keys.len() < 64 && keys.insert(path),
"UPDATE_RETAINED_KEY_LIMIT"
);
}
}
ensure!(!keys.is_empty(), "UPDATE_RETAINED_KEYS_MISSING");
Ok(keys)
}
const MANDATORY: [(&str, Retention); 9] = [
(
r"C:\ProgramData\RustDiscovery\state\telemetry.sqlite",
Retention::MutableDatabase,
),
(
r"C:\ProgramData\RustDiscovery\state\consumption.sqlite",
Retention::MutableDatabase,
),
(
r"C:\ProgramData\RustDiscovery\state\agent.lock",
Retention::ImmutableMetadata,
),
(
r"C:\ProgramData\RustDiscovery\state\identity.json",
Retention::ImmutableMetadata,
),
(
r"C:\ProgramData\RustDiscovery\state\device.key",
Retention::ImmutableMetadata,
),
(
r"C:\ProgramData\RustDiscovery\state\device.pem",
Retention::ImmutableMetadata,
),
(
r"C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite",
Retention::MutableDatabase,
),
(
r"C:\ProgramData\RustDiscoverySystem\state\executor.lock",
Retention::ImmutableMetadata,
),
(
r"C:\ProgramData\RustDiscoverySystem\agent-intents\system-intents.sqlite",
Retention::MutableDatabase,
),
];
pub struct RetainedSet {
config: Protected,
files: Vec<Held>,
proofs: Vec<RetainedProof>,
}
impl RetainedSet {
/// Administrative read-only metadata, not an admitted retained set or lease.
/// The original key data and mutable SQLite contents are never read here.
pub fn bootstrap_metadata() -> Result<Vec<RetainedProof>> {
let mut specs = MANDATORY
.iter()
.map(|(p, r)| (PathBuf::from(p), *r))
.collect::<std::collections::BTreeMap<_, _>>();
for key in key_paths()? {
specs.insert(key, Retention::ImmutableMetadata);
}
ensure!(specs.len() <= 64, "UPDATE_RETAINED_LIMIT");
let mut held = Vec::new();
for (path, retention) in specs {
let file = open_meta(&path, false)?;
held.push(Held::open(Spec {
identity: ipc::file_identity(&file)?,
path,
retention,
})?);
}
for file in &held {
file.verify()?;
}
Ok(held.iter().map(|file| file.proof.clone()).collect())
}
pub fn capture() -> Result<Self> {
let (config, raw) = Protected::read(Path::new(RETAINED), 65536)?;
let specs: Vec<Spec> = serde_json::from_slice(&raw)?;
ensure!(
!specs.is_empty() && specs.len() <= 64,
"UPDATE_RETAINED_LIMIT"
);
let mut files = Vec::new();
for spec in specs {
ensure!(
!files.iter().any(|h: &Held| h.proof.spec.path == spec.path),
"UPDATE_RETAINED_DUPLICATE"
);
files.push(Held::open(spec)?);
}
for (path, retention) in MANDATORY {
ensure!(
files
.iter()
.any(|h| h.proof.spec.path == Path::new(path)
&& h.proof.spec.retention == retention),
"UPDATE_RETAINED_MANDATORY"
);
}
// Read only names/metadata, never another role's SQLite or key data.
// Include EVERY immutable private key namespace member, so the current
// selector cannot name an unretained key; accepted jobs prevent normal
// TLS rotation and verify() rejects an added/removed key meanwhile.
for key in key_paths()? {
ensure!(
files.iter().any(|h| h.proof.spec.path == key
&& h.proof.spec.retention == Retention::ImmutableMetadata),
"UPDATE_RETAINED_TLS_KEYS"
);
}
let proofs = files.iter().map(|h| h.proof.clone()).collect();
let value = Self {
config,
files,
proofs,
};
value.verify()?;
Ok(value)
}
/// Reopen exactly the original public metadata set; no local JSON edit can
/// substitute a new key, journal inode or immutable identity after consume.
pub fn reopen(proofs: &[RetainedProof]) -> Result<Self> {
let result = Self::capture()?;
ensure!(
result.proofs == proofs,
"UPDATE_RETAINED_ORIGINAL_SET_CHANGED"
);
Ok(result)
}
pub fn verify(&self) -> Result<()> {
self.config.verify()?;
for f in &self.files {
f.verify()?;
}
let actual = key_paths()?;
let expected = self
.files
.iter()
.filter(|f| {
f.proof.spec.path.parent() == Some(Path::new(r"C:\ProgramData\RustDiscovery\state"))
&& f.proof.spec.path.extension().is_some_and(|v| v == "key")
})
.map(|f| f.proof.spec.path.clone())
.collect::<std::collections::BTreeSet<_>>();
ensure!(actual == expected, "UPDATE_RETAINED_TLS_NAMESPACE_CHANGED");
Ok(())
}
pub fn proofs(&self) -> &[RetainedProof] {
&self.proofs
}
pub fn sha256(&self) -> Result<String> {
Ok(hash(&serde_json::to_vec(&self.proofs)?))
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BoundFile {
pub role: Role,
pub original: files::Proof,
pub staged: files::Proof,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LedgerIdentity {
pub ledger: FileIdentity,
pub lock: FileIdentity,
}
impl LedgerIdentity {
pub fn sha256(&self) -> Result<String> {
Ok(hash(&serde_json::to_vec(self)?))
}
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Bundle {
pub schema_version: u32,
pub original: Request,
pub handoff_record: Vec<u8>,
pub delegation: UpdateDelegation,
pub files: Vec<BoundFile>,
pub retained: Vec<RetainedProof>,
pub ledger: LedgerIdentity,
/// ORIGINAL retained signed decision and request, not a claimed ready bit.
pub signed_sync_response: Vec<u8>,
pub signed_sync_request: Vec<u8>,
}
impl Bundle {
pub fn validate(&self) -> Result<Handoff> {
ensure!(
self.schema_version == 1 && self.handoff_record.len() <= 65536,
"UPDATE_BUNDLE_SCHEMA"
);
let h: Handoff = serde_json::from_slice(&self.handoff_record)?;
h.validate()?;
ensure!(
h.bytes()? == self.handoff_record
&& h.pin_transition == rmm_updater_handoff::PinTransition::WindowsCodePairClockV1
&& self.delegation.validate()
&& self.delegation.handoff_sha256 == hash(&self.handoff_record)
&& self.delegation.owner_nonce == h.owner_nonce
&& self.delegation.boot_id == h.boot_id
&& hash(&serde_json::to_vec(&self.original)?) == h.attempt.original_request_sha256
&& hash(&serde_json::to_vec(&self.files)?) == h.staged_files_sha256
&& hash(&serde_json::to_vec(&self.retained)?) == h.retained_state_sha256
&& self.ledger.sha256()? == h.ledger_identity_sha256
&& self.files.iter().map(|f| f.role).collect::<Vec<_>>()
== [
Role::Agent,
Role::Helper,
Role::Settings,
Role::Pin,
Role::TimeProfile
]
&& self.signed_sync_response.len() <= 1048576
&& self.signed_sync_request.len() <= 1048576,
"UPDATE_BUNDLE_BINDING"
);
for (f, t) in self.files.iter().zip(&h.files) {
ensure!(
f.role.handoff_role() == t.role
&& f.original.sha256 == t.old_sha256
&& f.staged.sha256 == t.new_sha256,
"UPDATE_BUNDLE_FILE_BINDING"
);
}
Ok(h)
}
pub fn write_before_consume(&self) -> Result<()> {
let h = self.validate()?;
let raw = serde_json::to_vec(self)?;
ensure!(raw.len() <= 3 * 1024 * 1024, "UPDATE_BUNDLE_SIZE");
let mut root = PinnedFile::open(Path::new(ATTEMPTS), true, &[], &[], false)?;
let directory = Path::new(ATTEMPTS).join(h.attempt.grant_id.to_string());
// Inherit only the separately provisioned SYS/Admin private ACL.
// No pre-existing/partial directory is reused or repaired.
std::fs::create_dir(&directory)?;
let mut dir = PinnedFile::open(&directory, true, &[], &[], false)?;
let path = directory.join("bundle.json");
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH)
.open(&path)?;
file.write_all(&raw)?;
file.sync_all()?;
drop(file);
let mut published = PinnedFile::open(&path, false, &[], &[], false)?;
ensure!(
published.sha256()? == hash(&raw),
"UPDATE_BUNDLE_WRITE_CHANGED"
);
published.check()?;
dir.check()?;
root.check()
}
pub fn load(grant: Uuid) -> Result<(Self, impl Fn() -> Result<()>)> {
ensure!(!grant.is_nil(), "UPDATE_BUNDLE_GRANT");
let path = Path::new(ATTEMPTS)
.join(grant.to_string())
.join("bundle.json");
let (file, raw) = Protected::read(&path, 3 * 1024 * 1024)?;
let value: Self = serde_json::from_slice(&raw)?;
let handoff = value.validate()?;
ensure!(
handoff.attempt.grant_id == grant,
"UPDATE_BUNDLE_WRONG_GRANT"
);
Ok((value, move || file.verify()))
}
}
/// Every registered reader is an explicit decoder-compatible baseline service.
/// This protected registry is not a claim of global future process absence.
/// Worker additionally proves all registered original instances have stopped
/// and holds BOTH original executor/journal locks before opening mutable state.
pub const READER_CONTRACT:&[u8]=b"rmm.windows-shared-readers.v2\0agent:existing-agent.lock-before-agent-sqlite-and-held-for-process-lifetime;helper:existing-executor.lock-before-helper-sqlite-and-every-sql-or-effect;all-registered-readers:original-update-handoff-v2-inflight-decoder-compatible;updater:both-original-locks-only-after-registered-instances-stopped;scope:no-global-future-exec-absence-promise\n";
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Reader {
pub service: String,
pub binary_sha256: String,
pub configuration_sha256: String,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct RegistryFile {
schema_version: u32,
profile: String,
bootstrap_receipt_sha256: String,
reader_contract_sha256: String,
readers: Vec<Reader>,
}
pub struct QualifiedRegistry {
file: Protected,
qualification: Protected,
readers: Vec<Reader>,
}
impl QualifiedRegistry {
pub fn load(trust: &TrustState) -> Result<Self> {
let p = trust.policy();
ensure!(
p.schema_version == 2 && p.profile == "windows_code_pair_clock_v1",
"UPDATE_READER_POLICY"
);
let (file, raw) = Protected::read(Path::new(&p.registry_path), 65536)?;
ensure!(
hash(&raw) == p.reader_registry_sha256,
"UPDATE_READER_REGISTRY_HASH"
);
let r: RegistryFile = serde_json::from_slice(&raw)?;
let baseline = p.initial_baseline.decode().map_err(anyhow::Error::msg)?;
let ActivationEvidence::Bootstrap {
qualification_receipt_sha256,
} = baseline.record.activation_evidence
else {
anyhow::bail!("UPDATE_READER_BASELINE_REQUIRED");
};
let initial = baseline
.record
.release_envelope
.decode()
.map_err(anyhow::Error::msg)?;
ensure!(
r.schema_version == 1
&& r.profile == "windows_compatible_readers_v2"
&& r.bootstrap_receipt_sha256 == qualification_receipt_sha256
&& r.reader_contract_sha256 == hash(READER_CONTRACT)
&& r.readers
.iter()
.map(|v| v.service.as_str())
.collect::<Vec<_>>()
== [
crate::SERVICE_NAME,
ipc::HELPER_SERVICE,
crate::update_ipc::SERVICE
]
&& r.readers[0].binary_sha256 == initial.manifest.artifacts[0].sha256
&& r.readers[1].binary_sha256 == initial.manifest.artifacts[1].sha256
&& r.readers[2].binary_sha256 == p.updater_binary_sha256
&& r.readers
.iter()
.all(|v| ipc::digest(&v.binary_sha256) && ipc::digest(&v.configuration_sha256))
&& r.readers[0].configuration_sha256 == p.services[0].unit_sha256
&& r.readers[1].configuration_sha256 == p.services[1].unit_sha256
&& r.readers[2].configuration_sha256 == p.updater_service.unit_sha256,
"UPDATE_READER_REGISTRY_BINDING"
);
let (qualification, qraw) = Protected::read(
Path::new(r"C:\ProgramData\RustDiscoveryUpdater\bootstrap-qualification.json"),
65536,
)?;
ensure!(
hash(&qraw) == qualification_receipt_sha256,
"UPDATE_READER_QUALIFICATION_PIN"
);
// Raw real native evidence is covered by the separately signed baseline
// receipt hash; parsing a label here never creates native qualification.
Ok(Self {
file,
qualification,
readers: r.readers,
})
}
pub fn verify(&self) -> Result<()> {
self.file.verify()?;
self.qualification.verify()
}
pub fn verify_observed(
&self,
pair: &[crate::update_native::services::Proof],
updater_configuration_sha256: &str,
) -> Result<()> {
self.verify()?;
ensure!(pair.len() == 2, "UPDATE_READER_PAIR");
for (proof, reader) in pair.iter().zip(&self.readers) {
ensure!(
proof.configuration.service.name() == reader.service
&& hash(&serde_json::to_vec(&proof.configuration)?)
== reader.configuration_sha256,
"UPDATE_READER_SCM_CONFIGURATION"
);
// For later releases the signed installed record/approved exact
// predecessor supplies current binary pins. This is the original
// compatible reader contract, not a permanent initial image pin.
}
ensure!(
self.readers[2].configuration_sha256 == updater_configuration_sha256,
"UPDATE_READER_STABLE_UPDATER_CONFIGURATION"
);
self.verify()
}
}
/// One-way uncertainty report from the actual original stable worker. It never
/// asserts readiness, missing effects, a new start window or recovery rights.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Uncertain {
schema_version: u32,
grant_id: Uuid,
owner_nonce: Uuid,
handoff_sha256: String,
delegation_sha256: String,
worker: rmm_domain::agent_update::ParticipantIdentity,
}
impl Uncertain {
pub(crate) fn write(
grant: Uuid,
worker: &rmm_domain::agent_update::ParticipantIdentity,
) -> Result<()> {
let (bundle, recheck) = Bundle::load(grant)?;
let h = bundle.validate()?;
ensure!(
&bundle.delegation.updater == worker,
"UPDATE_UNKNOWN_ORIGINAL_WORKER_REQUIRED"
);
let value = Self {
schema_version: 1,
grant_id: grant,
owner_nonce: h.owner_nonce,
handoff_sha256: hash(&h.bytes()?),
delegation_sha256: hash(&serde_json::to_vec(&bundle.delegation)?),
worker: worker.clone(),
};
let raw = serde_json::to_vec(&value)?;
ensure!(raw.len() <= 4096, "UPDATE_UNKNOWN_REPORT_LIMIT");
let directory = Path::new(ATTEMPTS).join(grant.to_string());
let mut root = PinnedFile::open(&directory, true, &[], &[], false)?;
let path = directory.join("uncertain.json");
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH)
.open(&path)?;
ipc::check_acl(file.as_raw_handle(), &[], &[], None)?;
file.write_all(&raw)?;
file.sync_all()?;
drop(file);
let (published, bytes) = Protected::read(&path, 4096)?;
ensure!(bytes == raw, "UPDATE_UNKNOWN_REPORT_WRITE_CHANGED");
published.verify()?;
root.check()?;
recheck()
}
pub(crate) fn read(header: &Handoff, delegation: &UpdateDelegation) -> Result<bool> {
let path = Path::new(ATTEMPTS)
.join(header.attempt.grant_id.to_string())
.join("uncertain.json");
if !path.try_exists()? {
return Ok(false);
}
let (file, raw) = Protected::read(&path, 4096)?;
let value: Self = serde_json::from_slice(&raw)?;
ensure!(
serde_json::to_vec(&value)? == raw
&& value.schema_version == 1
&& value.grant_id == header.attempt.grant_id
&& value.owner_nonce == header.owner_nonce
&& value.handoff_sha256 == hash(&header.bytes()?)
&& value.delegation_sha256 == hash(&serde_json::to_vec(delegation)?)
&& value.worker == delegation.updater,
"UPDATE_UNKNOWN_REPORT_ORIGINAL_CONTEXT_REQUIRED"
);
file.verify()?;
Ok(true)
}
}