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
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "rmm-agent-core"
version.workspace = true
edition.workspace = true
license.workspace = true
[features]
default = []
openssl-verifier = ["dep:openssl"]
[dependencies]
anyhow.workspace = true
chrono.workspace = true
hex.workspace = true
prost.workspace = true
serde.workspace = true
serde_json.workspace = true
uuid.workspace = true
rmm-domain = { path = "../domain" }
rmm-protocol = { path = "../protocol" }
rusqlite = { version = "0.32.1", features = ["bundled"] }
ed25519-dalek = "=2.2.0"
[target.'cfg(unix)'.dependencies]
openssl = { workspace = true, optional = true }
[target.'cfg(unix)'.dev-dependencies]
openssl.workspace = true
+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
+292
View File
@@ -0,0 +1,292 @@
//! Signature/codec/consumption contracts, with no transport or OS execution.
use chrono::{DateTime, Duration, Utc};
use ed25519_dalek::{Signer, SigningKey};
#[cfg(unix)]
use rmm_agent_core::crypto::{DalekVerifier, Ed25519Verifier};
use rmm_agent_core::{
auth::{Binding, Outcome, Request},
jobs, ledger,
};
use rmm_domain::jobs::{Action, ExecutionPermitPayload, JobPayload, encode, hash};
use rmm_protocol::JobOffer;
use rusqlite::Connection;
use uuid::Uuid;
fn fixture() -> (Binding, Request, ExecutionPermitPayload, DateTime<Utc>) {
let key = SigningKey::from_bytes(&[9; 32]);
let id = Uuid::from_u128(1);
let now = DateTime::parse_from_rfc3339("2026-11-14T00:00:00Z")
.unwrap()
.with_timezone(&Utc);
let binding = Binding {
tenant_id: id,
asset_id: Uuid::from_u128(2),
agent_id: Uuid::from_u128(3),
enrollment_generation: 2,
assignment_version: 4,
public_key_hex: hex::encode(key.verifying_key().as_bytes()),
};
let job = JobPayload {
schema_version: 1,
tenant_id: binding.tenant_id,
asset_id: binding.asset_id,
agent_id: binding.agent_id,
enrollment_generation: 2,
assignment_version: 4,
job_id: Uuid::from_u128(5),
attempt_id: Uuid::from_u128(6),
action: Action::RunScript {
interpreter: "posix_sh".into(),
script_utf8: "printf 'Hello\\n'\n".into(),
arguments: vec![],
expected_stdout: Some("Hello\n".into()),
},
execution_identity: "agent_service".into(),
not_before: now - Duration::minutes(1),
start_before: now + Duration::minutes(5),
max_runtime_seconds: 10,
max_output_bytes: 4096,
};
let job_bytes = encode(&job).unwrap();
let permit = ExecutionPermitPayload {
domain: "rmm.execution-permit".into(),
schema_version: 1,
grant_id: Uuid::from_u128(7),
authorization_id: Uuid::from_u128(8),
tenant_id: binding.tenant_id,
asset_id: binding.asset_id,
agent_id: binding.agent_id,
enrollment_generation: 2,
assignment_version: 4,
job_id: job.job_id,
attempt_id: job.attempt_id,
plan_hash: hash(b"immutable approved plan"),
job_payload_hash: hash(&job_bytes),
action: job.action.name().into(),
execution_identity: job.execution_identity,
max_runtime_seconds: 10,
not_before: now - Duration::seconds(1),
start_before: now + Duration::seconds(59),
key_id: hash(key.verifying_key().as_bytes()),
};
let permit_bytes = encode(&permit).unwrap();
let signature = key.sign(&permit_bytes).to_bytes().to_vec();
let request = Request {
job_bytes,
permit_bytes,
signature,
plan_hash: permit.plan_hash.clone(),
authorization_id: permit.authorization_id,
};
(binding, request, permit, now)
}
#[test]
fn historical_request_and_binding_codecs_keep_field_order_arrays_and_strictness() {
let request = Request {
job_bytes: vec![0, 255],
permit_bytes: vec![1],
signature: vec![2],
plan_hash: "ab".into(),
authorization_id: Uuid::nil(),
};
let expected = r#"{"job_bytes":[0,255],"permit_bytes":[1],"signature":[2],"plan_hash":"ab","authorization_id":"00000000-0000-0000-0000-000000000000"}"#;
assert_eq!(serde_json::to_vec(&request).unwrap(), expected.as_bytes());
let parsed: Request = serde_json::from_str(expected).unwrap();
assert_eq!(serde_json::to_string(&parsed).unwrap(), expected);
assert!(
serde_json::from_str::<Request>(
&expected.replace("\"job_bytes\"", "\"extra\":0,\"job_bytes\"")
)
.is_err()
);
let binding = Binding {
tenant_id: Uuid::nil(),
asset_id: Uuid::nil(),
agent_id: Uuid::nil(),
enrollment_generation: 1,
assignment_version: 2,
public_key_hex: "key".into(),
};
assert_eq!(
serde_json::to_string(&binding).unwrap(),
r#"{"tenant_id":"00000000-0000-0000-0000-000000000000","asset_id":"00000000-0000-0000-0000-000000000000","agent_id":"00000000-0000-0000-0000-000000000000","enrollment_generation":1,"assignment_version":2,"public_key_hex":"key"}"#
);
}
#[test]
fn exact_permit_bytes_time_and_all_identity_hash_bindings_are_required() {
let (binding, request, permit, now) = fixture();
assert_eq!(binding.verify(&request, now).unwrap().1, permit);
assert!(binding.verify(&request, permit.not_before).is_ok());
assert!(
binding
.verify(&request, permit.not_before - Duration::nanoseconds(1))
.is_err()
);
assert!(binding.verify(&request, permit.start_before).is_err());
let key = SigningKey::from_bytes(&[9; 32]);
let value = serde_json::to_value(&permit).unwrap();
for (field, replacement) in [
("domain", serde_json::json!("rmm.reconciliation-decision")),
("schema_version", serde_json::json!(2)),
("tenant_id", serde_json::json!(Uuid::new_v4())),
("asset_id", serde_json::json!(Uuid::new_v4())),
("agent_id", serde_json::json!(Uuid::new_v4())),
("enrollment_generation", serde_json::json!(3)),
("assignment_version", serde_json::json!(5)),
("job_id", serde_json::json!(Uuid::new_v4())),
("attempt_id", serde_json::json!(Uuid::new_v4())),
("authorization_id", serde_json::json!(Uuid::new_v4())),
("plan_hash", serde_json::json!(hash(b"other plan"))),
(
"job_payload_hash",
serde_json::json!(hash(b"different bytes")),
),
("action", serde_json::json!("reboot")),
("execution_identity", serde_json::json!("root")),
("max_runtime_seconds", serde_json::json!(11)),
("key_id", serde_json::json!(hash(b"otherkey"))),
("grant_id", serde_json::json!(Uuid::nil())),
(
"start_before",
serde_json::json!(now + Duration::seconds(60)),
),
] {
let mut value = value.clone();
value[field] = replacement;
let changed: ExecutionPermitPayload = serde_json::from_value(value).unwrap();
let mut changed_request = request.clone();
changed_request.permit_bytes = encode(&changed).unwrap();
changed_request.signature = key.sign(&changed_request.permit_bytes).to_bytes().to_vec();
assert!(binding.verify(&changed_request, now).is_err(), "{field}");
}
let mut changed = request.clone();
changed.job_bytes.push(b' ');
assert!(binding.verify(&changed, now).is_err());
let mut changed = request.clone();
changed.signature[0] ^= 1;
assert!(binding.verify(&changed, now).is_err());
let mut changed = request;
changed.signature.truncate(63);
assert!(binding.verify(&changed, now).is_err());
}
#[cfg(unix)]
#[test]
fn openssl_and_portable_ed25519_agree_on_current_keys_bytes_and_tampering() {
use openssl::{
pkey::PKey,
sign::{Signer as OpenSigner, Verifier},
};
let key = PKey::generate_ed25519().unwrap();
let public = key.raw_public_key().unwrap();
let bytes = b"exact stored signed payload\r\n";
let signature = OpenSigner::new_without_digest(&key)
.unwrap()
.sign_oneshot_to_vec(bytes)
.unwrap();
let verify_openssl = |message: &[u8], signature: &[u8]| {
Verifier::new_without_digest(&key)
.unwrap()
.verify_oneshot(signature, message)
.unwrap_or(false)
};
for message in [bytes.as_slice(), b"exact stored signed payload\n", b""] {
assert_eq!(
DalekVerifier.verify(&public, message, &signature).unwrap(),
verify_openssl(message, &signature)
);
}
let mut changed = signature.clone();
changed[0] ^= 1;
for signature in [&signature[..], &changed[..], &signature[..63]] {
assert_eq!(
DalekVerifier.verify(&public, bytes, signature).unwrap(),
verify_openssl(bytes, signature)
);
}
assert!(!DalekVerifier.verify(&[0; 32], bytes, &[0; 64]).unwrap());
assert!(!DalekVerifier.verify(&[0; 31], bytes, &signature).unwrap());
// Reverse direction uses raw Ed25519, never prehashes the message.
let signing = SigningKey::from_bytes(&[11; 32]);
let p = PKey::public_key_from_raw_bytes(
signing.verifying_key().as_bytes(),
openssl::pkey::Id::ED25519,
)
.unwrap();
assert!(
Verifier::new_without_digest(&p)
.unwrap()
.verify_oneshot(&signing.sign(bytes).to_bytes(), bytes)
.unwrap()
);
}
#[test]
fn consumed_attempt_and_unknown_lock_survive_reopen_without_reexecution() {
let (_, request, permit, now) = fixture();
let path = std::env::temp_dir().join(format!("rmm-core-ledger-{}", Uuid::new_v4()));
{
let mut db = Connection::open(&path).unwrap();
ledger::initialize_ledger(&db).unwrap();
ledger::consume(&mut db, &permit).unwrap();
ledger::save_start(&db, &permit, &request, Uuid::from_u128(9), now).unwrap();
ledger::finish(&db, &permit, &Outcome::unknown("EFFECT_UNKNOWN")).unwrap();
}
{
let mut db = Connection::open(&path).unwrap();
ledger::initialize_ledger(&db).unwrap();
assert!(ledger::consume(&mut db, &permit).is_err());
let mut replacement = permit.clone();
replacement.grant_id = Uuid::new_v4();
assert!(ledger::consume(&mut db, &replacement).is_err());
assert_eq!(
db.query_row(
"SELECT count(*) FROM consumed WHERE result IS NULL",
[],
|r| r.get::<_, u32>(0)
)
.unwrap(),
1
);
assert_eq!(
db.query_row("PRAGMA max_page_count", [], |r| r.get::<_, u32>(0))
.unwrap(),
262144
);
}
std::fs::remove_file(path).unwrap();
}
#[test]
fn portable_acceptance_requires_platform_capability_and_exact_redelivery() {
let (binding, request, permit, _) = fixture();
let offer = JobOffer {
job_id: permit.job_id.to_string(),
attempt_id: permit.attempt_id.to_string(),
payload_bytes: request.job_bytes,
job_payload_hash: permit.job_payload_hash,
plan_hash: permit.plan_hash,
authorization_id: permit.authorization_id.to_string(),
};
let db = Connection::open_in_memory().unwrap();
db.execute_batch("CREATE TABLE job_attempts(job TEXT,attempt TEXT,offer BLOB,state TEXT,revision INTEGER DEFAULT 0,grant_id TEXT DEFAULT '',cancel_requested INTEGER DEFAULT 0,PRIMARY KEY(job,attempt))").unwrap();
assert!(jobs::accept(&db, &binding, &offer, |_| false).is_err());
assert_eq!(
db.query_row("SELECT count(*) FROM job_attempts", [], |r| r
.get::<_, u32>(0))
.unwrap(),
0
);
assert!(jobs::accept(&db, &binding, &offer, |_| true).unwrap());
assert!(!jobs::accept(&db, &binding, &offer, |_| true).unwrap());
let mut changed = offer.clone();
changed.authorization_id = Uuid::new_v4().to_string();
assert!(jobs::accept(&db, &binding, &changed, |_| true).is_err());
jobs::reserve_request(&db, &offer).unwrap();
assert!(jobs::reserve_request(&db, &offer).is_err());
assert_eq!(jobs::transition(&db, &offer, "unknown", "").unwrap(), 1);
assert!(jobs::next(&db).unwrap().is_none());
assert!(jobs::transition(&db, &offer, "running", "").is_err());
}
File diff suppressed because it is too large Load Diff