1255 lines
49 KiB
Rust
1255 lines
49 KiB
Rust
//! Authenticated local control of the SAME consumed SYSTEM update. IPC bytes
|
|
//! identify an original attempt; actual retained handles supply every proof.
|
|
use crate::{
|
|
helper_ipc::{PeerProof, Pin},
|
|
helper_system::{LedgerGuard, UpdateContext},
|
|
signed_clock::BoundClock,
|
|
update_ipc,
|
|
update_native::{Budget, services::Running},
|
|
update_original::Original,
|
|
update_state::{Bundle, QualifiedRegistry, RetainedSet},
|
|
update_trust::TrustState,
|
|
};
|
|
use anyhow::{Context, Result, ensure};
|
|
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
|
use rmm_agent_core::{
|
|
auth::Binding,
|
|
helper_reconcile::ExecutorLedgerGuard,
|
|
reconcile::SyncClock,
|
|
update_handoff::{
|
|
self as core, NativeControlOperation, NativeControlReply, NativeControlRequest,
|
|
NativeEffect, NativeEffectStage, NativeService, Participant, UpdateParticipantGuard,
|
|
},
|
|
};
|
|
use rmm_domain::{
|
|
agent_update::{ParticipantRole, UpdateDelegation},
|
|
jobs::hash,
|
|
};
|
|
use rmm_updater_handoff::{Event, Evidence, Handoff, Phase, SignedHealth};
|
|
use rusqlite::Connection;
|
|
use std::{cell::RefCell, path::Path, time::Duration};
|
|
use uuid::Uuid;
|
|
pub(crate) struct Guard<'a, 'b> {
|
|
ledger: &'a LedgerGuard,
|
|
binding: &'a Binding,
|
|
clock: &'a BoundClock,
|
|
pin: &'a Pin,
|
|
budget: &'a Budget<'b>,
|
|
original: Original,
|
|
trust: TrustState,
|
|
bundle: Bundle,
|
|
bundle_recheck: Box<dyn Fn() -> Result<()>>,
|
|
retained: RetainedSet,
|
|
registry: QualifiedRegistry,
|
|
running: RefCell<Running>,
|
|
own: RefCell<PeerProof>,
|
|
updater: RefCell<Option<PeerProof>>,
|
|
participant: Participant,
|
|
sqlite: usize,
|
|
verified_health: RefCell<Option<String>>,
|
|
publication: RefCell<Option<crate::update_record::Transition>>,
|
|
code_files: Vec<(
|
|
crate::update_native::files::Proof,
|
|
RefCell<crate::helper_ipc::PinnedFile>,
|
|
)>,
|
|
}
|
|
impl<'a, 'b> Guard<'a, 'b> {
|
|
pub(crate) fn open(
|
|
db: &Connection,
|
|
ledger: &'a LedgerGuard,
|
|
binding: &'a Binding,
|
|
clock: &'a BoundClock,
|
|
pin: &'a Pin,
|
|
budget: &'a Budget<'b>,
|
|
grant: Uuid,
|
|
) -> Result<Self> {
|
|
ledger.check(db)?;
|
|
let journal = core::read(db, ledger, grant)?;
|
|
ensure!(
|
|
!matches!(journal.phase(), Phase::Unknown | Phase::OutcomePersisted),
|
|
"UPDATE_NOT_ACTIVE"
|
|
);
|
|
let (record,start):(Vec<u8>,Vec<u8>)=db.query_row(
|
|
"SELECT h.record,e.start FROM agent_update_handoffs h JOIN execution_evidence e USING(grant_id) WHERE h.grant_id=?1",
|
|
[grant.to_string()],|r|Ok((r.get(0)?,r.get(1)?)))?;
|
|
let original =
|
|
Original::verify_retained(binding, &start, &record, core::read_delegation(db, grant)?)?;
|
|
let trust = TrustState::load_retained(
|
|
original.update(),
|
|
binding,
|
|
original.delegation().prepared_at,
|
|
)?;
|
|
let (bundle, recheck) = Bundle::load(grant)?;
|
|
ensure!(
|
|
bundle.handoff_record == record && bundle.delegation == *original.delegation(),
|
|
"UPDATE_ORIGINAL_BUNDLE_CHANGED"
|
|
);
|
|
ensure!(
|
|
ledger.update_identity(db)?.sha256()? == original.handoff().ledger_identity_sha256,
|
|
"UPDATE_ORIGINAL_LEDGER_IDENTITY"
|
|
);
|
|
let retained = RetainedSet::reopen(&bundle.retained)?;
|
|
let registry = QualifiedRegistry::load(&trust)?;
|
|
let running = Running::observe([pin.agent.clone(), pin.helper.clone()], budget)?;
|
|
let own = PeerProof::for_service(&pin.helper, std::process::id())?;
|
|
let identity = update_ipc::participant(&own, ParticipantRole::WindowsHelper)?;
|
|
let restored = matches!(
|
|
journal.phase(),
|
|
Phase::RollbackLedgerReturnIntent
|
|
| Phase::RollbackServicesStarted
|
|
| Phase::RollbackHealthVerified
|
|
);
|
|
let target = matches!(
|
|
journal.phase(),
|
|
Phase::LedgerReturnIntent | Phase::ServicesStarted | Phase::HealthVerified
|
|
);
|
|
let participant = if identity == original.delegation().original_helper {
|
|
Participant::OriginalHelper
|
|
} else if restored && identity.image_sha256 == original.handoff().predecessor.helper_sha256
|
|
{
|
|
Participant::RestoredHelper
|
|
} else if target && identity.image_sha256 == original.handoff().target.helper_sha256 {
|
|
Participant::NewHelper
|
|
} else {
|
|
Participant::Observer
|
|
};
|
|
// Historical capture must be able to classify owner loss as Unknown;
|
|
// an observer never authorizes an effect or a successful outcome.
|
|
let updater_pin = crate::update_native::services::updater_pin(trust.policy())?;
|
|
let updater = update_ipc::observe(&updater_pin, ParticipantRole::WindowsUpdater)
|
|
.ok()
|
|
.map(|(peer, _)| peer);
|
|
|
|
// Read-sharing without WRITE/DELETE sharing makes the observed code
|
|
// bytes immutable for this real control operation. Later checks retain
|
|
// those exact handles/IDs/security instead of hashing EXEs repeatedly.
|
|
let readers = vec![
|
|
crate::helper_ipc::service_sid(crate::SERVICE_NAME)?,
|
|
crate::helper_ipc::service_sid(crate::helper_ipc::HELPER_SERVICE)?,
|
|
crate::helper_ipc::service_sid(crate::update_ipc::SERVICE)?,
|
|
];
|
|
let mut code_files = vec![];
|
|
for bound in &bundle.files {
|
|
let expected = if participant == Participant::NewHelper {
|
|
&bound.staged
|
|
} else {
|
|
&bound.original
|
|
};
|
|
let path = Path::new(bound.role.target());
|
|
let mut file = crate::helper_ipc::PinnedFile::open(path, false, &readers, &[], false)?;
|
|
let proof =
|
|
crate::update_native::files::proof(&mut file.file, path, bound.role.max_bytes())?;
|
|
ensure!(&proof == expected, "UPDATE_ACTUAL_CODE_PAIR_FILES_CHANGED");
|
|
code_files.push((proof, RefCell::new(file)));
|
|
}
|
|
let result = Self {
|
|
ledger,
|
|
binding,
|
|
clock,
|
|
pin,
|
|
budget,
|
|
original,
|
|
trust,
|
|
bundle,
|
|
bundle_recheck: Box::new(recheck),
|
|
retained,
|
|
registry,
|
|
running: RefCell::new(running),
|
|
own: RefCell::new(own),
|
|
updater: RefCell::new(updater),
|
|
participant,
|
|
sqlite: unsafe { db.handle() } as usize,
|
|
verified_health: RefCell::new(None),
|
|
publication: RefCell::new(None),
|
|
code_files,
|
|
};
|
|
result.check(db)?;
|
|
Ok(result)
|
|
}
|
|
fn current(&self) -> Result<()> {
|
|
(self.bundle_recheck)()?;
|
|
self.budget.check()?;
|
|
if let Some(namespace) = self.publication.try_borrow()?.as_ref() {
|
|
self.trust.recheck_other_protected()?;
|
|
namespace.verify_original(self.trust.installed_raw())?;
|
|
} else {
|
|
self.trust.recheck_protected()?;
|
|
}
|
|
self.registry.verify()?;
|
|
self.retained.verify()?;
|
|
self.running.try_borrow_mut()?.check(self.budget)?;
|
|
let proofs = self.running.try_borrow()?.proofs();
|
|
let pair = if self.participant == Participant::NewHelper {
|
|
&self.original.handoff().target
|
|
} else {
|
|
&self.original.handoff().predecessor
|
|
};
|
|
ensure!(
|
|
proofs[0].process.image_sha256 == pair.agent_sha256
|
|
&& proofs[1].process.image_sha256 == pair.helper_sha256
|
|
&& proofs
|
|
.iter()
|
|
.zip(&self.trust.policy().services)
|
|
.all(|(actual, pin)| serde_json::to_vec(&actual.configuration)
|
|
.is_ok_and(|raw| hash(&raw) == pin.unit_sha256)),
|
|
"UPDATE_ACTUAL_PAIR_CONFIGURATION_CHANGED"
|
|
);
|
|
let updater = crate::update_native::services::updater_pin(self.trust.policy())?;
|
|
ensure!(
|
|
crate::update_native::services::updater_configuration_sha256(&updater)?
|
|
== self.trust.policy().updater_service.unit_sha256,
|
|
"UPDATE_UPDATER_CONFIGURATION_CHANGED"
|
|
);
|
|
self.own.try_borrow_mut()?.check()?;
|
|
for (proof, file) in &self.code_files {
|
|
let mut file = file.try_borrow_mut()?;
|
|
file.check()?;
|
|
ensure!(
|
|
file.identity == proof.identity
|
|
&& file.file.metadata()?.len() == proof.bytes
|
|
&& crate::update_native::files::security_sha256(&file.file)?
|
|
== proof.security_sha256,
|
|
"UPDATE_HELD_CODE_FILES_CHANGED"
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
fn owner_current(&self) -> Result<()> {
|
|
ensure!(
|
|
self.participant != Participant::Observer,
|
|
"UPDATE_ACTUAL_HELPER_GENERATION_REQUIRED"
|
|
);
|
|
let mut owner = self.updater.try_borrow_mut()?;
|
|
let owner = owner
|
|
.as_mut()
|
|
.context("UPDATE_ORIGINAL_UPDATER_UNAVAILABLE")?;
|
|
owner.check()?;
|
|
ensure!(
|
|
update_ipc::participant(owner, ParticipantRole::WindowsUpdater)?
|
|
== self.original.delegation().updater,
|
|
"UPDATE_ORIGINAL_UPDATER_PROCESS_CHANGED"
|
|
);
|
|
Ok(())
|
|
}
|
|
fn effects(&self, db: &Connection) -> Result<()> {
|
|
self.check(db)?;
|
|
self.owner_current()?;
|
|
self.original
|
|
.check_current(self.binding, self.clock, self.budget)?;
|
|
self.trust
|
|
.recheck_crypto(self.original.update(), self.clock)?;
|
|
self.trust.qualify_history(db, self.ledger, self.binding)
|
|
}
|
|
fn same(&self, h: &Handoff, d: &UpdateDelegation) -> Result<()> {
|
|
ensure!(
|
|
h.bytes()? == self.original.handoff().bytes()? && d == self.original.delegation(),
|
|
"UPDATE_ORIGINAL_OWNER_CHANGED"
|
|
);
|
|
self.current()
|
|
}
|
|
fn started(&self) -> Result<(Vec<rmm_updater_handoff::StartedService>, String)> {
|
|
self.current()?;
|
|
let proofs = self.running.try_borrow()?.proofs();
|
|
for (p, b) in proofs.iter().zip([&self.pin.agent, &self.pin.helper]) {
|
|
ensure!(
|
|
p.process.image_sha256 == b.binary_sha256,
|
|
"UPDATE_STARTED_IMAGE_CHANGED"
|
|
);
|
|
}
|
|
Ok((
|
|
proofs.iter().map(|p| p.started()).collect(),
|
|
hash(&serde_json::to_vec(&proofs)?),
|
|
))
|
|
}
|
|
fn verify_health(&self, db: &Connection, signed: &SignedHealth) -> Result<()> {
|
|
self.effects(db)?;
|
|
ensure!(
|
|
matches!(
|
|
self.participant,
|
|
Participant::NewHelper | Participant::RestoredHelper
|
|
),
|
|
"UPDATE_NEW_HELPER_REQUIRED"
|
|
);
|
|
let mut journal = core::read(db, self, self.original.permit().grant_id)?;
|
|
if matches!(
|
|
journal.phase(),
|
|
Phase::ServicesStarted | Phase::RollbackServicesStarted
|
|
) {
|
|
let event = journal.prepare(
|
|
u64::try_from(self.clock.reading()?.upper.timestamp())?,
|
|
if self.participant == Participant::RestoredHelper {
|
|
Evidence::RollbackHealthVerified {
|
|
receipt: signed.clone(),
|
|
}
|
|
} else {
|
|
Evidence::HealthVerified {
|
|
receipt: signed.clone(),
|
|
}
|
|
},
|
|
)?;
|
|
journal.replay(&event)?;
|
|
} else {
|
|
ensure!(
|
|
matches!(
|
|
journal.phase(),
|
|
Phase::HealthVerified | Phase::RollbackHealthVerified
|
|
),
|
|
"UPDATE_HEALTH_PHASE"
|
|
);
|
|
let raw:Vec<u8>=db.query_row("SELECT event FROM agent_update_handoff_events WHERE grant_id=?1 ORDER BY sequence DESC LIMIT 1",
|
|
[self.original.permit().grant_id.to_string()],|r|r.get(0))?;
|
|
let event: Event = serde_json::from_slice(&raw)?;
|
|
ensure!(
|
|
hash(&raw) == journal.head_sha256()
|
|
&& match event.evidence {
|
|
Evidence::HealthVerified { receipt }
|
|
| Evidence::RollbackHealthVerified { receipt } => receipt == *signed,
|
|
_ => false,
|
|
},
|
|
"UPDATE_ORIGINAL_STORED_HEALTH_REQUIRED"
|
|
);
|
|
}
|
|
let receipt: rmm_updater_handoff::HealthReceipt = serde_json::from_slice(&signed.payload)?;
|
|
let (generation,agent,helper):(u64,String,String)=db.query_row(
|
|
"SELECT generation,agent_journal_id,journal_id FROM helper_sync_meta WHERE id=1 AND fault IS NULL",[],
|
|
|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?;
|
|
ensure!(
|
|
generation == receipt.connection_generation
|
|
&& agent == receipt.agent_journal_id.to_string()
|
|
&& helper == receipt.helper_journal_id.to_string()
|
|
&& self.started()?.0 == receipt.service_processes,
|
|
"UPDATE_HEALTH_CURRENT_CHANNEL_OR_PROCESSES"
|
|
);
|
|
rmm_agent_core::update_health_sync::verified_span(
|
|
db,
|
|
self.ledger,
|
|
self.binding,
|
|
self.original.handoff(),
|
|
&receipt,
|
|
self.trust.health_public_key(),
|
|
)?;
|
|
verify_inventory(&self.retained, &self.original, &receipt)?;
|
|
*self.verified_health.try_borrow_mut()? = Some(hash(&serde_json::to_vec(signed)?));
|
|
Ok(())
|
|
}
|
|
}
|
|
impl ExecutorLedgerGuard for Guard<'_, '_> {
|
|
fn check(&self, db: &Connection) -> Result<()> {
|
|
self.ledger.check(db)?;
|
|
self.current()?;
|
|
ensure!(
|
|
unsafe { db.handle() } as usize == self.sqlite,
|
|
"UPDATE_ORIGINAL_SQLITE_HANDLE_CHANGED"
|
|
);
|
|
ensure!(
|
|
self.ledger.update_identity(db)?.sha256()?
|
|
== self.original.handoff().ledger_identity_sha256,
|
|
"UPDATE_ORIGINAL_LEDGER_CHANGED"
|
|
);
|
|
let start: Vec<u8> = db.query_row(
|
|
"SELECT start FROM execution_evidence WHERE grant_id=?1",
|
|
[self.original.permit().grant_id.to_string()],
|
|
|r| r.get(0),
|
|
)?;
|
|
ensure!(
|
|
start == self.original.start_bytes(),
|
|
"UPDATE_ORIGINAL_START_CHANGED"
|
|
);
|
|
Ok(())
|
|
}
|
|
fn check_update_owner(
|
|
&self,
|
|
h: &Handoff,
|
|
d: &UpdateDelegation,
|
|
_phase: Phase,
|
|
_events: &[Event],
|
|
) -> Result<()> {
|
|
self.same(h, d)?;
|
|
self.owner_current()?;
|
|
self.original
|
|
.check_current(self.binding, self.clock, self.budget)?;
|
|
self.trust
|
|
.recheck_crypto(self.original.update(), self.clock)
|
|
}
|
|
}
|
|
impl UpdateParticipantGuard for Guard<'_, '_> {
|
|
fn participant(&self) -> Participant {
|
|
self.participant
|
|
}
|
|
fn verify_native_effect(
|
|
&self,
|
|
h: &Handoff,
|
|
d: &UpdateDelegation,
|
|
effect: &NativeEffect,
|
|
stage: NativeEffectStage,
|
|
) -> Result<()> {
|
|
self.same(h, d)?;
|
|
self.owner_current()?;
|
|
self.original
|
|
.check_current(self.binding, self.clock, self.budget)?;
|
|
self.trust
|
|
.recheck_crypto(self.original.update(), self.clock)?;
|
|
match (effect, stage) {
|
|
(
|
|
NativeEffect::StopService {
|
|
service: NativeService::WindowsAgent | NativeService::WindowsHelper,
|
|
},
|
|
NativeEffectStage::Claim,
|
|
) if self.participant == Participant::OriginalHelper => {
|
|
let proofs = self.running.try_borrow()?.proofs();
|
|
self.registry
|
|
.verify_observed(&proofs, &self.trust.policy().updater_service.unit_sha256)?;
|
|
ensure!(
|
|
proofs[0].process.image_sha256 == h.predecessor.agent_sha256
|
|
&& proofs[1].process.image_sha256 == h.predecessor.helper_sha256,
|
|
"UPDATE_STOP_PREDECESSOR_REQUIRED"
|
|
);
|
|
Ok(())
|
|
}
|
|
(NativeEffect::StartService { service }, NativeEffectStage::Observe)
|
|
if self.participant == Participant::NewHelper =>
|
|
{
|
|
self.verify_started_service(
|
|
*service,
|
|
h.target.agent_sha256.as_str(),
|
|
h.target.helper_sha256.as_str(),
|
|
)
|
|
}
|
|
(NativeEffect::RollbackStartService { service }, NativeEffectStage::Observe)
|
|
if self.participant == Participant::RestoredHelper =>
|
|
{
|
|
self.verify_started_service(
|
|
*service,
|
|
h.predecessor.agent_sha256.as_str(),
|
|
h.predecessor.helper_sha256.as_str(),
|
|
)
|
|
}
|
|
(
|
|
NativeEffect::SaveInstalledRecord { .. }
|
|
| NativeEffect::PublishInstalledRecord { .. },
|
|
NativeEffectStage::Claim | NativeEffectStage::Observe,
|
|
) if self.participant == Participant::NewHelper => self
|
|
.publication
|
|
.try_borrow()?
|
|
.as_ref()
|
|
.context("UPDATE_RECORD_NAMESPACE_REQUIRED")?
|
|
.verify_effect(effect, stage == NativeEffectStage::Observe),
|
|
_ => anyhow::bail!("UPDATE_WINDOWS_HELPER_EFFECT_NOT_QUALIFIED"),
|
|
}
|
|
}
|
|
fn verify_update_event(&self, h: &Handoff, d: &UpdateDelegation, event: &Event) -> Result<()> {
|
|
self.same(h, d)?;
|
|
self.owner_current()?;
|
|
self.original
|
|
.check_current(self.binding, self.clock, self.budget)?;
|
|
self.trust
|
|
.recheck_crypto(self.original.update(), self.clock)?;
|
|
match &event.evidence {
|
|
Evidence::ServicesStarted {
|
|
services,
|
|
ledger_identity_sha256,
|
|
observation_sha256,
|
|
}
|
|
| Evidence::RollbackServicesStarted {
|
|
services,
|
|
ledger_identity_sha256,
|
|
observation_sha256,
|
|
} => {
|
|
let (actual, digest) = self.started()?;
|
|
ensure!(
|
|
*services == actual
|
|
&& *observation_sha256 == digest
|
|
&& *ledger_identity_sha256 == self.bundle.ledger.sha256()?,
|
|
"UPDATE_ACTUAL_STARTS_REQUIRED"
|
|
);
|
|
Ok(())
|
|
}
|
|
Evidence::HealthVerified { receipt } | Evidence::RollbackHealthVerified { receipt } => {
|
|
ensure!(
|
|
self.verified_health.try_borrow()?.as_ref()
|
|
== Some(&hash(&serde_json::to_vec(receipt)?)),
|
|
"UPDATE_ACTUAL_LOCAL_HEALTH_REQUIRED"
|
|
);
|
|
Ok(())
|
|
}
|
|
Evidence::OutcomePersisted { .. } => {
|
|
ensure!(
|
|
self.verified_health.try_borrow()?.is_some(),
|
|
"UPDATE_ACTUAL_HEALTH_REQUIRED"
|
|
);
|
|
self.publication
|
|
.try_borrow()?
|
|
.as_ref()
|
|
.context("UPDATE_RECORD_NAMESPACE_REQUIRED")?
|
|
.published()
|
|
}
|
|
Evidence::RollbackOutcomePersisted { .. } => {
|
|
ensure!(
|
|
self.participant == Participant::RestoredHelper
|
|
&& self.publication.try_borrow()?.is_none()
|
|
&& self.verified_health.try_borrow()?.is_some(),
|
|
"UPDATE_ROLLBACK_NO_RECORD_CHANGE"
|
|
);
|
|
self.trust.recheck_protected()
|
|
}
|
|
_ => anyhow::bail!("UPDATE_WINDOWS_HELPER_EVENT_NOT_QUALIFIED"),
|
|
}
|
|
}
|
|
}
|
|
impl Guard<'_, '_> {
|
|
fn verify_started_service(
|
|
&self,
|
|
service: NativeService,
|
|
agent: &str,
|
|
helper: &str,
|
|
) -> Result<()> {
|
|
let (service, image) = match service {
|
|
NativeService::WindowsAgent => (crate::update_native::Service::Agent, agent),
|
|
NativeService::WindowsHelper => (crate::update_native::Service::Helper, helper),
|
|
_ => anyhow::bail!("UPDATE_WINDOWS_SERVICE_REQUIRED"),
|
|
};
|
|
ensure!(
|
|
self.running
|
|
.try_borrow()?
|
|
.proofs()
|
|
.iter()
|
|
.any(|p| p.configuration.service == service && p.process.image_sha256 == image),
|
|
"UPDATE_ACTUAL_STARTED_SERVICE_REQUIRED"
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|
|
pub(crate) fn handle_updater(
|
|
ctx: UpdateContext<'_>,
|
|
peer: &mut PeerProof,
|
|
request: &NativeControlRequest,
|
|
) -> Result<NativeControlReply> {
|
|
handle(ctx, peer, request, false)
|
|
}
|
|
pub(crate) fn handle_agent_health(
|
|
ctx: UpdateContext<'_>,
|
|
peer: &mut PeerProof,
|
|
request: &NativeControlRequest,
|
|
) -> Result<NativeControlReply> {
|
|
ensure!(
|
|
matches!(request.method, NativeControlOperation::Health { .. }),
|
|
"UPDATE_AGENT_HEALTH_ONLY"
|
|
);
|
|
handle(ctx, peer, request, true)
|
|
}
|
|
fn handle(
|
|
ctx: UpdateContext<'_>,
|
|
peer: &mut PeerProof,
|
|
request: &NativeControlRequest,
|
|
agent_health: bool,
|
|
) -> Result<NativeControlReply> {
|
|
ensure!(
|
|
request.operation == "agent_update_control_v1"
|
|
&& request.schema_version == 1
|
|
&& !request.challenge.is_nil()
|
|
&& request.tenant_id == ctx.binding.tenant_id
|
|
&& request.asset_id == ctx.binding.asset_id
|
|
&& request.agent_id == ctx.binding.agent_id
|
|
&& request.enrollment_generation == ctx.binding.enrollment_generation
|
|
&& request.assignment_version == ctx.binding.assignment_version,
|
|
"UPDATE_CONTROL_BINDING"
|
|
);
|
|
use rmm_agent_core::helper_reconcile::BootSource;
|
|
let budget = Budget::new(ctx.boot, ctx.boot.current_boot()?, Duration::from_secs(5))?;
|
|
let guard = Guard::open(
|
|
ctx.db,
|
|
ctx.guard,
|
|
ctx.binding,
|
|
ctx.clock,
|
|
ctx.pin,
|
|
&budget,
|
|
request.grant_id,
|
|
)?;
|
|
let header = guard.original.handoff();
|
|
ensure!(
|
|
header.owner_nonce == request.owner_nonce
|
|
&& hash(&header.bytes()?) == request.handoff_sha256,
|
|
"UPDATE_CONTROL_ORIGINAL_REQUIRED"
|
|
);
|
|
peer.check()?;
|
|
if agent_health {
|
|
peer.identity()
|
|
.validate(&ctx.pin.agent, peer.identity().pid)?;
|
|
let agent = guard.running.try_borrow()?.proofs()[0].process.clone();
|
|
ensure!(
|
|
peer.identity().pid == agent.pid
|
|
&& peer.identity().creation_ticks == agent.birth
|
|
&& peer.identity().image_sha256 == agent.image_sha256,
|
|
"UPDATE_CURRENT_AGENT_PEER_REQUIRED"
|
|
);
|
|
} else {
|
|
ensure!(
|
|
update_ipc::participant(peer, ParticipantRole::WindowsUpdater)?
|
|
== guard.original.delegation().updater,
|
|
"UPDATE_ORIGINAL_UPDATER_PEER_REQUIRED"
|
|
);
|
|
}
|
|
if !matches!(request.method, NativeControlOperation::ReadOriginal) {
|
|
ensure!(ctx.sync.is_some(), "UPDATE_EXISTING_SYNC_OWNER_REQUIRED");
|
|
let generation: u64 = ctx.db.query_row(
|
|
"SELECT generation FROM helper_sync_meta WHERE id=1 AND fault IS NULL",
|
|
[],
|
|
|r| r.get(0),
|
|
)?;
|
|
ctx.clock.require_generation(generation)?;
|
|
guard.effects(ctx.db)?;
|
|
}
|
|
let mut original_start_base64url = None;
|
|
let mut original_outcome_base64url = None;
|
|
let mut claim = None;
|
|
match &request.method {
|
|
NativeControlOperation::ReadOriginal => {
|
|
original_start_base64url = Some(URL_SAFE_NO_PAD.encode(guard.original.start_bytes()))
|
|
}
|
|
NativeControlOperation::ClaimStop {
|
|
expected_head_sha256,
|
|
service,
|
|
} => {
|
|
claim = Some(core::claim_native_effect(
|
|
ctx.db,
|
|
&guard,
|
|
request.grant_id,
|
|
expected_head_sha256,
|
|
&NativeEffect::StopService { service: *service },
|
|
ctx.clock.reading()?.upper,
|
|
)?);
|
|
}
|
|
NativeControlOperation::ObserveStarts {
|
|
services,
|
|
observation_sha256,
|
|
} => {
|
|
let journal = core::read(ctx.db, &guard, request.grant_id)?;
|
|
ensure!(
|
|
matches!(
|
|
journal.phase(),
|
|
Phase::LedgerReturnIntent | Phase::RollbackLedgerReturnIntent
|
|
),
|
|
"UPDATE_START_PHASE"
|
|
);
|
|
let (actual, digest) = guard.started()?;
|
|
ensure!(
|
|
*services == actual && *observation_sha256 == digest,
|
|
"UPDATE_ACTUAL_STARTS_REQUIRED"
|
|
);
|
|
for service in [NativeService::WindowsHelper, NativeService::WindowsAgent] {
|
|
let effect = if guard.participant == Participant::RestoredHelper {
|
|
NativeEffect::RollbackStartService { service }
|
|
} else {
|
|
NativeEffect::StartService { service }
|
|
};
|
|
let reserved = core::read_native_claim(ctx.db, &guard, request.grant_id, &effect)?;
|
|
let proof = guard
|
|
.running
|
|
.try_borrow()?
|
|
.proofs()
|
|
.into_iter()
|
|
.find(|p| {
|
|
p.configuration.service.handoff_service()
|
|
== match service {
|
|
NativeService::WindowsHelper => {
|
|
rmm_updater_handoff::Service::WindowsHelper
|
|
}
|
|
NativeService::WindowsAgent => {
|
|
rmm_updater_handoff::Service::WindowsAgent
|
|
}
|
|
_ => unreachable!(),
|
|
}
|
|
})
|
|
.context("UPDATE_ACTUAL_START_PROOF_REQUIRED")?;
|
|
core::observe_native_effect(
|
|
ctx.db,
|
|
&guard,
|
|
&reserved,
|
|
&hash(&serde_json::to_vec(&proof)?),
|
|
ctx.clock.reading()?.upper,
|
|
)?;
|
|
}
|
|
let event = journal.prepare(
|
|
u64::try_from(ctx.clock.reading()?.upper.timestamp())?,
|
|
if guard.participant == Participant::RestoredHelper {
|
|
Evidence::RollbackServicesStarted {
|
|
services: actual,
|
|
ledger_identity_sha256: header.ledger_identity_sha256.clone(),
|
|
observation_sha256: digest,
|
|
}
|
|
} else {
|
|
Evidence::ServicesStarted {
|
|
services: actual,
|
|
ledger_identity_sha256: header.ledger_identity_sha256.clone(),
|
|
observation_sha256: digest,
|
|
}
|
|
},
|
|
)?;
|
|
core::append(
|
|
ctx.db,
|
|
&guard,
|
|
request.grant_id,
|
|
journal.head_sha256(),
|
|
&event,
|
|
)?;
|
|
}
|
|
NativeControlOperation::Health { receipt } => {
|
|
guard.verify_health(ctx.db, receipt)?;
|
|
let journal = core::read(ctx.db, &guard, request.grant_id)?;
|
|
let event = journal.prepare(
|
|
u64::try_from(ctx.clock.reading()?.upper.timestamp())?,
|
|
if guard.participant == Participant::RestoredHelper {
|
|
Evidence::RollbackHealthVerified {
|
|
receipt: receipt.clone(),
|
|
}
|
|
} else {
|
|
Evidence::HealthVerified {
|
|
receipt: receipt.clone(),
|
|
}
|
|
},
|
|
)?;
|
|
core::append(
|
|
ctx.db,
|
|
&guard,
|
|
request.grant_id,
|
|
journal.head_sha256(),
|
|
&event,
|
|
)?;
|
|
}
|
|
NativeControlOperation::Finalize => {
|
|
original_outcome_base64url = Some(URL_SAFE_NO_PAD.encode(guard.finalize(ctx.db)?));
|
|
}
|
|
}
|
|
let proof = if original_outcome_base64url.is_none() {
|
|
Some(
|
|
core::current_proof(ctx.db, &guard, request.grant_id)?
|
|
.context("UPDATE_ACTIVE_PROOF_REQUIRED")?,
|
|
)
|
|
} else {
|
|
None
|
|
};
|
|
let pre_stop = if matches!(request.method, NativeControlOperation::ReadOriginal) {
|
|
pre_stop_snapshot(
|
|
ctx.db,
|
|
&guard,
|
|
proof.as_ref().context("UPDATE_ACTIVE_PROOF_REQUIRED")?,
|
|
)?
|
|
} else {
|
|
None
|
|
};
|
|
let (pre_stop_sync_request_base64url, pre_stop_sync_response_base64url) = match pre_stop {
|
|
Some((request, response)) => (
|
|
Some(URL_SAFE_NO_PAD.encode(request)),
|
|
Some(URL_SAFE_NO_PAD.encode(response)),
|
|
),
|
|
None => (None, None),
|
|
};
|
|
Ok(NativeControlReply {
|
|
schema_version: 1,
|
|
challenge: request.challenge,
|
|
tenant_id: ctx.binding.tenant_id,
|
|
asset_id: ctx.binding.asset_id,
|
|
agent_id: ctx.binding.agent_id,
|
|
enrollment_generation: ctx.binding.enrollment_generation,
|
|
assignment_version: ctx.binding.assignment_version,
|
|
grant_id: request.grant_id,
|
|
owner_nonce: request.owner_nonce,
|
|
handoff_sha256: request.handoff_sha256.clone(),
|
|
ready: false,
|
|
proof,
|
|
claim,
|
|
original_start_base64url,
|
|
original_outcome_base64url,
|
|
pre_stop_sync_request_base64url,
|
|
pre_stop_sync_response_base64url,
|
|
})
|
|
}
|
|
|
|
fn verify_inventory(
|
|
retained: &RetainedSet,
|
|
original: &Original,
|
|
receipt: &rmm_updater_handoff::HealthReceipt,
|
|
) -> Result<()> {
|
|
use crate::update_state::Retention;
|
|
use prost::Message;
|
|
use rusqlite::OpenFlags;
|
|
const PATH: &str = r"C:\ProgramData\RustDiscovery\state\telemetry.sqlite";
|
|
ensure!(
|
|
retained
|
|
.proofs()
|
|
.iter()
|
|
.any(|s| s.spec.path == Path::new(PATH)
|
|
&& s.spec.retention == Retention::MutableDatabase),
|
|
"UPDATE_RETAINED_AGENT_JOURNAL_REQUIRED"
|
|
);
|
|
retained.verify()?;
|
|
let journal_pin = crate::update_state::AgentStateFile::journal()?;
|
|
let db = Connection::open_with_flags(
|
|
PATH,
|
|
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
|
)?;
|
|
db.busy_timeout(Duration::ZERO)?;
|
|
// This journal belongs to the unprivileged agent. Bound SQLite's own
|
|
// materialization before querying; a hostile oversized BLOB/view cannot
|
|
// turn a root health check into an unbounded allocation or schema program.
|
|
unsafe {
|
|
rusqlite::ffi::sqlite3_limit(
|
|
db.handle(),
|
|
rusqlite::ffi::SQLITE_LIMIT_LENGTH,
|
|
(rmm_domain::MAX_MESSAGE + 65536) as i32,
|
|
);
|
|
}
|
|
db.execute_batch("PRAGMA trusted_schema=OFF;PRAGMA query_only=ON;")?;
|
|
let tx = db.unchecked_transaction()?;
|
|
let kind: String = tx.query_row(
|
|
"SELECT type FROM sqlite_master WHERE name='update_health_inventory'",
|
|
[],
|
|
|r| r.get(0),
|
|
)?;
|
|
ensure!(kind == "table", "UPDATE_AGENT_RETENTION_MUST_BE_TABLE");
|
|
let length: u64 = tx.query_row(
|
|
"SELECT length(envelope) FROM update_health_inventory WHERE grant_id=?1 AND message_id=?2",
|
|
rusqlite::params![
|
|
original.permit().grant_id.to_string(),
|
|
receipt.inventory_message_id.to_string()
|
|
],
|
|
|r| r.get(0),
|
|
)?;
|
|
ensure!(
|
|
length > 0 && length <= rmm_domain::MAX_MESSAGE as u64,
|
|
"UPDATE_LOCAL_INVENTORY_RAW_LIMIT"
|
|
);
|
|
journal_pin.check()?;
|
|
let envelope = rmm_agent_core::update_health_inventory::read(
|
|
&tx,
|
|
original.permit().grant_id,
|
|
receipt.inventory_message_id,
|
|
)?;
|
|
let marker:(String,String)=tx.query_row("SELECT signed_decision_id,signed_response_sha256 FROM update_health_inventory WHERE grant_id=?1 AND message_id=?2",rusqlite::params![original.permit().grant_id.to_string(),receipt.inventory_message_id.to_string()],|r|Ok((r.get(0)?,r.get(1)?)))?;
|
|
ensure!(
|
|
marker
|
|
== (
|
|
receipt.signed_sync_decision_id.to_string(),
|
|
receipt.signed_sync_response_sha256.clone()
|
|
)
|
|
&& envelope.agent_id == original.handoff().attempt.agent_id.to_string()
|
|
&& envelope.boot_id == original.handoff().boot_id.to_string()
|
|
&& envelope.enrollment_generation == original.handoff().attempt.enrollment_generation
|
|
&& envelope.connection_generation == receipt.connection_generation,
|
|
"UPDATE_LOCAL_INVENTORY_ORIGINAL_BINDING"
|
|
);
|
|
let Some(rmm_protocol::Payload::InventorySnapshot(snapshot)) = &envelope.payload else {
|
|
anyhow::bail!("UPDATE_LOCAL_BASE_INVENTORY_REQUIRED")
|
|
};
|
|
ensure!(
|
|
snapshot.scope == "windows.base"
|
|
&& !snapshot.data.is_empty()
|
|
&& snapshot.sha256 == hex::decode(hash(&snapshot.data))?
|
|
&& envelope.encode_to_vec().len() <= rmm_domain::MAX_MESSAGE,
|
|
"UPDATE_LOCAL_BASE_INVENTORY_HASH"
|
|
);
|
|
rmm_domain::inventory_document::validate_for_scope(
|
|
&snapshot.data,
|
|
chrono::Utc::now(),
|
|
"windows.base",
|
|
)
|
|
.map_err(anyhow::Error::msg)?;
|
|
tx.commit()?;
|
|
journal_pin.check()?;
|
|
retained.verify()
|
|
}
|
|
|
|
/// Read-only selection of the one active ORIGINAL; never creates an attempt.
|
|
pub(crate) fn active_grant(db: &Connection) -> Result<Option<Uuid>> {
|
|
let exists:bool=db.query_row("SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='agent_update_handoffs')",[],|r|r.get(0))?;
|
|
if !exists {
|
|
return Ok(None);
|
|
}
|
|
let mut query=db.prepare("SELECT grant_id FROM agent_update_handoffs WHERE phase NOT IN ('unknown','outcome_persisted') ORDER BY grant_id LIMIT 2")?;
|
|
let rows = query
|
|
.query_map([], |r| r.get::<_, String>(0))?
|
|
.collect::<rusqlite::Result<Vec<_>>>()?;
|
|
ensure!(rows.len() <= 1, "UPDATE_MULTIPLE_ORIGINAL_HANDOFFS");
|
|
rows.first()
|
|
.map(|id| Uuid::parse_str(id).map_err(Into::into))
|
|
.transpose()
|
|
}
|
|
pub(crate) fn server_pin(
|
|
binding: &Binding,
|
|
helper: &crate::helper_ipc::PeerPin,
|
|
) -> Result<Option<update_ipc::Pin>> {
|
|
if !crate::update_admission::configured(binding) {
|
|
return Ok(None);
|
|
}
|
|
let (file, raw) = crate::update_trust::Protected::read(
|
|
Path::new(r"C:\ProgramData\RustDiscoveryUpdater\policy.json"),
|
|
65536,
|
|
)?;
|
|
let (policy, policy_sha256) =
|
|
rmm_domain::agent_update_provisioning::LocalUpdatePolicy::from_bytes(&raw)
|
|
.map_err(anyhow::Error::msg)?;
|
|
ensure!(
|
|
policy.schema_version == 2
|
|
&& policy.tenant_id == binding.tenant_id
|
|
&& policy.asset_id == binding.asset_id
|
|
&& policy.agent_id == binding.agent_id
|
|
&& policy.enrollment_generation == binding.enrollment_generation
|
|
&& policy.assignment_version == binding.assignment_version,
|
|
"UPDATE_CONTROL_PROTECTED_POLICY_BINDING"
|
|
);
|
|
let pin = update_ipc::Pin {
|
|
schema_version: 1,
|
|
binding: binding.clone(),
|
|
policy_sha256,
|
|
helper: helper.clone(),
|
|
updater: crate::update_native::services::updater_pin(&policy)?,
|
|
};
|
|
file.verify()?;
|
|
pin.validate()?;
|
|
Ok(Some(pin))
|
|
}
|
|
fn pre_stop_snapshot(
|
|
db: &Connection,
|
|
guard: &Guard<'_, '_>,
|
|
proof: &rmm_domain::agent_update::UpdateInflightProof,
|
|
) -> Result<Option<(Vec<u8>, Vec<u8>)>> {
|
|
use prost::Message;
|
|
let (_, journal) =
|
|
rmm_domain::agent_update::verify_inflight_proof(proof, guard.trust.health_public_key())
|
|
.map_err(anyhow::Error::msg)?;
|
|
if journal.phase() != Phase::StopIntent {
|
|
return Ok(None);
|
|
}
|
|
let latest: Option<String> = db.query_row(
|
|
"SELECT last_decision FROM helper_sync_meta WHERE id=1 AND fault IS NULL",
|
|
[],
|
|
|r| r.get(0),
|
|
)?;
|
|
let Some(id) = latest else { return Ok(None) };
|
|
let applied:bool=db.query_row("SELECT EXISTS(SELECT 1 FROM agent_update_sync_applied WHERE grant_id=?1 AND decision_id=?2)",
|
|
rusqlite::params![guard.original.permit().grant_id.to_string(),id],|r|r.get(0))?;
|
|
if !applied {
|
|
return Ok(None);
|
|
}
|
|
let round = rmm_agent_core::update_health_sync::read_round(
|
|
db,
|
|
guard.ledger,
|
|
guard.binding,
|
|
guard.original.permit().grant_id,
|
|
id.parse()?,
|
|
)?;
|
|
let (request_len, response_len): (usize, usize) = db.query_row(
|
|
"SELECT length(request),length(response) FROM helper_sync_decisions WHERE decision_id=?1",
|
|
[&id],
|
|
|r| Ok((r.get(0)?, r.get(1)?)),
|
|
)?;
|
|
ensure!(
|
|
request_len <= 512 * 1024 && response_len <= 512 * 1024,
|
|
"UPDATE_PRE_STOP_SYNC_LIMIT"
|
|
);
|
|
let (request, response): (Vec<u8>, Vec<u8>) = db.query_row(
|
|
"SELECT request,response FROM helper_sync_decisions WHERE decision_id=?1",
|
|
[&id],
|
|
|r| Ok((r.get(0)?, r.get(1)?)),
|
|
)?;
|
|
let decoded = rmm_protocol::SyncRequest::decode(request.as_slice())?;
|
|
if decoded.previous_decision_id.is_empty()
|
|
|| decoded.previous_decision_id != decoded.helper_previous_decision_id
|
|
{
|
|
return Ok(None);
|
|
}
|
|
let previous: Uuid = decoded.previous_decision_id.parse()?;
|
|
let prior_applied:bool=db.query_row("SELECT EXISTS(SELECT 1 FROM agent_update_sync_applied WHERE grant_id=?1 AND decision_id=?2)",
|
|
rusqlite::params![guard.original.permit().grant_id.to_string(),previous.to_string()],|r|r.get(0))?;
|
|
if !prior_applied {
|
|
return Ok(None);
|
|
}
|
|
let prior = rmm_agent_core::update_health_sync::read_round(
|
|
db,
|
|
guard.ledger,
|
|
guard.binding,
|
|
guard.original.permit().grant_id,
|
|
previous,
|
|
)?;
|
|
let expected =
|
|
rmm_domain::agent_update::inflight_decision(proof, guard.trust.health_public_key())
|
|
.map_err(anyhow::Error::msg)?;
|
|
for decision in [round.decision(), prior.decision()] {
|
|
ensure!(
|
|
decision
|
|
.attempts
|
|
.iter()
|
|
.any(|a| a.job_id == guard.original.permit().job_id
|
|
&& a.attempt_id == guard.original.permit().attempt_id
|
|
&& a.update_inflight.as_ref() == Some(&expected)
|
|
&& !a.unlock),
|
|
"UPDATE_PRE_STOP_ORIGINAL_ACK_REQUIRED"
|
|
);
|
|
}
|
|
let proof_bytes = proof.bytes().map_err(anyhow::Error::msg)?;
|
|
ensure!(
|
|
decoded
|
|
.attempts
|
|
.iter()
|
|
.any(|a| a.job_id == guard.original.permit().job_id.to_string()
|
|
&& a.attempt_id == guard.original.permit().attempt_id.to_string()
|
|
&& a.update_handoff_bytes == proof_bytes),
|
|
"UPDATE_PRE_STOP_ORIGINAL_REQUEST_REQUIRED"
|
|
);
|
|
guard.check(db)?;
|
|
Ok(Some((request, response)))
|
|
}
|
|
impl Guard<'_, '_> {
|
|
fn finalize(&self, db: &mut Connection) -> Result<Vec<u8>> {
|
|
self.effects(db)?;
|
|
let grant = self.original.permit().grant_id;
|
|
let journal = core::read(db, self, grant)?;
|
|
let raw:Vec<u8>=db.query_row("SELECT event FROM agent_update_handoff_events WHERE grant_id=?1 ORDER BY sequence DESC LIMIT 1",
|
|
[grant.to_string()],|r|r.get(0))?;
|
|
ensure!(
|
|
hash(&raw) == journal.head_sha256(),
|
|
"UPDATE_STORED_HEALTH_HEAD_CHANGED"
|
|
);
|
|
let event: Event = serde_json::from_slice(&raw)?;
|
|
let signed = match &event.evidence {
|
|
Evidence::HealthVerified { receipt } if self.participant == Participant::NewHelper => {
|
|
receipt
|
|
}
|
|
Evidence::RollbackHealthVerified { receipt }
|
|
if self.participant == Participant::RestoredHelper =>
|
|
{
|
|
receipt
|
|
}
|
|
_ => anyhow::bail!("UPDATE_ORIGINAL_STORED_HEALTH_REQUIRED"),
|
|
};
|
|
self.verify_health(db, signed)?;
|
|
let health_sha256 = hash(&serde_json::to_vec(signed)?);
|
|
if self.participant == Participant::RestoredHelper {
|
|
self.trust.recheck_protected()?;
|
|
let outcome = rmm_agent_core::auth::Outcome {
|
|
state: "failed".into(),
|
|
stdout: vec![],
|
|
stderr: vec![],
|
|
exit_code: None,
|
|
output_truncated: false,
|
|
reboot_required: false,
|
|
error_code: "AGENT_UPDATE_RETURNED_TO_PREDECESSOR".into(),
|
|
evidence: serde_json::json!({"postconditions_passed":false,"previous_boot_id":self.original.handoff().boot_id,
|
|
"agent_update":{"schema_version":2,"handoff_sha256":journal.handoff_sha256(),
|
|
"manifest_sha256":self.original.handoff().target.manifest_sha256,
|
|
"predecessor_record_sha256":self.original.handoff().predecessor_record_sha256,
|
|
"installed_record_sha256":self.original.handoff().predecessor_record_sha256,
|
|
"signed_health_sha256":health_sha256,"rolled_back":true}}),
|
|
};
|
|
core::finalize_rollback(
|
|
db,
|
|
self,
|
|
self.original.permit(),
|
|
journal.head_sha256(),
|
|
u64::try_from(self.clock.reading()?.upper.timestamp())?,
|
|
&outcome,
|
|
)?;
|
|
} else {
|
|
let built = crate::update_record::BuiltRecord::build(
|
|
&self.original,
|
|
self.trust.installed_raw(),
|
|
&journal,
|
|
&raw,
|
|
)?;
|
|
let namespace = crate::update_record::Transition::prepare(built)?;
|
|
ensure!(
|
|
self.publication
|
|
.try_borrow_mut()?
|
|
.replace(namespace)
|
|
.is_none(),
|
|
"UPDATE_RECORD_NO_RESUME"
|
|
);
|
|
for index in 0..2 {
|
|
let effect = self
|
|
.publication
|
|
.try_borrow()?
|
|
.as_ref()
|
|
.context("UPDATE_RECORD_NAMESPACE_REQUIRED")?
|
|
.effect()?;
|
|
let claim = core::claim_native_effect(
|
|
db,
|
|
self,
|
|
grant,
|
|
journal.head_sha256(),
|
|
&effect,
|
|
self.clock.reading()?.upper,
|
|
)?;
|
|
if index == 0 {
|
|
let new_sha256 = self
|
|
.publication
|
|
.try_borrow()?
|
|
.as_ref()
|
|
.context("UPDATE_RECORD_NAMESPACE_REQUIRED")?
|
|
.built()
|
|
.sha256()
|
|
.to_owned();
|
|
self.trust.release_installed_pin(&claim, &new_sha256)?;
|
|
}
|
|
self.publication
|
|
.try_borrow_mut()?
|
|
.as_mut()
|
|
.context("UPDATE_RECORD_NAMESPACE_REQUIRED")?
|
|
.apply(&claim)?;
|
|
let observation = self
|
|
.publication
|
|
.try_borrow()?
|
|
.as_ref()
|
|
.context("UPDATE_RECORD_NAMESPACE_REQUIRED")?
|
|
.observation()?;
|
|
core::observe_native_effect(
|
|
db,
|
|
self,
|
|
&claim,
|
|
&observation,
|
|
self.clock.reading()?.upper,
|
|
)?;
|
|
}
|
|
let (record_sha256, floor) = {
|
|
let namespace = self.publication.try_borrow()?;
|
|
let namespace = namespace
|
|
.as_ref()
|
|
.context("UPDATE_RECORD_NAMESPACE_REQUIRED")?;
|
|
namespace.published()?;
|
|
(
|
|
namespace.built().sha256().to_owned(),
|
|
namespace.built().record().activation_floor,
|
|
)
|
|
};
|
|
let outcome = rmm_agent_core::auth::Outcome {
|
|
state: "succeeded".into(),
|
|
stdout: vec![],
|
|
stderr: vec![],
|
|
exit_code: Some(0),
|
|
output_truncated: false,
|
|
reboot_required: false,
|
|
error_code: String::new(),
|
|
evidence: serde_json::json!({"postconditions_passed":true,"previous_boot_id":self.original.handoff().boot_id,
|
|
"agent_update":{"schema_version":2,"handoff_sha256":journal.handoff_sha256(),
|
|
"manifest_sha256":self.original.handoff().target.manifest_sha256,
|
|
"predecessor_record_sha256":self.original.handoff().predecessor_record_sha256,
|
|
"installed_record_sha256":record_sha256,"signed_health_sha256":health_sha256,"activation_floor":floor,"rolled_back":false}}),
|
|
};
|
|
core::finalize(
|
|
db,
|
|
self,
|
|
self.original.permit(),
|
|
journal.head_sha256(),
|
|
u64::try_from(self.clock.reading()?.upper.timestamp())?,
|
|
&outcome,
|
|
)?;
|
|
}
|
|
db.query_row(
|
|
"SELECT outcome FROM execution_evidence WHERE grant_id=?1",
|
|
[grant.to_string()],
|
|
|r| r.get(0),
|
|
)
|
|
.map_err(Into::into)
|
|
}
|
|
}
|
|
/// This guard can persist uncertainty only. It cannot qualify native effects,
|
|
/// success, health, lease, rollback or a replacement original.
|
|
struct UnknownGuard<'a> {
|
|
ledger: &'a LedgerGuard,
|
|
original: Original,
|
|
helper: RefCell<PeerProof>,
|
|
sqlite: usize,
|
|
}
|
|
impl ExecutorLedgerGuard for UnknownGuard<'_> {
|
|
fn check(&self, db: &Connection) -> Result<()> {
|
|
self.ledger.check(db)?;
|
|
self.helper.try_borrow_mut()?.check()?;
|
|
ensure!(
|
|
unsafe { db.handle() } as usize == self.sqlite
|
|
&& self.ledger.update_identity(db)?.sha256()?
|
|
== self.original.handoff().ledger_identity_sha256,
|
|
"UPDATE_UNKNOWN_ORIGINAL_LEDGER_REQUIRED"
|
|
);
|
|
let (record,start):(Vec<u8>,Vec<u8>)=db.query_row(
|
|
"SELECT h.record,e.start FROM agent_update_handoffs h JOIN execution_evidence e USING(grant_id) WHERE h.grant_id=?1",
|
|
[self.original.permit().grant_id.to_string()],|r|Ok((r.get(0)?,r.get(1)?)))?;
|
|
ensure!(
|
|
record == self.original.handoff().bytes()? && start == self.original.start_bytes(),
|
|
"UPDATE_UNKNOWN_ORIGINAL_CHANGED"
|
|
);
|
|
Ok(())
|
|
}
|
|
}
|
|
impl UpdateParticipantGuard for UnknownGuard<'_> {
|
|
fn participant(&self) -> Participant {
|
|
Participant::Observer
|
|
}
|
|
fn verify_update_event(&self, h: &Handoff, d: &UpdateDelegation, event: &Event) -> Result<()> {
|
|
ensure!(
|
|
matches!(event.evidence, Evidence::Unknown { .. })
|
|
&& h.bytes()? == self.original.handoff().bytes()?
|
|
&& d == self.original.delegation()
|
|
&& crate::update_state::Uncertain::read(h, d)?,
|
|
"UPDATE_UNKNOWN_ONLY_ORIGINAL_REPORT"
|
|
);
|
|
self.helper.try_borrow_mut()?.check()
|
|
}
|
|
}
|
|
pub(crate) fn observe_worker_unknown(ctx: UpdateContext<'_>) -> Result<bool> {
|
|
let Some(grant) = active_grant(ctx.db)? else {
|
|
return Ok(false);
|
|
};
|
|
ctx.guard.check(ctx.db)?;
|
|
let (record,start):(Vec<u8>,Vec<u8>)=ctx.db.query_row(
|
|
"SELECT h.record,e.start FROM agent_update_handoffs h JOIN execution_evidence e USING(grant_id) WHERE h.grant_id=?1",
|
|
[grant.to_string()],|r|Ok((r.get(0)?,r.get(1)?)))?;
|
|
let delegation = core::read_delegation(ctx.db, grant)?;
|
|
let header: Handoff = serde_json::from_slice(&record)?;
|
|
if !crate::update_state::Uncertain::read(&header, &delegation)? {
|
|
return Ok(false);
|
|
}
|
|
let original = Original::verify_retained(ctx.binding, &start, &record, delegation)?;
|
|
let helper = PeerProof::for_service(&ctx.pin.helper, std::process::id())?;
|
|
ensure!(
|
|
helper.identity().image_sha256 == header.predecessor.helper_sha256
|
|
|| helper.identity().image_sha256 == header.target.helper_sha256,
|
|
"UPDATE_UNKNOWN_QUALIFIED_HELPER_IMAGE_REQUIRED"
|
|
);
|
|
let guard = UnknownGuard {
|
|
ledger: ctx.guard,
|
|
original,
|
|
helper: RefCell::new(helper),
|
|
sqlite: unsafe { ctx.db.handle() } as usize,
|
|
};
|
|
let journal = core::read(ctx.db, &guard, grant)?;
|
|
// Never rewrite a known outcome, including a successful Finalize whose
|
|
// receipt the worker could not observe. Already persisted bytes win.
|
|
let outcome: Option<Vec<u8>> = ctx.db.query_row(
|
|
"SELECT outcome FROM execution_evidence WHERE grant_id=?1",
|
|
[grant.to_string()],
|
|
|r| r.get(0),
|
|
)?;
|
|
if outcome.is_some() {
|
|
return Ok(false);
|
|
}
|
|
let observed = ctx
|
|
.clock
|
|
.reading()
|
|
.map(|r| r.upper)
|
|
.unwrap_or_else(|_| chrono::Utc::now());
|
|
// When time is unqualified this is only an observed wall timestamp on an
|
|
// Unknown event, never time evidence or permission. Kernel chronology must
|
|
// still accept it; no invented/backdated maximum or new deadline is used.
|
|
core::mark_unknown(
|
|
ctx.db,
|
|
&guard,
|
|
guard.original.permit(),
|
|
journal.head_sha256(),
|
|
u64::try_from(observed.timestamp())?,
|
|
rmm_updater_handoff::UnknownReason::StateChanged,
|
|
)?;
|
|
if let Some(sync) = ctx.sync {
|
|
sync.close();
|
|
}
|
|
Ok(true)
|
|
}
|