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:
@@ -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
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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)?,
|
||||
})
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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
@@ -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
@@ -20,10 +20,14 @@ tokio.workspace = true
|
||||
tokio-tungstenite.workspace = true
|
||||
uuid.workspace = true
|
||||
rmm-domain = { path = "../domain" }
|
||||
rmm-agent-core = { path = "../agent-core" }
|
||||
rmm-protocol = { path = "../protocol" }
|
||||
rusqlite = { version = "0.32.1", features = ["bundled"] }
|
||||
fs2 = "0.4.3"
|
||||
rcgen = { version = "=0.14.10", default-features = false, features = ["crypto", "ring", "pem"] }
|
||||
|
||||
[build-dependencies]
|
||||
cc = "=1.11.1"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] }
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] }
|
||||
|
||||
@@ -5,6 +5,7 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
default-run = "rmm-agent"
|
||||
[dependencies]
|
||||
rmm-agent-core = { path = "../agent-core", features = ["openssl-verifier"] }
|
||||
anyhow.workspace = true
|
||||
chrono.workspace = true
|
||||
futures-util.workspace = true
|
||||
|
||||
+14
-248
@@ -1,9 +1,13 @@
|
||||
use anyhow::{Result, ensure};
|
||||
#[cfg(test)]
|
||||
use prost::Message;
|
||||
use rmm_domain::jobs::{Action, JobPayload, hash};
|
||||
use rmm_privileged_helper::{Binding, Outcome, Request};
|
||||
#[cfg(test)]
|
||||
use rmm_domain::jobs::hash;
|
||||
use rmm_domain::jobs::{Action, JobPayload};
|
||||
use rmm_privileged_helper::{Binding, Outcome};
|
||||
use rmm_protocol::*;
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use rusqlite::Connection;
|
||||
#[cfg(test)]
|
||||
use uuid::Uuid;
|
||||
|
||||
pub fn supported(job: &JobPayload) -> bool {
|
||||
@@ -53,242 +57,14 @@ fn supported_as(job: &JobPayload, uid: u32, helper_configured: bool) -> bool {
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
pub use rmm_agent_core::jobs::{
|
||||
ack, event, events, interrupted, interrupted_request, next, no_start, permit_request,
|
||||
requesting, reserve_request, result, transition,
|
||||
};
|
||||
pub fn accept(db: &Connection, binding: &Binding, offer: &JobOffer) -> 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_with_binding(&job, Some(binding)),
|
||||
"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)>> {
|
||||
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(&request, permit.not_before)?;
|
||||
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>> {
|
||||
// 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))?;
|
||||
let now = chrono::Utc::now();
|
||||
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)
|
||||
}
|
||||
rmm_agent_core::jobs::accept(db, binding, offer, |job| {
|
||||
supported_with_binding(job, Some(binding))
|
||||
})
|
||||
}
|
||||
pub fn execute(job: &JobPayload) -> Outcome {
|
||||
let result = match &job.action {
|
||||
@@ -397,16 +173,6 @@ fn query_logs(job: &JobPayload) -> Result<Outcome> {
|
||||
},
|
||||
})
|
||||
}
|
||||
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)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// With no backend SyncResponse contract, a reconnect/restart cannot prove an
|
||||
/// earlier reservation never started. Telemetry and evidence replay continue;
|
||||
/// all new effects stop. Do not paper over this with a new start request.
|
||||
|
||||
+4
-1212
File diff suppressed because it is too large
Load Diff
+121
-2
@@ -100,7 +100,10 @@ impl Action {
|
||||
arguments,
|
||||
expected_stdout,
|
||||
} => {
|
||||
matches!(interpreter.as_str(), "posix_sh" | "bash")
|
||||
matches!(interpreter.as_str(), "posix_sh" | "bash" | "powershell")
|
||||
&& (interpreter != "powershell"
|
||||
|| script_utf8.is_ascii()
|
||||
|| script_utf8.starts_with('\u{feff}'))
|
||||
&& !script_utf8.is_empty()
|
||||
&& script_utf8.len() <= 32768
|
||||
&& !script_utf8.contains('\0')
|
||||
@@ -110,7 +113,9 @@ impl Action {
|
||||
.all(|a| a.len() <= 4096 && !a.contains('\0'))
|
||||
&& expected_stdout.as_ref().is_none_or(|s| s.len() <= 65536)
|
||||
}
|
||||
Self::RefreshInventory { scope } => scope == "linux.base",
|
||||
Self::RefreshInventory { scope } => {
|
||||
matches!(scope.as_str(), "linux.base" | "windows.base")
|
||||
}
|
||||
Self::QueryLogs {
|
||||
unit: u,
|
||||
since,
|
||||
@@ -193,6 +198,45 @@ impl Action {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Interpreter identity is part of the immutable action, never inferred at execution.
|
||||
pub fn script_platform(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::RunScript { interpreter, .. } => match interpreter.as_str() {
|
||||
"posix_sh" | "bash" => Some("linux"),
|
||||
"powershell" => Some("windows"),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Shared plan/revalidation/start gate. Passive Windows never implies job support.
|
||||
pub fn available_for(&self, identity: &str, capabilities: &[String]) -> bool {
|
||||
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
|
||||
if !has(self.name()) {
|
||||
return false;
|
||||
}
|
||||
match self {
|
||||
Self::RunScript { interpreter, .. } if interpreter == "powershell" => {
|
||||
identity == "agent_service"
|
||||
&& has("windows.base/1")
|
||||
&& !has("linux.base/1")
|
||||
&& has("rmm.sync.v1")
|
||||
&& has("script.powershell/1")
|
||||
}
|
||||
Self::RunScript { .. } => {
|
||||
self.script_platform() == Some("linux")
|
||||
&& has("linux.base/1")
|
||||
&& !has("windows.base/1")
|
||||
}
|
||||
Self::RefreshInventory { scope } => {
|
||||
(identity == "agent_service" || scope == "linux.base")
|
||||
&& has(&format!("{scope}/1"))
|
||||
&& !(has("linux.base/1") && has("windows.base/1"))
|
||||
&& (scope != "windows.base" || has("rmm.sync.v1"))
|
||||
}
|
||||
_ => !has("windows.base/1"), // Windows adapters are separately qualified.
|
||||
}
|
||||
}
|
||||
pub fn resource(&self) -> &'static str {
|
||||
match self {
|
||||
Self::EnsurePackage { .. }
|
||||
@@ -387,6 +431,81 @@ impl JobState {
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn windows_interpreter_and_capability_contract() {
|
||||
let mut action = Action::RunScript {
|
||||
interpreter: "powershell".into(),
|
||||
script_utf8: "Write-Output 'Hello'\r\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("Hello\r\n".into()),
|
||||
};
|
||||
let caps: Vec<String> = [
|
||||
"windows.base/1",
|
||||
"rmm.sync.v1",
|
||||
"run_script",
|
||||
"script.powershell/1",
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
assert!(action.validate());
|
||||
assert!(action.available_for("agent_service", &caps));
|
||||
for missing in 0..caps.len() {
|
||||
let mut short = caps.clone();
|
||||
short.remove(missing);
|
||||
assert!(!action.available_for("agent_service", &short));
|
||||
}
|
||||
assert!(!action.available_for("root", &caps));
|
||||
assert!(!action.available_for("SYSTEM", &caps));
|
||||
assert!(!action.available_for(
|
||||
"agent_service",
|
||||
&["linux.base/1".into(), "run_script".into()]
|
||||
));
|
||||
let mut both = caps.clone();
|
||||
both.push("linux.base/1".into());
|
||||
assert!(!action.available_for("agent_service", &both));
|
||||
if let Action::RunScript {
|
||||
interpreter,
|
||||
script_utf8,
|
||||
..
|
||||
} = &mut action
|
||||
{
|
||||
*script_utf8 = "Write-Output 'é'".into();
|
||||
assert!(interpreter == "powershell");
|
||||
}
|
||||
assert!(!action.validate());
|
||||
if let Action::RunScript { script_utf8, .. } = &mut action {
|
||||
*script_utf8 = "\u{feff}Write-Output 'é'\r\n".into();
|
||||
}
|
||||
assert!(action.validate());
|
||||
let bytes = encode(&action).unwrap();
|
||||
assert_eq!(serde_json::from_slice::<Action>(&bytes).unwrap(), action);
|
||||
if let Action::RunScript { interpreter, .. } = &mut action {
|
||||
*interpreter = "pwsh".into();
|
||||
}
|
||||
assert!(!action.validate());
|
||||
assert!(!action.available_for("agent_service", &caps));
|
||||
let refresh = Action::RefreshInventory {
|
||||
scope: "windows.base".into(),
|
||||
};
|
||||
assert!(refresh.validate());
|
||||
assert!(refresh.available_for(
|
||||
"agent_service",
|
||||
&[
|
||||
"windows.base/1".into(),
|
||||
"rmm.sync.v1".into(),
|
||||
"refresh_inventory".into()
|
||||
]
|
||||
));
|
||||
assert!(!refresh.available_for(
|
||||
"root",
|
||||
&[
|
||||
"windows.base/1".into(),
|
||||
"rmm.sync.v1".into(),
|
||||
"refresh_inventory".into()
|
||||
]
|
||||
));
|
||||
}
|
||||
#[test]
|
||||
fn codec_golden_and_exact_script_bytes() {
|
||||
let a = Action::RunScript {
|
||||
interpreter: "posix_sh".into(),
|
||||
|
||||
@@ -5,6 +5,7 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
rmm-agent-core = { path = "../agent-core", features = ["openssl-verifier"] }
|
||||
anyhow.workspace = true
|
||||
chrono.workspace = true
|
||||
hex.workspace = true
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -262,11 +262,11 @@ pub async fn permit(
|
||||
};
|
||||
let payload: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
|
||||
let plan: PlanPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("plan_payload"))?;
|
||||
let capabilities: Value = row.get("capabilities");
|
||||
let capabilities: Vec<String> = serde_json::from_value(row.get("capabilities"))?;
|
||||
if row.get::<Uuid, _>("bound_asset") != payload.asset_id
|
||||
|| !capabilities
|
||||
.as_array()
|
||||
.is_some_and(|c| c.iter().any(|v| v.as_str() == Some(payload.action.name())))
|
||||
|| !payload
|
||||
.action
|
||||
.available_for(&payload.execution_identity, &capabilities)
|
||||
|| hash(&row.get::<Vec<u8>, _>("plan_payload")) != row.get::<String, _>("plan_hash")
|
||||
|| !plan.jobs.iter().any(|j| {
|
||||
j.payload.job_id == payload.job_id
|
||||
@@ -491,11 +491,20 @@ pub async fn next(
|
||||
if let Some(r)=sqlx::query("SELECT job_id,attempt_id FROM jobs WHERE agent_id=$1 AND cancel_requested AND state IN ('accepted','running','verifying','awaiting_reboot') ORDER BY job_id LIMIT 1").bind(agent).fetch_optional(&mut *tx).await?{
|
||||
tx.commit().await?;return Ok(Some(Payload::CancelRequest(CancelRequest{job_id:r.get::<Uuid,_>("job_id").to_string(),attempt_id:r.get::<Uuid,_>("attempt_id").to_string(),reason:"operator_cancel_requested".into()})))
|
||||
}
|
||||
let row=sqlx::query("SELECT j.job_id,j.attempt_id,j.payload,j.payload_hash,a.authorization_id,p.plan_hash FROM outbox b JOIN jobs j USING(tenant_id,job_id,attempt_id) JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=j.tenant_id AND p.plan_id=r.plan_id JOIN tenants t ON t.tenant_id=j.tenant_id WHERE j.agent_id=$1 AND j.state='queued' AND NOT j.cancel_requested AND NOT t.changes_stopped AND a.revoked_at IS NULL AND r.approval_state='approved' AND p.expires_at>now() AND b.acknowledged_at IS NULL AND (b.lease_until IS NULL OR b.lease_until<now()) ORDER BY j.job_id FOR UPDATE OF b SKIP LOCKED LIMIT 1").bind(agent).fetch_optional(&mut *tx).await?;
|
||||
let row=sqlx::query("SELECT j.job_id,j.attempt_id,j.payload,j.payload_hash,a.authorization_id,p.plan_hash,i.capabilities FROM outbox b JOIN jobs j USING(tenant_id,job_id,attempt_id) JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=j.tenant_id AND p.plan_id=r.plan_id JOIN tenants t ON t.tenant_id=j.tenant_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.state='queued' AND NOT j.cancel_requested AND NOT t.changes_stopped AND a.revoked_at IS NULL AND r.approval_state='approved' AND p.expires_at>now() AND b.acknowledged_at IS NULL AND (b.lease_until IS NULL OR b.lease_until<now()) ORDER BY j.job_id FOR UPDATE OF b SKIP LOCKED LIMIT 1").bind(agent).fetch_optional(&mut *tx).await?;
|
||||
let Some(row) = row else {
|
||||
tx.commit().await?;
|
||||
return Ok(None);
|
||||
};
|
||||
let payload: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
|
||||
let caps: Vec<String> = serde_json::from_value(row.get("capabilities"))?;
|
||||
if !payload
|
||||
.action
|
||||
.available_for(&payload.execution_identity, &caps)
|
||||
{
|
||||
tx.commit().await?;
|
||||
return Ok(None);
|
||||
}
|
||||
sqlx::query("UPDATE outbox SET lease_until=now()+interval '30 seconds' WHERE job_id=$1")
|
||||
.bind(row.get::<Uuid, _>("job_id"))
|
||||
.execute(&mut *tx)
|
||||
|
||||
+303
-25
@@ -107,6 +107,8 @@ pub struct Rollout {
|
||||
pub struct PlanInput {
|
||||
pub targets: Targets,
|
||||
pub action: Action,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub script_variants: Vec<Variant>,
|
||||
pub execution_identity: String,
|
||||
pub schedule: Schedule,
|
||||
pub max_runtime_seconds: u32,
|
||||
@@ -144,7 +146,7 @@ struct WebSchedule {
|
||||
}
|
||||
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Variant {
|
||||
pub struct Variant {
|
||||
os_family: String,
|
||||
interpreter: String,
|
||||
encoding: String,
|
||||
@@ -200,21 +202,17 @@ impl PlanRequest {
|
||||
|value: Option<String>| value.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
let action = match w.action.as_str() {
|
||||
"run_script" => {
|
||||
let mut variants = p
|
||||
let variants = p
|
||||
.variants
|
||||
.as_ref()
|
||||
.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"))?;
|
||||
if variants.len() != 1 {
|
||||
return Err(fail("AMBIGUOUS_TARGET"));
|
||||
}
|
||||
let v = variants.remove(0);
|
||||
if v.os_family != "linux" || v.encoding != "utf-8" {
|
||||
return Err(fail("UNSUPPORTED_CAPABILITY"));
|
||||
}
|
||||
validate_variants(variants)?;
|
||||
let v = &variants[0];
|
||||
Action::RunScript {
|
||||
interpreter: v.interpreter,
|
||||
script_utf8: v.script_utf8,
|
||||
arguments: p.arguments.unwrap_or_default(),
|
||||
expected_stdout: p.expected_stdout,
|
||||
interpreter: v.interpreter.clone(),
|
||||
script_utf8: v.script_utf8.clone(),
|
||||
arguments: p.arguments.clone().unwrap_or_default(),
|
||||
expected_stdout: p.expected_stdout.clone(),
|
||||
}
|
||||
}
|
||||
"refresh_inventory" => Action::RefreshInventory {
|
||||
@@ -287,6 +285,7 @@ impl PlanRequest {
|
||||
Ok(PlanInput {
|
||||
targets: w.targets,
|
||||
action,
|
||||
script_variants: p.variants.unwrap_or_default(),
|
||||
execution_identity: p.execution_identity,
|
||||
schedule: Schedule {
|
||||
not_before: w.schedule.not_before,
|
||||
@@ -300,6 +299,71 @@ impl PlanRequest {
|
||||
})
|
||||
}
|
||||
}
|
||||
fn validate_variants(variants: &[Variant]) -> Result<()> {
|
||||
if variants.is_empty() || variants.len() > 2 {
|
||||
return Err(fail("AMBIGUOUS_TARGET"));
|
||||
}
|
||||
let mut platforms = std::collections::HashSet::new();
|
||||
for v in variants {
|
||||
let action = Action::RunScript {
|
||||
interpreter: v.interpreter.clone(),
|
||||
script_utf8: v.script_utf8.clone(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
};
|
||||
if v.encoding != "utf-8"
|
||||
|| action.script_platform() != Some(v.os_family.as_str())
|
||||
|| !action.validate()
|
||||
{
|
||||
return Err(fail("UNSUPPORTED_CAPABILITY"));
|
||||
}
|
||||
if !platforms.insert(v.os_family.as_str()) {
|
||||
return Err(fail("AMBIGUOUS_TARGET"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn capabilities(value: Value) -> Result<Vec<String>> {
|
||||
serde_json::from_value(value).map_err(|_| fail("UNSUPPORTED_CAPABILITY"))
|
||||
}
|
||||
fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
|
||||
if input.script_variants.is_empty() {
|
||||
return Ok(input.action.clone());
|
||||
}
|
||||
validate_variants(&input.script_variants)?;
|
||||
let Action::RunScript {
|
||||
interpreter,
|
||||
script_utf8,
|
||||
arguments,
|
||||
expected_stdout,
|
||||
} = &input.action
|
||||
else {
|
||||
return Err(fail("VALIDATION_ERROR"));
|
||||
};
|
||||
let first = &input.script_variants[0];
|
||||
if interpreter != &first.interpreter || script_utf8 != &first.script_utf8 {
|
||||
return Err(fail("VALIDATION_ERROR"));
|
||||
}
|
||||
let platform = match (
|
||||
caps.iter().any(|c| c == "linux.base/1"),
|
||||
caps.iter().any(|c| c == "windows.base/1"),
|
||||
) {
|
||||
(true, false) => "linux",
|
||||
(false, true) => "windows",
|
||||
_ => return Err(fail("UNSUPPORTED_CAPABILITY")),
|
||||
};
|
||||
let v = input
|
||||
.script_variants
|
||||
.iter()
|
||||
.find(|v| v.os_family == platform)
|
||||
.ok_or_else(|| fail("UNSUPPORTED_CAPABILITY"))?;
|
||||
Ok(Action::RunScript {
|
||||
interpreter: v.interpreter.clone(),
|
||||
script_utf8: v.script_utf8.clone(),
|
||||
arguments: arguments.clone(),
|
||||
expected_stdout: expected_stdout.clone(),
|
||||
})
|
||||
}
|
||||
async fn policy(tx: &mut Transaction<'_, Postgres>) -> Result<()> {
|
||||
let stopped: bool = sqlx::query_scalar("SELECT changes_stopped FROM tenants")
|
||||
.fetch_one(&mut **tx)
|
||||
@@ -353,7 +417,7 @@ pub async fn plan(
|
||||
if matches!(input.action, Action::Reboot { .. }) && input.rollout.max_parallel != 1 {
|
||||
return Err(fail("POLICY_DENIED"));
|
||||
}
|
||||
let mut ids = input.targets.asset_ids;
|
||||
let mut ids = input.targets.asset_ids.clone();
|
||||
ids.sort();
|
||||
ids.dedup();
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
||||
@@ -384,11 +448,9 @@ pub async fn plan(
|
||||
}));
|
||||
}
|
||||
let row = &rows[0];
|
||||
let caps: Value = row.get("capabilities");
|
||||
if !caps
|
||||
.as_array()
|
||||
.is_some_and(|c| c.iter().any(|v| v.as_str() == Some(input.action.name())))
|
||||
{
|
||||
let caps = capabilities(row.get("capabilities"))?;
|
||||
let action = target_action(&input, &caps)?;
|
||||
if !action.available_for(&input.execution_identity, &caps) {
|
||||
return Err(fail("UNSUPPORTED_CAPABILITY"));
|
||||
}
|
||||
let payload = JobPayload {
|
||||
@@ -400,7 +462,7 @@ pub async fn plan(
|
||||
assignment_version: row.get::<i64, _>("assignment_version") as u64,
|
||||
job_id: Uuid::new_v4(),
|
||||
attempt_id: Uuid::new_v4(),
|
||||
action: input.action.clone(),
|
||||
action,
|
||||
execution_identity: input.execution_identity.clone(),
|
||||
not_before: input.schedule.not_before,
|
||||
start_before: input.schedule.start_before,
|
||||
@@ -530,13 +592,19 @@ async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Resu
|
||||
{
|
||||
return Err(fail("AUTHORIZATION_REVOKED"));
|
||||
}
|
||||
let caps: Value = r.get("capabilities");
|
||||
if !caps.as_array().is_some_and(|c| {
|
||||
c.iter()
|
||||
.any(|v| v.as_str() == Some(job.payload.action.name()))
|
||||
}) {
|
||||
let caps = capabilities(r.get("capabilities"))?;
|
||||
if !job
|
||||
.payload
|
||||
.action
|
||||
.available_for(&job.payload.execution_identity, &caps)
|
||||
{
|
||||
return Err(fail("UNSUPPORTED_CAPABILITY"));
|
||||
}
|
||||
if let Action::RunScript { script_utf8, .. } = &job.payload.action
|
||||
&& job.script_sha256.as_deref() != Some(hash(script_utf8.as_bytes()).as_str())
|
||||
{
|
||||
return Err(fail("PLAN_HASH_MISMATCH"));
|
||||
}
|
||||
if hash(&encode(&job.payload)?) != job.job_payload_hash {
|
||||
return Err(fail("PLAN_HASH_MISMATCH"));
|
||||
}
|
||||
@@ -921,3 +989,213 @@ async fn operations_http(
|
||||
json!({"items":items,"next_cursor":next,"completeness":if truncated{"partial"}else{"complete"},"truncated":truncated,"as_of":page.as_of}),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod windows_contract_tests {
|
||||
use super::*;
|
||||
fn input() -> PlanInput {
|
||||
let tenant = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
serde_json::from_value::<PlanRequest>(json!({"tenant_id":tenant,"action":"run_script","targets":{"asset_ids":[Uuid::new_v4()]},"parameters":{"execution_identity":"agent_service","timeout_seconds":60,"max_output_bytes":4096,"variants":[{"os_family":"linux","interpreter":"posix_sh","encoding":"utf-8","script_utf8":"printf hi\n"},{"os_family":"windows","interpreter":"powershell","encoding":"utf-8","script_utf8":"Write-Output 'hi'\r\n"}]},"schedule":{"not_before":now,"start_before":now+chrono::Duration::minutes(10),"offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"fixed mixed plan"})).unwrap().resolve(tenant).unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn exact_fixed_variants_and_typed_bypass_denials() {
|
||||
assert!(capabilities(json!(["windows.base/1", 42])).is_err());
|
||||
assert!(capabilities(json!({"run_script": true})).is_err());
|
||||
let mut i = input();
|
||||
let linux = target_action(&i, &["linux.base/1".into()]).unwrap();
|
||||
assert_eq!(linux, i.action);
|
||||
let windows = target_action(&i, &["windows.base/1".into()]).unwrap();
|
||||
assert_eq!(windows.script_platform(), Some("windows"));
|
||||
assert!(
|
||||
matches!(windows,Action::RunScript{ref script_utf8,..} if script_utf8.as_bytes()==b"Write-Output 'hi'\r\n")
|
||||
);
|
||||
assert!(target_action(&i, &[]).is_err());
|
||||
assert!(target_action(&i, &["linux.base/1".into(), "windows.base/1".into()]).is_err());
|
||||
i.script_variants.push(i.script_variants[0].clone());
|
||||
assert!(target_action(&i, &["linux.base/1".into()]).is_err());
|
||||
let mut i = input();
|
||||
i.script_variants[1].interpreter = "bash".into();
|
||||
assert!(target_action(&i, &["windows.base/1".into()]).is_err());
|
||||
let mut i = input();
|
||||
i.script_variants[0].script_utf8.push('x');
|
||||
assert!(target_action(&i, &["linux.base/1".into()]).is_err());
|
||||
let mut i = input();
|
||||
i.script_variants.remove(1);
|
||||
assert!(target_action(&i, &["windows.base/1".into()]).is_err());
|
||||
}
|
||||
#[tokio::test]
|
||||
#[ignore = "requires dedicated isolated PostgreSQL; tests/windows_plan_database.py"]
|
||||
async fn windows_plan_caps_persisted_database() {
|
||||
let admin = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let pool = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
rmm_persistence::verify_application_role(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let tenant = Uuid::new_v4();
|
||||
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'isolated Windows contract')")
|
||||
.bind(tenant)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let principal = Principal {
|
||||
tenant,
|
||||
name: "windows-contract".into(),
|
||||
operator: true,
|
||||
session_hash: None,
|
||||
csrf: None,
|
||||
scopes: None,
|
||||
testsimulation: false,
|
||||
identity: None,
|
||||
tenants: vec![tenant],
|
||||
};
|
||||
sqlx::query("INSERT INTO memberships VALUES($1,$2,'automation',ARRAY['operations:plan','operations:submit','operations:read','scripts:execute'],NULL)").bind(tenant).bind(&principal.name).execute(&admin).await.unwrap();
|
||||
let windows_caps = json!([
|
||||
"windows.base/1",
|
||||
"rmm.sync.v1",
|
||||
"run_script",
|
||||
"script.powershell/1"
|
||||
]);
|
||||
let mut assets = Vec::new();
|
||||
let mut agents = Vec::new();
|
||||
for caps in [json!(["linux.base/1", "run_script"]), windows_caps.clone()] {
|
||||
let asset = Uuid::new_v4();
|
||||
let agent = Uuid::new_v4();
|
||||
assets.push(asset);
|
||||
agents.push(agent);
|
||||
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
|
||||
.bind(tenant)
|
||||
.bind(asset)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256,capabilities,connection_generation) VALUES($1,$2,$3,$4,$5,1)").bind(tenant).bind(agent).bind(asset).bind(hash(agent.as_bytes())).bind(caps).execute(&admin).await.unwrap();
|
||||
}
|
||||
let temp = std::path::PathBuf::from(format!("/tmp/windows-contract-{}", Uuid::new_v4()));
|
||||
let state = crate::State {
|
||||
pool,
|
||||
signer: None,
|
||||
viewer_a: [0; 32],
|
||||
viewer_b: [1; 32],
|
||||
auth: std::sync::Arc::new(crate::auth::Auth::from_env("development").await.unwrap()),
|
||||
job_signer: std::sync::Arc::new(
|
||||
crate::job_signer::JobSigner::load_or_create(&temp.join("key.pem")).unwrap(),
|
||||
),
|
||||
};
|
||||
let mut request = input();
|
||||
request.targets.asset_ids = assets.clone();
|
||||
let view = plan(&state, &principal, tenant, request.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap();
|
||||
let original: Vec<u8> =
|
||||
sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1")
|
||||
.bind(id)
|
||||
.fetch_one(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let bound: PlanPayload = serde_json::from_slice(&original).unwrap();
|
||||
assert_eq!(bound.jobs.len(), 2);
|
||||
for job in &bound.jobs {
|
||||
assert_eq!(hash(&encode(&job.payload).unwrap()), job.job_payload_hash);
|
||||
let expected = if job.payload.asset_id == assets[0] {
|
||||
"linux"
|
||||
} else {
|
||||
"windows"
|
||||
};
|
||||
assert_eq!(job.payload.action.script_platform(), Some(expected));
|
||||
}
|
||||
let pending = submit(
|
||||
&state,
|
||||
&principal,
|
||||
tenant,
|
||||
id,
|
||||
Submit {
|
||||
idempotency_key: "fixed-mixed".into(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(pending["approval_state"], "pending_approval");
|
||||
assert_eq!(pending["job_count"], 0);
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
recheck(&mut tx, &bound).await.unwrap();
|
||||
tx.rollback().await.unwrap();
|
||||
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
||||
.bind(agents[1])
|
||||
.bind(json!(["windows.base/1", "run_script", "rmm.sync.v1"]))
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
recheck(&mut tx, &bound).await.unwrap_err().1,
|
||||
"UNSUPPORTED_CAPABILITY"
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
assert_eq!(
|
||||
plan(&state, &principal, tenant, request.clone())
|
||||
.await
|
||||
.unwrap_err()
|
||||
.1,
|
||||
"UNSUPPORTED_CAPABILITY"
|
||||
);
|
||||
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
||||
.bind(agents[1])
|
||||
.bind(&windows_caps)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut changed = bound.clone();
|
||||
changed.jobs[0].script_sha256 = Some("00".repeat(32));
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
recheck(&mut tx, &changed).await.unwrap_err().1,
|
||||
"PLAN_HASH_MISMATCH"
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
request.script_variants.clear();
|
||||
assert_eq!(
|
||||
plan(&state, &principal, tenant, request.clone())
|
||||
.await
|
||||
.unwrap_err()
|
||||
.1,
|
||||
"UNSUPPORTED_CAPABILITY"
|
||||
);
|
||||
request.targets.asset_ids = vec![assets[0]];
|
||||
plan(&state, &principal, tenant, request).await.unwrap();
|
||||
assert_eq!(
|
||||
plan(&state, &principal, Uuid::new_v4(), input())
|
||||
.await
|
||||
.unwrap_err()
|
||||
.1,
|
||||
"NOT_FOUND"
|
||||
);
|
||||
assert!(
|
||||
crate::job_gateway::next(&state, tenant, agents[1], 1)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
let counts:(i64,i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM jobs WHERE tenant_id=$1),(SELECT count(*) FROM outbox WHERE tenant_id=$1),(SELECT count(*) FROM execution_permits WHERE tenant_id=$1)").bind(tenant).fetch_one(&admin).await.unwrap();
|
||||
assert_eq!(counts, (0, 0, 0));
|
||||
let after: Vec<u8> =
|
||||
sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1")
|
||||
.bind(id)
|
||||
.fetch_one(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(original, after);
|
||||
std::fs::remove_dir_all(temp).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,6 +78,7 @@ pub async fn query(
|
||||
asset_ids: vec![i.asset_id],
|
||||
},
|
||||
action,
|
||||
script_variants: vec![],
|
||||
execution_identity: "agent_service".into(),
|
||||
schedule: crate::jobs::Schedule {
|
||||
not_before: Utc::now(),
|
||||
|
||||
Reference in New Issue
Block a user