831 lines
31 KiB
Rust
831 lines
31 KiB
Rust
//! Stable updater ownership of the existing SYSTEM ledger. No CREATE, schema
|
|
//! initialization, replayed activation, replacement ledger or reset is allowed.
|
|
use crate::{
|
|
helper_ipc::{self as ipc, PeerProof, PinnedFile},
|
|
signed_clock::BoundClock,
|
|
update_ipc,
|
|
update_native::{
|
|
Budget, Role,
|
|
files::{self, Location},
|
|
services::Stopped,
|
|
},
|
|
update_original::Original,
|
|
update_state::{AgentStateFile, Bundle, QualifiedRegistry, RetainedSet},
|
|
update_trust::TrustState,
|
|
};
|
|
use anyhow::{Context, Result, ensure};
|
|
use fs2::FileExt;
|
|
use rmm_agent_core::{
|
|
auth::Binding,
|
|
helper_reconcile::ExecutorLedgerGuard,
|
|
reconcile::SyncClock,
|
|
update_handoff::{
|
|
self as core, NativeEffect, NativeEffectStage, NativeFileRole, NativeService, Participant,
|
|
UpdateParticipantGuard,
|
|
},
|
|
};
|
|
use rmm_domain::{
|
|
agent_update::{ParticipantRole, UpdateDelegation},
|
|
jobs::hash,
|
|
};
|
|
use rmm_updater_handoff::{Event, Evidence, Handoff, Phase};
|
|
use rusqlite::{Connection, OpenFlags};
|
|
use std::{cell::RefCell, path::Path, time::Duration};
|
|
const ROOT: &str = r"C:\ProgramData\RustDiscoverySystem\state";
|
|
const LEDGER: &str = r"C:\ProgramData\RustDiscoverySystem\state\ledger.sqlite";
|
|
const LOCK: &str = r"C:\ProgramData\RustDiscoverySystem\state\executor.lock";
|
|
const AGENT_LOCK: &str = r"C:\ProgramData\RustDiscovery\state\agent.lock";
|
|
/// These are the TWO original locks used by the registered helper and agent,
|
|
/// acquired only after their exact original instances have terminated.
|
|
pub struct ClosedFiles {
|
|
root: RefCell<PinnedFile>,
|
|
ledger: RefCell<PinnedFile>,
|
|
executor: RefCell<PinnedFile>,
|
|
agent: RefCell<AgentStateFile>,
|
|
}
|
|
impl ClosedFiles {
|
|
pub fn acquire(bundle: &Bundle, stopped: &Stopped, budget: &Budget<'_>) -> Result<Self> {
|
|
bundle.validate()?;
|
|
stopped.check(budget)?;
|
|
let helper = ipc::service_sid(ipc::HELPER_SERVICE)?;
|
|
let root = PinnedFile::open(
|
|
Path::new(ROOT),
|
|
true,
|
|
&[],
|
|
std::slice::from_ref(&helper),
|
|
true,
|
|
)?;
|
|
let executor = PinnedFile::open(
|
|
Path::new(LOCK),
|
|
false,
|
|
&[],
|
|
std::slice::from_ref(&helper),
|
|
true,
|
|
)?;
|
|
ensure!(
|
|
executor.identity == bundle.ledger.lock,
|
|
"UPDATE_ORIGINAL_LOCK_IDENTITY"
|
|
);
|
|
executor
|
|
.file
|
|
.try_lock_exclusive()
|
|
.context("UPDATE_ORIGINAL_EXECUTOR_BUSY")?;
|
|
let agent = AgentStateFile::lock()?;
|
|
let expected_agent = bundle
|
|
.retained
|
|
.iter()
|
|
.find(|p| p.spec.path == Path::new(AGENT_LOCK))
|
|
.context("UPDATE_ORIGINAL_AGENT_LOCK_REQUIRED")?;
|
|
ensure!(
|
|
agent.identity == expected_agent.spec.identity,
|
|
"UPDATE_ORIGINAL_AGENT_LOCK_IDENTITY"
|
|
);
|
|
agent
|
|
.file
|
|
.try_lock_exclusive()
|
|
.context("UPDATE_ORIGINAL_AGENT_BUSY")?;
|
|
let ledger = PinnedFile::open(Path::new(LEDGER), false, &[], &[helper], true)?;
|
|
ensure!(
|
|
ledger.identity == bundle.ledger.ledger,
|
|
"UPDATE_ORIGINAL_LEDGER_IDENTITY"
|
|
);
|
|
stopped.check(budget)?;
|
|
let value = Self {
|
|
root: RefCell::new(root),
|
|
ledger: RefCell::new(ledger),
|
|
executor: RefCell::new(executor),
|
|
agent: RefCell::new(agent),
|
|
};
|
|
value.verify(bundle, stopped, budget)?;
|
|
Ok(value)
|
|
}
|
|
fn verify(&self, bundle: &Bundle, stopped: &Stopped, budget: &Budget<'_>) -> Result<()> {
|
|
stopped.check(budget)?;
|
|
for file in [&self.root, &self.ledger, &self.executor] {
|
|
file.try_borrow_mut()?.check()?;
|
|
}
|
|
self.agent.try_borrow()?.check()?;
|
|
ensure!(
|
|
self.ledger.try_borrow()?.identity == bundle.ledger.ledger
|
|
&& self.executor.try_borrow()?.identity == bundle.ledger.lock,
|
|
"UPDATE_OWNED_LEDGER_REPLACED"
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|
|
/// Produced by consuming both actually-held original locks after the SQLite
|
|
/// connection has closed; the retained handles continue to pin their names.
|
|
pub struct ReleasedFiles {
|
|
files: ClosedFiles,
|
|
}
|
|
impl ReleasedFiles {
|
|
pub(crate) fn check(&self, bundle: &Bundle) -> Result<()> {
|
|
for file in [&self.files.root, &self.files.ledger, &self.files.executor] {
|
|
file.try_borrow_mut()?.check()?;
|
|
}
|
|
self.files.agent.try_borrow()?.check()?;
|
|
ensure!(
|
|
self.files.ledger.try_borrow()?.identity == bundle.ledger.ledger
|
|
&& self.files.executor.try_borrow()?.identity == bundle.ledger.lock,
|
|
"UPDATE_RELEASED_FILES_CHANGED"
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|
|
impl ClosedFiles {
|
|
pub fn release(
|
|
self,
|
|
bundle: &Bundle,
|
|
stopped: &Stopped,
|
|
budget: &Budget<'_>,
|
|
) -> Result<ReleasedFiles> {
|
|
self.verify(bundle, stopped, budget)?;
|
|
FileExt::unlock(&self.executor.try_borrow()?.file)?;
|
|
FileExt::unlock(&self.agent.try_borrow()?.file)?;
|
|
let result = ReleasedFiles { files: self };
|
|
result.check(bundle)?;
|
|
Ok(result)
|
|
}
|
|
}
|
|
pub struct Inputs<'a, 'b> {
|
|
pub closed: &'a ClosedFiles,
|
|
pub stopped: &'a Stopped,
|
|
pub bundle: &'a Bundle,
|
|
pub bundle_recheck: &'a dyn Fn() -> Result<()>,
|
|
pub original: &'a Original,
|
|
pub binding: &'a Binding,
|
|
pub clock: &'a BoundClock,
|
|
pub budget: &'a Budget<'b>,
|
|
pub updater: &'a RefCell<PeerProof>,
|
|
pub retained: &'a RetainedSet,
|
|
pub registry: &'a QualifiedRegistry,
|
|
pub trust: &'a TrustState,
|
|
}
|
|
pub struct Guard<'a, 'b> {
|
|
input: Inputs<'a, 'b>,
|
|
sqlite: usize,
|
|
return_before: Option<u64>,
|
|
}
|
|
pub struct OwnedLedger<'a, 'b> {
|
|
db: Connection,
|
|
guard: Guard<'a, 'b>,
|
|
}
|
|
impl<'a, 'b> OwnedLedger<'a, 'b> {
|
|
pub fn open(input: Inputs<'a, 'b>) -> Result<Self> {
|
|
input
|
|
.closed
|
|
.verify(input.bundle, input.stopped, input.budget)?;
|
|
ensure!(
|
|
input.bundle.ledger.sha256()? == input.original.handoff().ledger_identity_sha256
|
|
&& input.retained.sha256()? == input.original.handoff().retained_state_sha256,
|
|
"UPDATE_ORIGINAL_STATE_BINDING"
|
|
);
|
|
let db = Connection::open_with_flags(
|
|
LEDGER,
|
|
OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
|
)?;
|
|
db.busy_timeout(Duration::ZERO)?;
|
|
ensure!(
|
|
db.query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))? == "delete"
|
|
&& db.query_row("PRAGMA synchronous", [], |r| r.get::<_, u32>(0))? >= 2,
|
|
"UPDATE_LEDGER_DURABILITY_REQUIRED"
|
|
);
|
|
let sqlite = unsafe { db.handle() } as usize;
|
|
let (count, max): (usize, Option<usize>) = db.query_row(
|
|
"SELECT count(*),max(length(event)) FROM agent_update_handoff_events WHERE grant_id=?1",
|
|
[input.original.permit().grant_id.to_string()],
|
|
|r| Ok((r.get(0)?, r.get(1)?)),
|
|
)?;
|
|
ensure!(
|
|
count <= rmm_updater_handoff::MAX_V2_EVENTS
|
|
&& max.is_none_or(|n| n <= rmm_updater_handoff::MAX_EVENT_BYTES),
|
|
"UPDATE_ORIGINAL_EVENT_LIMIT"
|
|
);
|
|
let mut query = db.prepare(
|
|
"SELECT event FROM agent_update_handoff_events WHERE grant_id=?1 ORDER BY sequence",
|
|
)?;
|
|
let rows = query
|
|
.query_map([input.original.permit().grant_id.to_string()], |r| {
|
|
r.get::<_, Vec<u8>>(0)
|
|
})?
|
|
.collect::<rusqlite::Result<Vec<_>>>()?;
|
|
drop(query);
|
|
let mut return_before = None;
|
|
for raw in rows {
|
|
let event: Event = serde_json::from_slice(&raw)?;
|
|
if matches!(event.evidence, Evidence::LedgerReturnIntent) {
|
|
ensure!(
|
|
return_before.is_none(),
|
|
"UPDATE_MULTIPLE_ORIGINAL_RETURN_EVENTS"
|
|
);
|
|
return_before = Some(
|
|
event
|
|
.observed_at
|
|
.checked_add(180)
|
|
.context("UPDATE_RETURN_DEADLINE_OVERFLOW")?,
|
|
);
|
|
}
|
|
}
|
|
let guard = Guard {
|
|
input,
|
|
sqlite,
|
|
return_before,
|
|
};
|
|
guard.check(&db)?;
|
|
core::read(&db, &guard, guard.input.original.permit().grant_id)?;
|
|
guard
|
|
.input
|
|
.trust
|
|
.qualify_history(&db, &guard, guard.input.binding)?;
|
|
db.execute_batch("PRAGMA foreign_keys=ON")?;
|
|
ensure!(
|
|
db.query_row("PRAGMA foreign_keys", [], |r| r.get::<_, bool>(0))?,
|
|
"UPDATE_LEDGER_FOREIGN_KEYS_REQUIRED"
|
|
);
|
|
rmm_agent_core::ledger::bounded_journal_capacity(&db)?;
|
|
Ok(Self { db, guard })
|
|
}
|
|
pub fn record_stops(
|
|
&mut self,
|
|
observations: crate::update_native::control_fence::StopObservations,
|
|
) -> Result<()> {
|
|
self.guard.effect_window()?;
|
|
ensure!(
|
|
self.guard.input.stopped.proofs() == observations.proofs,
|
|
"UPDATE_STOP_SOURCE_CHANGED"
|
|
);
|
|
for (claim, observed) in observations.claims.iter().zip(&observations.observations) {
|
|
core::observe_native_effect(
|
|
&mut self.db,
|
|
&self.guard,
|
|
claim,
|
|
observed,
|
|
self.guard.input.clock.reading()?.upper,
|
|
)?;
|
|
}
|
|
self.append(Evidence::AllStopped {
|
|
observation_sha256: hash(&serde_json::to_vec(self.guard.input.stopped.proofs())?),
|
|
})?;
|
|
let owner = &self.guard.input.original.delegation().updater;
|
|
self.append(Evidence::UpdaterOwnsLedger {
|
|
process: rmm_updater_handoff::Process {
|
|
pid: owner.pid,
|
|
birth: owner.birth,
|
|
image_sha256: owner.image_sha256.clone(),
|
|
},
|
|
ledger_identity_sha256: self.guard.input.bundle.ledger.sha256()?,
|
|
})
|
|
}
|
|
fn append(&mut self, evidence: Evidence) -> Result<()> {
|
|
let grant = self.guard.input.original.permit().grant_id;
|
|
let journal = core::read(&self.db, &self.guard, grant)?;
|
|
let event = journal.prepare(
|
|
u64::try_from(self.guard.input.clock.reading()?.upper.timestamp())?,
|
|
evidence,
|
|
)?;
|
|
core::append(
|
|
&mut self.db,
|
|
&self.guard,
|
|
grant,
|
|
journal.head_sha256(),
|
|
&event,
|
|
)
|
|
}
|
|
pub fn prepare_return_and_close(
|
|
mut self,
|
|
) -> Result<crate::update_native::control_fence::PreparedStart> {
|
|
self.guard.effect_window()?;
|
|
let grant = self.guard.input.original.permit().grant_id;
|
|
let journal = core::read(&self.db, &self.guard, grant)?;
|
|
ensure!(
|
|
journal.phase() == Phase::PairVerified,
|
|
"UPDATE_VERIFIED_PAIR_REQUIRED"
|
|
);
|
|
let now = self.guard.input.clock.reading()?.upper;
|
|
let event = journal.prepare(
|
|
u64::try_from(now.timestamp())?,
|
|
Evidence::LedgerReturnIntent,
|
|
)?;
|
|
let claims = core::prepare_windows_return_and_starts(
|
|
&mut self.db,
|
|
&self.guard,
|
|
grant,
|
|
journal.head_sha256(),
|
|
&event,
|
|
now,
|
|
)?;
|
|
let proof = core::current_proof(&self.db, &self.guard, grant)?
|
|
.context("UPDATE_RETURN_PREFIX_REQUIRED")?;
|
|
self.close()?;
|
|
Ok(
|
|
crate::update_native::control_fence::PreparedStart::after_closed_connection(
|
|
claims, proof,
|
|
),
|
|
)
|
|
}
|
|
pub fn parts(&mut self) -> (&mut Connection, &Guard<'a, 'b>) {
|
|
(&mut self.db, &self.guard)
|
|
}
|
|
pub fn close(self) -> Result<()> {
|
|
self.guard.check(&self.db)?;
|
|
self.db.close().map_err(|(_, error)| error)?;
|
|
self.guard.input.closed.verify(
|
|
self.guard.input.bundle,
|
|
self.guard.input.stopped,
|
|
self.guard.input.budget,
|
|
)
|
|
}
|
|
}
|
|
impl Guard<'_, '_> {
|
|
fn current(&self) -> Result<()> {
|
|
let i = &self.input;
|
|
(i.bundle_recheck)()?;
|
|
i.closed.verify(i.bundle, i.stopped, i.budget)?;
|
|
Original::verify_retained(
|
|
i.binding,
|
|
i.original.start_bytes(),
|
|
&i.original.handoff().bytes()?,
|
|
i.original.delegation().clone(),
|
|
)?;
|
|
i.trust.recheck_protected()?;
|
|
let updater_pin = crate::update_native::services::updater_pin(i.trust.policy())?;
|
|
let updater_configuration =
|
|
crate::update_native::services::updater_configuration_sha256(&updater_pin)?;
|
|
ensure!(
|
|
updater_configuration == i.trust.policy().updater_service.unit_sha256,
|
|
"UPDATE_UPDATER_CONFIGURATION_CHANGED"
|
|
);
|
|
i.registry
|
|
.verify_observed(i.stopped.proofs(), &updater_configuration)?;
|
|
i.retained.verify()?;
|
|
let mut updater = i.updater.try_borrow_mut()?;
|
|
updater.check()?;
|
|
ensure!(
|
|
update_ipc::participant(&updater, ParticipantRole::WindowsUpdater)?
|
|
== i.original.delegation().updater,
|
|
"UPDATE_ORIGINAL_UPDATER_PROCESS_CHANGED"
|
|
);
|
|
Ok(())
|
|
}
|
|
fn effect_window(&self) -> Result<()> {
|
|
self.current()?;
|
|
let i = &self.input;
|
|
i.original.check_current(i.binding, i.clock, i.budget)?;
|
|
if let Some(until) = self.return_before {
|
|
ensure!(
|
|
u64::try_from(i.clock.reading()?.upper.timestamp())? < until,
|
|
"UPDATE_ORIGINAL_HEALTH_WINDOW_EXPIRED"
|
|
);
|
|
}
|
|
i.trust.recheck_prepared(i.original.update(), i.clock)
|
|
}
|
|
fn same(&self, h: &Handoff, d: &UpdateDelegation) -> Result<()> {
|
|
ensure!(
|
|
h.bytes()? == self.input.original.handoff().bytes()?
|
|
&& d == self.input.original.delegation(),
|
|
"UPDATE_ORIGINAL_OWNER_CHANGED"
|
|
);
|
|
self.current()
|
|
}
|
|
fn file(&self, role: Role, location: Location, candidate: bool) -> Result<()> {
|
|
let bound = self
|
|
.input
|
|
.bundle
|
|
.files
|
|
.iter()
|
|
.find(|v| v.role == role)
|
|
.context("UPDATE_ORIGINAL_ROLE_REQUIRED")?;
|
|
let expected = if candidate {
|
|
&bound.staged
|
|
} else {
|
|
&bound.original
|
|
};
|
|
ensure!(
|
|
files::observe_bound(
|
|
role,
|
|
self.input.original.handoff().owner_nonce,
|
|
location,
|
|
self.input.budget
|
|
)? == *expected,
|
|
"UPDATE_OWNED_FILE_CHANGED"
|
|
);
|
|
Ok(())
|
|
}
|
|
fn pair(&self, candidate: bool) -> Result<()> {
|
|
for f in &self.input.bundle.files {
|
|
self.file(f.role, Location::Target, candidate)?;
|
|
self.file(
|
|
f.role,
|
|
if candidate {
|
|
Location::Previous
|
|
} else {
|
|
Location::Rejected
|
|
},
|
|
!candidate,
|
|
)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
impl ExecutorLedgerGuard for Guard<'_, '_> {
|
|
fn check(&self, db: &Connection) -> Result<()> {
|
|
self.current()?;
|
|
self.input
|
|
.stopped
|
|
.verify_failure_claims(db, self.input.original.handoff())?;
|
|
ensure!(
|
|
unsafe { db.handle() } as usize == self.sqlite && db.path() == Some(LEDGER),
|
|
"UPDATE_OWNED_SQLITE_CONNECTION_CHANGED"
|
|
);
|
|
let start: Vec<u8> = db.query_row(
|
|
"SELECT start FROM execution_evidence WHERE grant_id=?1",
|
|
[self.input.original.permit().grant_id.to_string()],
|
|
|r| r.get(0),
|
|
)?;
|
|
ensure!(
|
|
start == self.input.original.start_bytes(),
|
|
"UPDATE_ORIGINAL_START_CHANGED"
|
|
);
|
|
let other: u64 = db.query_row(
|
|
"SELECT count(*) FROM consumed WHERE result IS NULL AND grant_id<>?1",
|
|
[self.input.original.permit().grant_id.to_string()],
|
|
|r| r.get(0),
|
|
)?;
|
|
ensure!(other == 0, "UPDATE_OTHER_UNRESOLVED_ATTEMPT");
|
|
Ok(())
|
|
}
|
|
fn check_update_owner(
|
|
&self,
|
|
h: &Handoff,
|
|
d: &UpdateDelegation,
|
|
phase: Phase,
|
|
_events: &[Event],
|
|
) -> Result<()> {
|
|
ensure!(
|
|
!matches!(
|
|
phase,
|
|
Phase::HandoffConsumed
|
|
| Phase::ServicesStarted
|
|
| Phase::HealthVerified
|
|
| Phase::RollbackServicesStarted
|
|
| Phase::RollbackHealthVerified
|
|
| Phase::OutcomePersisted
|
|
),
|
|
"UPDATE_STABLE_WRITER_PHASE"
|
|
);
|
|
self.same(h, d)?;
|
|
self.effect_window()
|
|
}
|
|
}
|
|
fn role(r: NativeFileRole) -> Result<Role> {
|
|
Ok(match r {
|
|
NativeFileRole::AgentBinary => Role::Agent,
|
|
NativeFileRole::HelperBinary => Role::Helper,
|
|
NativeFileRole::WindowsSettings => Role::Settings,
|
|
NativeFileRole::WindowsPin => Role::Pin,
|
|
NativeFileRole::WindowsTimeProfile => Role::TimeProfile,
|
|
_ => anyhow::bail!("UPDATE_WINDOWS_FILE_ROLE_REQUIRED"),
|
|
})
|
|
}
|
|
impl UpdateParticipantGuard for Guard<'_, '_> {
|
|
fn participant(&self) -> Participant {
|
|
Participant::StableUpdater
|
|
}
|
|
fn verify_native_effect(
|
|
&self,
|
|
h: &Handoff,
|
|
d: &UpdateDelegation,
|
|
effect: &NativeEffect,
|
|
stage: NativeEffectStage,
|
|
) -> Result<()> {
|
|
self.same(h, d)?;
|
|
self.effect_window()?;
|
|
match (effect, stage) {
|
|
(
|
|
NativeEffect::StartService { .. } | NativeEffect::RollbackStopService { .. },
|
|
NativeEffectStage::ObserveNonstart,
|
|
) => self
|
|
.input
|
|
.stopped
|
|
.failure_observation(h, d, effect, self.input.budget)
|
|
.map(|_| ()),
|
|
(NativeEffect::StopService { service }, NativeEffectStage::Observe) => {
|
|
let expected = match service {
|
|
NativeService::WindowsAgent => super::update_native::Service::Agent,
|
|
NativeService::WindowsHelper => super::update_native::Service::Helper,
|
|
_ => anyhow::bail!("UPDATE_WINDOWS_SERVICE_REQUIRED"),
|
|
};
|
|
ensure!(
|
|
self.input
|
|
.stopped
|
|
.proofs()
|
|
.iter()
|
|
.any(|p| p.configuration.service == expected),
|
|
"UPDATE_STOPPED_ORIGINAL_SERVICE_REQUIRED"
|
|
);
|
|
self.input.stopped.check(self.input.budget)
|
|
}
|
|
(NativeEffect::SavePredecessor { role: r }, NativeEffectStage::Claim) => {
|
|
self.file(role(*r)?, Location::Target, false)?;
|
|
self.file(role(*r)?, Location::Stage, true)
|
|
}
|
|
(NativeEffect::SavePredecessor { role: r }, NativeEffectStage::Observe) => {
|
|
self.file(role(*r)?, Location::Previous, false)
|
|
}
|
|
(NativeEffect::PublishReplacement { role: r }, NativeEffectStage::Claim) => {
|
|
self.file(role(*r)?, Location::Previous, false)?;
|
|
self.file(role(*r)?, Location::Stage, true)
|
|
}
|
|
(NativeEffect::PublishReplacement { role: r }, NativeEffectStage::Observe) => {
|
|
self.file(role(*r)?, Location::Target, true)
|
|
}
|
|
(NativeEffect::SaveRejectedCandidate { role: r }, NativeEffectStage::Claim) => {
|
|
self.file(role(*r)?, Location::Target, true)?;
|
|
self.file(role(*r)?, Location::Previous, false)
|
|
}
|
|
(NativeEffect::SaveRejectedCandidate { role: r }, NativeEffectStage::Observe) => {
|
|
self.file(role(*r)?, Location::Rejected, true)
|
|
}
|
|
(NativeEffect::RestorePredecessor { role: r }, NativeEffectStage::Claim) => {
|
|
self.file(role(*r)?, Location::Previous, false)?;
|
|
self.file(role(*r)?, Location::Rejected, true)
|
|
}
|
|
(NativeEffect::RestorePredecessor { role: r }, NativeEffectStage::Observe) => {
|
|
self.file(role(*r)?, Location::Target, false)
|
|
}
|
|
(NativeEffect::ReturnLedger, NativeEffectStage::Claim) => self.pair(true),
|
|
(NativeEffect::RollbackReturnLedger, NativeEffectStage::Claim) => self.pair(false),
|
|
(
|
|
NativeEffect::StartService {
|
|
service: NativeService::WindowsHelper | NativeService::WindowsAgent,
|
|
},
|
|
NativeEffectStage::ReserveFutureStart,
|
|
) => self.pair(true),
|
|
(
|
|
NativeEffect::RollbackStartService {
|
|
service: NativeService::WindowsHelper | NativeService::WindowsAgent,
|
|
},
|
|
NativeEffectStage::ReserveFutureStart,
|
|
) => self.pair(false),
|
|
_ => anyhow::bail!("UPDATE_WINDOWS_OWNED_EFFECT_NOT_QUALIFIED"),
|
|
}
|
|
}
|
|
fn native_observation_sha256(
|
|
&self,
|
|
h: &Handoff,
|
|
d: &UpdateDelegation,
|
|
effect: &NativeEffect,
|
|
stage: NativeEffectStage,
|
|
) -> Result<String> {
|
|
self.same(h, d)?;
|
|
self.effect_window()?;
|
|
ensure!(
|
|
stage == NativeEffectStage::ObserveNonstart,
|
|
"UPDATE_KNOWN_NONSTART_STAGE_REQUIRED"
|
|
);
|
|
self.input
|
|
.stopped
|
|
.failure_observation(h, d, effect, self.input.budget)
|
|
}
|
|
fn verify_update_event(&self, h: &Handoff, d: &UpdateDelegation, event: &Event) -> Result<()> {
|
|
self.same(h, d)?;
|
|
if matches!(event.evidence, Evidence::Unknown { .. }) {
|
|
return Ok(());
|
|
}
|
|
self.effect_window()?;
|
|
match &event.evidence {
|
|
Evidence::AllStopped { observation_sha256 } => ensure!(
|
|
*observation_sha256 == hash(&serde_json::to_vec(self.input.stopped.proofs())?),
|
|
"UPDATE_STOPPED_OBSERVATION_CHANGED"
|
|
),
|
|
Evidence::UpdaterOwnsLedger {
|
|
process,
|
|
ledger_identity_sha256,
|
|
} => ensure!(
|
|
process.pid == d.updater.pid
|
|
&& process.birth == d.updater.birth
|
|
&& process.image_sha256 == d.updater.image_sha256
|
|
&& *ledger_identity_sha256 == self.input.bundle.ledger.sha256()?,
|
|
"UPDATE_UPDATER_OWNER_OBSERVATION_CHANGED"
|
|
),
|
|
Evidence::ReplaceIntent { role: r } => {
|
|
let r = self
|
|
.input
|
|
.bundle
|
|
.files
|
|
.iter()
|
|
.find(|v| v.role.handoff_role() == *r)
|
|
.context("UPDATE_ORIGINAL_ROLE_REQUIRED")?
|
|
.role;
|
|
self.file(r, Location::Target, false)?;
|
|
self.file(r, Location::Stage, true)?;
|
|
}
|
|
Evidence::Replaced {
|
|
role: r,
|
|
observed_sha256,
|
|
} => {
|
|
let f = self
|
|
.input
|
|
.bundle
|
|
.files
|
|
.iter()
|
|
.find(|v| v.role.handoff_role() == *r)
|
|
.context("UPDATE_ORIGINAL_ROLE_REQUIRED")?;
|
|
ensure!(
|
|
*observed_sha256 == f.staged.sha256,
|
|
"UPDATE_REPLACED_HASH_CHANGED"
|
|
);
|
|
self.file(f.role, Location::Target, true)?;
|
|
self.file(f.role, Location::Previous, false)?;
|
|
}
|
|
Evidence::PairVerified {
|
|
pair,
|
|
retained_state_sha256,
|
|
} => {
|
|
ensure!(
|
|
*pair == h.target && *retained_state_sha256 == self.input.retained.sha256()?,
|
|
"UPDATE_PAIR_OBSERVATION_CHANGED"
|
|
);
|
|
self.pair(true)?;
|
|
}
|
|
Evidence::LedgerReturnIntent => self.pair(true)?,
|
|
Evidence::RollbackIntent {
|
|
cause:
|
|
rmm_updater_handoff::RollbackCause::StartupFailed {
|
|
service: rmm_updater_handoff::Service::WindowsHelper,
|
|
},
|
|
failure_observation_sha256,
|
|
} => {
|
|
let failed = self
|
|
.input
|
|
.stopped
|
|
.failed_start()
|
|
.context("UPDATE_KNOWN_HELPER_FAILURE_REQUIRED")?;
|
|
ensure!(
|
|
*failure_observation_sha256 == failed.sha256()?,
|
|
"UPDATE_ACTUAL_HELPER_FAILURE_CHANGED"
|
|
);
|
|
self.input.stopped.failure_observation(
|
|
h,
|
|
d,
|
|
&NativeEffect::StartService {
|
|
service: NativeService::WindowsHelper,
|
|
},
|
|
self.input.budget,
|
|
)?;
|
|
self.pair(true)?;
|
|
}
|
|
Evidence::RollbackStopped {
|
|
process,
|
|
ledger_identity_sha256,
|
|
observation_sha256,
|
|
} => {
|
|
let failed = self
|
|
.input
|
|
.stopped
|
|
.failed_start()
|
|
.context("UPDATE_KNOWN_HELPER_FAILURE_REQUIRED")?;
|
|
ensure!(
|
|
process.pid == d.updater.pid
|
|
&& process.birth == d.updater.birth
|
|
&& process.image_sha256 == d.updater.image_sha256
|
|
&& *ledger_identity_sha256 == self.input.bundle.ledger.sha256()?
|
|
&& *observation_sha256
|
|
== hash(&serde_json::to_vec(&(failed, self.input.stopped.proofs()))?),
|
|
"UPDATE_ACTUAL_ROLLBACK_STOPPED_CHANGED"
|
|
);
|
|
self.input.stopped.check(self.input.budget)?;
|
|
}
|
|
Evidence::RestoreIntent { role: r }
|
|
| Evidence::CandidatePreserved { role: r, .. }
|
|
| Evidence::PredecessorRestored { role: r, .. } => {
|
|
let bound = self
|
|
.input
|
|
.bundle
|
|
.files
|
|
.iter()
|
|
.find(|f| f.role.handoff_role() == *r)
|
|
.context("UPDATE_ORIGINAL_RESTORE_ROLE_REQUIRED")?;
|
|
match &event.evidence {
|
|
Evidence::RestoreIntent { .. } => {
|
|
self.file(bound.role, Location::Target, true)?;
|
|
self.file(bound.role, Location::Previous, false)?;
|
|
}
|
|
Evidence::CandidatePreserved {
|
|
observation_sha256, ..
|
|
} => {
|
|
self.file(bound.role, Location::Rejected, true)?;
|
|
self.file(bound.role, Location::Previous, false)?;
|
|
ensure!(
|
|
*observation_sha256 == hash(&serde_json::to_vec(&bound.staged)?),
|
|
"UPDATE_ACTUAL_PRESERVED_CANDIDATE_CHANGED"
|
|
);
|
|
}
|
|
Evidence::PredecessorRestored {
|
|
observed_sha256, ..
|
|
} => {
|
|
self.file(bound.role, Location::Target, false)?;
|
|
self.file(bound.role, Location::Rejected, true)?;
|
|
ensure!(
|
|
*observed_sha256 == bound.original.sha256,
|
|
"UPDATE_ACTUAL_RESTORED_PREDECESSOR_CHANGED"
|
|
);
|
|
}
|
|
_ => unreachable!(),
|
|
}
|
|
}
|
|
Evidence::PredecessorVerified {
|
|
pair,
|
|
retained_state_sha256,
|
|
predecessor_record_sha256,
|
|
} => {
|
|
ensure!(
|
|
*pair == h.predecessor
|
|
&& *retained_state_sha256 == self.input.retained.sha256()?
|
|
&& *predecessor_record_sha256 == hash(self.input.trust.installed_raw()),
|
|
"UPDATE_PREDECESSOR_OBSERVATION_CHANGED"
|
|
);
|
|
self.pair(false)?;
|
|
}
|
|
Evidence::RollbackLedgerReturnIntent => self.pair(false)?,
|
|
// Failed-start/rollback events require a retained native failure
|
|
// source; a caller-provided reason or hash is never sufficient.
|
|
_ => anyhow::bail!("UPDATE_WINDOWS_OWNED_EVENT_NOT_QUALIFIED"),
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
impl OwnedLedger<'_, '_> {
|
|
pub fn begin_failed_helper_rollback(&mut self) -> Result<()> {
|
|
self.guard.effect_window()?;
|
|
let failed = self
|
|
.guard
|
|
.input
|
|
.stopped
|
|
.failed_start()
|
|
.context("UPDATE_KNOWN_HELPER_FAILURE_REQUIRED")?;
|
|
ensure!(
|
|
failed.service() == crate::update_native::Service::Helper,
|
|
"UPDATE_HELPER_FAILURE_REQUIRED"
|
|
);
|
|
let grant = self.guard.input.original.permit().grant_id;
|
|
let journal = core::read(&self.db, &self.guard, grant)?;
|
|
core::begin_rollback(
|
|
&mut self.db,
|
|
&self.guard,
|
|
grant,
|
|
journal.head_sha256(),
|
|
&rmm_updater_handoff::RollbackCause::StartupFailed {
|
|
service: rmm_updater_handoff::Service::WindowsHelper,
|
|
},
|
|
&failed.sha256()?,
|
|
self.guard.input.clock.reading()?.upper,
|
|
)?;
|
|
let owner = &self.guard.input.original.delegation().updater;
|
|
self.append(Evidence::RollbackStopped {
|
|
process: rmm_updater_handoff::Process {
|
|
pid: owner.pid,
|
|
birth: owner.birth,
|
|
image_sha256: owner.image_sha256.clone(),
|
|
},
|
|
ledger_identity_sha256: self.guard.input.bundle.ledger.sha256()?,
|
|
observation_sha256: hash(&serde_json::to_vec(&(
|
|
failed,
|
|
self.guard.input.stopped.proofs(),
|
|
))?),
|
|
})
|
|
}
|
|
pub fn prepare_rollback_return_and_close(
|
|
mut self,
|
|
) -> Result<crate::update_native::control_fence::PreparedStart> {
|
|
self.guard.effect_window()?;
|
|
let grant = self.guard.input.original.permit().grant_id;
|
|
let journal = core::read(&self.db, &self.guard, grant)?;
|
|
ensure!(
|
|
journal.phase() == Phase::PredecessorVerified,
|
|
"UPDATE_VERIFIED_PREDECESSOR_REQUIRED"
|
|
);
|
|
let now = self.guard.input.clock.reading()?.upper;
|
|
let event = journal.prepare(
|
|
u64::try_from(now.timestamp())?,
|
|
Evidence::RollbackLedgerReturnIntent,
|
|
)?;
|
|
let claims = core::prepare_windows_rollback_return_and_starts(
|
|
&mut self.db,
|
|
&self.guard,
|
|
grant,
|
|
journal.head_sha256(),
|
|
&event,
|
|
now,
|
|
)?;
|
|
let proof = core::current_proof(&self.db, &self.guard, grant)?
|
|
.context("UPDATE_ROLLBACK_RETURN_PREFIX_REQUIRED")?;
|
|
self.close()?;
|
|
Ok(
|
|
crate::update_native::control_fence::PreparedStart::after_closed_connection(
|
|
claims, proof,
|
|
),
|
|
)
|
|
}
|
|
}
|