Implement bounded Windows MSI delegation with deny-only cancellation and retained installer ownership
Rust development slice / linux (push) Failing after 7s

This commit is contained in:
2026-11-14 13:53:05 +01:00
parent 66c1855056
commit 66e77ad83e
9 changed files with 996 additions and 16 deletions
+170 -5
View File
@@ -16,16 +16,67 @@ pub const ROOT: &str = r"C:\ProgramData\RustDiscoverySystem\agent-intents";
pub const DB: &str = r"C:\ProgramData\RustDiscoverySystem\agent-intents\system-intents.sqlite";
const ACTOR_RW: u32 = 0x0012_019f;
const SCHEMA:&str="CREATE TABLE IF NOT EXISTS system_intent_meta(id INTEGER PRIMARY KEY CHECK(id=1),file_identity BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS system_intents(id TEXT PRIMARY KEY,job TEXT NOT NULL,attempt TEXT NOT NULL,grant_id TEXT NOT NULL UNIQUE,body BLOB NOT NULL CHECK(length(body)<=196608),digest TEXT NOT NULL,phase TEXT NOT NULL CHECK(phase IN ('prepared','known_no_dispatch','may_have_dispatched')),UNIQUE(job,attempt));
CREATE TABLE IF NOT EXISTS system_intents(id TEXT PRIMARY KEY,job TEXT NOT NULL,attempt TEXT NOT NULL,grant_id TEXT NOT NULL UNIQUE,body BLOB NOT NULL CHECK(length(body)<=196608),digest TEXT NOT NULL,phase TEXT NOT NULL CHECK(phase IN ('prepared','known_no_dispatch','may_have_dispatched')),cancel_requested INTEGER NOT NULL DEFAULT 0 CHECK(cancel_requested IN (0,1)),UNIQUE(job,attempt));
CREATE TABLE IF NOT EXISTS system_intent_mirrors(id TEXT PRIMARY KEY,outcome_sha256 TEXT NOT NULL,mirror_observed_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS system_intent_denial_resumes(id TEXT NOT NULL,agent_instance TEXT NOT NULL,observed_at TEXT NOT NULL,PRIMARY KEY(id,agent_instance));
CREATE TRIGGER IF NOT EXISTS system_intents_no_delete BEFORE DELETE ON system_intents BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_intents_monotonic BEFORE UPDATE ON system_intents WHEN NEW.id!=OLD.id OR NEW.job!=OLD.job OR NEW.attempt!=OLD.attempt OR NEW.grant_id!=OLD.grant_id OR NEW.body!=OLD.body OR NEW.digest!=OLD.digest OR OLD.phase!='prepared' OR NEW.phase NOT IN ('known_no_dispatch','may_have_dispatched') BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_intents_monotonic BEFORE UPDATE ON system_intents WHEN NEW.id!=OLD.id OR NEW.job!=OLD.job OR NEW.attempt!=OLD.attempt OR NEW.grant_id!=OLD.grant_id OR NEW.body!=OLD.body OR NEW.digest!=OLD.digest OR NOT ((NEW.phase=OLD.phase AND NEW.cancel_requested=1 AND OLD.cancel_requested IN (0,1)) OR (OLD.phase='prepared' AND NEW.phase IN ('known_no_dispatch','may_have_dispatched') AND NEW.cancel_requested=OLD.cancel_requested)) BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_mirrors_no_delete BEFORE DELETE ON system_intent_mirrors BEGIN SELECT RAISE(ABORT,'SYSTEM_MIRROR_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_mirrors_no_update BEFORE UPDATE ON system_intent_mirrors BEGIN SELECT RAISE(ABORT,'SYSTEM_MIRROR_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_denial_resumes_no_delete BEFORE DELETE ON system_intent_denial_resumes BEGIN SELECT RAISE(ABORT,'SYSTEM_DENIAL_RESUME_IMMUTABLE');END;
CREATE TRIGGER IF NOT EXISTS system_denial_resumes_no_update BEFORE UPDATE ON system_intent_denial_resumes BEGIN SELECT RAISE(ABORT,'SYSTEM_DENIAL_RESUME_IMMUTABLE');END;";
const LEGACY_INTENTS_TABLE: &str = "CREATE TABLE IF NOT EXISTS system_intents(id TEXT PRIMARY KEY,job TEXT NOT NULL,attempt TEXT NOT NULL,grant_id TEXT NOT NULL UNIQUE,body BLOB NOT NULL CHECK(length(body)<=196608),digest TEXT NOT NULL,phase TEXT NOT NULL CHECK(phase IN ('prepared','known_no_dispatch','may_have_dispatched')),UNIQUE(job,attempt));";
const LEGACY_MONOTONIC: &str = "CREATE TRIGGER IF NOT EXISTS system_intents_monotonic BEFORE UPDATE ON system_intents WHEN NEW.id!=OLD.id OR NEW.job!=OLD.job OR NEW.attempt!=OLD.attempt OR NEW.grant_id!=OLD.grant_id OR NEW.body!=OLD.body OR NEW.digest!=OLD.digest OR OLD.phase!='prepared' OR NEW.phase NOT IN ('known_no_dispatch','may_have_dispatched') BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;";
const CLAIM_RESUME: &str = "INSERT OR IGNORE INTO system_intent_denial_resumes(id,agent_instance,observed_at) VALUES(?1,?2,?3)";
fn initialize_schema(db: &mut Connection) -> Result<()> {
let exists: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='system_intents')",
[],
|r| r.get(0),
)?;
if exists {
let columns = db
.prepare("PRAGMA table_info(system_intents)")?
.query_map([], |r| r.get::<_, String>(1))?
.collect::<rusqlite::Result<Vec<_>>>()?;
if !columns.iter().any(|name| name == "cancel_requested") {
ensure!(
columns
== [
"id", "job", "attempt", "grant_id", "body", "digest", "phase"
],
"SYSTEM_INTENT_LEGACY_SCHEMA"
);
let old:String=db.query_row("SELECT sql FROM sqlite_master WHERE type='trigger' AND name='system_intents_monotonic'",[],|r|r.get(0))?;
let normalize = |s: &str| {
s.replace("IF NOT EXISTS ", "")
.trim_end_matches(';')
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
};
ensure!(
normalize(&old) == normalize(LEGACY_MONOTONIC),
"SYSTEM_INTENT_LEGACY_TRIGGER"
);
let table: String = db.query_row(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='system_intents'",
[],
|r| r.get(0),
)?;
ensure!(
normalize(&table) == normalize(LEGACY_INTENTS_TABLE),
"SYSTEM_INTENT_LEGACY_SCHEMA"
);
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
tx.execute_batch("ALTER TABLE system_intents ADD COLUMN cancel_requested INTEGER NOT NULL DEFAULT 0 CHECK(cancel_requested IN (0,1));DROP TRIGGER system_intents_monotonic;")?;
tx.execute_batch(SCHEMA)?;
tx.commit()?;
}
}
db.execute_batch(SCHEMA)?;
Ok(())
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Intent {
@@ -148,14 +199,14 @@ impl Store {
} else {
OpenFlags::SQLITE_OPEN_READ_ONLY
};
let db = Connection::open_with_flags(DB, flags)?;
let mut db = Connection::open_with_flags(DB, flags)?;
db.busy_timeout(Duration::from_millis(250))?;
if write {
rmm_agent_core::ledger::bounded_journal_capacity(&db)?;
let mode: String = db.query_row("PRAGMA journal_mode=PERSIST", [], |r| r.get(0))?;
ensure!(mode == "persist", "SYSTEM_INTENT_JOURNAL_MODE");
db.execute_batch("PRAGMA synchronous=FULL;PRAGMA temp_store=MEMORY;PRAGMA journal_size_limit=1048576;")?;
db.execute_batch(SCHEMA)?;
initialize_schema(&mut db)?;
db.execute(
"INSERT OR IGNORE INTO system_intent_meta VALUES(1,?1)",
[serde_json::to_vec(&identity)?],
@@ -241,10 +292,60 @@ impl Store {
}
pub fn cancel_before_dispatch(&mut self, id: Uuid) -> Result<Phase> {
self.check()?;
self.db.execute(
"UPDATE system_intents SET cancel_requested=1 WHERE id=?1",
[id.to_string()],
)?;
let (_, phase) = advance(&mut self.db, id, Phase::KnownNoDispatch)?;
self.check()?;
Ok(phase)
}
/// Denial only. Original phase/request/anchor never changes, even after IPC.
pub fn deny(&mut self, original: &Request, boot: Uuid) -> Result<()> {
self.check()?;
let permit: ExecutionPermitPayload = serde_json::from_slice(&original.permit_bytes)?;
let intent = self.by_grant(permit.grant_id)?;
ensure!(
serde_json::to_vec(&intent.request)? == serde_json::to_vec(original)?
&& intent.original_boot_id == boot,
"SYSTEM_CANCEL_ORIGINAL_BINDING"
);
self.db.execute(
"UPDATE system_intents SET cancel_requested=1 WHERE id=?1",
[intent.id.to_string()],
)?;
self.check()
}
/// Open a new ordinary RO connection for each observation. No long-lived
/// SQLite read transaction or immutable-mode shortcut may hide actor denial.
pub fn require_not_denied(
original: &Request,
boot: Uuid,
generation: u64,
policy: &str,
binary: &str,
) -> Result<()> {
let mut store = Self::open(false)?;
let permit: ExecutionPermitPayload = serde_json::from_slice(&original.permit_bytes)?;
let intent = store.by_grant(permit.grant_id)?;
let (_, phase) = store.load(intent.id)?;
ensure!(
serde_json::to_vec(&intent.request)? == serde_json::to_vec(original)?
&& intent.original_boot_id == boot
&& intent.connection_generation == generation
&& phase == Phase::MayHaveDispatched
&& intent.policy_sha256 == policy
&& intent.helper_binary_sha256 == binary,
"SYSTEM_CANCEL_ORIGINAL_BINDING"
);
let denied: i64 = store.db.query_row(
"SELECT cancel_requested FROM system_intents WHERE id=?1",
[intent.id.to_string()],
|r| r.get(0),
)?;
ensure!(denied == 0, "SYSTEM_MSI_CANCELLED_OR_FENCED");
store.check()
}
pub fn pending(&self) -> Result<Vec<Intent>> {
let mut rows=self.db.prepare("SELECT i.id FROM system_intents i WHERE NOT EXISTS(SELECT 1 FROM system_intent_mirrors m WHERE m.id=i.id) ORDER BY i.rowid LIMIT 2")?;
let ids = rows
@@ -356,7 +457,7 @@ mod tests {
let dispatched = Uuid::new_v4();
for id in [cancelled, dispatched] {
db.execute(
"INSERT INTO system_intents VALUES(?1,?1,?1,?1,x'01','immutable','prepared')",
"INSERT INTO system_intents(id,job,attempt,grant_id,body,digest,phase) VALUES(?1,?1,?1,?1,x'01','immutable','prepared')",
[id.to_string()],
)
.unwrap();
@@ -377,6 +478,29 @@ mod tests {
advance(&mut db, dispatched, Phase::KnownNoDispatch).unwrap(),
(0, Phase::MayHaveDispatched)
);
for _ in 0..2 {
db.execute(
"UPDATE system_intents SET cancel_requested=1 WHERE id=?1",
[dispatched.to_string()],
)
.unwrap();
}
assert_eq!(
db.query_row(
"SELECT phase,cancel_requested FROM system_intents WHERE id=?1",
[dispatched.to_string()],
|r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?))
)
.unwrap(),
("may_have_dispatched".into(), 1)
);
assert!(
db.execute(
"UPDATE system_intents SET cancel_requested=0 WHERE id=?1",
[dispatched.to_string()]
)
.is_err()
);
assert!(
db.execute(
"UPDATE system_intents SET phase='prepared' WHERE id=?1",
@@ -411,4 +535,45 @@ mod tests {
assert_eq!(db.execute(CLAIM_RESUME, args).unwrap(), 1);
assert_eq!(db.execute(CLAIM_RESUME, args).unwrap(), 0);
}
#[test]
fn additive_denial_column_preserves_original_legacy_intents_and_rejects_unknown_trigger() {
let mut db = Connection::open_in_memory().unwrap();
db.execute_batch(LEGACY_INTENTS_TABLE).unwrap();
db.execute_batch(LEGACY_MONOTONIC).unwrap();
db.execute("INSERT INTO system_intents VALUES('id','job','attempt','grant',x'0102','original','may_have_dispatched')",[]).unwrap();
initialize_schema(&mut db).unwrap();
initialize_schema(&mut db).unwrap();
assert_eq!(
db.query_row(
"SELECT body,digest,phase,cancel_requested FROM system_intents",
[],
|r| Ok((
r.get::<_, Vec<u8>>(0)?,
r.get::<_, String>(1)?,
r.get::<_, String>(2)?,
r.get::<_, i64>(3)?
))
)
.unwrap(),
(
vec![1, 2],
"original".into(),
"may_have_dispatched".into(),
0
)
);
db.execute("UPDATE system_intents SET cancel_requested=1", [])
.unwrap();
assert!(
db.execute("UPDATE system_intents SET body=x'03'", [])
.is_err()
);
assert!(
db.execute("UPDATE system_intents SET cancel_requested=0", [])
.is_err()
);
let mut foreign = Connection::open_in_memory().unwrap();
foreign.execute_batch("CREATE TABLE system_intents(id,job,attempt,grant_id,body,digest,phase);CREATE TRIGGER system_intents_monotonic BEFORE UPDATE ON system_intents BEGIN SELECT 1;END;").unwrap();
assert!(initialize_schema(&mut foreign).is_err());
}
}