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

This commit is contained in:
2026-11-14 00:52:40 +01:00
parent 1fef7f6ce9
commit 31278bedec
32 changed files with 4452 additions and 1715 deletions
Generated
+22
View File
@@ -2184,6 +2184,7 @@ dependencies = [
"prost", "prost",
"rand 0.9.5", "rand 0.9.5",
"reqwest", "reqwest",
"rmm-agent-core",
"rmm-agent-linux", "rmm-agent-linux",
"rmm-domain", "rmm-domain",
"rmm-privileged-helper", "rmm-privileged-helper",
@@ -2199,6 +2200,24 @@ dependencies = [
"uuid", "uuid",
] ]
[[package]]
name = "rmm-agent-core"
version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
"ed25519-dalek",
"hex",
"openssl",
"prost",
"rmm-domain",
"rmm-protocol",
"rusqlite",
"serde",
"serde_json",
"uuid",
]
[[package]] [[package]]
name = "rmm-agent-linux" name = "rmm-agent-linux"
version = "0.1.0" version = "0.1.0"
@@ -2217,6 +2236,7 @@ name = "rmm-agent-windows"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"cc",
"chrono", "chrono",
"fs2", "fs2",
"futures-util", "futures-util",
@@ -2224,6 +2244,7 @@ dependencies = [
"rand 0.9.5", "rand 0.9.5",
"rcgen", "rcgen",
"reqwest", "reqwest",
"rmm-agent-core",
"rmm-domain", "rmm-domain",
"rmm-protocol", "rmm-protocol",
"rusqlite", "rusqlite",
@@ -2292,6 +2313,7 @@ dependencies = [
"hex", "hex",
"libc", "libc",
"openssl", "openssl",
"rmm-agent-core",
"rmm-agent-linux", "rmm-agent-linux",
"rmm-domain", "rmm-domain",
"rusqlite", "rusqlite",
+1 -1
View File
@@ -1,7 +1,7 @@
[workspace] [workspace]
resolver = "2" resolver = "2"
exclude = ["crates/oidc-auth"] exclude = ["crates/oidc-auth"]
members = ["crates/domain", "crates/protocol", "crates/persistence", "crates/server", "crates/agent-linux", "crates/agent-windows", "crates/agent", "crates/privileged-helper"] members = ["crates/domain", "crates/protocol", "crates/persistence", "crates/server", "crates/agent-linux", "crates/agent-core", "crates/agent-windows", "crates/agent", "crates/privileged-helper"]
[workspace.package] [workspace.package]
version = "0.1.0" version = "0.1.0"
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "rmm-agent-core"
version.workspace = true
edition.workspace = true
license.workspace = true
[features]
default = []
openssl-verifier = ["dep:openssl"]
[dependencies]
anyhow.workspace = true
chrono.workspace = true
hex.workspace = true
prost.workspace = true
serde.workspace = true
serde_json.workspace = true
uuid.workspace = true
rmm-domain = { path = "../domain" }
rmm-protocol = { path = "../protocol" }
rusqlite = { version = "0.32.1", features = ["bundled"] }
ed25519-dalek = "=2.2.0"
[target.'cfg(unix)'.dependencies]
openssl = { workspace = true, optional = true }
[target.'cfg(unix)'.dev-dependencies]
openssl.workspace = true
+140
View File
@@ -0,0 +1,140 @@
//! Exact historical helper request/binding codecs and signed permit rules.
use crate::crypto::{DefaultVerifier, Ed25519Verifier};
use anyhow::{Result, ensure};
use chrono::{DateTime, Utc};
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload, hash};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Binding {
pub tenant_id: Uuid,
pub asset_id: Uuid,
pub agent_id: Uuid,
pub enrollment_generation: u64,
pub assignment_version: u64,
pub public_key_hex: String,
}
pub type AuthBinding = Binding;
impl Binding {
pub fn job(&self, bytes: &[u8]) -> Result<JobPayload> {
ensure!(bytes.len() <= 65536, "JOB_SIZE");
let j: JobPayload = serde_json::from_slice(bytes)?;
ensure!(
j.schema_version == 1
&& j.tenant_id == self.tenant_id
&& j.asset_id == self.asset_id
&& j.agent_id == self.agent_id
&& j.enrollment_generation == self.enrollment_generation
&& j.assignment_version == self.assignment_version,
"IDENTITY_BINDING"
);
ensure!(
j.action.validate()
&& (1..=3600).contains(&j.max_runtime_seconds)
&& (1..=262144).contains(&j.max_output_bytes)
&& j.not_before < j.start_before,
"INVALID_JOB"
);
Ok(j)
}
pub fn verify(
&self,
request: &Request,
now: DateTime<Utc>,
) -> Result<(JobPayload, ExecutionPermitPayload)> {
self.verify_with(request, now, &DefaultVerifier::default())
}
pub fn verify_with(
&self,
request: &Request,
now: DateTime<Utc>,
verifier: &impl Ed25519Verifier,
) -> Result<(JobPayload, ExecutionPermitPayload)> {
let job = self.job(&request.job_bytes)?;
ensure!(
request.permit_bytes.len() <= 8192 && request.signature.len() == 64,
"PERMIT_SIZE"
);
let raw = hex::decode(&self.public_key_hex)?;
ensure!(raw.len() == 32, "TRUST_KEY_SIZE");
ensure!(
verifier.verify(&raw, &request.permit_bytes, &request.signature)?,
"INVALID_SIGNATURE"
);
let p: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
ensure!(
p.domain == "rmm.execution-permit"
&& p.schema_version == 1
&& p.key_id == hash(&raw)
&& !p.grant_id.is_nil()
&& !p.authorization_id.is_nil(),
"PERMIT_DOMAIN"
);
ensure!(
p.authorization_id == request.authorization_id
&& p.plan_hash == request.plan_hash
&& p.plan_hash.len() == 64
&& hex::decode(&p.plan_hash)?.len() == 32
&& p.job_payload_hash == hash(&request.job_bytes)
&& p.tenant_id == job.tenant_id
&& p.asset_id == job.asset_id
&& p.agent_id == job.agent_id
&& p.enrollment_generation == job.enrollment_generation
&& p.assignment_version == job.assignment_version
&& p.job_id == job.job_id
&& p.attempt_id == job.attempt_id
&& p.action == job.action.name()
&& p.execution_identity == job.execution_identity
&& p.max_runtime_seconds == job.max_runtime_seconds,
"PERMIT_BINDING"
);
ensure!(
p.not_before >= job.not_before
&& p.start_before <= job.start_before
&& p.not_before < p.start_before
&& (p.start_before - p.not_before).num_seconds() <= 60
&& now >= p.not_before
&& now < p.start_before,
"PERMIT_TIME"
);
Ok((job, p))
}
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Request {
pub job_bytes: Vec<u8>,
pub permit_bytes: Vec<u8>,
pub signature: Vec<u8>,
pub plan_hash: String,
pub authorization_id: Uuid,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Outcome {
pub state: String,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub exit_code: Option<i32>,
pub output_truncated: bool,
pub reboot_required: bool,
pub evidence: serde_json::Value,
pub error_code: String,
}
impl Outcome {
pub fn unknown(code: &str) -> Self {
Self {
state: "unknown".into(),
stdout: vec![],
stderr: vec![],
exit_code: None,
output_truncated: false,
reboot_required: false,
evidence: serde_json::json!({"postconditions_passed":false}),
error_code: code.into(),
}
}
}
+54
View File
@@ -0,0 +1,54 @@
//! Fixed Ed25519 verification; no algorithm negotiation or trust-key discovery.
use anyhow::Result;
use ed25519_dalek::{Signature, VerifyingKey};
pub trait Ed25519Verifier {
fn verify(&self, public_key: &[u8], message: &[u8], signature: &[u8]) -> Result<bool>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct DalekVerifier;
impl Ed25519Verifier for DalekVerifier {
fn verify(&self, public_key: &[u8], message: &[u8], signature: &[u8]) -> Result<bool> {
let Ok(raw): Result<&[u8; 32], _> = public_key.try_into() else {
return Ok(false);
};
let Ok(key) = VerifyingKey::from_bytes(raw) else {
return Ok(false);
};
let Ok(signature) = Signature::from_slice(signature) else {
return Ok(false);
};
// Reject weak points and scalar/point malleability. This is raw Ed25519,
// never Ed25519ph: the exact stored bytes are the signed message.
Ok(key.verify_strict(message, &signature).is_ok())
}
}
/// Existing Linux verifier semantics, retained explicitly during extraction.
#[cfg(all(unix, feature = "openssl-verifier"))]
#[derive(Clone, Copy, Debug, Default)]
pub struct OpenSslVerifier;
#[cfg(all(unix, feature = "openssl-verifier"))]
impl Ed25519Verifier for OpenSslVerifier {
fn verify(&self, public_key: &[u8], message: &[u8], signature: &[u8]) -> Result<bool> {
use openssl::{
pkey::{Id, PKey},
sign::Verifier,
};
if public_key.len() != 32 || signature.len() != 64 {
return Ok(false);
}
let key = PKey::public_key_from_raw_bytes(public_key, Id::ED25519)?;
Ok(Verifier::new_without_digest(&key)?.verify_oneshot(signature, message)?)
}
}
/// Preserve the existing Linux OpenSSL profile when selected by its adapter;
/// Windows never depends on OpenSSL, including workspace feature unification.
#[cfg(all(unix, feature = "openssl-verifier"))]
pub type DefaultVerifier = OpenSslVerifier;
#[cfg(not(all(unix, feature = "openssl-verifier")))]
pub type DefaultVerifier = DalekVerifier;
+274
View File
@@ -0,0 +1,274 @@
//! Durable job persistence without capability discovery or OS execution.
//! Caller performs fresh Sync/Clock/permit checks before consuming or executing.
use crate::auth::{Binding, Outcome, Request};
use anyhow::{Result, ensure};
use prost::Message;
use rmm_domain::jobs::{JobPayload, hash};
use rmm_protocol::*;
use rusqlite::{Connection, OptionalExtension, params};
use uuid::Uuid;
pub fn accept(
db: &Connection,
binding: &Binding,
offer: &JobOffer,
supported: impl FnOnce(&JobPayload) -> bool,
) -> Result<bool> {
let job = binding.job(&offer.payload_bytes)?;
ensure!(
offer.job_id == job.job_id.to_string()
&& offer.attempt_id == job.attempt_id.to_string()
&& offer.job_payload_hash == hash(&offer.payload_bytes)
&& Uuid::parse_str(&offer.authorization_id).is_ok_and(|id| !id.is_nil())
&& offer.plan_hash.len() == 64
&& hex_hash(&offer.plan_hash),
"OFFER_BINDING"
);
ensure!(supported(&job), "UNSUPPORTED_CAPABILITY");
let bytes = offer.encode_to_vec();
let existing: Option<Vec<u8>> = db
.query_row(
"SELECT offer FROM job_attempts WHERE job=?1 AND attempt=?2",
params![offer.job_id, offer.attempt_id],
|r| r.get(0),
)
.optional()?;
if let Some(old) = existing {
ensure!(old == bytes, "OFFER_CONFLICT");
return Ok(false);
}
let count: i64 = db.query_row("SELECT count(*) FROM job_attempts", [], |r| r.get(0))?;
ensure!(count < 10000, "JOURNAL_CAPACITY_NEW_EFFECTS_BLOCKED");
db.execute(
"INSERT INTO job_attempts(job,attempt,offer,state) VALUES(?1,?2,?3,'accepted')",
params![offer.job_id, offer.attempt_id, bytes],
)?;
Ok(true)
}
fn hex_hash(s: &str) -> bool {
s.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
/// Inspect ONLY at a new process startup, never on a transport reconnect: no
/// executor thread from the previous process can still deliver its outcome.
/// This does not execute, release consumption or invent a successful outcome.
pub fn interrupted(
db: &Connection,
ledger: &Connection,
binding: &Binding,
) -> Result<Vec<(JobOffer, String)>> {
interrupted_with(
db,
ledger,
binding,
&crate::crypto::DefaultVerifier::default(),
)
}
pub fn interrupted_with(
db: &Connection,
ledger: &Connection,
binding: &Binding,
verifier: &impl crate::crypto::Ed25519Verifier,
) -> Result<Vec<(JobOffer, String)>> {
let mut statement = db.prepare(
"SELECT offer,grant_id FROM job_attempts WHERE state IN ('requesting','running','verifying') ORDER BY job,attempt",
)?;
let rows = statement.query_map([], |r| {
Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, String>(1)?))
})?;
let mut interrupted = Vec::new();
for row in rows {
let (bytes, grant) = row?;
let offer = JobOffer::decode(bytes.as_slice())?;
let job = binding.job(&offer.payload_bytes)?;
ensure!(
offer.job_id == job.job_id.to_string()
&& offer.attempt_id == job.attempt_id.to_string()
&& offer.job_payload_hash == hash(&offer.payload_bytes)
&& Uuid::parse_str(&offer.authorization_id).is_ok_and(|id| !id.is_nil())
&& offer.plan_hash.len() == 64
&& hex_hash(&offer.plan_hash),
"INTERRUPTED_OFFER_BINDING"
);
if !grant.is_empty() {
let row: Option<(String, u64, String, String, Vec<u8>)> = ledger
.query_row(
"SELECT c.agent,c.generation,c.job,c.attempt,e.start FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1",
[&grant],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
)
.optional()?;
let (agent, generation, job_id, attempt, start) =
row.ok_or_else(|| anyhow::anyhow!("INTERRUPTED_START_EVIDENCE_MISSING"))?;
ensure!(
agent == binding.agent_id.to_string()
&& generation == binding.enrollment_generation
&& job_id == offer.job_id
&& attempt == offer.attempt_id,
"INTERRUPTED_CONSUMPTION_BINDING"
);
let start: serde_json::Value = serde_json::from_slice(&start)?;
let request: Request = serde_json::from_value(start["request"].clone())?;
let permit: rmm_domain::jobs::ExecutionPermitPayload =
serde_json::from_slice(&request.permit_bytes)?;
// Verify the historical signed request at its original valid time;
// this is evidence only, never permission to start it again.
let (_, verified) = binding.verify_with(&request, permit.not_before, verifier)?;
ensure!(
verified == permit
&& permit.grant_id.to_string() == grant
&& request.job_bytes == offer.payload_bytes
&& request.plan_hash == offer.plan_hash
&& request.authorization_id.to_string() == offer.authorization_id,
"INTERRUPTED_START_BINDING"
);
} else {
// A request may have committed remotely without its reply arriving.
// It can only become local unknown, never a fabricated grant/result.
let state: String = db.query_row(
"SELECT state FROM job_attempts WHERE job=?1 AND attempt=?2",
params![offer.job_id, offer.attempt_id],
|r| r.get(0),
)?;
ensure!(state == "requesting", "INTERRUPTED_RUNNING_GRANT_MISSING");
}
interrupted.push((offer, grant));
}
Ok(interrupted)
}
pub fn interrupted_request(db: &Connection, offer: &JobOffer) -> Result<()> {
ensure!(
db.execute(
"UPDATE job_attempts SET state='unknown',revision=revision+1 WHERE job=?1 AND attempt=?2 AND state='requesting' AND grant_id=''",
params![offer.job_id, offer.attempt_id],
)? == 1,
"INTERRUPTED_REQUEST_STATE"
);
Ok(())
}
pub fn event(db: &Connection, envelope: &Envelope) -> Result<()> {
let count: i64 = db.query_row("SELECT count(*) FROM job_events", [], |r| r.get(0))?;
ensure!(count < 1000, "UNACKNOWLEDGED_EVENT_LIMIT");
db.execute(
"INSERT INTO job_events(id,payload) VALUES(?1,?2)",
params![envelope.message_id, envelope.encode_to_vec()],
)?;
Ok(())
}
pub fn events(db: &Connection) -> Result<Vec<Envelope>> {
let mut statement = db.prepare("SELECT payload FROM job_events ORDER BY rowid LIMIT 100")?;
let bytes = statement
.query_map([], |r| r.get::<_, Vec<u8>>(0))?
.collect::<rusqlite::Result<Vec<_>>>()?;
bytes
.into_iter()
.map(|b| Ok(Envelope::decode(b.as_slice())?))
.collect()
}
pub fn ack(db: &mut Connection, id: &str) -> Result<()> {
let tx = db.transaction()?;
crate::reconcile::archive_events(&tx)?;
tx.execute("DELETE FROM job_events WHERE id=?1", [id])?;
tx.commit()?;
Ok(())
}
pub fn next(db: &Connection) -> Result<Option<JobOffer>> {
next_at(db, chrono::Utc::now())
}
/// Scheduling only; the qualified clock/Sync/permit gate still precedes effects.
pub fn next_at(db: &Connection, now: chrono::DateTime<chrono::Utc>) -> Result<Option<JobOffer>> {
// One device-wide effect at a time; unknown/reserved attempts retain locks.
let busy: i64 = db.query_row("SELECT count(*) FROM job_attempts WHERE state IN ('requesting','running','unknown','awaiting_reboot')", [], |r| r.get(0))?;
if busy != 0 {
return Ok(None);
}
let mut statement = db.prepare("SELECT offer FROM job_attempts WHERE state='accepted' AND cancel_requested=0 ORDER BY rowid")?;
let rows = statement.query_map([], |r| r.get::<_, Vec<u8>>(0))?;
for bytes in rows {
let offer = JobOffer::decode(bytes?.as_slice())?;
let job: JobPayload = serde_json::from_slice(&offer.payload_bytes)?;
if now >= job.not_before || now >= job.start_before {
return Ok(Some(offer));
}
}
Ok(None)
}
pub fn requesting(db: &Connection) -> Result<Option<JobOffer>> {
let bytes: Option<Vec<u8>> = db
.query_row(
"SELECT offer FROM job_attempts WHERE state='requesting' LIMIT 1",
[],
|r| r.get(0),
)
.optional()?;
bytes
.map(|b| Ok(JobOffer::decode(b.as_slice())?))
.transpose()
}
pub fn reserve_request(db: &Connection, offer: &JobOffer) -> Result<()> {
ensure!(db.execute("UPDATE job_attempts SET state='requesting' WHERE job=?1 AND attempt=?2 AND state='accepted' AND cancel_requested=0",
params![offer.job_id,offer.attempt_id])? == 1, "ATTEMPT_NOT_STARTABLE");
Ok(())
}
pub fn transition(db: &Connection, offer: &JobOffer, state: &str, grant: &str) -> Result<u64> {
let previous: String = db.query_row(
"SELECT state FROM job_attempts WHERE job=?1 AND attempt=?2",
params![offer.job_id, offer.attempt_id],
|r| r.get(0),
)?;
let allowed = match previous.as_str() {
"accepted" | "requesting" => matches!(
state,
"running" | "failed" | "cancelled" | "expired" | "unknown"
),
"running" | "verifying" => matches!(
state,
"verifying" | "succeeded" | "failed" | "cancelled" | "unknown" | "awaiting_reboot"
),
// Only a definitive completion of the already-running executor calls
// this reconciliation path. No new effect is started from unknown.
"unknown" | "awaiting_reboot" => matches!(
state,
"succeeded" | "failed" | "cancelled" | "unknown" | "awaiting_reboot"
),
_ => false,
};
ensure!(allowed, "INVALID_LOCAL_STATE_TRANSITION");
let rev: i64 = db.query_row("UPDATE job_attempts SET state=?3,grant_id=?4,revision=revision+1 WHERE job=?1 AND attempt=?2 RETURNING revision",
params![offer.job_id,offer.attempt_id,state,grant], |r| r.get(0))?;
Ok(u64::try_from(rev)?)
}
pub fn result(offer: &JobOffer, revision: u64, grant: &str, outcome: Outcome) -> JobResult {
JobResult {
job_id: offer.job_id.clone(),
attempt_id: offer.attempt_id.clone(),
revision,
state: outcome.state,
grant_id: grant.into(),
stdout: outcome.stdout,
stderr: outcome.stderr,
output_truncated: outcome.output_truncated,
reboot_required: outcome.reboot_required,
exit_code: outcome.exit_code,
evidence_json: outcome.evidence.to_string(),
error_code: outcome.error_code,
}
}
pub fn no_start(state: &str, code: &str) -> Outcome {
Outcome {
state: state.into(),
evidence: serde_json::json!({"not_started":true,"postconditions_passed":false}),
..Outcome::unknown(code)
}
}
pub fn permit_request(offer: &JobOffer, permit: &ExecutionPermit) -> Result<Request> {
Ok(Request {
job_bytes: offer.payload_bytes.clone(),
permit_bytes: permit.payload_bytes.clone(),
signature: permit.signature.clone(),
plan_hash: offer.plan_hash.clone(),
authorization_id: Uuid::parse_str(&offer.authorization_id)?,
})
}
+103
View File
@@ -0,0 +1,103 @@
//! Connection-level ledger rules, with OS path/lock/ACL handling left to adapters.
use crate::auth::{Outcome, Request};
use anyhow::{Result, ensure};
use chrono::{DateTime, Utc};
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload};
use uuid::Uuid;
/// Finite 1 GiB bound for durable agent/helper history. Unexpected page sizes
/// are refused rather than silently multiplying the byte limit. No compaction
/// or tombstone deletion occurs here; SQLITE_FULL must still fail closed.
pub fn bounded_journal_capacity(db: &rusqlite::Connection) -> Result<()> {
let page_size: u32 = db.query_row("PRAGMA page_size", [], |r| r.get(0))?;
ensure!(page_size == 4096, "JOURNAL_PAGE_SIZE_UNSUPPORTED");
let maximum: u32 = db.query_row("PRAGMA max_page_count=262144", [], |r| r.get(0))?;
ensure!(maximum == 262144, "JOURNAL_STORAGE_CAPACITY_BLOCKED");
Ok(())
}
/// The platform adapter must securely open/lock the file before calling this.
/// No file creation, ACL repair or journal reset is performed here.
pub fn initialize_ledger(db: &rusqlite::Connection) -> Result<()> {
bounded_journal_capacity(db)?;
db.execute_batch("PRAGMA synchronous=FULL; PRAGMA journal_mode=DELETE;
CREATE TABLE IF NOT EXISTS consumed(grant_id TEXT PRIMARY KEY, agent TEXT NOT NULL, generation INTEGER NOT NULL,
job TEXT NOT NULL, attempt TEXT NOT NULL, result BLOB, UNIQUE(agent,generation,job,attempt));
CREATE TABLE IF NOT EXISTS execution_evidence(grant_id TEXT PRIMARY KEY, start BLOB NOT NULL, outcome BLOB);")?;
let check: String = db.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
ensure!(check == "ok", "JOURNAL_INTEGRITY");
Ok(())
}
pub fn consume(db: &mut rusqlite::Connection, p: &ExecutionPermitPayload) -> Result<()> {
let tx = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
// Unknown effects retain the global device lock, including across restart.
let unresolved: i64 = tx.query_row(
"SELECT count(*) FROM consumed WHERE result IS NULL",
[],
|r| r.get(0),
)?;
ensure!(unresolved == 0, "UNRESOLVED_EFFECT_RESOURCE_LOCKED");
tx.execute(
"INSERT INTO consumed(grant_id,agent,generation,job,attempt) VALUES(?1,?2,?3,?4,?5)",
rusqlite::params![
p.grant_id.to_string(),
p.agent_id.to_string(),
p.enrollment_generation,
p.job_id.to_string(),
p.attempt_id.to_string()
],
)?;
tx.commit()?;
Ok(())
}
pub fn finish(
db: &rusqlite::Connection,
p: &ExecutionPermitPayload,
outcome: &Outcome,
) -> Result<()> {
db.execute(
"UPDATE execution_evidence SET outcome=?2 WHERE grant_id=?1",
rusqlite::params![p.grant_id.to_string(), serde_json::to_vec(outcome)?],
)?;
// Unknown / awaiting reboot keep the resource reserved until a real sync
// protocol exists. Never unlock on a process exit or a network reconnect.
if outcome.state != "unknown" && outcome.state != "awaiting_reboot" {
ensure!(
db.execute(
"UPDATE consumed SET result=?2 WHERE grant_id=?1 AND result IS NULL",
rusqlite::params![p.grant_id.to_string(), serde_json::to_vec(outcome)?]
)? == 1,
"CONSUMPTION_NOT_FOUND"
);
}
Ok(())
}
/// Persist the original boot and exact signed request BEFORE any reboot/effect.
/// Awaiting/unknown outcomes never release consumed.result's resource lock.
pub fn save_start(
db: &rusqlite::Connection,
permit: &ExecutionPermitPayload,
request: &Request,
previous_boot_id: Uuid,
recorded_at: DateTime<Utc>,
) -> Result<()> {
let job: JobPayload = serde_json::from_slice(&request.job_bytes)?;
ensure!(!previous_boot_id.is_nil(), "ORIGINAL_BOOT_MISSING");
let deadline = match job.action {
rmm_domain::jobs::Action::Reboot {
reconnect_timeout_seconds,
..
} => Some(recorded_at + chrono::Duration::seconds(reconnect_timeout_seconds.into())),
_ => None,
};
let evidence = serde_json::json!({"previous_boot_id":previous_boot_id.to_string(),
"reserved_at":recorded_at,"reconnect_deadline":deadline,"request":request,
"reauthentication_required":true,"postconditions_passed":false});
db.execute(
"INSERT INTO execution_evidence(grant_id,start) VALUES(?1,?2)",
rusqlite::params![permit.grant_id.to_string(), serde_json::to_vec(&evidence)?],
)?;
Ok(())
}
+9
View File
@@ -0,0 +1,9 @@
//! Platform-neutral signed authorization, durable job state and reconciliation.
//! This crate performs no OS effects, enrollment, ACL changes or clock bootstrap.
//! Callers must authenticate their transport, protect/lock their own journals and
//! supply a qualified clock. A successful signature is never UI approval itself.
pub mod auth;
pub mod crypto;
pub mod jobs;
pub mod ledger;
pub mod reconcile;
File diff suppressed because it is too large Load Diff
+292
View File
@@ -0,0 +1,292 @@
//! Signature/codec/consumption contracts, with no transport or OS execution.
use chrono::{DateTime, Duration, Utc};
use ed25519_dalek::{Signer, SigningKey};
#[cfg(unix)]
use rmm_agent_core::crypto::{DalekVerifier, Ed25519Verifier};
use rmm_agent_core::{
auth::{Binding, Outcome, Request},
jobs, ledger,
};
use rmm_domain::jobs::{Action, ExecutionPermitPayload, JobPayload, encode, hash};
use rmm_protocol::JobOffer;
use rusqlite::Connection;
use uuid::Uuid;
fn fixture() -> (Binding, Request, ExecutionPermitPayload, DateTime<Utc>) {
let key = SigningKey::from_bytes(&[9; 32]);
let id = Uuid::from_u128(1);
let now = DateTime::parse_from_rfc3339("2026-11-14T00:00:00Z")
.unwrap()
.with_timezone(&Utc);
let binding = Binding {
tenant_id: id,
asset_id: Uuid::from_u128(2),
agent_id: Uuid::from_u128(3),
enrollment_generation: 2,
assignment_version: 4,
public_key_hex: hex::encode(key.verifying_key().as_bytes()),
};
let job = JobPayload {
schema_version: 1,
tenant_id: binding.tenant_id,
asset_id: binding.asset_id,
agent_id: binding.agent_id,
enrollment_generation: 2,
assignment_version: 4,
job_id: Uuid::from_u128(5),
attempt_id: Uuid::from_u128(6),
action: Action::RunScript {
interpreter: "posix_sh".into(),
script_utf8: "printf 'Hello\\n'\n".into(),
arguments: vec![],
expected_stdout: Some("Hello\n".into()),
},
execution_identity: "agent_service".into(),
not_before: now - Duration::minutes(1),
start_before: now + Duration::minutes(5),
max_runtime_seconds: 10,
max_output_bytes: 4096,
};
let job_bytes = encode(&job).unwrap();
let permit = ExecutionPermitPayload {
domain: "rmm.execution-permit".into(),
schema_version: 1,
grant_id: Uuid::from_u128(7),
authorization_id: Uuid::from_u128(8),
tenant_id: binding.tenant_id,
asset_id: binding.asset_id,
agent_id: binding.agent_id,
enrollment_generation: 2,
assignment_version: 4,
job_id: job.job_id,
attempt_id: job.attempt_id,
plan_hash: hash(b"immutable approved plan"),
job_payload_hash: hash(&job_bytes),
action: job.action.name().into(),
execution_identity: job.execution_identity,
max_runtime_seconds: 10,
not_before: now - Duration::seconds(1),
start_before: now + Duration::seconds(59),
key_id: hash(key.verifying_key().as_bytes()),
};
let permit_bytes = encode(&permit).unwrap();
let signature = key.sign(&permit_bytes).to_bytes().to_vec();
let request = Request {
job_bytes,
permit_bytes,
signature,
plan_hash: permit.plan_hash.clone(),
authorization_id: permit.authorization_id,
};
(binding, request, permit, now)
}
#[test]
fn historical_request_and_binding_codecs_keep_field_order_arrays_and_strictness() {
let request = Request {
job_bytes: vec![0, 255],
permit_bytes: vec![1],
signature: vec![2],
plan_hash: "ab".into(),
authorization_id: Uuid::nil(),
};
let expected = r#"{"job_bytes":[0,255],"permit_bytes":[1],"signature":[2],"plan_hash":"ab","authorization_id":"00000000-0000-0000-0000-000000000000"}"#;
assert_eq!(serde_json::to_vec(&request).unwrap(), expected.as_bytes());
let parsed: Request = serde_json::from_str(expected).unwrap();
assert_eq!(serde_json::to_string(&parsed).unwrap(), expected);
assert!(
serde_json::from_str::<Request>(
&expected.replace("\"job_bytes\"", "\"extra\":0,\"job_bytes\"")
)
.is_err()
);
let binding = Binding {
tenant_id: Uuid::nil(),
asset_id: Uuid::nil(),
agent_id: Uuid::nil(),
enrollment_generation: 1,
assignment_version: 2,
public_key_hex: "key".into(),
};
assert_eq!(
serde_json::to_string(&binding).unwrap(),
r#"{"tenant_id":"00000000-0000-0000-0000-000000000000","asset_id":"00000000-0000-0000-0000-000000000000","agent_id":"00000000-0000-0000-0000-000000000000","enrollment_generation":1,"assignment_version":2,"public_key_hex":"key"}"#
);
}
#[test]
fn exact_permit_bytes_time_and_all_identity_hash_bindings_are_required() {
let (binding, request, permit, now) = fixture();
assert_eq!(binding.verify(&request, now).unwrap().1, permit);
assert!(binding.verify(&request, permit.not_before).is_ok());
assert!(
binding
.verify(&request, permit.not_before - Duration::nanoseconds(1))
.is_err()
);
assert!(binding.verify(&request, permit.start_before).is_err());
let key = SigningKey::from_bytes(&[9; 32]);
let value = serde_json::to_value(&permit).unwrap();
for (field, replacement) in [
("domain", serde_json::json!("rmm.reconciliation-decision")),
("schema_version", serde_json::json!(2)),
("tenant_id", serde_json::json!(Uuid::new_v4())),
("asset_id", serde_json::json!(Uuid::new_v4())),
("agent_id", serde_json::json!(Uuid::new_v4())),
("enrollment_generation", serde_json::json!(3)),
("assignment_version", serde_json::json!(5)),
("job_id", serde_json::json!(Uuid::new_v4())),
("attempt_id", serde_json::json!(Uuid::new_v4())),
("authorization_id", serde_json::json!(Uuid::new_v4())),
("plan_hash", serde_json::json!(hash(b"other plan"))),
(
"job_payload_hash",
serde_json::json!(hash(b"different bytes")),
),
("action", serde_json::json!("reboot")),
("execution_identity", serde_json::json!("root")),
("max_runtime_seconds", serde_json::json!(11)),
("key_id", serde_json::json!(hash(b"otherkey"))),
("grant_id", serde_json::json!(Uuid::nil())),
(
"start_before",
serde_json::json!(now + Duration::seconds(60)),
),
] {
let mut value = value.clone();
value[field] = replacement;
let changed: ExecutionPermitPayload = serde_json::from_value(value).unwrap();
let mut changed_request = request.clone();
changed_request.permit_bytes = encode(&changed).unwrap();
changed_request.signature = key.sign(&changed_request.permit_bytes).to_bytes().to_vec();
assert!(binding.verify(&changed_request, now).is_err(), "{field}");
}
let mut changed = request.clone();
changed.job_bytes.push(b' ');
assert!(binding.verify(&changed, now).is_err());
let mut changed = request.clone();
changed.signature[0] ^= 1;
assert!(binding.verify(&changed, now).is_err());
let mut changed = request;
changed.signature.truncate(63);
assert!(binding.verify(&changed, now).is_err());
}
#[cfg(unix)]
#[test]
fn openssl_and_portable_ed25519_agree_on_current_keys_bytes_and_tampering() {
use openssl::{
pkey::PKey,
sign::{Signer as OpenSigner, Verifier},
};
let key = PKey::generate_ed25519().unwrap();
let public = key.raw_public_key().unwrap();
let bytes = b"exact stored signed payload\r\n";
let signature = OpenSigner::new_without_digest(&key)
.unwrap()
.sign_oneshot_to_vec(bytes)
.unwrap();
let verify_openssl = |message: &[u8], signature: &[u8]| {
Verifier::new_without_digest(&key)
.unwrap()
.verify_oneshot(signature, message)
.unwrap_or(false)
};
for message in [bytes.as_slice(), b"exact stored signed payload\n", b""] {
assert_eq!(
DalekVerifier.verify(&public, message, &signature).unwrap(),
verify_openssl(message, &signature)
);
}
let mut changed = signature.clone();
changed[0] ^= 1;
for signature in [&signature[..], &changed[..], &signature[..63]] {
assert_eq!(
DalekVerifier.verify(&public, bytes, signature).unwrap(),
verify_openssl(bytes, signature)
);
}
assert!(!DalekVerifier.verify(&[0; 32], bytes, &[0; 64]).unwrap());
assert!(!DalekVerifier.verify(&[0; 31], bytes, &signature).unwrap());
// Reverse direction uses raw Ed25519, never prehashes the message.
let signing = SigningKey::from_bytes(&[11; 32]);
let p = PKey::public_key_from_raw_bytes(
signing.verifying_key().as_bytes(),
openssl::pkey::Id::ED25519,
)
.unwrap();
assert!(
Verifier::new_without_digest(&p)
.unwrap()
.verify_oneshot(&signing.sign(bytes).to_bytes(), bytes)
.unwrap()
);
}
#[test]
fn consumed_attempt_and_unknown_lock_survive_reopen_without_reexecution() {
let (_, request, permit, now) = fixture();
let path = std::env::temp_dir().join(format!("rmm-core-ledger-{}", Uuid::new_v4()));
{
let mut db = Connection::open(&path).unwrap();
ledger::initialize_ledger(&db).unwrap();
ledger::consume(&mut db, &permit).unwrap();
ledger::save_start(&db, &permit, &request, Uuid::from_u128(9), now).unwrap();
ledger::finish(&db, &permit, &Outcome::unknown("EFFECT_UNKNOWN")).unwrap();
}
{
let mut db = Connection::open(&path).unwrap();
ledger::initialize_ledger(&db).unwrap();
assert!(ledger::consume(&mut db, &permit).is_err());
let mut replacement = permit.clone();
replacement.grant_id = Uuid::new_v4();
assert!(ledger::consume(&mut db, &replacement).is_err());
assert_eq!(
db.query_row(
"SELECT count(*) FROM consumed WHERE result IS NULL",
[],
|r| r.get::<_, u32>(0)
)
.unwrap(),
1
);
assert_eq!(
db.query_row("PRAGMA max_page_count", [], |r| r.get::<_, u32>(0))
.unwrap(),
262144
);
}
std::fs::remove_file(path).unwrap();
}
#[test]
fn portable_acceptance_requires_platform_capability_and_exact_redelivery() {
let (binding, request, permit, _) = fixture();
let offer = JobOffer {
job_id: permit.job_id.to_string(),
attempt_id: permit.attempt_id.to_string(),
payload_bytes: request.job_bytes,
job_payload_hash: permit.job_payload_hash,
plan_hash: permit.plan_hash,
authorization_id: permit.authorization_id.to_string(),
};
let db = Connection::open_in_memory().unwrap();
db.execute_batch("CREATE TABLE job_attempts(job TEXT,attempt TEXT,offer BLOB,state TEXT,revision INTEGER DEFAULT 0,grant_id TEXT DEFAULT '',cancel_requested INTEGER DEFAULT 0,PRIMARY KEY(job,attempt))").unwrap();
assert!(jobs::accept(&db, &binding, &offer, |_| false).is_err());
assert_eq!(
db.query_row("SELECT count(*) FROM job_attempts", [], |r| r
.get::<_, u32>(0))
.unwrap(),
0
);
assert!(jobs::accept(&db, &binding, &offer, |_| true).unwrap());
assert!(!jobs::accept(&db, &binding, &offer, |_| true).unwrap());
let mut changed = offer.clone();
changed.authorization_id = Uuid::new_v4().to_string();
assert!(jobs::accept(&db, &binding, &changed, |_| true).is_err());
jobs::reserve_request(&db, &offer).unwrap();
assert!(jobs::reserve_request(&db, &offer).is_err());
assert_eq!(jobs::transition(&db, &offer, "unknown", "").unwrap(), 1);
assert!(jobs::next(&db).unwrap().is_none());
assert!(jobs::transition(&db, &offer, "running", "").is_err());
}
File diff suppressed because it is too large Load Diff
+5 -1
View File
@@ -20,10 +20,14 @@ tokio.workspace = true
tokio-tungstenite.workspace = true tokio-tungstenite.workspace = true
uuid.workspace = true uuid.workspace = true
rmm-domain = { path = "../domain" } rmm-domain = { path = "../domain" }
rmm-agent-core = { path = "../agent-core" }
rmm-protocol = { path = "../protocol" } rmm-protocol = { path = "../protocol" }
rusqlite = { version = "0.32.1", features = ["bundled"] } rusqlite = { version = "0.32.1", features = ["bundled"] }
fs2 = "0.4.3" fs2 = "0.4.3"
rcgen = { version = "=0.14.10", default-features = false, features = ["crypto", "ring", "pem"] } rcgen = { version = "=0.14.10", default-features = false, features = ["crypto", "ring", "pem"] }
[build-dependencies]
cc = "=1.11.1"
[target.'cfg(windows)'.dependencies] [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"] }
+1
View File
@@ -5,6 +5,7 @@ edition.workspace = true
license.workspace = true license.workspace = true
default-run = "rmm-agent" default-run = "rmm-agent"
[dependencies] [dependencies]
rmm-agent-core = { path = "../agent-core", features = ["openssl-verifier"] }
anyhow.workspace = true anyhow.workspace = true
chrono.workspace = true chrono.workspace = true
futures-util.workspace = true futures-util.workspace = true
+14 -248
View File
@@ -1,9 +1,13 @@
use anyhow::{Result, ensure}; use anyhow::{Result, ensure};
#[cfg(test)]
use prost::Message; use prost::Message;
use rmm_domain::jobs::{Action, JobPayload, hash}; #[cfg(test)]
use rmm_privileged_helper::{Binding, Outcome, Request}; use rmm_domain::jobs::hash;
use rmm_domain::jobs::{Action, JobPayload};
use rmm_privileged_helper::{Binding, Outcome};
use rmm_protocol::*; use rmm_protocol::*;
use rusqlite::{Connection, OptionalExtension, params}; use rusqlite::Connection;
#[cfg(test)]
use uuid::Uuid; use uuid::Uuid;
pub fn supported(job: &JobPayload) -> bool { pub fn supported(job: &JobPayload) -> bool {
@@ -53,242 +57,14 @@ fn supported_as(job: &JobPayload, uid: u32, helper_configured: bool) -> bool {
_ => false, _ => 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> { pub fn accept(db: &Connection, binding: &Binding, offer: &JobOffer) -> Result<bool> {
let job = binding.job(&offer.payload_bytes)?; rmm_agent_core::jobs::accept(db, binding, offer, |job| {
ensure!( supported_with_binding(job, Some(binding))
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)
}
} }
pub fn execute(job: &JobPayload) -> Outcome { pub fn execute(job: &JobPayload) -> Outcome {
let result = match &job.action { 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 /// With no backend SyncResponse contract, a reconnect/restart cannot prove an
/// earlier reservation never started. Telemetry and evidence replay continue; /// earlier reservation never started. Telemetry and evidence replay continue;
/// all new effects stop. Do not paper over this with a new start request. /// all new effects stop. Do not paper over this with a new start request.
File diff suppressed because it is too large Load Diff
+121 -2
View File
@@ -100,7 +100,10 @@ impl Action {
arguments, arguments,
expected_stdout, 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.is_empty()
&& script_utf8.len() <= 32768 && script_utf8.len() <= 32768
&& !script_utf8.contains('\0') && !script_utf8.contains('\0')
@@ -110,7 +113,9 @@ impl Action {
.all(|a| a.len() <= 4096 && !a.contains('\0')) .all(|a| a.len() <= 4096 && !a.contains('\0'))
&& expected_stdout.as_ref().is_none_or(|s| s.len() <= 65536) && 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 { Self::QueryLogs {
unit: u, unit: u,
since, 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 { pub fn resource(&self) -> &'static str {
match self { match self {
Self::EnsurePackage { .. } Self::EnsurePackage { .. }
@@ -387,6 +431,81 @@ impl JobState {
mod tests { mod tests {
use super::*; use super::*;
#[test] #[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() { fn codec_golden_and_exact_script_bytes() {
let a = Action::RunScript { let a = Action::RunScript {
interpreter: "posix_sh".into(), interpreter: "posix_sh".into(),
+1
View File
@@ -5,6 +5,7 @@ edition.workspace = true
license.workspace = true license.workspace = true
[dependencies] [dependencies]
rmm-agent-core = { path = "../agent-core", features = ["openssl-verifier"] }
anyhow.workspace = true anyhow.workspace = true
chrono.workspace = true chrono.workspace = true
hex.workspace = true hex.workspace = true
+12 -209
View File
@@ -11,10 +11,7 @@ pub mod reconcile;
mod tests; mod tests;
use anyhow::{Context, Result, ensure}; use anyhow::{Context, Result, ensure};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use openssl::{ use openssl::pkey::{Id, PKey};
pkey::{Id, PKey},
sign::Verifier,
};
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload, hash}; use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload, hash};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{fs, os::unix::fs::MetadataExt, path::Path}; use std::{fs, os::unix::fs::MetadataExt, path::Path};
@@ -50,130 +47,7 @@ impl SigningKey {
} }
} }
#[derive(Debug, Clone, Serialize, Deserialize)] pub use rmm_agent_core::auth::{Binding, Outcome, Request};
#[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(),
}
}
}
/// Config and journal directories must already be bootstrapped by the intended /// Config and journal directories must already be bootstrapped by the intended
/// owner; do not silently chmod a hostile existing path or follow symlinks. /// 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()?; f.try_lock_exclusive()?;
Ok(f) Ok(f)
} }
/// Finite 1 GiB bound for durable agent/helper history. Unexpected page sizes pub use rmm_agent_core::ledger::{bounded_journal_capacity, consume, finish};
/// 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 fn open_ledger(dir: &Path, uid: u32) -> Result<rusqlite::Connection> { pub fn open_ledger(dir: &Path, uid: u32) -> Result<rusqlite::Connection> {
use std::os::unix::fs::OpenOptionsExt; use std::os::unix::fs::OpenOptionsExt;
@@ -229,85 +94,23 @@ pub fn open_ledger(dir: &Path, uid: u32) -> Result<rusqlite::Connection> {
f.sync_all()?; f.sync_all()?;
private_path(&path, uid, false)?; private_path(&path, uid, false)?;
let db = rusqlite::Connection::open(path)?; let db = rusqlite::Connection::open(path)?;
bounded_journal_capacity(&db)?; rmm_agent_core::ledger::initialize_ledger(&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");
fs::File::open(dir)?.sync_all()?; fs::File::open(dir)?.sync_all()?;
Ok(db) Ok(db)
} }
pub fn consume(db: &mut rusqlite::Connection, p: &ExecutionPermitPayload) -> Result<()> { /// Persist the same exact request/boot/time evidence through the shared ledger.
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( pub fn save_start(
db: &rusqlite::Connection, db: &rusqlite::Connection,
permit: &ExecutionPermitPayload, permit: &ExecutionPermitPayload,
request: &Request, request: &Request,
) -> Result<()> { ) -> Result<()> {
let job: JobPayload = serde_json::from_slice(&request.job_bytes)?; rmm_agent_core::ledger::save_start(
let recorded_at = Utc::now(); db,
let deadline = match job.action { permit,
rmm_domain::jobs::Action::Reboot { request,
reconnect_timeout_seconds, Uuid::parse_str(&rmm_agent_linux::boot_id()?)?,
.. Utc::now(),
} => 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(())
} }
pub fn script(job: &JobPayload) -> Result<Outcome> { pub fn script(job: &JobPayload) -> Result<Outcome> {
+14 -5
View File
@@ -262,11 +262,11 @@ pub async fn permit(
}; };
let payload: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?; 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 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 if row.get::<Uuid, _>("bound_asset") != payload.asset_id
|| !capabilities || !payload
.as_array() .action
.is_some_and(|c| c.iter().any(|v| v.as_str() == Some(payload.action.name()))) .available_for(&payload.execution_identity, &capabilities)
|| hash(&row.get::<Vec<u8>, _>("plan_payload")) != row.get::<String, _>("plan_hash") || hash(&row.get::<Vec<u8>, _>("plan_payload")) != row.get::<String, _>("plan_hash")
|| !plan.jobs.iter().any(|j| { || !plan.jobs.iter().any(|j| {
j.payload.job_id == payload.job_id 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?{ 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()}))) 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 { let Some(row) = row else {
tx.commit().await?; tx.commit().await?;
return Ok(None); 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") sqlx::query("UPDATE outbox SET lease_until=now()+interval '30 seconds' WHERE job_id=$1")
.bind(row.get::<Uuid, _>("job_id")) .bind(row.get::<Uuid, _>("job_id"))
.execute(&mut *tx) .execute(&mut *tx)
+303 -25
View File
@@ -107,6 +107,8 @@ pub struct Rollout {
pub struct PlanInput { pub struct PlanInput {
pub targets: Targets, pub targets: Targets,
pub action: Action, pub action: Action,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub script_variants: Vec<Variant>,
pub execution_identity: String, pub execution_identity: String,
pub schedule: Schedule, pub schedule: Schedule,
pub max_runtime_seconds: u32, pub max_runtime_seconds: u32,
@@ -144,7 +146,7 @@ struct WebSchedule {
} }
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)] #[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
struct Variant { pub struct Variant {
os_family: String, os_family: String,
interpreter: String, interpreter: String,
encoding: String, encoding: String,
@@ -200,21 +202,17 @@ impl PlanRequest {
|value: Option<String>| value.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR")); |value: Option<String>| value.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
let action = match w.action.as_str() { let action = match w.action.as_str() {
"run_script" => { "run_script" => {
let mut variants = p let variants = p
.variants .variants
.as_ref()
.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"))?; .ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"))?;
if variants.len() != 1 { validate_variants(variants)?;
return Err(fail("AMBIGUOUS_TARGET")); let v = &variants[0];
}
let v = variants.remove(0);
if v.os_family != "linux" || v.encoding != "utf-8" {
return Err(fail("UNSUPPORTED_CAPABILITY"));
}
Action::RunScript { Action::RunScript {
interpreter: v.interpreter, interpreter: v.interpreter.clone(),
script_utf8: v.script_utf8, script_utf8: v.script_utf8.clone(),
arguments: p.arguments.unwrap_or_default(), arguments: p.arguments.clone().unwrap_or_default(),
expected_stdout: p.expected_stdout, expected_stdout: p.expected_stdout.clone(),
} }
} }
"refresh_inventory" => Action::RefreshInventory { "refresh_inventory" => Action::RefreshInventory {
@@ -287,6 +285,7 @@ impl PlanRequest {
Ok(PlanInput { Ok(PlanInput {
targets: w.targets, targets: w.targets,
action, action,
script_variants: p.variants.unwrap_or_default(),
execution_identity: p.execution_identity, execution_identity: p.execution_identity,
schedule: Schedule { schedule: Schedule {
not_before: w.schedule.not_before, 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<()> { async fn policy(tx: &mut Transaction<'_, Postgres>) -> Result<()> {
let stopped: bool = sqlx::query_scalar("SELECT changes_stopped FROM tenants") let stopped: bool = sqlx::query_scalar("SELECT changes_stopped FROM tenants")
.fetch_one(&mut **tx) .fetch_one(&mut **tx)
@@ -353,7 +417,7 @@ pub async fn plan(
if matches!(input.action, Action::Reboot { .. }) && input.rollout.max_parallel != 1 { if matches!(input.action, Action::Reboot { .. }) && input.rollout.max_parallel != 1 {
return Err(fail("POLICY_DENIED")); return Err(fail("POLICY_DENIED"));
} }
let mut ids = input.targets.asset_ids; let mut ids = input.targets.asset_ids.clone();
ids.sort(); ids.sort();
ids.dedup(); ids.dedup();
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?; let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
@@ -384,11 +448,9 @@ pub async fn plan(
})); }));
} }
let row = &rows[0]; let row = &rows[0];
let caps: Value = row.get("capabilities"); let caps = capabilities(row.get("capabilities"))?;
if !caps let action = target_action(&input, &caps)?;
.as_array() if !action.available_for(&input.execution_identity, &caps) {
.is_some_and(|c| c.iter().any(|v| v.as_str() == Some(input.action.name())))
{
return Err(fail("UNSUPPORTED_CAPABILITY")); return Err(fail("UNSUPPORTED_CAPABILITY"));
} }
let payload = JobPayload { let payload = JobPayload {
@@ -400,7 +462,7 @@ pub async fn plan(
assignment_version: row.get::<i64, _>("assignment_version") as u64, assignment_version: row.get::<i64, _>("assignment_version") as u64,
job_id: Uuid::new_v4(), job_id: Uuid::new_v4(),
attempt_id: Uuid::new_v4(), attempt_id: Uuid::new_v4(),
action: input.action.clone(), action,
execution_identity: input.execution_identity.clone(), execution_identity: input.execution_identity.clone(),
not_before: input.schedule.not_before, not_before: input.schedule.not_before,
start_before: input.schedule.start_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")); return Err(fail("AUTHORIZATION_REVOKED"));
} }
let caps: Value = r.get("capabilities"); let caps = capabilities(r.get("capabilities"))?;
if !caps.as_array().is_some_and(|c| { if !job
c.iter() .payload
.any(|v| v.as_str() == Some(job.payload.action.name())) .action
}) { .available_for(&job.payload.execution_identity, &caps)
{
return Err(fail("UNSUPPORTED_CAPABILITY")); 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 { if hash(&encode(&job.payload)?) != job.job_payload_hash {
return Err(fail("PLAN_HASH_MISMATCH")); 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}), 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();
}
}
+1
View File
@@ -78,6 +78,7 @@ pub async fn query(
asset_ids: vec![i.asset_id], asset_ids: vec![i.asset_id],
}, },
action, action,
script_variants: vec![],
execution_identity: "agent_service".into(), execution_identity: "agent_service".into(),
schedule: crate::jobs::Schedule { schedule: crate::jobs::Schedule {
not_before: Utc::now(), not_before: Utc::now(),
+47
View File
@@ -0,0 +1,47 @@
# Native gemeinsame Core-Unitabnahme
`shared_core_acceptance.py` führt ausschließlich die zwei source-/hashgebundenen
Testprogramme `contracts` und `reconcile` aus: eigene temporäre SQLite-Fixturen,
Testsignaturen, Fake-Clock und Fake-Channel. Keine RMM-Jobs, Hello-Wirkung,
Enrollment, Schlüsselzugriffe, Runtimeersetzung, Dienste oder Serverkontakte.
Die Tests enthalten keine Netzwerkstrecke; der Runner behauptet keine zusätzliche
OS-Netzwerksandbox. Bootstraptransport bleibt vorhandenes hostkeygeprüftes SSH/SFTP.
**Tatsächlich ausgeführt, 2026-11-14:**
```sh
python3 deploy/shared_core_acceptance.py linux
python3 deploy/shared_core_acceptance.py windows --case-id 4bc4db12-2990-4e93-bb86-8fbd94b691fb
```
Fall `4bc4db12-2990-4e93-bb86-8fbd94b691fb`: Linux 25/25 und danach Windows
24/24 nativ bestanden, jeweils ohne Skip. Permanente Dienste wurden nicht
ersetzt; insbesondere kein Windows-Job- oder Dienst-Syncnachweis daraus.
Der Runner prüft beide privaten Qualifikationsmanifeste, sämtliche gebundenen
Quellhashes und genau zwei Artefakte. Linux läuft zuerst (5+20 Fälle). Windows
(4+20 Fälle) verlangt denselben gespeicherten vollständigen Linux-Nativbeleg und
bindet dessen SHA256. Alle Fälle müssen erfolgreich und ohne Skip ausgeführt sein.
Exakte Testargumente: ausschließlich `--test-threads=1`.
Lokale Intent-/Start-/Readback-/PASS-Dateien unter
`devstate/shared-core/acceptance/<UUID>/` entstehen create-only. Remote nur eigene
geschützte Bootstrap-Testverzeichnisse: Linux
`/var/lib/rmm-shared-core-acceptance/<UUID>/<SHA256>/`, Windows bestehendes
`C:\ProgramData\RustDiscoveryBootstrap\<SHA256>\windows-core-*.exe` und eigener
`shared-core-<UUID>`-Fall. Ausgaben/Fehler bleiben privat; stdout enthält nur
sanitisierten Status und bei PASS Fall-/Artefakt-/Nachweishashes.
Bei verlorener Ausführungsantwort **nicht erneut starten**. Ausschließlich
vorhandene Remotequittungen lesen:
```sh
# GEPLANT, NICHT AUSGEFÜHRT: keine erneute Testausführung.
python3 deploy/shared_core_acceptance.py finish-linux --case-id <UUID>
python3 deploy/shared_core_acceptance.py finish-windows --case-id <UUID>
```
Fehlt eine Quittung, bleibt die Abnahme unvollständig; kein automatisches Resume,
keine Bereinigung oder Wiederholung. Native Unittests ersetzen weder den späteren
Linux-Dienst-Syncnachweis des extrahierten Kerns noch Windows-WebUI-/Clock-/
Prozess-/Jobabnahmen. Der aktuelle Windowsclient erhält dadurch keine Jobfähigkeit.
+252
View File
@@ -0,0 +1,252 @@
#!/usr/bin/env python3
"""Fixed native shared-core unit qualification: Linux FIRST, then Windows.
No RMM jobs, enrollment, runtime replacement, daemon changes or server contact.
A lost execution reply permits readback only, never an automatic test rerun.
"""
import argparse
import base64
import contextlib
import hashlib
import io
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import uuid
import remote_client_bootstrap as linux
import vm_mvp_acceptance as contract
from windows import client_bootstrap as windows
ROOT = Path(__file__).resolve().parents[1]
STATE = ROOT / 'devstate/shared-core/acceptance'
KINDS = ('contracts', 'reconcile')
REMOTE_LINUX = '/var/lib/rmm-shared-core-acceptance'
def sha(data):
return hashlib.sha256(data).hexdigest()
def write_new(path, value):
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
contract.write_private(path, value)
def qualified(platform):
folder = ROOT/'devstate'/('shared-core' if platform == 'linux' else 'windows-core')
manifest = contract.protected_json(folder/'manifest.json')
sources = [ROOT/'Cargo.toml', ROOT/'Cargo.lock', ROOT/'rust-toolchain.toml']
for name in ('agent-core', 'domain', 'protocol'):
sources.extend(p for p in (ROOT/'crates'/name).rglob('*') if p.is_file() and (p.suffix == '.rs' or p.name == 'Cargo.toml'))
sources.extend((ROOT/'proto').glob('*.proto'))
actual = {str(p.relative_to(ROOT)): sha(p.read_bytes()) for p in sources}
contract.require(manifest['source_files'] == actual and manifest['source_before_after_equal'] is True, 'qualified source bindings changed')
target = 'x86_64-unknown-linux-gnu' if platform == 'linux' else 'x86_64-pc-windows-gnu'
contract.require(manifest['schema_version'] == 1 and manifest['target'] == target and manifest['os_effects'] is False and manifest['native_vm_executed'] is False, 'fixed test-only qualification')
contract.require(all(manifest['checks'][n] is True for n in ('rustfmt_check', 'linux_all_target_clippy_warnings_denied', 'windows_all_target_clippy_warnings_denied')), 'qualified checks')
artifacts = {}
for kind, item in zip(KINDS, manifest['artifacts'], strict=True):
path = folder/(kind + ('.exe' if platform == 'windows' else ''))
contract.require(item['path'] == str(path.relative_to(ROOT)) and not path.is_symlink() and path.is_file(), 'fixed artifact path')
contract.require(stat.S_IMODE(path.stat().st_mode) == 0o600 and path.stat().st_uid == os.getuid(), 'private artifact owner/mode')
contract.require(item['binary_sha256'] == sha(path.read_bytes()) and item['size_bytes'] == path.stat().st_size, 'artifact hash/size')
contract.require(item['test_count'] == (20 if kind == 'reconcile' else (5 if platform == 'linux' else 4)), 'fixed test count')
artifacts[kind] = item
return dict(manifest_sha256=sha((folder/'manifest.json').read_bytes()), artifacts=artifacts)
# Functions sent by the existing pinned SSH/bootstrap RPC. Only fixed test files
# are touched, never production journals, keys, packages, services or endpoints.
def linux_case(payload):
import stat
root = Path('/var/lib/rmm-shared-core-acceptance')
ident = str(uuid.UUID(payload['id']))
require(ident == payload['id'] and payload['action'] in ('prepare', 'run', 'read'), 'fixed case')
entries = payload['artifacts']
require(set(entries) == {'contracts', 'reconcile'}, 'two fixed test artifacts')
for kind, item in entries.items():
require(len(item['binary_sha256']) == 64 and all(c in '0123456789abcdef' for c in item['binary_sha256']), 'fixed hash')
require(item['test_count'] == (5 if kind == 'contracts' else 20), 'fixed test count')
require(os.geteuid() == 0, 'bootstrap root only')
def safe(path, directory):
m = path.lstat()
require(not stat.S_ISLNK(m.st_mode) and m.st_uid == 0 and not m.st_mode & 0o022 and (stat.S_ISDIR(m.st_mode) if directory else stat.S_ISREG(m.st_mode)), 'private fixed test path')
def save(path, value):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'w') as out:
json.dump(value, out); out.flush(); os.fsync(out.fileno())
if not root.exists(): root.mkdir(mode=0o700)
safe(root, True)
case = root/ident
if payload['action'] == 'prepare':
case.mkdir(mode=0o700)
save(case/'intent.json', dict(id=ident, artifacts=entries, linux_manifest_sha256=payload['linux_manifest_sha256'], windows_manifest_sha256=payload['windows_manifest_sha256'], test_only=True))
for item in entries.values(): (case/item['binary_sha256']).mkdir(mode=0o700)
return dict(prepared=True)
safe(case, True); safe(case/'intent.json', False)
intent = json.loads((case/'intent.json').read_bytes())
require(intent['artifacts'] == entries and intent['linux_manifest_sha256'] == payload['linux_manifest_sha256'] and intent['windows_manifest_sha256'] == payload['windows_manifest_sha256'], 'same native intent')
kind = payload['kind']; require(kind in ('contracts', 'reconcile'), 'fixed test kind')
result_path = case/(kind+'-result.json')
if payload['action'] == 'read':
safe(result_path, False)
return json.loads(result_path.read_bytes())
save(case/(kind+'-started.json'), dict(kind=kind, binary_sha256=entries[kind]['binary_sha256']))
path = case/entries[kind]['binary_sha256']/kind
safe(path.parent, True); safe(path, False)
require(hashlib.sha256(path.read_bytes()).hexdigest() == entries[kind]['binary_sha256'], 'pinned test hash')
path.chmod(0o500)
outputs = []
for label in ('stdout', 'stderr'):
outputs.append(open(case/(kind+'-'+label+'.bin'), 'xb'))
os.chmod(outputs[-1].name, 0o600)
timed_out = False
try:
try:
result = subprocess.run([str(path), '--test-threads=1'], stdin=subprocess.DEVNULL, stdout=outputs[0], stderr=outputs[1], timeout=25)
code = result.returncode
except subprocess.TimeoutExpired:
timed_out = True; code = None
finally:
for out in outputs: out.flush(); os.fsync(out.fileno()); out.close()
raw = [(case/(kind+'-'+label+'.bin')).read_bytes() for label in ('stdout', 'stderr')]
require(all(len(b) <= 1024*1024 for b in raw), 'fixed unit output bound')
report = dict(kind=kind, binary_sha256=entries[kind]['binary_sha256'], exit_code=code, timed_out=timed_out, stdout_b64=base64.b64encode(raw[0]).decode(), stderr_b64=base64.b64encode(raw[1]).decode(), native_platform='linux')
save(result_path, report)
return report
WINDOWS = r'''
$ErrorActionPreference='Stop'
$p=([Console]::In.ReadLine() | ConvertFrom-Json)
if ([string]([guid]$p.id) -cne $p.id -or $p.kind -notin @('contracts','reconcile') -or $p.action -notin @('run','read') -or $p.sha256 -notmatch '^[0-9a-f]{64}$' -or $p.linux_evidence_sha256 -notmatch '^[0-9a-f]{64}$') {throw 'Fixed native core case'}
$root='C:\ProgramData\RustDiscoveryBootstrap'
$case=Join-Path $root ('shared-core-'+$p.id)
function Safe([string]$path,[bool]$directory) {
$i=Get-Item -LiteralPath $path -Force
if ($i.PSIsContainer -ne $directory -or ($i.Attributes -band [IO.FileAttributes]::ReparsePoint)) {throw 'Fixed test path type'}
$a=Get-Acl -LiteralPath $path
if ($a.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin @('S-1-5-18','S-1-5-32-544')) {throw 'Private test owner'}
$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]))
if (!$rules.Count) {throw 'Empty test DACL'}
foreach($r in $rules) {if ($r.AccessControlType -ne 'Allow' -or $r.IdentityReference.Value -notin @('S-1-5-18','S-1-5-32-544')) {throw 'Broad test DACL'}}
}
function Write-New([string]$path,$value) {
$b=[Text.Encoding]::UTF8.GetBytes(($value | ConvertTo-Json -Compress -Depth 8))
$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read)
try {$f.Write($b,0,$b.Length);$f.Flush($true)} finally {$f.Dispose()}
}
Safe $root $true
if (!(Test-Path -LiteralPath $case)) {
if ($p.action -ne 'run' -or $p.kind -ne 'contracts') {throw 'Native intent missing'}
New-Item -ItemType Directory -Path $case | Out-Null
Write-New (Join-Path $case 'intent.json') @{id=$p.id;linux_evidence_sha256=$p.linux_evidence_sha256;test_only=$true}
}
Safe $case $true
$intent=Get-Content -LiteralPath (Join-Path $case 'intent.json') -Raw | ConvertFrom-Json
if ($intent.id -cne $p.id -or $intent.linux_evidence_sha256 -cne $p.linux_evidence_sha256) {throw 'Bound Linux-first evidence'}
$result=Join-Path $case ($p.kind+'-result.json')
if ($p.action -eq 'read') {Safe $result $false;Get-Content -LiteralPath $result -Raw;exit 0}
Write-New (Join-Path $case ($p.kind+'-started.json')) @{kind=$p.kind;sha256=$p.sha256}
$folder=Join-Path $root $p.sha256;Safe $folder $true
$exe=Join-Path $folder ('windows-core-'+$p.kind+'.exe');Safe $exe $false
if ((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.sha256) {throw 'Pinned unit hash'}
$out=Join-Path $case ($p.kind+'-stdout.bin');$err=Join-Path $case ($p.kind+'-stderr.bin')
if ((Test-Path -LiteralPath $out) -or (Test-Path -LiteralPath $err)) {throw 'Existing native output'}
$proc=Start-Process -FilePath $exe -ArgumentList @('--test-threads=1') -PassThru -WindowStyle Hidden -RedirectStandardOutput $out -RedirectStandardError $err
$handle=$proc.Handle;$timeout=$false
if (!$proc.WaitForExit(25000)) {$timeout=$true;$proc.Kill();$proc.WaitForExit()}
$proc.Refresh();$code=$proc.ExitCode
if ((Get-Item -LiteralPath $out).Length -gt 1048576 -or (Get-Item -LiteralPath $err).Length -gt 1048576) {throw 'Fixed unit output bound'}
$value=@{kind=$p.kind;binary_sha256=$p.sha256;exit_code=$code;timed_out=$timeout;stdout_b64=[Convert]::ToBase64String([IO.File]::ReadAllBytes($out));stderr_b64=[Convert]::ToBase64String([IO.File]::ReadAllBytes($err));native_platform='windows'}
Write-New $result $value
$value | ConvertTo-Json -Compress -Depth 8
'''
def upload_linux(case, kind, item):
cfg = linux.access.load_config(ROOT/'credentials/linux-vm.conf')
args = ['sftp', '-F', '/dev/null', '-P', cfg.get('port', '22'), '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), '-b', '-', cfg['username']+'@'+cfg['address']]
path = ROOT/item['path']
remote = REMOTE_LINUX+'/'+case.name+'/'+item['binary_sha256']+'/'+kind
batch = 'put '+json.dumps(str(path))+' '+json.dumps(remote)+'\n'
result = subprocess.run(args, input=batch.encode(), capture_output=True, timeout=120)
write_new(case/('linux-'+kind+'-sftp.json'), dict(returncode=result.returncode, stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
contract.require(result.returncode == 0, 'private Linux SFTP failure; inspect case')
def payload(intent, action, kind=None):
return dict(id=intent['id'], action=action, kind=kind, artifacts=intent['linux']['artifacts'], linux_manifest_sha256=intent['linux']['manifest_sha256'], windows_manifest_sha256=intent['windows']['manifest_sha256'])
def verify_result(platform, kind, result, expected):
contract.require(result['native_platform'] == platform and result['kind'] == kind and result['binary_sha256'] == expected['binary_sha256'] and result['exit_code'] == 0 and result['timed_out'] is False, 'native test exit/hash')
out = base64.b64decode(result['stdout_b64'], validate=True)
err = base64.b64decode(result['stderr_b64'], validate=True)
contract.require(len(out) <= 1024*1024 and len(err) <= 1024*1024, 'private unit output limit')
pattern = rb'test result: ok\. '+str(expected['test_count']).encode()+rb' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;'
contract.require(re.search(pattern, out) is not None, 'exact native unit counts, no skipped cases')
def main():
os.umask(0o077)
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('linux', 'windows', 'finish-linux', 'finish-windows'))
parser.add_argument('--case-id')
args = parser.parse_args()
if args.action == 'linux':
contract.require(args.case_id is None, 'new Linux case chooses fresh UUID')
ident = str(uuid.uuid4()); case = STATE/ident
intent = dict(id=ident, linux=qualified('linux'), windows=qualified('windows'))
write_new(case/'intent.json', intent)
else:
contract.require(args.case_id is not None and str(uuid.UUID(args.case_id)) == args.case_id, 'fixed existing case UUID')
case = STATE/args.case_id
intent = contract.protected_json(case/'intent.json')
contract.require(intent['id'] == args.case_id and intent['linux'] == qualified('linux') and intent['windows'] == qualified('windows'), 'same qualified case source/artifacts')
platform = 'linux' if args.action.endswith('linux') else 'windows'
if platform == 'windows':
proof = contract.protected_json(case/'linux-passed.json')
contract.require(proof['id'] == intent['id'] and proof['passed'] is True and proof['qualification'] == intent['linux'], 'Linux-first native qualification required')
for kind in KINDS: verify_result('linux', kind, proof['results'][kind], intent['linux']['artifacts'][kind])
linux_sha = sha((case/'linux-passed.json').read_bytes())
else: linux_sha = None
finish = args.action.startswith('finish-')
if not finish:
write_new(case/(platform+'-started.json'), dict(id=intent['id'], linux_evidence_sha256=linux_sha))
if args.action == 'linux':
linux.rpc('linux-vm.conf', linux_case, payload(intent, 'prepare'))
for kind in KINDS: upload_linux(case, kind, intent['linux']['artifacts'][kind])
results = {}
for kind in KINDS:
if platform == 'linux':
result = linux.rpc('linux-vm.conf', linux_case, payload(intent, 'read' if finish else 'run', kind))
else:
item = intent['windows']['artifacts'][kind]
# Existing bootstrap prints only sanitized failures; keep even these
# in the protected case so this CLI never prints remote diagnostics.
captured = io.StringIO()
try:
with contextlib.redirect_stdout(captured):
if not finish: windows.upload(ROOT/item['path'], 'windows-core-'+kind+'.exe')
result = windows.powershell(WINDOWS, dict(id=intent['id'], kind=kind, action='read' if finish else 'run', sha256=item['binary_sha256'], linux_evidence_sha256=linux_sha), timeout=40)
finally:
write_new(case/('windows-'+kind+'-transport-'+uuid.uuid4().hex+'.json'), dict(sanitized_bootstrap_output=captured.getvalue()))
write_new(case/(platform+'-'+kind+'-readback-'+uuid.uuid4().hex+'.json'), result)
verify_result(platform, kind, result, intent[platform]['artifacts'][kind]); results[kind] = result
proof = dict(id=intent['id'], passed=True, native_platform=platform, qualification=intent[platform], linux_evidence_sha256=linux_sha, results=results)
destination = case/(platform+'-passed.json')
if destination.exists(): contract.require(contract.protected_json(destination) == proof, 'identical original native proof')
else: write_new(destination, proof)
print(json.dumps(dict(result='PASS', native_platform=platform, case_id=intent['id'], evidence_sha256=sha(destination.read_bytes()), artifact_sha256={k:v['binary_sha256'] for k,v in intent[platform]['artifacts'].items()})))
if __name__ == '__main__':
try: main()
except Exception as error:
print('SHARED_CORE_ACCEPTANCE_INCOMPLETE:'+type(error).__name__)
raise SystemExit(2) from None
+2 -2
View File
@@ -45,7 +45,7 @@ def powershell(script, payload=None, timeout=60, remote_signed=False):
UPLOAD = r''' UPLOAD = r'''
$ErrorActionPreference='Stop' $ErrorActionPreference='Stop'
$p=([Console]::In.ReadLine() | ConvertFrom-Json) $p=([Console]::In.ReadLine() | ConvertFrom-Json)
if ($p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin|acl))\.exe|Install-PassiveClient\.ps1|PassiveStateProbe\.exe|WindowsTlsProbe\.exe)$') {throw 'Artifact allowlist'} if ($p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin|acl)|windows-core-(contracts|reconcile))\.exe|Install-PassiveClient\.ps1|PassiveStateProbe\.exe|WindowsTlsProbe\.exe)$') {throw 'Artifact allowlist'}
$root='C:\ProgramData\RustDiscoveryBootstrap' $root='C:\ProgramData\RustDiscoveryBootstrap'
if (!(Test-Path -LiteralPath $root)) { if (!(Test-Path -LiteralPath $root)) {
New-Item -ItemType Directory -Path $root | Out-Null New-Item -ItemType Directory -Path $root | Out-Null
@@ -68,7 +68,7 @@ if (Test-Path -LiteralPath $path) {throw 'Artifact already exists'}
VERIFY_UPLOAD = r''' VERIFY_UPLOAD = r'''
$ErrorActionPreference='Stop' $ErrorActionPreference='Stop'
$p=([Console]::In.ReadLine() | ConvertFrom-Json) $p=([Console]::In.ReadLine() | ConvertFrom-Json)
if ($p.sha256 -notmatch '^[0-9a-f]{64}$' -or $p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin|acl))\.exe|Install-PassiveClient\.ps1|PassiveStateProbe\.exe|WindowsTlsProbe\.exe)$') {throw 'Artifact allowlist'} if ($p.sha256 -notmatch '^[0-9a-f]{64}$' -or $p.name -notmatch '^((rmm-agent-windows|windows-tests-(lib|bin|acl)|windows-core-(contracts|reconcile))\.exe|Install-PassiveClient\.ps1|PassiveStateProbe\.exe|WindowsTlsProbe\.exe)$') {throw 'Artifact allowlist'}
$path='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\'+$p.name $path='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\'+$p.name
$hash=(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() $hash=(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()
if ($hash -cne $p.sha256) {throw 'Artifact hash'} if ($hash -cne $p.sha256) {throw 'Artifact hash'}
+11
View File
@@ -52,6 +52,17 @@ Zugänge und private Rohbelege bleiben gitignoriert.
## Aktuelle Windowsfortsetzung ## Aktuelle Windowsfortsetzung
**Fortsetzung 2026-11-14:** Gemeinsamer `rmm-agent-core` und Linuxadapter
implementiert. Eigene Core-Unittests zuerst auf Cloud-Linux (25) und danach auf
Windows (24) nativ ohne Skip bestanden; Fall
`4bc4db12-2990-4e93-bb86-8fbd94b691fb`. Geschützte Manifest-/Quell-/Artefaktbindung
in `devstate/shared-core/acceptance/<Fall>/`. Keine Dienst-/Serverersetzung oder
Jobwirkung durch diese Tests. Native Dienstintegration, vertrauenswürdige Uhr
und erste tatsächliche WebUI-genehmigte PowerShell-Strecke bleiben offen.
Server/Domain/WebUI unterstützen lokal geprüft feste Plattformvarianten;
Clouddeployment steht noch aus. Vollständiger Restumfang:
[Windows-Gates](windows-gates.md), [Umsetzungsplan](windows-remaining-implementation.md).
Der bestehende Windows-11-LocalService bleibt passiv: gleiche Geräteidentität, Der bestehende Windows-11-LocalService bleibt passiv: gleiche Geräteidentität,
Telemetriehistorie und Schlüssel; keine Jobs, Outbox oder Startgrants. Native Telemetriehistorie und Schlüssel; keine Jobs, Outbox oder Startgrants. Native
WSS-/Inventar-/Tenantnachweise und sieben Rusttests liegen vor. Explizites HTTPS WSS-/Inventar-/Tenantnachweise und sieben Rusttests liegen vor. Explizites HTTPS
+32
View File
@@ -1,5 +1,37 @@
# Tatsächlicher Implementierungsstand # Tatsächlicher Implementierungsstand
## Gemeinsamer Jobkern nativ auf Linux und Windows geprüft — 2026-11-14
Der neue `rmm-agent-core` enthält die gemeinsame signierte Sync-/Checkpoint-
Maschine, Permit-/Request-/Outcome-Codecs, Verbrauchsledger und portable
Jobpersistenz. Linux verwendet diese Implementierung über dünne Adapter;
seine bisherige OpenSSL-Verifikation bleibt erhalten. Windows verwendet Dalek,
ohne OpenSSL-Abhängigkeit. Die bisherigen Linux-Codecbytes bleiben unverändert.
Tatsächlich bestanden: 151 betroffene lokale Rusttests und Clippy; danach im
eigenen Fall `4bc4db12-2990-4e93-bb86-8fbd94b691fb` zuerst 25 native
Core-Unittests auf der Cloud-Linux-VM, anschließend 24 auf der Windows-VM,
jeweils ohne Skip. Quell-/Artefakthashes und vollständige Ausgabe bleiben in
geschützten Manifesten und `devstate/shared-core/acceptance/<Fall>/` erhalten.
Die unterschiedlichen Zahlen entstehen durch den zusätzlichen Unix-OpenSSL-
Paritytest. Diese Programme verwenden ausschließlich eigene SQLite-Fixturen,
Testsignaturen und simulierte Clock/Channel-Objekte. Kein RMM-Job, Dienstwechsel,
Enrollment oder Netzwerkpfad wurde damit ausgeführt. Ein nativer Sync des
laufenden Dienstes mit dem extrahierten Kern bleibt separat nachzuweisen.
Server/Domain/WebUI sind additiv für feste Windows-/Linux-Skriptvarianten und
Windows-Basisinventur vorbereitet. Gemeinsame Plattform-/Capabilityprüfung bei
Planung, erneuter Prüfung, Grant und Zustellung; vor Genehmigung unverändert
0 Jobs/Outbox/Grants. Exakte stdout-Nachbedingungen lassen sich als JSON-String
einschließlich CRLF eingeben. Lokal bestanden: 14 Domainfälle einschließlich
Linux-Goldenbytes, Variantenprüfung, isolierter PostgreSQL-Test mit Migrationen
und Tenant-/Capability-Verweigerungen, Clippy sowie 29 Webtests/Typecheck.
Dies ist noch kein Clouddeployment oder Windows-Ausführungsnachweis.
Windows-Dienst, Identität und bisherige passive Capabilities blieben bei diesem
Schritt unverändert. Clock-, Executor-, Helper-, Paket- und übrige native
Windows-Abnahmen laufen weiter; die Plattform meldet dafür keinen Erfolg.
## Windows: dauerhaftes Auto auf bestehender VM nativ bestanden — 2026-11-13 ## Windows: dauerhaftes Auto auf bestehender VM nativ bestanden — 2026-11-13
Separater Fall `422562e8-18eb-4865-977d-ab2af65f510b` verifiziert und abgeschlossen. Separater Fall `422562e8-18eb-4865-977d-ab2af65f510b` verifiziert und abgeschlossen.
+1 -1
View File
@@ -11,7 +11,7 @@ bleibt eine eigenständige Abnahme. Dieser Bericht erweitert dessen Umfang nicht
| Passiver Client | SCM-Dienst, Service-SID/ACLs, Enrollment/mTLS/WSS, Inventar mit Quelle/Zeit, Heartbeats und Mandantentrennung nativ bestanden; sieben native Rusttests. | Bestehende Identität und Telemetriehistorie bei allen weiteren Schritten erhalten. | | Passiver Client | SCM-Dienst, Service-SID/ACLs, Enrollment/mTLS/WSS, Inventar mit Quelle/Zeit, Heartbeats und Mandantentrennung nativ bestanden; sieben native Rusttests. | Bestehende Identität und Telemetriehistorie bei allen weiteren Schritten erhalten. |
| HTTPS/Fallback | Explizites HTTPS und automatischer Fallback nach zwei tatsächlichen mTLS-WSS503 unter LocalService nativ bestanden, jeweils mit frischen Heartbeats und Inventar-ACK. Testhooks geschlossen. Anschließend bestehende VM separat dauerhaft auf `auto` gestellt und bevorzugtes WSS erneut mit zwei frischen Heartbeats/ACK geprüft; Identität und ACLs erhalten, 0 Jobs/Grants. | Transportnachweise abgeschlossen; kein automatischer HTTPS→WSS-Switchback nachgewiesen. Installerdefault ebenfalls `auto`, aber keine neue Installationsabnahme. | | HTTPS/Fallback | Explizites HTTPS und automatischer Fallback nach zwei tatsächlichen mTLS-WSS503 unter LocalService nativ bestanden, jeweils mit frischen Heartbeats und Inventar-ACK. Testhooks geschlossen. Anschließend bestehende VM separat dauerhaft auf `auto` gestellt und bevorzugtes WSS erneut mit zwei frischen Heartbeats/ACK geprüft; Identität und ACLs erhalten, 0 Jobs/Grants. | Transportnachweise abgeschlossen; kein automatischer HTTPS→WSS-Switchback nachgewiesen. Installerdefault ebenfalls `auto`, aber keine neue Installationsabnahme. |
| TLS-Lifecycle | Falsche CA, falscher Name und abgelaufenes Clientzertifikat mit gültigen Kontrollen nativ als getrennte Admin-TLS-Proben bestanden. Permanente Identität/Dienst unverändert. | Rotation und Widerruf noch gesondert sicher implementieren und prüfen. Permanente Identität nicht widerrufen oder ersetzen. | | TLS-Lifecycle | Falsche CA, falscher Name und abgelaufenes Clientzertifikat mit gültigen Kontrollen nativ als getrennte Admin-TLS-Proben bestanden. Permanente Identität/Dienst unverändert. | Rotation und Widerruf noch gesondert sicher implementieren und prüfen. Permanente Identität nicht widerrufen oder ersetzen. |
| Signierter Jobkern | Windows verweigert Jobangebote/Grants ausdrücklich und meldet keine Ausführungscapability. | Gemeinsamen Sync-/Checkpoint-/Einmalverbrauchskern portieren; vertrauenswürdige Uhr, Journalmigration ohne Reset, Schlüsselbindung und Fehlerpfade qualifizieren. | | Signierter Jobkern | Gemeinsamer Core und Linuxadapter implementiert; native Core-Unittests zuerst Linux (25), dann Windows (24) bestanden. Bestehender Windows-Dienst bleibt passiv und verweigert Jobs/Grants. | Native Dienstintegration, vertrauenswürdige Uhr, erhaltende Journalmigration und vollständige Startgrenze qualifizieren. Unit-Fixturen ersetzen keinen tatsächlichen Jobnachweis. |
| PowerShell | Noch kein Executor oder freigegebener Interpreter. Server/UI lösen derzeit Linuxvarianten auf. | Exakte Windows-PowerShell-5.1-Bytes, Ausgabeencoding, Prozessgrenzen und unprivilegierte Ausführungsidentität binden. Erst nach vollständigem Antrag und tatsächlichem WebUI-Klick ausführen. | | PowerShell | Noch kein Executor oder freigegebener Interpreter. Server/UI lösen derzeit Linuxvarianten auf. | Exakte Windows-PowerShell-5.1-Bytes, Ausgabeencoding, Prozessgrenzen und unprivilegierte Ausführungsidentität binden. Erst nach vollständigem Antrag und tatsächlichem WebUI-Klick ausführen. |
| Privilegierte Aktionen | Kein Windows-Helper, keine Named-Pipe-Aktionsschnittstelle. | Eigenständiger restriktiver Helper mit geprüfter Pipe-Identität und unabhängiger Signatur-/Plan-/Grantprüfung; keine SYSTEM-Netzwerkkomponente. | | Privilegierte Aktionen | Kein Windows-Helper, keine Named-Pipe-Aktionsschnittstelle. | Eigenständiger restriktiver Helper mit geprüfter Pipe-Identität und unabhängiger Signatur-/Plan-/Grantprüfung; keine SYSTEM-Netzwerkkomponente. |
| Pakete/Dienste/Logs | Noch keine native Windows-Aktionsabnahme. | Begrenzte geprüfte MSI-/EXE-Rezepte, Dienst-/Eventlogadapter und unabhängige Nachbedingungen. Keine allgemeinen Installershellstrings oder impliziten Reboots. | | Pakete/Dienste/Logs | Noch keine native Windows-Aktionsabnahme. | Begrenzte geprüfte MSI-/EXE-Rezepte, Dienst-/Eventlogadapter und unabhängige Nachbedingungen. Keine allgemeinen Installershellstrings oder impliziten Reboots. |
+237
View File
@@ -0,0 +1,237 @@
# Windows: verbleibende Umsetzung nach der passiven Foundation
Stand 2026-11-14, Spezifikation1.15. **Umsetzungsplan, keine native Abnahme.**
Linux-M0–M5 bleiben separat abgeschlossen. Der Windows-Testgast ist ein eigenes
Gerät; das Notebook bleibt Entwicklungsrechner. Server bleibt
`discovery.ease-technologies.de`. RustDesk, PVE und M7 werden nicht vorgezogen.
Diese Planung erstellt weder Jobs noch Grants und verändert keine Zielmaschine.
Die passive Windowsstrecke umfasst bereits LocalService, Enrollment/mTLS,
WSS/HTTPS/Auto-Fallback und gespeicherte Telemetrie. TLS-Negativproben als
Bootstrapadministrator ersetzen keine LocalService-Negativprobe oder Rotation.
Der gemeinsame Agentkern und die additive Plattform-/Interpreterplanung werden
aktuell separat qualifiziert. Keine daraus abgeleitete Windowscapability oder
Jobbereitschaft behaupten. Vor dem ersten Hello gelten weiterhin
[Jobgrenze](windows-job-boundary.md) und [Windows-Gates](windows-gates.md).
## Reihenfolge mit konkreter Lieferung
| Schritt | Kleinste lauffähige Lieferung | Eigener nativer Nachweis |
| --- | --- | --- |
| W1 unprivilegierte Jobs | Konfigurierte Signingbindung, TrustedClock, gemeinsamer signierter Sync, erhaltendes Jobjournal und begrenzter PowerShell5.1-Executor unter LocalService. | Fester UI-Hello mit exakten Rohbytes; Live-Inventur; ACK/Redelivery, Offline/Frist/Entzug, Prozessabbruch und gesperrter Wiederanlauf. Keine SYSTEM-Ausnahme. |
| W2 Helpergrenze | Ein lokaler SYSTEM-Dienst ohne Netzwerklistener, wechselseitig authentisierte Named Pipe, eigenes geschütztes Ledger, unabhängige Signatur-/Sync-/Policyprüfung. Zunächst alle Wirkungen verweigert. | Erreichbarkeit aus dem eigenen LocalService, fremde SID/PID, Pipebesetzung, falsche Signatur/Generation/Hash/Frist und volle Journale verweigert; keine Wirkung. |
| W3 Dienst und Logs | Nur eigener ungefährlicher Fixturedienst; SCM-Aktion und begrenzter Event-Log-Provider. | Je eigener UI-Plan für Start/Stop/Nachprüfung und Live-Logfenster, unabhängige OS-Nachprüfung; sensible/fremde Quellen verweigert. |
| W4 MSI und EXE | Je ein geprüftes, kleines Fixture-Rezept, feste Versionen1.0/1.1, eigener Produkt-/Dateinachweis, kein Reboot. | Native Installation, Upgrade und Noop je festem UI-Plan; Paketbestand/Nutzdateien unabhängig prüfen. MSI und EXE sind getrennte Providerabnahmen. |
| W5 Wiederaufnahme und Reboot | Bewahrte Originalaufträge/Marker; genau ein ausdrücklich erlaubter Windows-Reboot mit ursprünglichem Grant und neuer Bootkennung. | Kein blindes Wiederholen nach Wirkung; rechtzeitiger unabhängiger Wiederkontakt, zusätzlicher frischer Verifikationsbeleg und normaler signierter Abschluss. |
| W6 Abschluss der Windowsmatrix | Rotation/Widerruf auf getrennter Testidentität, Windows/Linux-Mischplan AT-15, geprüfte unterstützte Inventarquellen, Windows-Installer-/Signiernachweis. | Keine Ableitung aus Linux-/Cross-Build-/Adminproben. Offene Betriebssystemupdate-/Patchfähigkeiten sichtbar lassen, bis ihr eigener Provider und Umfang geprüft sind. |
Jeder Schritt endet mit tatsächlichem Bericht und eigenem Commit/Push. Neue
Wirkungsversuche benötigen neue UI-Pläne. Ein fehlgeschlagener Versuch bleibt
fehlgeschlagen, Unknown bleibt gesperrt bis zum gebundenen Abgleich. Die Tabelle
ist keine pauschale Erlaubnis, Installationen oder einen Windows-Reboot auszuführen.
## Gemeinsamer Nachweisvertrag, Windowsadapter
Bestehende Bytes von `agent-core::auth::{Binding,Request,Outcome}`,
`ExecutionPermitPayload`, Job-/Planhashes und Signaturdomain bleiben erhalten.
Der Helper erhält denselben vollständigen Request wie der Agent und prüft ihn
selbst: Gerät/Kunde/Zuordnung, genaue Jobbytes, Genehmigungsreferenz,
Signierschlüssel, kurze Startfrist und Clock. Vor Wirkung hält er die eigene
Ressourcensperre und persistiert Grant-/Versuchsverbrauch samt Originalboot und
Originalrequest. Gleicher Versuch mit neuer Grant-ID ist keine neue Erlaubnis.
Ergebnis bleibt bis konkretem ACK; `unknown` und `awaiting_reboot` geben den
Verbrauch nicht frei. Der aktuelle gemeinsame Ledgerkern begrenzt SQLite bereits
auf1GiB/4096-Byte-Seiten und ignoriert keine Kapazitätsfehler.
`privileged-helper/src/reconcile.rs` und `control.rs` enthalten derzeit weiterhin
Unix-Datei-/Peerzugriff, OpenSSL und Linux-Boot/Clock. Sie sind kein fertiger
Windowshelper. Deren reine Helper-Abgleichregeln werden wie der Agentkern in
einen gemeinsamen Kern mit Ports für Dateisperre/Dateiidentität, Clock, Boot und
Verifier extrahiert; Linuxbytes und vorhandene Goldenfixtures bleiben identisch.
Keine zweite abweichende Syncmaschine, kein lokales `ready=true` als Ersatz.
Windows bindet Volume-/File-ID der offenen Ledger-/Sperrhandles; Unix-`dev/ino`
werden nicht erfunden. Helper-Snapshot/Apply prüfen die ursprünglichen signierten
Entscheidungsbytes und frische Challenge-/Generationsbindung unabhängig.
Die lokale Windowskonfiguration ist ein neuer, ausdrücklich benannter
SYSTEM-Policyvertrag, kein Linux-Rootpolicyprofil unter anderem Namen. Sie bindet
festes Gerät, Signierschlüssel, Agent-/Helperservice-SIDs, erlaubte Aktionen,
exakte Fixturedienste/Rezepthashes/Logkanäle, Laufzeitgrenzen und
`allow_reboot=false` als Default. Policyhash und Helperbuild müssen im
Readinessnachweis und in der zentralen Zielpolicy übereinstimmen.
## Named Pipe und Identitäten
Ein fest benannter lokaler Pipeendpunkt verwendet explizite DACL,
`PIPE_REJECT_REMOTE_CLIENTS`, `FILE_FLAG_FIRST_PIPE_INSTANCE` beim ersten Server-
Handle und zeitbegrenzte Overlapped-I/O. Keine Default-DACL: Microsoft beschreibt
sonst zusätzliche Lesezugriffe für Everyone/Anonymous. Die Agent-SID erhält nur
die konkreten benötigten Daten-/Attributrechte, kein generisches Schreibrecht,
das zugleich die Erstellung weiterer Pipeinstanzen erlauben kann.
[Pipe-Rechte](https://learn.microsoft.com/en-us/windows/win32/ipc/named-pipe-security-and-access-rights),
[CreateNamedPipeW](https://learn.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-createnamedpipew).
Der Helper liest zunächst nur einen begrenzten Frame, prüft den tatsächlichen
Client-PID und impersonierten Token: LocalService **und** eigene aktivierte
Service-SID, SCM-Prozess und gehaltenes Prozesshandle/Startidentität. LocalService
allein genügt nicht, da weitere Dienste dieses Konto nutzen können. Der Agent
prüft umgekehrt Server-PID, SYSTEM-Token, erwartete Helperservice-SID, SCM-Bindung
und geschützte Helperbinary. PID allein ist wegen Wiederverwendung kein Beleg.
Diese Kombination ist die vorgeschlagene Projektprüfung, keine Garantie einer
Einzel-API. Fehlgeschlagene Impersonation verweigert; vor Handlerausführung
`RevertToSelf` sicherstellen. Keine Kindprozesse unter versehentlich verbliebener
Impersonation starten.
[Client-PID](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getnamedpipeclientprocessid),
[Server-PID](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getnamedpipeserverprocessid),
[Impersonation und Fehlerfall](https://learn.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-impersonatenamedpipeclient).
Helperstate und Konfiguration sind SYSTEM/Administrators-geschützt; der
Netzwerkagent kann sie nicht ersetzen. Bestehende Gerätekeys bleiben beim Agenten,
der Helper erhält ausschließlich die provisionierte öffentliche Signingbindung.
Ein eigener Windowshelper-Binarypfad innerhalb der Windowscrate vermeidet
Unix-Abhängigkeiten des Linuxhelper-Binaries. Bereits vor dem ersten autorisierten
Systemjob müssen Pipeauthentisierung und unabhängiger Sync nativ bestanden sein.
## Minimaler additiver Aktions-/Manifestvertrag
Vorgeschlagen ist ein optionales `windows_manifest` am `JobPayload` mit
`default`/`skip_serializing_if=None`; Linuxjobs behalten exakt ihre historischen
Bytes. Noch keine neue produktive Schemaversion oder Policyentscheidung.
Manifesttyp `rmm.windows.execution`, eigene Version1, strikte Felder:
| Feldgruppe | Inhalt/Prüfung |
| --- | --- |
| Ziel und Auftrag | Kunde, Asset, Agent, Enrollment-/Assignmentgeneration, Job, Versuch und Action; müssen exakt dem Job entsprechen. |
| Runtime/Policy | Plattform/Architektur, Manifestversion, Helperpolicyhash und abgenommene Providerkennung. Keine vom Agenten gewählte Policy. |
| Rezept | Bei Paketaktionen unveränderliche Rezept-ID/-Version/-SHA, Produkt/Version/Installationskontext, Artifact-ID/-SHA/-Länge, fester strukturierter Argumentvektor, feste Exitklassifikation und typisierte Nachbedingungen. |
| Systemaktion | Bei Dienst/Log/Reboot ausschließlich die erforderlichen typisierten Felder und Nachbedingungen; kein Paketmanifest als allgemeiner Shellcontainer. |
Kein `job_payload_hash` innerhalb des Manifests: dieser würde sich selbst
referenzieren. Der Startgrant bindet den Hash des **gesamten** Jobpayloads samt
Manifest. Unbekannte Felder/Provider, widersprüchliche Actionparameter,
abweichende Recipe-/Artifactbytes oder fehlende Nachbedingungen verweigern vor
Verbrauch/Wirkung. Neue Windowsfelder sind Pflicht nur für die entsprechenden
Windowsaktionen; alte APT-Manifeste werden nicht umgedeutet.
Bestehende Fachaktionen bleiben `ensure_package`, `apply_updates`,
`set_service_state`, `query_logs` und `reboot`. Windowsprovider werden additiv
validiert, mit eindeutiger Plattformbindung. `system` wäre ein neuer expliziter
Ausführungsidentitätswert mit eigenem `system:execute`-Recht und eigener
SYSTEM-Policy; Linux-`root` bedeutet niemals Windows-SYSTEM. Freie SYSTEM-Skripte
sind kein notwendiger Ersatz für typisierte Aktionen. Capabilitynamen und genaue
Manifestfelder erst gemeinsam mit Helper/Server festschreiben; keine
Capabilities anbieten, bevor der tatsächliche Adapter bereit ist.
Für Windowsrezepte empfiehlt sich eine eigene immutable Tabelle mit Tenant-RLS,
zusammengesetzten Tenant-FKs und getrennten MSI-/EXE-Kennungen. Der aktuelle
APT-Katalog ist auf `architecture='amd64'` und APT-Abfragen beschränkt; seine
Schlüssel dürfen nicht still für Windowsprodukte wiederverwendet werden.
Bestehende Artifactreferenzen/Hashes können erhalten bleiben. Das aktuelle
Artifactlimit beträgt256KiB: kleine Fixtureartefakte zunächst dagegen prüfen;
eine notwendige größere, begrenzte Übertragung wäre eine eigene implementierte
und getestete Vertragsänderung, kein Bootstrap-SFTP als RMM-Paketnachweis.
## Providerverhalten und überprüfbare Wirkung
**MSI:** Feste systemweite Installation aus dem Helper-eigenen geschützten Cache;
`msiexec /i <fester-cachepfad> /qn /norestart REBOOT=ReallySuppress`, ergänzt nur
um die im Rezept gebundenen Properties. Keine URL, UNC-Quelle, frei gewählte
Transformdatei oder weitere Installerargumente. Nach dem Kopieren erneut hashen,
Pfadkomponenten/Reparsepoints und Schreibrechte prüfen, während der Nutzung
Ersetzung/Änderung verweigern. `0` ist nur ein Prozessresultat; `3010` bedeutet
Neustartbedarf. `1641` meldet bereits eingeleiteten Neustart und verletzt diesen
No-Reboot-Rezeptvertrag; nicht als normale erfolgreiche Abnahme werten.
`1618` respektiert fremde Installation, kein Beenden fremder Prozesse.
[Installeroptionen](https://learn.microsoft.com/en-us/windows/win32/msi/standard-installer-command-line-options),
[REBOOT](https://learn.microsoft.com/en-us/windows/win32/msi/reboot),
[Exitcodes](https://learn.microsoft.com/en-us/windows/win32/msi/error-codes).
Nachprüfung kombiniert `MsiGetProductInfoExW` im expliziten Machine-Kontext
mit installiertem Produktzustand/Version und eigener Fixture-Nutzdatei samt Hash.
Ein beworbenes Produkt ist nicht automatisch installiert. Keine
`Win32_Product`-Erhebung. MSI-Fehler, Timeout oder verlorener Installerkontakt
belegen keine Abwesenheit einer Teilwirkung: gegebenenfalls Unknown und ein
gebundener Nur-Lese-Abgleich, keine automatische neue Installation.
[Produktinformation und Kontext](https://learn.microsoft.com/en-us/windows/win32/api/msi/nf-msi-msigetproductinfoexw).
**EXE:** Eigenes, nachvollziehbar gebautes Fixture mit genau dokumentierten
Quiet-/No-Reboot-Argumenten, Hash, Architektur und Exitsemantik. MSI-Codes gelten
nicht automatisch für EXE. Ausschließlich verifizierte feste Rezeptparameter;
kein beliebiges EXE als SYSTEM ausführen. Nachprüfung über eigene Registry-
Produktkennung und Nutzdatei/Version/Hash. No-Reboot-Flags schützen nicht gegen
beliebige bösartige SYSTEM-Customactions: die ausdrücklich geprüfte Herkunft und
der begrenzte Rezeptumfang bleiben erforderlich. Ein Timeout beendet nicht
pauschal einen systemweiten Installationsdienst oder fremde Installer.
**Dienste:** `OpenSCManager/OpenService` mit benötigten Einzelrechten,
`StartServiceW`/`ControlService`, danach begrenztes Warten und unabhängiges
`QueryServiceStatusEx`. Startannahme ist nicht gleich Running. Zustandsübergänge,
Checkpoint/WaitHint, Dienstexit und fehlende Rechte strukturiert melden.
Abnahme zunächst nur am eigenen Fixturedienst mit festem Binaryhash; nicht am
RMM-Agenten, SSH oder einer fremden Produktionskomponente.
[StartServiceW](https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-startservicew),
[Status](https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-queryservicestatusex),
[SCM-Rechte](https://learn.microsoft.com/en-us/windows/win32/services/service-security-and-access-rights).
**Event Log:** Eigener Kanal-/Providerfilter und fixes Zeitfenster; keine freie
Datei, kein roher vom Modell gelieferter XPath. `EvtQuery/EvtNext/EvtRender`,
maximal1000Events/256KiB und Laufzeitlimit. Quelle, EventRecordID, Provider,
UTC-Zeit, Fehlermeldungen und Trunkierung erhalten; fehlender Zugang bleibt
permission_denied. Bookmark erst nach dauerhafter Übernahme/konkretem ACK
fortschreiben. Einzelnes Livefenster ist ein UI-genehmigter Diagnosejob;
gespeicherte Ergebnisse danach tenantgebunden lesen. Kein allgemeiner Zugriff
auf Security-Kanäle durch die Abnahme eines Fixturekanals.
[Eventabfragen](https://learn.microsoft.com/en-us/windows/win32/wes/querying-for-events),
[Bookmark](https://learn.microsoft.com/en-us/windows/win32/api/winevt/nf-winevt-evtupdatebookmark).
**Reboot:** Nur lokales `InitiateSystemShutdownExW`, fest gebundene Begründung,
keine erzwungene Schließung fremder Anwendungen, eigenes gezielt aktiviertes
Shutdownprivileg im Helper. Dauerhaften Originalverbrauch und Bootbeleg zuerst
speichern. APIannahme ist asynchron und kein Erfolgsnachweis; Anwendungen können
den Vorgang verzögern/verhindern. Konservative zentrale Frist ab Startreservierung
und beide bestehenden Inventarbelege gelten unverändert. Die bisherige
CIM-LastBootUpTime-basierte Windowskennung muss einen tatsächlichen OS-Reboot von
Agent-/Helperneustart und Zeitänderung unterscheiden; aktuelle wiederholte
Abfrage allein beweist das noch nicht.
[Shutdown-API und Einschränkungen](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-initiatesystemshutdownexw).
## Dateien und Freigaben vor nativer Wirkung
Geplante Änderungen, **hier nicht umgesetzt**:
- `crates/domain/src/windows_execution.rs`, `jobs.rs`: strikte Manifest-/Rezept-
und Identitätsprüfung, optionale Jobfelder, erhaltene Linuxgoldenbytes.
- `crates/agent-core`: reiner Helper-Abgleich mit Plattformports;
`crates/privileged-helper`: bestehender Linuxadapter gegen unveränderte Verträge.
- `crates/agent-windows/src/{helper,pipe,service_provider,event_log,package,reboot}.rs`
und eigenes Helperbinary: nur tatsächlich gelieferte Provider anlegen, keine
leeren Stubs; SCM-/IPC-/Datei-/Clockadapter und eigenes Ledger.
- Server `jobs`, `root_policy` oder neue explizite `windows_policy`, `catalog`,
`job_gateway`, `synchronization`: Rechte/Caps an jeder Grenze und unabhängiger
Rebootabschluss; neue RLS-Migration nur für tatsächlich benötigte Windowsrezepte.
- WebUI/Schemas: vollständige unveränderliche Rezept-/Manifest-/Rebootpreview,
keine neue Genehmigungsabkürzung; dieselben Anwendungsfälle für HTTP und MCP.
- `deploy/windows`: erhaltender Helperbootstrap, kleine geprüfte Fixturequelle/
Rezeptartefakte, geschützte native Nachweisrunner und tatsächliche Requalifikation.
Reversible Entwicklung, Builds und Bootstrapvorbereitung sind im Auftrag.
Konkrete native Paket-/Dienstwirkungen brauchen jeweils den fertig einsehbaren
festen dev/test-UI-Plan. Ein Windows-VM-Reboot ist eine gesondert konkret zu
vereinbarende Zielaktion; der frühere einzelne Linux-Reboot erlaubt ihn nicht.
Kein pauschales „alles okay“ anfordern: zuerst Artefakt, Rezept, Ziel, Plan,
No-Reboot-Vertrag, Nachprüfung und Wiederaufnahme vorbereiten, dann nur die
wirklich fehlende konkrete Freigabe klären. Ein Installerfehler berechtigt weder
Markerreset noch zweiten Versuch. Nach jedem Abnahmeschritt dokumentieren/pushen.
Zur vollständigen Windowsabnahme zählen außerdem bisher offene Rotation/
Widerruf, Installer-/Signierstatus und plattformspezifische Fehlerfälle.
MSI-/EXE-Fixtureupdates sind kein Nachweis von Windows-OS-/Kernelupdates.
Ein WUA-Provider benötigt eigene COM-Threads, versionierte Scan-/Update-IDs,
Updateeinzelergebnisse und eigene Start-/Nachprüfung; solange nicht geliefert
bleibt diese Capability unsupported. Microsofts Beispiele sind keine fertigen
Produktprovider: [WUA-Vertrag](https://learn.microsoft.com/en-us/windows/win32/wua_sdk/using-the-windows-update-agent-api).
Diese Grenzen dürfen bei einem späteren „Windows vollständig“ nicht verschwinden.
Für diesen Plan wurden ausschließlich Repositoryquellen und die verlinkten
Microsoft-Primärquellen gelesen. Keine neuen Tests, Builds, Dienste,
Installationen, Genehmigungen oder VM-/Serverkontakte ausgeführt.
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Fixed Linux/Windows plan guards against isolated PostgreSQL; no approval/job."""
from pathlib import Path
import subprocess
import time
import uuid
ROOT=Path(__file__).resolve().parents[1]
NAME='rmm-windows-plan-'+uuid.uuid4().hex[:10]
def command(args, data=None, timeout=120):
result=subprocess.run(args,input=data,capture_output=True,timeout=timeout)
if result.returncode:
raise RuntimeError(result.stderr.decode(errors='replace')[-4000:])
return result.stdout
def main():
command(['docker','run','-d','--network','none','--name',NAME,
'-e','POSTGRES_HOST_AUTH_METHOD=trust','postgres:17.6-bookworm'])
try:
for _ in range(100):
logs=command(['docker','logs',NAME])
ready=subprocess.run(['docker','exec',NAME,'pg_isready','-U','postgres'],capture_output=True)
if b'init process complete' in logs and ready.returncode==0:break
time.sleep(.2)
else:raise RuntimeError('ISOLATED_POSTGRES_NOT_READY')
def sql(raw):
return command(['docker','exec','-i',NAME,'psql','-X','-qAt','-v','ON_ERROR_STOP=1','-U','postgres'],raw.encode())
sql('CREATE ROLE rmm_app LOGIN NOINHERIT NOSUPERUSER NOBYPASSRLS;')
for path in sorted((ROOT/'migrations').glob('*.sql')):sql(path.read_text())
output=command(['docker','run','--rm','--network','container:'+NAME,
'--read-only','--tmpfs','/tmp:rw,size=512m','-v',str(ROOT)+':/src:ro',
'-v',str(ROOT/'devstate/windows-server-contract/target')+':/target','-e','CARGO_TARGET_DIR=/target',
'-e','RMM_TEST_REPAIR_ADMIN_URL=postgres://postgres@127.0.0.1/postgres',
'-e','RMM_TEST_REPAIR_APP_URL=postgres://rmm_app@127.0.0.1/postgres',
'--entrypoint','cargo','rust-discovery-windows-tls-full:local',
'test','--locked','--offline','-p','rmm-server','windows_plan_caps_persisted_database',
'--','--include-ignored','--nocapture'],timeout=300)
print(output.decode())
print('PASS: real isolated PostgreSQL, fixed mixed variants/hashes, missing interpreter capability, submit/recheck, tenant denial; zero jobs/outbox/permits, no approval.')
finally:
subprocess.run(['docker','rm','-f',NAME],capture_output=True)
if __name__=='__main__':main()
+17 -1
View File
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest'; import { afterEach, describe, expect, it, vi } from 'vitest';
import { approvalBlockers, page, PlanInput, request, session, validateInput } from './api'; import { expectedStdout, approvalBlockers, page, PlanInput, request, session, validateInput } from './api';
afterEach(() => vi.unstubAllGlobals()); afterEach(() => vi.unstubAllGlobals());
describe('JSON contract boundary', () => { describe('JSON contract boundary', () => {
it('refuses missing simulation identity metadata', () => { it('refuses missing simulation identity metadata', () => {
@@ -49,6 +49,22 @@ describe('JSON contract boundary', () => {
validateInput(input); expect(input.parameters.variants).toEqual([variant]); validateInput(input); expect(input.parameters.variants).toEqual([variant]);
expect(() => validateInput({ ...input, targets: { asset_ids: ['a', 'a'] } })).toThrow('eindeutige'); expect(() => validateInput({ ...input, targets: { asset_ids: ['a', 'a'] } })).toThrow('eindeutige');
}); });
it('binds explicitly escaped stdout CRLF before planning and leaves text unchanged', () => {
expect(expectedStdout('"Hello\\r\\n"', 'json')).toBe('Hello\r\n');
expect(expectedStdout('Hello\n', 'text')).toBe('Hello\n');
expect(expectedStdout('', 'json')).toBeNull();
expect(() => expectedStdout('{}', 'json')).toThrow();
expect(() => expectedStdout('x', 'unknown')).toThrow();
});
it('binds explicit Windows and mixed variants without normalizing script bytes', () => {
const windows = { os_family: 'windows', interpreter: 'powershell', encoding: 'utf-8', script_utf8: "Write-Output 'hi'\r\n" };
const linux = { os_family: 'linux', interpreter: 'posix_sh', encoding: 'utf-8', script_utf8: "printf hi\n" };
const input: PlanInput = { tenant_id: 't', action: 'run_script', targets: { asset_ids: ['a', 'b'] }, parameters: { variants: [linux, windows], execution_identity: 'agent_service', timeout_seconds: 60, max_output_bytes: 4096 }, schedule: { not_before: new Date().toISOString(), start_before: new Date(Date.now() + 60000).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'fixed mixed plan' };
const original = JSON.stringify(input); validateInput(input); expect(JSON.stringify(input)).toBe(original);
for (const variants of [[windows, windows], [{ ...windows, interpreter: 'pwsh' }], [{ ...windows, interpreter: 'bash' }], [{ ...windows, script_utf8: "Write-Output 'é'" }]]) expect(() => validateInput({ ...input, parameters: { ...input.parameters, variants } })).toThrow();
expect(() => validateInput({ ...input, parameters: { ...input.parameters, execution_identity: 'root' } })).toThrow('agent_service');
validateInput({ ...input, parameters: { ...input.parameters, variants: [{ ...windows, script_utf8: "\ufeffWrite-Output 'é'\r\n" }] } });
});
it('accepts explicit existing dev simulation evidence but not a principal-name guess', () => { it('accepts explicit existing dev simulation evidence but not a principal-name guess', () => {
expect(session({ principal: 'sim-test', tenant_id: 't', testsimulation: true, csrf_token: 'csrf' }).principal.simulated).toBe(true); expect(session({ principal: 'sim-test', tenant_id: 't', testsimulation: true, csrf_token: 'csrf' }).principal.simulated).toBe(true);
expect(() => session({ principal: 'sim-test', tenant_id: 't', csrf_token: 'csrf' })).toThrow(); expect(() => session({ principal: 'sim-test', tenant_id: 't', csrf_token: 'csrf' })).toThrow();
+16 -4
View File
@@ -60,6 +60,13 @@ export const pretty = (v: unknown) => JSON.stringify(v, null, 2);
export const actions = ['run_script', 'refresh_inventory', 'query_logs', 'set_service_state', 'ensure_package', 'apply_updates', 'reboot', 'apt_native_acceptance'] as const; export const actions = ['run_script', 'refresh_inventory', 'query_logs', 'set_service_state', 'ensure_package', 'apply_updates', 'reboot', 'apt_native_acceptance'] as const;
export type Action = typeof actions[number]; export type Action = typeof actions[number];
export interface PlanInput { tenant_id: string; action: Action; targets: { asset_ids: string[] }; parameters: RecordValue; artifact_ids?: string[]; schedule: { not_before: string; start_before: string; offline_policy: 'wait_until_deadline' }; rollout: { max_parallel: number; halt_after_failures: number }; reason: string } export interface PlanInput { tenant_id: string; action: Action; targets: { asset_ids: string[] }; parameters: RecordValue; artifact_ids?: string[]; schedule: { not_before: string; start_before: string; offline_policy: 'wait_until_deadline' }; rollout: { max_parallel: number; halt_after_failures: number }; reason: string }
/** Decode explicit escaped CRLF before planning; never alter approved output bytes. */
export function expectedStdout(value: string, format: string): string | null {
if (value === '') return null;
const output: unknown = format === 'json' ? JSON.parse(value) : format === 'text' ? value : undefined;
if (typeof output !== 'string' || new TextEncoder().encode(output).length > 65536) throw new Error('stdout-Nachbedingung benötigt einen String (max.64KiB UTF-8)');
return output;
}
export function validateInput(input: PlanInput): void { export function validateInput(input: PlanInput): void {
if (!input.targets.asset_ids.length || new Set(input.targets.asset_ids).size !== input.targets.asset_ids.length) throw new Error('Feste eindeutige Ziele erforderlich'); if (!input.targets.asset_ids.length || new Set(input.targets.asset_ids).size !== input.targets.asset_ids.length) throw new Error('Feste eindeutige Ziele erforderlich');
if (!input.reason.trim()) throw new Error('Begründung erforderlich'); if (!input.reason.trim()) throw new Error('Begründung erforderlich');
@@ -68,10 +75,15 @@ export function validateInput(input: PlanInput): void {
for (const n of [input.rollout.max_parallel, input.rollout.halt_after_failures, input.parameters.timeout_seconds, input.parameters.max_output_bytes]) if (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 1) throw new Error('Limits müssen positive Ganzzahlen sein'); for (const n of [input.rollout.max_parallel, input.rollout.halt_after_failures, input.parameters.timeout_seconds, input.parameters.max_output_bytes]) if (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 1) throw new Error('Limits müssen positive Ganzzahlen sein');
if (input.action === 'run_script') { if (input.action === 'run_script') {
const variants = input.parameters.variants; const variants = input.parameters.variants;
if (!Array.isArray(variants) || !variants.length || !variants.every(v => { if (!Array.isArray(variants) || !variants.length || variants.length > 2 || !variants.every(v => {
const variant = record(v), bytes = typeof variant.script_utf8 === 'string' ? new TextEncoder().encode(variant.script_utf8).length : 0; const variant = record(v), script = typeof variant.script_utf8 === 'string' ? variant.script_utf8 : '';
return bytes > 0 && bytes <= 32768 && !String(variant.script_utf8).includes('\0') && variant.os_family === 'linux' && variant.encoding === 'utf-8' && ['posix_sh', 'bash'].includes(String(variant.interpreter)); const bytes = new TextEncoder().encode(script).length;
})) throw new Error('Exakte Linux UTF-8 Skriptbytes und Interpreter erforderlich (max. 32 KiB)'); const platform = variant.os_family === 'linux' && ['posix_sh', 'bash'].includes(String(variant.interpreter))
|| variant.os_family === 'windows' && variant.interpreter === 'powershell';
return bytes > 0 && bytes <= 32768 && !script.includes('\0') && variant.encoding === 'utf-8' && platform
&& (variant.os_family !== 'windows' || /^[\x00-\x7f]*$/.test(script) || script.startsWith('\ufeff'));
}) || new Set(variants.map(v => record(v).os_family)).size !== variants.length) throw new Error('Je Plattform genau eine passende UTF-8 Variante (max.32KiB); PowerShell5.1: ASCII oder explizites UTF-8-BOM vor Hashbildung');
if (variants.some(v => record(v).os_family === 'windows') && input.parameters.execution_identity !== 'agent_service') throw new Error('Windows PowerShell benötigt agent_service; kein SYSTEM-/Root-Fallback');
} }
if (!['agent_service', 'root'].includes(String(input.parameters.execution_identity))) throw new Error('Explizite Ausführungsidentität erforderlich'); if (!['agent_service', 'root'].includes(String(input.parameters.execution_identity))) throw new Error('Explizite Ausführungsidentität erforderlich');
const required = (key: string) => text(input.parameters[key], `parameters.${key}`); const required = (key: string) => text(input.parameters[key], `parameters.${key}`);
+5 -4
View File
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client'; import { createRoot } from 'react-dom/client';
import { actions, Action, ApiError, authConfig, approvalBlockers, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput } from './api'; import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput } from './api';
import './style.css'; import './style.css';
import { AdminControl, Catalog, TenantControls } from './management'; import { AdminControl, Catalog, TenantControls } from './management';
import { allowed, availableActions, parseStrictJson, rootWarning, validateSensitiveInput, verifyPlanIntegrity } from './safety'; import { allowed, availableActions, parseStrictJson, rootWarning, validateSensitiveInput, verifyPlanIntegrity } from './safety';
@@ -37,19 +37,20 @@ const initialParameters: Record<Action, RecordValue> = {
run_script: {}, refresh_inventory: { scope: 'linux.base' }, query_logs: { unit: '', since: '', until: '', max_lines: 1000 }, set_service_state: { unit: '', state: 'running' }, ensure_package: { provider: 'apt', recipe_version: '', package: '', version: '', architecture: 'amd64', installation_context: 'system', apt_manifest: null }, apply_updates: { provider: 'apt', packages: [], reboot_policy: 'never', apt_manifest: null }, reboot: { reason: '', dependency_group: '', reconnect_timeout_seconds: 300 }, apt_native_acceptance: { recipe_id: 'rmm-apt-fixture-install-1.0', recipe_version: '1', apt_manifest: null }, run_script: {}, refresh_inventory: { scope: 'linux.base' }, query_logs: { unit: '', since: '', until: '', max_lines: 1000 }, set_service_state: { unit: '', state: 'running' }, ensure_package: { provider: 'apt', recipe_version: '', package: '', version: '', architecture: 'amd64', installation_context: 'system', apt_manifest: null }, apply_updates: { provider: 'apt', packages: [], reboot_policy: 'never', apt_manifest: null }, reboot: { reason: '', dependency_group: '', reconnect_timeout_seconds: 300 }, apt_native_acceptance: { recipe_id: 'rmm-apt-fixture-install-1.0', recipe_version: '1', apt_manifest: null },
}; };
function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; auth: Session; selected: string[]; showPlan: (id: string) => void }) { function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; auth: Session; selected: string[]; showPlan: (id: string) => void }) {
const [scriptPlatform, setScriptPlatform] = useState('linux'), [mixedVariants, setMixedVariants] = useState('[]');
const [action, setAction] = useState<Action>('run_script'), [parameters, setParameters] = useState('{}'), [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false); const [action, setAction] = useState<Action>('run_script'), [parameters, setParameters] = useState('{}'), [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false);
const [identity, setIdentity] = useState('agent_service'); const [identity, setIdentity] = useState('agent_service');
return <section><h2>Neuen unveränderlichen Plan vorbereiten</h2><p>Nur fest ausgewählte Asset-IDs. Keine Ausführung durch Planung oder Antrag; jede Aktion einschließlich Live-Inventar benötigt Genehmigung.</p> return <section><h2>Neuen unveränderlichen Plan vorbereiten</h2><p>Nur fest ausgewählte Asset-IDs. Keine Ausführung durch Planung oder Antrag; jede Aktion einschließlich Live-Inventar benötigt Genehmigung.</p>
<form onSubmit={async e => { e.preventDefault(); setBusy(true); setError(null); const f = new FormData(e.currentTarget); try { <form onSubmit={async e => { e.preventDefault(); setBusy(true); setError(null); const f = new FormData(e.currentTarget); try {
const common = { execution_identity: String(f.get('identity')), timeout_seconds: Number(f.get('timeout')), max_output_bytes: Number(f.get('output')) }; const common = { execution_identity: String(f.get('identity')), timeout_seconds: Number(f.get('timeout')), max_output_bytes: Number(f.get('output')) };
const params = action === 'run_script' ? { ...common, variants: [{ os_family: 'linux', interpreter: String(f.get('interpreter')), encoding: 'utf-8', script_utf8: String(f.get('script')) }], arguments: [], expected_stdout: f.get('expected') === '' ? null : String(f.get('expected')) } : { ...record(parseStrictJson(parameters)), ...common }; const params = action === 'run_script' ? { ...common, variants: scriptPlatform === 'mixed' ? parseStrictJson(mixedVariants) : [{ os_family: scriptPlatform, interpreter: String(f.get('interpreter')), encoding: 'utf-8', script_utf8: String(f.get('script')) }], arguments: [], expected_stdout: expectedStdout(String(f.get('expected')), String(f.get('expected_format'))) } : { ...record(parseStrictJson(parameters)), ...common };
const input: PlanInput = { tenant_id: tenantId, action, targets: { asset_ids: [...selected] }, parameters: params, schedule: { not_before: new Date(String(f.get('not_before'))).toISOString(), start_before: new Date(String(f.get('expires'))).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: Number(f.get('parallel')), halt_after_failures: Number(f.get('failures')) }, reason: String(f.get('reason')) }; const input: PlanInput = { tenant_id: tenantId, action, targets: { asset_ids: [...selected] }, parameters: params, schedule: { not_before: new Date(String(f.get('not_before'))).toISOString(), start_before: new Date(String(f.get('expires'))).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: Number(f.get('parallel')), halt_after_failures: Number(f.get('failures')) }, reason: String(f.get('reason')) };
const ids = String(f.get('artifact_ids') ?? '').split(/[\s,]+/).filter(Boolean); if (ids.length) { if (ids.length > 16 || new Set(ids).size !== ids.length || ids.some(id => !/^[0-9a-f-]{36}$/i.test(id))) throw new Error('Maximal 16 eindeutige feste Artefakt-UUIDs'); input.artifact_ids = ids; } const ids = String(f.get('artifact_ids') ?? '').split(/[\s,]+/).filter(Boolean); if (ids.length) { if (ids.length > 16 || new Set(ids).size !== ids.length || ids.some(id => !/^[0-9a-f-]{36}$/i.test(id))) throw new Error('Maximal 16 eindeutige feste Artefakt-UUIDs'); input.artifact_ids = ids; }
validateInput(input); await validateSensitiveInput(input, auth); const plan = record(await request(tenantPath(tenantId, '/operation-plans'), { body: input, csrf: auth.csrf_token })); showPlan(objectId(plan, 'plan')); validateInput(input); await validateSensitiveInput(input, auth); const plan = record(await request(tenantPath(tenantId, '/operation-plans'), { body: input, csrf: auth.csrf_token })); showPlan(objectId(plan, 'plan'));
} catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}> } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>
<label>Aktion<select aria-label="Aktion" value={action} onChange={e => { const next = availableActions(auth, actions).find(a => a === e.target.value); if (next) { setAction(next); setParameters(pretty(initialParameters[next])); } }}>{availableActions(auth, actions).map(a => <option key={a} value={a}>{a}</option>)}</select></label> <label>Aktion<select aria-label="Aktion" value={action} onChange={e => { const next = availableActions(auth, actions).find(a => a === e.target.value); if (next) { setAction(next); setParameters(pretty(initialParameters[next])); } }}>{availableActions(auth, actions).map(a => <option key={a} value={a}>{a}</option>)}</select></label>
{action === 'apt_native_acceptance' && <p className="warning">NUR SIMULIERTE DEV/TEST-NATIVABNAHME. In Vorbereitung; Backend/Helper/Scope müssen diese eigene Aktion unterstützen. Nur rmm-apt-fixture-install-1.0 oder rmm-apt-fixture-update-1.1, Rezeptversion 1, vollständiges Schema-2-Manifest. null/Platzhalter sind nicht konfiguriert, keine Produktionsaktion, keine automatische Ausführung.</p>} {action === 'apt_native_acceptance' && <p className="warning">NUR SIMULIERTE DEV/TEST-NATIVABNAHME. In Vorbereitung; Backend/Helper/Scope müssen diese eigene Aktion unterstützen. Nur rmm-apt-fixture-install-1.0 oder rmm-apt-fixture-update-1.1, Rezeptversion 1, vollständiges Schema-2-Manifest. null/Platzhalter sind nicht konfiguriert, keine Produktionsaktion, keine automatische Ausführung.</p>}
{action === 'run_script' ? <><label>Interpreter<select name="interpreter"><option value="posix_sh">posix_sh · /bin/sh</option><option value="bash">bash · nur mit gemeldeter Capability</option></select></label><label>Exakte UTF-8 Skriptbytes (LF; keine automatische Ergänzung)<textarea name="script" required rows={7} spellCheck={false}/></label><label>Erwartete stdout-Ausgabe (exakt, optional)<textarea name="expected" rows={2} spellCheck={false}/></label></> : <label>Typisierte Aktionsparameter (JSON; leere Pflichtwerte ergänzen)<textarea aria-label="Aktionsparameter" value={parameters} onChange={e => setParameters(e.target.value)} rows={9} spellCheck={false}/></label>} {action === 'run_script' ? <><label>Skriptplattform<select aria-label="Skriptplattform" value={scriptPlatform} onChange={e => setScriptPlatform(e.target.value)}><option value="linux">Linux</option><option value="windows">Windows</option><option value="mixed">Linux und Windows · feste Varianten</option></select></label>{scriptPlatform === 'mixed' ? <label>Exakte Plattformvarianten (JSON)<textarea aria-label="Skriptvarianten" value={mixedVariants} onChange={e => setMixedVariants(e.target.value)} rows={9} spellCheck={false}/></label> : <><label>Interpreter<select name="interpreter" key={scriptPlatform}>{scriptPlatform === 'windows' ? <option value="powershell">powershell · Windows PowerShell 5.1</option> : <><option value="posix_sh">posix_sh · /bin/sh</option><option value="bash">bash · nur mit gemeldeter Capability</option></>}</select></label><label>Exakte UTF-8 Skriptbytes (keine automatische Ergänzung)<textarea name="script" required rows={7} spellCheck={false}/></label></>}<label>Format der stdout-Nachbedingung<select name="expected_format" aria-label="Format der stdout-Nachbedingung"><option value="text">Text · Linux-Default</option><option value="json">JSON-String · explizite CRLF mit \r\n</option></select></label><label>Erwartete stdout-Ausgabe (exakte Rohbytes als UTF-8, optional)<textarea name="expected" rows={2} spellCheck={false}/></label>{scriptPlatform !== 'linux' && <p>PowerShell5.1: -NoLogo -NoProfile -NonInteractive; keine ExecutionPolicy-Umgehung. Nicht-ASCII benötigt ein ausdrücklich enthaltenes UTF-8-BOM vor Hashbildung. Skriptbytes und Ausgabe werden nicht normalisiert. Fehlende Plattform-/Interpreter-/Sync-Capability sperrt den ganzen Plan; kein stiller Zielausschluss.</p>}</> : <label>Typisierte Aktionsparameter (JSON; leere Pflichtwerte ergänzen)<textarea aria-label="Aktionsparameter" value={parameters} onChange={e => setParameters(e.target.value)} rows={9} spellCheck={false}/></label>}
<div className="grid"><label>Ausführungsidentität<select aria-label="Ausführungsidentität" name="identity" value={identity} onChange={e => setIdentity(e.target.value)}><option value="agent_service">agent_service</option><option value="root" disabled={!allowed(auth, 'root:execute')}>root · root:execute und unabhängiger Helper erforderlich</option></select></label><label>Laufzeitlimit (s)<input name="timeout" type="number" min="1" max="86400" defaultValue="60" required/></label><label>Ausgabelimit (Bytes)<input name="output" type="number" min="1" max="524288" defaultValue="65536" required/></label><label>Frühester Start (lokale Zeit)<input name="not_before" type="datetime-local" defaultValue={localDate(new Date())} required/></label><label>Startfrist / Ablauf (lokale Zeit)<input name="expires" type="datetime-local" defaultValue={localDate(new Date(Date.now() + 86400000))} required/></label><label>Maximal parallel<input name="parallel" type="number" min="1" defaultValue="1" required/></label><label>Stopp nach Fehlern<input name="failures" type="number" min="1" defaultValue="1" required/></label></div> <div className="grid"><label>Ausführungsidentität<select aria-label="Ausführungsidentität" name="identity" value={identity} onChange={e => setIdentity(e.target.value)}><option value="agent_service">agent_service</option><option value="root" disabled={!allowed(auth, 'root:execute')}>root · root:execute und unabhängiger Helper erforderlich</option></select></label><label>Laufzeitlimit (s)<input name="timeout" type="number" min="1" max="86400" defaultValue="60" required/></label><label>Ausgabelimit (Bytes)<input name="output" type="number" min="1" max="524288" defaultValue="65536" required/></label><label>Frühester Start (lokale Zeit)<input name="not_before" type="datetime-local" defaultValue={localDate(new Date())} required/></label><label>Startfrist / Ablauf (lokale Zeit)<input name="expires" type="datetime-local" defaultValue={localDate(new Date(Date.now() + 86400000))} required/></label><label>Maximal parallel<input name="parallel" type="number" min="1" defaultValue="1" required/></label><label>Stopp nach Fehlern<input name="failures" type="number" min="1" defaultValue="1" required/></label></div>
{identity === 'root' && <p className="warning">{rootWarning}</p>} {identity === 'root' && <p className="warning">{rootWarning}</p>}
{['ensure_package', 'apply_updates', 'apt_native_acceptance'].includes(action) && <details open><summary>Unveränderte Parameter-/Manifestpreview: gesamte Closure, alte/neue Versionen, Origins, Archivbytes/Hashes und Bindungen</summary><pre>{parameters}</pre><p>Struktur, exakte Transaktionsbytes und Hash werden vor Planung geprüft. Diese Vorschau behauptet keine native Akzeptanz oder Bereitschaft; keine automatische Ergänzung/Reduzierung der Closure.</p></details>} {['ensure_package', 'apply_updates', 'apt_native_acceptance'].includes(action) && <details open><summary>Unveränderte Parameter-/Manifestpreview: gesamte Closure, alte/neue Versionen, Origins, Archivbytes/Hashes und Bindungen</summary><pre>{parameters}</pre><p>Struktur, exakte Transaktionsbytes und Hash werden vor Planung geprüft. Diese Vorschau behauptet keine native Akzeptanz oder Bereitschaft; keine automatische Ergänzung/Reduzierung der Closure.</p></details>}
@@ -103,7 +104,7 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
const [tenantId, setTenant] = useState(auth.tenants[0]?.tenant_id ?? ''), [error, setError] = useState<string | null>(null); const [tenantId, setTenant] = useState(auth.tenants[0]?.tenant_id ?? ''), [error, setError] = useState<string | null>(null);
const options = tenants.data?.items.map(tenant) ?? auth.tenants; const options = tenants.data?.items.map(tenant) ?? auth.tenants;
useEffect(() => { if (!tenantId && options[0]) setTenant(options[0].tenant_id); }, [options, tenantId]); useEffect(() => { if (!tenantId && options[0]) setTenant(options[0].tenant_id); }, [options, tenantId]);
return <><header><div><h1>RMM <span>Linux Verwaltung</span></h1><p>{auth.principal.display_name} · {auth.principal.id}</p></div><button onClick={async () => { try { await request('/auth/logout', { csrf: auth.csrf_token, body: {} }); logout(); } catch (e) { setError(errorText(e)); } }}>Abmelden</button></header> return <><header><div><h1>RMM <span>Geräteverwaltung</span></h1><p>{auth.principal.display_name} · {auth.principal.id}</p></div><button onClick={async () => { try { await request('/auth/logout', { csrf: auth.csrf_token, body: {} }); logout(); } catch (e) { setError(errorText(e)); } }}>Abmelden</button></header>
{auth.principal.simulated && <aside className="simulation" role="status">SIMULIERT · dev/test-Testprincipal · Genehmigung ist eine Entwicklungs-Browsersimulation, kein menschlicher Produktions-Freigabenachweis.</aside>} {auth.principal.simulated && <aside className="simulation" role="status">SIMULIERT · dev/test-Testprincipal · Genehmigung ist eine Entwicklungs-Browsersimulation, kein menschlicher Produktions-Freigabenachweis.</aside>}
<main><ErrorBox error={error}/><ErrorBox error={tenants.error}/><label>Mandant<select aria-label="Mandant" value={tenantId} onChange={e => setTenant(e.target.value)}><option value="" disabled>Mandant wählen</option>{options.map(t => <option key={t.tenant_id} value={t.tenant_id}>{t.name} · {t.tenant_id}</option>)}</select></label>{tenantId && <TenantWorkspace key={tenantId} tenantId={tenantId} auth={auth}/>}</main></>; <main><ErrorBox error={error}/><ErrorBox error={tenants.error}/><label>Mandant<select aria-label="Mandant" value={tenantId} onChange={e => setTenant(e.target.value)}><option value="" disabled>Mandant wählen</option>{options.map(t => <option key={t.tenant_id} value={t.tenant_id}>{t.name} · {t.tenant_id}</option>)}</select></label>{tenantId && <TenantWorkspace key={tenantId} tenantId={tenantId} auth={auth}/>}</main></>;
} }