Share signed job core and verify native Linux then Windows contracts
Rust development slice / linux (push) Failing after 6s

This commit is contained in:
2026-11-14 00:52:40 +01:00
parent 1fef7f6ce9
commit 31278bedec
32 changed files with 4452 additions and 1715 deletions
+140
View File
@@ -0,0 +1,140 @@
//! Exact historical helper request/binding codecs and signed permit rules.
use crate::crypto::{DefaultVerifier, Ed25519Verifier};
use anyhow::{Result, ensure};
use chrono::{DateTime, Utc};
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload, hash};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Binding {
pub tenant_id: Uuid,
pub asset_id: Uuid,
pub agent_id: Uuid,
pub enrollment_generation: u64,
pub assignment_version: u64,
pub public_key_hex: String,
}
pub type AuthBinding = Binding;
impl Binding {
pub fn job(&self, bytes: &[u8]) -> Result<JobPayload> {
ensure!(bytes.len() <= 65536, "JOB_SIZE");
let j: JobPayload = serde_json::from_slice(bytes)?;
ensure!(
j.schema_version == 1
&& j.tenant_id == self.tenant_id
&& j.asset_id == self.asset_id
&& j.agent_id == self.agent_id
&& j.enrollment_generation == self.enrollment_generation
&& j.assignment_version == self.assignment_version,
"IDENTITY_BINDING"
);
ensure!(
j.action.validate()
&& (1..=3600).contains(&j.max_runtime_seconds)
&& (1..=262144).contains(&j.max_output_bytes)
&& j.not_before < j.start_before,
"INVALID_JOB"
);
Ok(j)
}
pub fn verify(
&self,
request: &Request,
now: DateTime<Utc>,
) -> Result<(JobPayload, ExecutionPermitPayload)> {
self.verify_with(request, now, &DefaultVerifier::default())
}
pub fn verify_with(
&self,
request: &Request,
now: DateTime<Utc>,
verifier: &impl Ed25519Verifier,
) -> Result<(JobPayload, ExecutionPermitPayload)> {
let job = self.job(&request.job_bytes)?;
ensure!(
request.permit_bytes.len() <= 8192 && request.signature.len() == 64,
"PERMIT_SIZE"
);
let raw = hex::decode(&self.public_key_hex)?;
ensure!(raw.len() == 32, "TRUST_KEY_SIZE");
ensure!(
verifier.verify(&raw, &request.permit_bytes, &request.signature)?,
"INVALID_SIGNATURE"
);
let p: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
ensure!(
p.domain == "rmm.execution-permit"
&& p.schema_version == 1
&& p.key_id == hash(&raw)
&& !p.grant_id.is_nil()
&& !p.authorization_id.is_nil(),
"PERMIT_DOMAIN"
);
ensure!(
p.authorization_id == request.authorization_id
&& p.plan_hash == request.plan_hash
&& p.plan_hash.len() == 64
&& hex::decode(&p.plan_hash)?.len() == 32
&& p.job_payload_hash == hash(&request.job_bytes)
&& p.tenant_id == job.tenant_id
&& p.asset_id == job.asset_id
&& p.agent_id == job.agent_id
&& p.enrollment_generation == job.enrollment_generation
&& p.assignment_version == job.assignment_version
&& p.job_id == job.job_id
&& p.attempt_id == job.attempt_id
&& p.action == job.action.name()
&& p.execution_identity == job.execution_identity
&& p.max_runtime_seconds == job.max_runtime_seconds,
"PERMIT_BINDING"
);
ensure!(
p.not_before >= job.not_before
&& p.start_before <= job.start_before
&& p.not_before < p.start_before
&& (p.start_before - p.not_before).num_seconds() <= 60
&& now >= p.not_before
&& now < p.start_before,
"PERMIT_TIME"
);
Ok((job, p))
}
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Request {
pub job_bytes: Vec<u8>,
pub permit_bytes: Vec<u8>,
pub signature: Vec<u8>,
pub plan_hash: String,
pub authorization_id: Uuid,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Outcome {
pub state: String,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub exit_code: Option<i32>,
pub output_truncated: bool,
pub reboot_required: bool,
pub evidence: serde_json::Value,
pub error_code: String,
}
impl Outcome {
pub fn unknown(code: &str) -> Self {
Self {
state: "unknown".into(),
stdout: vec![],
stderr: vec![],
exit_code: None,
output_truncated: false,
reboot_required: false,
evidence: serde_json::json!({"postconditions_passed":false}),
error_code: code.into(),
}
}
}
+54
View File
@@ -0,0 +1,54 @@
//! Fixed Ed25519 verification; no algorithm negotiation or trust-key discovery.
use anyhow::Result;
use ed25519_dalek::{Signature, VerifyingKey};
pub trait Ed25519Verifier {
fn verify(&self, public_key: &[u8], message: &[u8], signature: &[u8]) -> Result<bool>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct DalekVerifier;
impl Ed25519Verifier for DalekVerifier {
fn verify(&self, public_key: &[u8], message: &[u8], signature: &[u8]) -> Result<bool> {
let Ok(raw): Result<&[u8; 32], _> = public_key.try_into() else {
return Ok(false);
};
let Ok(key) = VerifyingKey::from_bytes(raw) else {
return Ok(false);
};
let Ok(signature) = Signature::from_slice(signature) else {
return Ok(false);
};
// Reject weak points and scalar/point malleability. This is raw Ed25519,
// never Ed25519ph: the exact stored bytes are the signed message.
Ok(key.verify_strict(message, &signature).is_ok())
}
}
/// Existing Linux verifier semantics, retained explicitly during extraction.
#[cfg(all(unix, feature = "openssl-verifier"))]
#[derive(Clone, Copy, Debug, Default)]
pub struct OpenSslVerifier;
#[cfg(all(unix, feature = "openssl-verifier"))]
impl Ed25519Verifier for OpenSslVerifier {
fn verify(&self, public_key: &[u8], message: &[u8], signature: &[u8]) -> Result<bool> {
use openssl::{
pkey::{Id, PKey},
sign::Verifier,
};
if public_key.len() != 32 || signature.len() != 64 {
return Ok(false);
}
let key = PKey::public_key_from_raw_bytes(public_key, Id::ED25519)?;
Ok(Verifier::new_without_digest(&key)?.verify_oneshot(signature, message)?)
}
}
/// Preserve the existing Linux OpenSSL profile when selected by its adapter;
/// Windows never depends on OpenSSL, including workspace feature unification.
#[cfg(all(unix, feature = "openssl-verifier"))]
pub type DefaultVerifier = OpenSslVerifier;
#[cfg(not(all(unix, feature = "openssl-verifier")))]
pub type DefaultVerifier = DalekVerifier;
+274
View File
@@ -0,0 +1,274 @@
//! Durable job persistence without capability discovery or OS execution.
//! Caller performs fresh Sync/Clock/permit checks before consuming or executing.
use crate::auth::{Binding, Outcome, Request};
use anyhow::{Result, ensure};
use prost::Message;
use rmm_domain::jobs::{JobPayload, hash};
use rmm_protocol::*;
use rusqlite::{Connection, OptionalExtension, params};
use uuid::Uuid;
pub fn accept(
db: &Connection,
binding: &Binding,
offer: &JobOffer,
supported: impl FnOnce(&JobPayload) -> bool,
) -> Result<bool> {
let job = binding.job(&offer.payload_bytes)?;
ensure!(
offer.job_id == job.job_id.to_string()
&& offer.attempt_id == job.attempt_id.to_string()
&& offer.job_payload_hash == hash(&offer.payload_bytes)
&& Uuid::parse_str(&offer.authorization_id).is_ok_and(|id| !id.is_nil())
&& offer.plan_hash.len() == 64
&& hex_hash(&offer.plan_hash),
"OFFER_BINDING"
);
ensure!(supported(&job), "UNSUPPORTED_CAPABILITY");
let bytes = offer.encode_to_vec();
let existing: Option<Vec<u8>> = db
.query_row(
"SELECT offer FROM job_attempts WHERE job=?1 AND attempt=?2",
params![offer.job_id, offer.attempt_id],
|r| r.get(0),
)
.optional()?;
if let Some(old) = existing {
ensure!(old == bytes, "OFFER_CONFLICT");
return Ok(false);
}
let count: i64 = db.query_row("SELECT count(*) FROM job_attempts", [], |r| r.get(0))?;
ensure!(count < 10000, "JOURNAL_CAPACITY_NEW_EFFECTS_BLOCKED");
db.execute(
"INSERT INTO job_attempts(job,attempt,offer,state) VALUES(?1,?2,?3,'accepted')",
params![offer.job_id, offer.attempt_id, bytes],
)?;
Ok(true)
}
fn hex_hash(s: &str) -> bool {
s.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
/// Inspect ONLY at a new process startup, never on a transport reconnect: no
/// executor thread from the previous process can still deliver its outcome.
/// This does not execute, release consumption or invent a successful outcome.
pub fn interrupted(
db: &Connection,
ledger: &Connection,
binding: &Binding,
) -> Result<Vec<(JobOffer, String)>> {
interrupted_with(
db,
ledger,
binding,
&crate::crypto::DefaultVerifier::default(),
)
}
pub fn interrupted_with(
db: &Connection,
ledger: &Connection,
binding: &Binding,
verifier: &impl crate::crypto::Ed25519Verifier,
) -> Result<Vec<(JobOffer, String)>> {
let mut statement = db.prepare(
"SELECT offer,grant_id FROM job_attempts WHERE state IN ('requesting','running','verifying') ORDER BY job,attempt",
)?;
let rows = statement.query_map([], |r| {
Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, String>(1)?))
})?;
let mut interrupted = Vec::new();
for row in rows {
let (bytes, grant) = row?;
let offer = JobOffer::decode(bytes.as_slice())?;
let job = binding.job(&offer.payload_bytes)?;
ensure!(
offer.job_id == job.job_id.to_string()
&& offer.attempt_id == job.attempt_id.to_string()
&& offer.job_payload_hash == hash(&offer.payload_bytes)
&& Uuid::parse_str(&offer.authorization_id).is_ok_and(|id| !id.is_nil())
&& offer.plan_hash.len() == 64
&& hex_hash(&offer.plan_hash),
"INTERRUPTED_OFFER_BINDING"
);
if !grant.is_empty() {
let row: Option<(String, u64, String, String, Vec<u8>)> = ledger
.query_row(
"SELECT c.agent,c.generation,c.job,c.attempt,e.start FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1",
[&grant],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
)
.optional()?;
let (agent, generation, job_id, attempt, start) =
row.ok_or_else(|| anyhow::anyhow!("INTERRUPTED_START_EVIDENCE_MISSING"))?;
ensure!(
agent == binding.agent_id.to_string()
&& generation == binding.enrollment_generation
&& job_id == offer.job_id
&& attempt == offer.attempt_id,
"INTERRUPTED_CONSUMPTION_BINDING"
);
let start: serde_json::Value = serde_json::from_slice(&start)?;
let request: Request = serde_json::from_value(start["request"].clone())?;
let permit: rmm_domain::jobs::ExecutionPermitPayload =
serde_json::from_slice(&request.permit_bytes)?;
// Verify the historical signed request at its original valid time;
// this is evidence only, never permission to start it again.
let (_, verified) = binding.verify_with(&request, permit.not_before, verifier)?;
ensure!(
verified == permit
&& permit.grant_id.to_string() == grant
&& request.job_bytes == offer.payload_bytes
&& request.plan_hash == offer.plan_hash
&& request.authorization_id.to_string() == offer.authorization_id,
"INTERRUPTED_START_BINDING"
);
} else {
// A request may have committed remotely without its reply arriving.
// It can only become local unknown, never a fabricated grant/result.
let state: String = db.query_row(
"SELECT state FROM job_attempts WHERE job=?1 AND attempt=?2",
params![offer.job_id, offer.attempt_id],
|r| r.get(0),
)?;
ensure!(state == "requesting", "INTERRUPTED_RUNNING_GRANT_MISSING");
}
interrupted.push((offer, grant));
}
Ok(interrupted)
}
pub fn interrupted_request(db: &Connection, offer: &JobOffer) -> Result<()> {
ensure!(
db.execute(
"UPDATE job_attempts SET state='unknown',revision=revision+1 WHERE job=?1 AND attempt=?2 AND state='requesting' AND grant_id=''",
params![offer.job_id, offer.attempt_id],
)? == 1,
"INTERRUPTED_REQUEST_STATE"
);
Ok(())
}
pub fn event(db: &Connection, envelope: &Envelope) -> Result<()> {
let count: i64 = db.query_row("SELECT count(*) FROM job_events", [], |r| r.get(0))?;
ensure!(count < 1000, "UNACKNOWLEDGED_EVENT_LIMIT");
db.execute(
"INSERT INTO job_events(id,payload) VALUES(?1,?2)",
params![envelope.message_id, envelope.encode_to_vec()],
)?;
Ok(())
}
pub fn events(db: &Connection) -> Result<Vec<Envelope>> {
let mut statement = db.prepare("SELECT payload FROM job_events ORDER BY rowid LIMIT 100")?;
let bytes = statement
.query_map([], |r| r.get::<_, Vec<u8>>(0))?
.collect::<rusqlite::Result<Vec<_>>>()?;
bytes
.into_iter()
.map(|b| Ok(Envelope::decode(b.as_slice())?))
.collect()
}
pub fn ack(db: &mut Connection, id: &str) -> Result<()> {
let tx = db.transaction()?;
crate::reconcile::archive_events(&tx)?;
tx.execute("DELETE FROM job_events WHERE id=?1", [id])?;
tx.commit()?;
Ok(())
}
pub fn next(db: &Connection) -> Result<Option<JobOffer>> {
next_at(db, chrono::Utc::now())
}
/// Scheduling only; the qualified clock/Sync/permit gate still precedes effects.
pub fn next_at(db: &Connection, now: chrono::DateTime<chrono::Utc>) -> Result<Option<JobOffer>> {
// One device-wide effect at a time; unknown/reserved attempts retain locks.
let busy: i64 = db.query_row("SELECT count(*) FROM job_attempts WHERE state IN ('requesting','running','unknown','awaiting_reboot')", [], |r| r.get(0))?;
if busy != 0 {
return Ok(None);
}
let mut statement = db.prepare("SELECT offer FROM job_attempts WHERE state='accepted' AND cancel_requested=0 ORDER BY rowid")?;
let rows = statement.query_map([], |r| r.get::<_, Vec<u8>>(0))?;
for bytes in rows {
let offer = JobOffer::decode(bytes?.as_slice())?;
let job: JobPayload = serde_json::from_slice(&offer.payload_bytes)?;
if now >= job.not_before || now >= job.start_before {
return Ok(Some(offer));
}
}
Ok(None)
}
pub fn requesting(db: &Connection) -> Result<Option<JobOffer>> {
let bytes: Option<Vec<u8>> = db
.query_row(
"SELECT offer FROM job_attempts WHERE state='requesting' LIMIT 1",
[],
|r| r.get(0),
)
.optional()?;
bytes
.map(|b| Ok(JobOffer::decode(b.as_slice())?))
.transpose()
}
pub fn reserve_request(db: &Connection, offer: &JobOffer) -> Result<()> {
ensure!(db.execute("UPDATE job_attempts SET state='requesting' WHERE job=?1 AND attempt=?2 AND state='accepted' AND cancel_requested=0",
params![offer.job_id,offer.attempt_id])? == 1, "ATTEMPT_NOT_STARTABLE");
Ok(())
}
pub fn transition(db: &Connection, offer: &JobOffer, state: &str, grant: &str) -> Result<u64> {
let previous: String = db.query_row(
"SELECT state FROM job_attempts WHERE job=?1 AND attempt=?2",
params![offer.job_id, offer.attempt_id],
|r| r.get(0),
)?;
let allowed = match previous.as_str() {
"accepted" | "requesting" => matches!(
state,
"running" | "failed" | "cancelled" | "expired" | "unknown"
),
"running" | "verifying" => matches!(
state,
"verifying" | "succeeded" | "failed" | "cancelled" | "unknown" | "awaiting_reboot"
),
// Only a definitive completion of the already-running executor calls
// this reconciliation path. No new effect is started from unknown.
"unknown" | "awaiting_reboot" => matches!(
state,
"succeeded" | "failed" | "cancelled" | "unknown" | "awaiting_reboot"
),
_ => false,
};
ensure!(allowed, "INVALID_LOCAL_STATE_TRANSITION");
let rev: i64 = db.query_row("UPDATE job_attempts SET state=?3,grant_id=?4,revision=revision+1 WHERE job=?1 AND attempt=?2 RETURNING revision",
params![offer.job_id,offer.attempt_id,state,grant], |r| r.get(0))?;
Ok(u64::try_from(rev)?)
}
pub fn result(offer: &JobOffer, revision: u64, grant: &str, outcome: Outcome) -> JobResult {
JobResult {
job_id: offer.job_id.clone(),
attempt_id: offer.attempt_id.clone(),
revision,
state: outcome.state,
grant_id: grant.into(),
stdout: outcome.stdout,
stderr: outcome.stderr,
output_truncated: outcome.output_truncated,
reboot_required: outcome.reboot_required,
exit_code: outcome.exit_code,
evidence_json: outcome.evidence.to_string(),
error_code: outcome.error_code,
}
}
pub fn no_start(state: &str, code: &str) -> Outcome {
Outcome {
state: state.into(),
evidence: serde_json::json!({"not_started":true,"postconditions_passed":false}),
..Outcome::unknown(code)
}
}
pub fn permit_request(offer: &JobOffer, permit: &ExecutionPermit) -> Result<Request> {
Ok(Request {
job_bytes: offer.payload_bytes.clone(),
permit_bytes: permit.payload_bytes.clone(),
signature: permit.signature.clone(),
plan_hash: offer.plan_hash.clone(),
authorization_id: Uuid::parse_str(&offer.authorization_id)?,
})
}
+103
View File
@@ -0,0 +1,103 @@
//! Connection-level ledger rules, with OS path/lock/ACL handling left to adapters.
use crate::auth::{Outcome, Request};
use anyhow::{Result, ensure};
use chrono::{DateTime, Utc};
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload};
use uuid::Uuid;
/// Finite 1 GiB bound for durable agent/helper history. Unexpected page sizes
/// are refused rather than silently multiplying the byte limit. No compaction
/// or tombstone deletion occurs here; SQLITE_FULL must still fail closed.
pub fn bounded_journal_capacity(db: &rusqlite::Connection) -> Result<()> {
let page_size: u32 = db.query_row("PRAGMA page_size", [], |r| r.get(0))?;
ensure!(page_size == 4096, "JOURNAL_PAGE_SIZE_UNSUPPORTED");
let maximum: u32 = db.query_row("PRAGMA max_page_count=262144", [], |r| r.get(0))?;
ensure!(maximum == 262144, "JOURNAL_STORAGE_CAPACITY_BLOCKED");
Ok(())
}
/// The platform adapter must securely open/lock the file before calling this.
/// No file creation, ACL repair or journal reset is performed here.
pub fn initialize_ledger(db: &rusqlite::Connection) -> Result<()> {
bounded_journal_capacity(db)?;
db.execute_batch("PRAGMA synchronous=FULL; PRAGMA journal_mode=DELETE;
CREATE TABLE IF NOT EXISTS consumed(grant_id TEXT PRIMARY KEY, agent TEXT NOT NULL, generation INTEGER NOT NULL,
job TEXT NOT NULL, attempt TEXT NOT NULL, result BLOB, UNIQUE(agent,generation,job,attempt));
CREATE TABLE IF NOT EXISTS execution_evidence(grant_id TEXT PRIMARY KEY, start BLOB NOT NULL, outcome BLOB);")?;
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
ensure!(check == "ok", "JOURNAL_INTEGRITY");
Ok(())
}
pub fn consume(db: &mut rusqlite::Connection, p: &ExecutionPermitPayload) -> Result<()> {
let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
// Unknown effects retain the global device lock, including across restart.
let unresolved: i64 = tx.query_row(
"SELECT count(*) FROM consumed WHERE result IS NULL",
[],
|r| r.get(0),
)?;
ensure!(unresolved == 0, "UNRESOLVED_EFFECT_RESOURCE_LOCKED");
tx.execute(
"INSERT INTO consumed(grant_id,agent,generation,job,attempt) VALUES(?1,?2,?3,?4,?5)",
rusqlite::params![
p.grant_id.to_string(),
p.agent_id.to_string(),
p.enrollment_generation,
p.job_id.to_string(),
p.attempt_id.to_string()
],
)?;
tx.commit()?;
Ok(())
}
pub fn finish(
db: &rusqlite::Connection,
p: &ExecutionPermitPayload,
outcome: &Outcome,
) -> Result<()> {
db.execute(
"UPDATE execution_evidence SET outcome=?2 WHERE grant_id=?1",
rusqlite::params![p.grant_id.to_string(), serde_json::to_vec(outcome)?],
)?;
// Unknown / awaiting reboot keep the resource reserved until a real sync
// protocol exists. Never unlock on a process exit or a network reconnect.
if outcome.state != "unknown" && outcome.state != "awaiting_reboot" {
ensure!(
db.execute(
"UPDATE consumed SET result=?2 WHERE grant_id=?1 AND result IS NULL",
rusqlite::params![p.grant_id.to_string(), serde_json::to_vec(outcome)?]
)? == 1,
"CONSUMPTION_NOT_FOUND"
);
}
Ok(())
}
/// Persist the original boot and exact signed request BEFORE any reboot/effect.
/// Awaiting/unknown outcomes never release consumed.result's resource lock.
pub fn save_start(
db: &rusqlite::Connection,
permit: &ExecutionPermitPayload,
request: &Request,
previous_boot_id: Uuid,
recorded_at: DateTime<Utc>,
) -> Result<()> {
let job: JobPayload = serde_json::from_slice(&request.job_bytes)?;
ensure!(!previous_boot_id.is_nil(), "ORIGINAL_BOOT_MISSING");
let deadline = match job.action {
rmm_domain::jobs::Action::Reboot {
reconnect_timeout_seconds,
..
} => Some(recorded_at + chrono::Duration::seconds(reconnect_timeout_seconds.into())),
_ => None,
};
let evidence = serde_json::json!({"previous_boot_id":previous_boot_id.to_string(),
"reserved_at":recorded_at,"reconnect_deadline":deadline,"request":request,
"reauthentication_required":true,"postconditions_passed":false});
db.execute(
"INSERT INTO execution_evidence(grant_id,start) VALUES(?1,?2)",
rusqlite::params![permit.grant_id.to_string(), serde_json::to_vec(&evidence)?],
)?;
Ok(())
}
+9
View File
@@ -0,0 +1,9 @@
//! Platform-neutral signed authorization, durable job state and reconciliation.
//! This crate performs no OS effects, enrollment, ACL changes or clock bootstrap.
//! Callers must authenticate their transport, protect/lock their own journals and
//! supply a qualified clock. A successful signature is never UI approval itself.
pub mod auth;
pub mod crypto;
pub mod jobs;
pub mod ledger;
pub mod reconcile;
File diff suppressed because it is too large Load Diff