Share signed job core and verify native Linux then Windows contracts
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -11,10 +11,7 @@ pub mod reconcile;
|
||||
mod tests;
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use chrono::{DateTime, Utc};
|
||||
use openssl::{
|
||||
pkey::{Id, PKey},
|
||||
sign::Verifier,
|
||||
};
|
||||
use openssl::pkey::{Id, PKey};
|
||||
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload, hash};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{fs, os::unix::fs::MetadataExt, path::Path};
|
||||
@@ -50,130 +47,7 @@ impl SigningKey {
|
||||
}
|
||||
}
|
||||
|
||||
#[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,
|
||||
}
|
||||
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)> {
|
||||
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");
|
||||
let key = PKey::public_key_from_raw_bytes(&raw, Id::ED25519)?;
|
||||
ensure!(
|
||||
Verifier::new_without_digest(&key)?
|
||||
.verify_oneshot(&request.signature, &request.permit_bytes)?,
|
||||
"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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub use rmm_agent_core::auth::{Binding, Outcome, Request};
|
||||
|
||||
/// Config and journal directories must already be bootstrapped by the intended
|
||||
/// owner; do not silently chmod a hostile existing path or follow symlinks.
|
||||
@@ -204,16 +78,7 @@ pub fn lock_state(dir: &Path, uid: u32) -> Result<fs::File> {
|
||||
f.try_lock_exclusive()?;
|
||||
Ok(f)
|
||||
}
|
||||
/// 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(())
|
||||
}
|
||||
pub use rmm_agent_core::ledger::{bounded_journal_capacity, consume, finish};
|
||||
|
||||
pub fn open_ledger(dir: &Path, uid: u32) -> Result<rusqlite::Connection> {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
@@ -229,85 +94,23 @@ pub fn open_ledger(dir: &Path, uid: u32) -> Result<rusqlite::Connection> {
|
||||
f.sync_all()?;
|
||||
private_path(&path, uid, false)?;
|
||||
let db = rusqlite::Connection::open(path)?;
|
||||
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");
|
||||
rmm_agent_core::ledger::initialize_ledger(&db)?;
|
||||
fs::File::open(dir)?.sync_all()?;
|
||||
Ok(db)
|
||||
}
|
||||
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.
|
||||
/// Persist the same exact request/boot/time evidence through the shared ledger.
|
||||
pub fn save_start(
|
||||
db: &rusqlite::Connection,
|
||||
permit: &ExecutionPermitPayload,
|
||||
request: &Request,
|
||||
) -> Result<()> {
|
||||
let job: JobPayload = serde_json::from_slice(&request.job_bytes)?;
|
||||
let recorded_at = Utc::now();
|
||||
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":rmm_agent_linux::boot_id()?,
|
||||
"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(())
|
||||
rmm_agent_core::ledger::save_start(
|
||||
db,
|
||||
permit,
|
||||
request,
|
||||
Uuid::parse_str(&rmm_agent_linux::boot_id()?)?,
|
||||
Utc::now(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn script(job: &JobPayload) -> Result<Outcome> {
|
||||
|
||||
Reference in New Issue
Block a user