Apply reviewed Windows generation 205 closure while preserving original history
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -1308,7 +1308,7 @@ fn ledger_rows(db: &Connection) -> Result<Vec<LedgerRow>> {
|
||||
})?
|
||||
.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
fn ledger_fingerprint(db: &Connection) -> Result<String> {
|
||||
pub(crate) fn ledger_fingerprint(db: &Connection) -> Result<String> {
|
||||
let rows = ledger_rows(db)?;
|
||||
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 {
|
||||
|
||||
@@ -12,3 +12,5 @@ pub mod update_handoff;
|
||||
pub mod update_health_inventory;
|
||||
pub mod update_health_sync;
|
||||
pub mod windows_sync_history;
|
||||
|
||||
pub mod windows_sync_alignment;
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
//! Closed, append-only administrator closure of the explicitly approved G205
|
||||
//! incident. Never calls HelperSync::apply, creates a lease, or touches effects.
|
||||
use crate::{
|
||||
auth::{Binding, HelperIdentity, Request},
|
||||
crypto::{DalekVerifier, Ed25519Verifier},
|
||||
helper_reconcile::{self, SignedResponse, Snapshot},
|
||||
reconcile::{Channel, verify_response_with},
|
||||
};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use chrono::{DateTime, Utc};
|
||||
use prost::Message;
|
||||
use rmm_domain::{
|
||||
checkpoint_repair::{SignedDecision, SignedReceipt, inventory_sha256},
|
||||
jobs::{ExecutionPermitPayload, JobPayload, hash},
|
||||
windows_echo_completion,
|
||||
windows_sync_alignment::{self as dto, Counts, NativeFile, Receipt, Witness},
|
||||
};
|
||||
use rmm_protocol::{Envelope, JobOffer, Payload, SyncRequest, SyncResponse};
|
||||
use rusqlite::{Connection, TransactionBehavior, params, types::ValueRef};
|
||||
use serde_json::{Value, json};
|
||||
use uuid::Uuid;
|
||||
const TABLE: &str = "windows_sync_admin_closed_alignment_205";
|
||||
const DDL: &str = "CREATE TABLE windows_sync_admin_closed_alignment_205(id INTEGER PRIMARY KEY CHECK(id=1),receipt_id TEXT NOT NULL,original_receipt BLOB NOT NULL,witness_sha256 TEXT NOT NULL,actual_applied_at TEXT NOT NULL,ready INTEGER NOT NULL CHECK(ready=0),helper_ready INTEGER NOT NULL CHECK(helper_ready=0),unlock INTEGER NOT NULL CHECK(unlock=0))";
|
||||
pub trait ClosedPairGuard {
|
||||
fn check(&self) -> Result<()>;
|
||||
fn files(&self) -> Result<[NativeFile; 6]>;
|
||||
fn boot(&self) -> Result<Uuid>;
|
||||
}
|
||||
pub struct Local<'a> {
|
||||
pub agent: &'a Connection,
|
||||
pub consumption: &'a Connection,
|
||||
pub helper: &'a Connection,
|
||||
pub intents: &'a Connection,
|
||||
pub binding: &'a Binding,
|
||||
pub helper_binding: &'a Binding,
|
||||
}
|
||||
fn number(db: &Connection, sql: &str) -> Result<u64> {
|
||||
Ok(db.query_row(sql, [], |r| r.get(0))?)
|
||||
}
|
||||
/// Canonical bounded complete logical schema/row inventory. Bytes never leave
|
||||
/// the process; only the digest is published. No executable SQL is read/run.
|
||||
pub fn inventory(db: &Connection, excluded: &[&str]) -> Result<String> {
|
||||
ensure!(
|
||||
db.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))? == "ok",
|
||||
"ALIGN_JOURNAL_INTEGRITY"
|
||||
);
|
||||
let mut q =
|
||||
db.prepare("SELECT type,name,tbl_name,sql FROM sqlite_schema ORDER BY type,name")?;
|
||||
let entries = q
|
||||
.query_map([], |r| {
|
||||
Ok((
|
||||
r.get::<_, String>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, String>(2)?,
|
||||
r.get::<_, Option<String>>(3)?,
|
||||
))
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
let mut doc = vec![];
|
||||
let mut size = 0usize;
|
||||
let mut rows_total = 0usize;
|
||||
for (kind, name, table, sql) in entries {
|
||||
if excluded.contains(&table.as_str()) {
|
||||
continue;
|
||||
}
|
||||
ensure!(
|
||||
matches!(kind.as_str(), "table" | "index" | "trigger")
|
||||
&& !sql
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.to_ascii_uppercase()
|
||||
.contains("VIRTUAL TABLE"),
|
||||
"ALIGN_UNEXPECTED_SCHEMA"
|
||||
);
|
||||
doc.push(json!([kind, name, table, sql]));
|
||||
if kind != "table" {
|
||||
continue;
|
||||
}
|
||||
ensure!(
|
||||
!name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_'),
|
||||
"ALIGN_TABLE_IDENTIFIER"
|
||||
);
|
||||
let mut stmt = db.prepare(&format!("SELECT rowid,* FROM \"{name}\" ORDER BY rowid"))?;
|
||||
let cols = stmt.column_count();
|
||||
let mut rows = stmt.query([])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
rows_total += 1;
|
||||
ensure!(rows_total <= 100000, "ALIGN_ROW_LIMIT");
|
||||
let mut record = vec![];
|
||||
for col in 0..cols {
|
||||
record.push(match row.get_ref(col)? {
|
||||
ValueRef::Null => json!(["null"]),
|
||||
ValueRef::Integer(n) => json!(["integer", n]),
|
||||
ValueRef::Real(n) => json!(["real", n.to_bits().to_string()]),
|
||||
ValueRef::Text(v) => {
|
||||
size += v.len();
|
||||
json!(["text", hex::encode(v)])
|
||||
}
|
||||
ValueRef::Blob(v) => {
|
||||
size += v.len();
|
||||
json!(["blob", hex::encode(v)])
|
||||
}
|
||||
});
|
||||
}
|
||||
ensure!(size <= 64 * 1024 * 1024, "ALIGN_INVENTORY_LIMIT");
|
||||
doc.push(json!([name, record]));
|
||||
}
|
||||
}
|
||||
Ok(inventory_sha256(&Value::Array(doc))?)
|
||||
}
|
||||
fn signed(binding: &Binding, raw: &[u8]) -> Result<SignedReceipt> {
|
||||
ensure!(raw.len() <= 4 * 1024 * 1024, "ALIGN_RECEIPT_SIZE");
|
||||
let r: SignedReceipt = serde_json::from_slice(raw)?;
|
||||
let key = hex::decode(&binding.public_key_hex)?;
|
||||
ensure!(
|
||||
key.len() == 32
|
||||
&& r.signature.len() == 64
|
||||
&& DalekVerifier.verify(&key, &r.payload, &r.signature)?,
|
||||
"ALIGN_RECEIPT_SIGNATURE"
|
||||
);
|
||||
Ok(r)
|
||||
}
|
||||
fn original(
|
||||
local: &Local<'_>,
|
||||
id: Uuid,
|
||||
expected: Uuid,
|
||||
cp: u64,
|
||||
hcp: u64,
|
||||
) -> Result<(Vec<u8>, SignedDecision)> {
|
||||
let (raw, envelope, response): (Vec<u8>, Vec<u8>, Vec<u8>) = local.agent.query_row(
|
||||
"SELECT request,envelope,response FROM reconcile_requests WHERE id=?1 AND generation=205",
|
||||
[id.to_string()],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
raw.len() <= 65536 && response.len() <= 131072 && envelope.len() <= 131072,
|
||||
"ALIGN_ORIGINAL_LIMIT"
|
||||
);
|
||||
let request = SyncRequest::decode(raw.as_slice())?;
|
||||
let env = Envelope::decode(envelope.as_slice())?;
|
||||
let reply = SyncResponse::decode(response.as_slice())?;
|
||||
ensure!(
|
||||
request.encode_to_vec() == raw
|
||||
&& env.encode_to_vec() == envelope
|
||||
&& reply.encode_to_vec() == response
|
||||
&& rmm_protocol::valid_envelope(&env, &local.binding.agent_id.to_string(), 205)
|
||||
&& env.boot_id == dto::BOOT.to_string()
|
||||
&& env.sequence == cp
|
||||
&& env.payload == Some(Payload::SyncRequest(request.clone())),
|
||||
"ALIGN_ORIGINAL_ENVELOPE"
|
||||
);
|
||||
let historical: rmm_domain::reconciliation::ReconcileDecisionPayload =
|
||||
serde_json::from_slice(&reply.decision_bytes)?;
|
||||
for binding in [local.binding, local.helper_binding] {
|
||||
let d = verify_response_with(
|
||||
&DalekVerifier,
|
||||
binding,
|
||||
&request,
|
||||
&Channel {
|
||||
connection_generation: 205,
|
||||
boot_id: dto::BOOT,
|
||||
},
|
||||
&reply,
|
||||
historical.issued_at,
|
||||
)?;
|
||||
ensure!(
|
||||
d.decision_id == expected
|
||||
&& d.request_id == id
|
||||
&& d.checkpoint == cp
|
||||
&& d.helper_checkpoint == hcp
|
||||
&& request.checkpoint == cp
|
||||
&& request.helper_checkpoint == hcp
|
||||
&& request.journal_complete
|
||||
&& request.assignment_version == 1,
|
||||
"ALIGN_ORIGINAL_BINDING"
|
||||
);
|
||||
}
|
||||
let consumed: Vec<u8> = local
|
||||
.consumption
|
||||
.query_row(
|
||||
"SELECT response FROM reconcile_consumption WHERE decision_id=?1",
|
||||
[expected.to_string()],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.context("ALIGN_ORIGINAL_CONSUMPTION_REPLY_ROW")?;
|
||||
ensure!(consumed == response, "ALIGN_CONSUMPTION_ORIGINAL_REPLY");
|
||||
let captured: Vec<u8> = local
|
||||
.helper
|
||||
.query_row(
|
||||
"SELECT snapshot FROM helper_sync_captures WHERE checkpoint=?1",
|
||||
[hcp],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.context("ALIGN_ORIGINAL_HELPER_CAPTURE_ROW")?;
|
||||
let capture: Snapshot = serde_json::from_slice(&captured)?;
|
||||
let current_helper: String = local.helper.query_row(
|
||||
"SELECT journal_id FROM helper_sync_meta WHERE id=1",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let current_agent: String = local.agent.query_row(
|
||||
"SELECT journal_id FROM reconcile_meta WHERE id=1",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(
|
||||
request.helper_journal_id == current_helper
|
||||
&& request.journal_id == current_agent
|
||||
&& capture.journal_id.to_string() == current_helper,
|
||||
"ALIGN_ORIGINAL_JOURNAL_IDENTITIES"
|
||||
);
|
||||
ensure!(
|
||||
capture.checkpoint == hcp
|
||||
&& capture.boot_id == dto::BOOT
|
||||
&& capture.captured_at <= historical.issued_at
|
||||
&& capture.attempts.is_empty()
|
||||
&& capture
|
||||
.previous_decision_id
|
||||
.map(|v| v.to_string())
|
||||
.unwrap_or_default()
|
||||
== request.helper_previous_decision_id,
|
||||
"ALIGN_ORIGINAL_HELPER_CAPTURE"
|
||||
);
|
||||
ensure!(
|
||||
[dto::ECHO_JOB, dto::EXPIRED_JOB].iter().all(|id| request
|
||||
.attempts
|
||||
.iter()
|
||||
.filter(|a| a.job_id == id.to_string())
|
||||
.count()
|
||||
== 1),
|
||||
"ALIGN_EXACT_ATTEMPT_SET"
|
||||
);
|
||||
ensure!(
|
||||
request.attempts.len() == 2
|
||||
&& request
|
||||
.attempts
|
||||
.iter()
|
||||
.all(|a| (a.job_id == dto::ECHO_JOB.to_string()
|
||||
&& a.attempt_id == dto::ECHO_ATTEMPT.to_string()
|
||||
&& a.state == "succeeded"
|
||||
&& a.consumption == "consumed")
|
||||
|| (a.job_id == dto::EXPIRED_JOB.to_string()
|
||||
&& a.attempt_id == dto::EXPIRED_ATTEMPT.to_string()
|
||||
&& a.grant_id.is_empty()
|
||||
&& a.consumption == "unconsumed"
|
||||
&& a.outcome_bytes.is_empty())),
|
||||
"ALIGN_ONLY_ORIGINAL_JOB_HISTORY"
|
||||
);
|
||||
Ok((
|
||||
raw,
|
||||
SignedDecision {
|
||||
decision_bytes: reply.decision_bytes,
|
||||
signature: reply.signature,
|
||||
},
|
||||
))
|
||||
}
|
||||
pub fn witness(local: &Local<'_>, guard: &impl ClosedPairGuard) -> Result<Witness> {
|
||||
guard.check()?;
|
||||
ensure!(guard.boot()? == dto::BOOT, "ALIGN_BOOT");
|
||||
let binding_sha256 = hash(&serde_json::to_vec(local.binding)?);
|
||||
let helper_binding_sha256 = hash(&serde_json::to_vec(local.helper_binding)?);
|
||||
ensure!(
|
||||
binding_sha256 == helper_binding_sha256,
|
||||
"ALIGN_INDEPENDENT_DEVICE_IDENTITY"
|
||||
);
|
||||
let(agent_journal,helper_journal,hcp):(String,String,u64)=local.agent.query_row("SELECT journal_id,helper_id,helper_checkpoint FROM reconcile_meta WHERE id=1 AND generation=205 AND checkpoint=10137 AND last_decision=?1 AND pending_request IS NULL AND fault IS NULL",[dto::SECOND.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?;
|
||||
ensure!(hcp == 135, "ALIGN_AGENT_HELPER_REFERENCE");
|
||||
let helper_cp:u64=local.helper.query_row("SELECT checkpoint FROM helper_sync_meta WHERE id=1 AND generation=205 AND journal_id=?1 AND last_decision=?2 AND agent_journal_id=?3 AND agent_checkpoint=10135 AND fault IS NULL",params![helper_journal,dto::FIRST.to_string(),agent_journal],|r|r.get(0))?;
|
||||
ensure!(
|
||||
number(
|
||||
local.intents,
|
||||
"SELECT (SELECT count(*) FROM system_intents)+(SELECT count(*) FROM system_intent_mirrors)+(SELECT count(*) FROM system_intent_denial_resumes)"
|
||||
)? == 0,
|
||||
"ALIGN_NO_SYSTEM_DELEGATION_HISTORY"
|
||||
);
|
||||
let counts = Counts {
|
||||
agent_jobs: number(local.agent, "SELECT count(*) FROM job_attempts")?,
|
||||
agent_consumed: number(local.consumption, "SELECT count(*) FROM consumed")?,
|
||||
agent_starts: number(local.consumption, "SELECT count(*) FROM execution_evidence")?,
|
||||
agent_outcomes: number(
|
||||
local.consumption,
|
||||
"SELECT count(*) FROM execution_evidence WHERE outcome IS NOT NULL",
|
||||
)?,
|
||||
helper_consumed: number(local.helper, "SELECT count(*) FROM consumed")?,
|
||||
helper_starts: number(local.helper, "SELECT count(*) FROM execution_evidence")?,
|
||||
helper_outcomes: number(
|
||||
local.helper,
|
||||
"SELECT count(*) FROM execution_evidence WHERE outcome IS NOT NULL",
|
||||
)?,
|
||||
system_intents: number(local.intents, "SELECT count(*) FROM system_intents")?,
|
||||
};
|
||||
let (first_req, first) = original(local, dto::FIRST_REQUEST, dto::FIRST, 10135, 134)
|
||||
.context("ALIGN_FIRST_ORIGINAL")?;
|
||||
let (second_req, second) = original(local, dto::SECOND_REQUEST, dto::SECOND, 10137, 135)
|
||||
.context("ALIGN_SECOND_ORIGINAL")?;
|
||||
let second_request = SyncRequest::decode(second_req.as_slice())?;
|
||||
ensure!(
|
||||
second_request.previous_decision_id == dto::FIRST.to_string()
|
||||
&& second_request.helper_previous_decision_id == dto::FIRST.to_string(),
|
||||
"ALIGN_EXACT_PREDECESSOR"
|
||||
);
|
||||
let(hraw,hrequest):(Vec<u8>,Vec<u8>)=local.helper.query_row("SELECT response,request FROM helper_sync_decisions WHERE decision_id=?1 AND checkpoint=134",[dto::FIRST.to_string()],|r|Ok((r.get(0)?,r.get(1)?)))?;
|
||||
let stored: SignedResponse = serde_json::from_slice(&hraw)?;
|
||||
ensure!(
|
||||
stored.decision_bytes == first.decision_bytes
|
||||
&& stored.signature == first.signature
|
||||
&& hrequest == first_req
|
||||
&& number(
|
||||
local.helper,
|
||||
"SELECT count(*) FROM helper_sync_decisions WHERE decision_id='2af359c5-5b5c-4992-b445-1c00e271a288'"
|
||||
)? == 0,
|
||||
"ALIGN_HELPER_EXACT_CONTROL_GAP"
|
||||
);
|
||||
ensure!(
|
||||
number(
|
||||
local.helper,
|
||||
"SELECT count(*) FROM sqlite_schema WHERE type='trigger' AND tbl_name IN ('helper_sync_meta','helper_sync_decisions')"
|
||||
)? == 0,
|
||||
"ALIGN_UNEXPECTED_CONTROL_TRIGGER"
|
||||
);
|
||||
helper_reconcile::verify_checkpoint_repair_history_with(
|
||||
local.helper,
|
||||
local.helper_binding,
|
||||
None,
|
||||
HelperIdentity::System,
|
||||
&DalekVerifier,
|
||||
)?;
|
||||
let (echo_offer, state, grant): (Vec<u8>, String, String) = local.agent.query_row(
|
||||
"SELECT offer,state,grant_id FROM job_attempts WHERE job=?1 AND attempt=?2",
|
||||
params![dto::ECHO_JOB.to_string(), dto::ECHO_ATTEMPT.to_string()],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
state == "succeeded" && !grant.is_empty(),
|
||||
"ALIGN_ECHO_STATE"
|
||||
);
|
||||
let(echo_start,echo_outcome,echo_result):(Vec<u8>,Vec<u8>,Vec<u8>)=local.consumption.query_row("SELECT e.start,e.outcome,c.result FROM execution_evidence e JOIN consumed c USING(grant_id) WHERE c.grant_id=?1 AND c.job=?2 AND c.attempt=?3",params![grant,dto::ECHO_JOB.to_string(),dto::ECHO_ATTEMPT.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?)))?;
|
||||
let echo_completion_receipt: Vec<u8> = local.agent.query_row(
|
||||
"SELECT original_receipt FROM windows_echo_scope_completion WHERE id=1",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let completion = signed(local.binding, &echo_completion_receipt)?;
|
||||
signed(local.helper_binding, &echo_completion_receipt)?;
|
||||
let completed: windows_echo_completion::Receipt = serde_json::from_slice(&completion.payload)?;
|
||||
ensure!(
|
||||
completed.valid(completed.issued_at),
|
||||
"ALIGN_COMPLETION_HISTORY"
|
||||
);
|
||||
let offer = JobOffer::decode(echo_offer.as_slice())?;
|
||||
let job: JobPayload = local.binding.job(&offer.payload_bytes)?;
|
||||
let start: Value = serde_json::from_slice(&echo_start)?;
|
||||
let request: Request = serde_json::from_value(start["request"].clone())?;
|
||||
let permit: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
|
||||
for b in [local.binding, local.helper_binding] {
|
||||
b.verify_with(&request, permit.not_before, &DalekVerifier)?;
|
||||
}
|
||||
let outcome: Value = serde_json::from_slice(&echo_outcome)?;
|
||||
let reserved: DateTime<Utc> = serde_json::from_value(start["reserved_at"].clone())?;
|
||||
ensure!(
|
||||
completed.witness.boot_id == dto::BOOT
|
||||
&& start["previous_boot_id"] == dto::BOOT.to_string()
|
||||
&& reserved >= permit.not_before
|
||||
&& reserved < permit.start_before
|
||||
&& start["reauthentication_required"] == true
|
||||
&& start["postconditions_passed"] == false,
|
||||
"ALIGN_ORIGINAL_ECHO_START"
|
||||
);
|
||||
ensure!(
|
||||
completed.witness.scope.matches_job(&job)
|
||||
&& request.job_bytes == offer.payload_bytes
|
||||
&& permit.grant_id.to_string() == grant
|
||||
&& hash(&request.permit_bytes) == completed.witness.grant_payload_sha256
|
||||
&& hash(&request.signature) == completed.witness.grant_signature_sha256
|
||||
&& inventory_sha256(&outcome)? == completed.witness.outcome_sha256
|
||||
&& outcome == serde_json::from_slice::<Value>(&echo_result)?
|
||||
&& windows_echo_completion::successful_outcome(&outcome),
|
||||
"ALIGN_ORIGINAL_ECHO_EVIDENCE"
|
||||
);
|
||||
let (expired_offer, expired, expired_grant): (Vec<u8>, String, String) =
|
||||
local.agent.query_row(
|
||||
"SELECT offer,state,grant_id FROM job_attempts WHERE job=?1 AND attempt=?2",
|
||||
params![
|
||||
dto::EXPIRED_JOB.to_string(),
|
||||
dto::EXPIRED_ATTEMPT.to_string()
|
||||
],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
expired == "expired" && expired_grant.is_empty(),
|
||||
"ALIGN_EXPIRED_NO_GRANT"
|
||||
);
|
||||
let expired = JobOffer::decode(expired_offer.as_slice())?;
|
||||
let payload = local.binding.job(&expired.payload_bytes)?;
|
||||
ensure!(
|
||||
payload.job_id == dto::EXPIRED_JOB
|
||||
&& payload.attempt_id == dto::EXPIRED_ATTEMPT
|
||||
&& expired.job_payload_hash == hash(&expired.payload_bytes),
|
||||
"ALIGN_EXPIRED_ORIGINAL_OFFER"
|
||||
);
|
||||
ensure!(
|
||||
number(local.agent, "SELECT count(*) FROM events")? == 0
|
||||
&& number(local.agent, "SELECT count(*) FROM job_events")? == 0,
|
||||
"ALIGN_NO_PENDING_EVENTS"
|
||||
);
|
||||
let w = Witness {
|
||||
schema_version: 1,
|
||||
tenant_id: local.binding.tenant_id,
|
||||
asset_id: local.binding.asset_id,
|
||||
agent_id: local.binding.agent_id,
|
||||
enrollment_generation: local.binding.enrollment_generation,
|
||||
assignment_version: local.binding.assignment_version,
|
||||
boot_id: guard.boot()?,
|
||||
connection_generation: 205,
|
||||
agent_journal_id: Uuid::parse_str(&agent_journal)?,
|
||||
helper_journal_id: Uuid::parse_str(&helper_journal)?,
|
||||
agent_checkpoint: 10137,
|
||||
helper_checkpoint: helper_cp,
|
||||
agent_last_decision: dto::SECOND,
|
||||
helper_last_decision: dto::FIRST,
|
||||
verification_key_id: hash(&hex::decode(&local.binding.public_key_hex)?),
|
||||
verification_public_key_hex: local.binding.public_key_hex.clone(),
|
||||
binding_sha256,
|
||||
helper_binding_sha256,
|
||||
files: guard.files()?,
|
||||
agent_inventory_sha256: inventory(local.agent, &[]).context("ALIGN_AGENT_INVENTORY")?,
|
||||
consumption_inventory_sha256: inventory(local.consumption, &[])
|
||||
.context("ALIGN_CONSUMPTION_INVENTORY")?,
|
||||
helper_inventory_sha256: inventory(local.helper, &[]).context("ALIGN_HELPER_INVENTORY")?,
|
||||
counts,
|
||||
original_requests: [first_req, second_req],
|
||||
original_responses: [first, second],
|
||||
echo_offer,
|
||||
echo_start,
|
||||
echo_outcome,
|
||||
echo_result,
|
||||
echo_completion_receipt,
|
||||
expired_offer,
|
||||
};
|
||||
ensure!(w.valid(), "ALIGN_WITNESS_PROFILE");
|
||||
guard.check()?;
|
||||
Ok(w)
|
||||
}
|
||||
/// Caller must keep both original process lifetime locks and all file identities
|
||||
/// held for the complete transaction. A UI receipt is never an execution grant.
|
||||
pub fn apply(
|
||||
local: &Local<'_>,
|
||||
helper: &mut Connection,
|
||||
guard: &impl ClosedPairGuard,
|
||||
raw: &[u8],
|
||||
now: DateTime<Utc>,
|
||||
) -> Result<()> {
|
||||
let signed_receipt = signed(local.binding, raw)?;
|
||||
signed(local.helper_binding, raw)?;
|
||||
let receipt: Receipt = serde_json::from_slice(&signed_receipt.payload)?;
|
||||
ensure!(receipt.valid(now), "ALIGN_FRESH_CLOSED_UI_RECEIPT");
|
||||
let tx = helper.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let current = Local {
|
||||
agent: local.agent,
|
||||
consumption: local.consumption,
|
||||
helper: &tx,
|
||||
intents: local.intents,
|
||||
binding: local.binding,
|
||||
helper_binding: local.helper_binding,
|
||||
};
|
||||
ensure!(
|
||||
witness(¤t, guard)? == receipt.witness,
|
||||
"ALIGN_UI_WITNESS_CHANGED"
|
||||
);
|
||||
let untouched = inventory(&tx, &["helper_sync_decisions", "helper_sync_meta", TABLE])?;
|
||||
tx.execute(DDL, [])?;
|
||||
for (name, kind) in [
|
||||
("no_replace", "INSERT"),
|
||||
("no_update", "UPDATE"),
|
||||
("no_delete", "DELETE"),
|
||||
] {
|
||||
let condition = if kind == "INSERT" {
|
||||
" WHEN EXISTS(SELECT 1 FROM windows_sync_admin_closed_alignment_205)"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
tx.execute_batch(&format!("CREATE TRIGGER windows_alignment_205_{name} BEFORE {kind} ON {TABLE}{condition} BEGIN SELECT RAISE(ABORT,'WINDOWS_ALIGNMENT_205_IMMUTABLE'); END"))?;
|
||||
}
|
||||
let response = &receipt.witness.original_responses[1];
|
||||
let request = &receipt.witness.original_requests[1];
|
||||
let fingerprint: String = tx.query_row(
|
||||
"SELECT fingerprint FROM helper_sync_captures WHERE checkpoint=135",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(
|
||||
fingerprint == helper_reconcile::ledger_fingerprint(&tx)?,
|
||||
"ALIGN_ORIGINAL_LEDGER_UNCHANGED"
|
||||
);
|
||||
tx.execute("INSERT INTO helper_sync_decisions(decision_id,checkpoint,response,request,fingerprint) VALUES(?1,135,?2,?3,?4)",params![dto::SECOND.to_string(),serde_json::to_vec(&SignedResponse{decision_bytes:response.decision_bytes.clone(),signature:response.signature.clone()})?,request,fingerprint])?;
|
||||
ensure!(tx.execute("UPDATE helper_sync_meta SET last_decision=?1,agent_checkpoint=10137 WHERE id=1 AND checkpoint=?2 AND generation=205 AND last_decision=?3 AND agent_checkpoint=10135 AND fault IS NULL",params![dto::SECOND.to_string(),receipt.witness.helper_checkpoint,dto::FIRST.to_string()])?==1,"ALIGN_HELPER_HEAD_CAS");
|
||||
tx.execute(
|
||||
"INSERT INTO windows_sync_admin_closed_alignment_205 VALUES(1,?1,?2,?3,?4,0,0,0)",
|
||||
params![
|
||||
receipt.receipt_id.to_string(),
|
||||
raw,
|
||||
receipt.witness_sha256,
|
||||
now.to_rfc3339()
|
||||
],
|
||||
)?;
|
||||
ensure!(tx.query_row("SELECT EXISTS(SELECT 1 FROM helper_sync_meta WHERE id=1 AND journal_id=?1 AND checkpoint=?2 AND generation=205 AND last_decision=?3 AND agent_journal_id=?4 AND agent_checkpoint=10137 AND fault IS NULL)",params![receipt.witness.helper_journal_id.to_string(),receipt.witness.helper_checkpoint,dto::SECOND.to_string(),receipt.witness.agent_journal_id.to_string()],|r|r.get::<_,bool>(0))?,"ALIGN_ONLY_FORWARD_HEAD_FIELDS");
|
||||
ensure!(
|
||||
inventory(&tx, &["helper_sync_decisions", "helper_sync_meta", TABLE])? == untouched
|
||||
&& inventory(local.agent, &[])? == receipt.witness.agent_inventory_sha256
|
||||
&& inventory(local.consumption, &[])? == receipt.witness.consumption_inventory_sha256,
|
||||
"ALIGN_UNRELATED_HISTORY_CHANGED"
|
||||
);
|
||||
helper_reconcile::verify_checkpoint_repair_history_with(
|
||||
&tx,
|
||||
local.helper_binding,
|
||||
None,
|
||||
HelperIdentity::System,
|
||||
&DalekVerifier,
|
||||
)?;
|
||||
guard.check()?;
|
||||
ensure!(
|
||||
receipt.valid(Utc::now()),
|
||||
"ALIGN_RECEIPT_EXPIRED_BEFORE_COMMIT"
|
||||
);
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user