Implement bounded Windows Event Log jobs and verify contracts on cloud Linux
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -33,8 +33,8 @@ impl Binding {
|
||||
);
|
||||
ensure!(
|
||||
j.action.validate()
|
||||
&& (1..=3600).contains(&j.max_runtime_seconds)
|
||||
&& (1..=262144).contains(&j.max_output_bytes)
|
||||
&& j.action
|
||||
.valid_job_limits(j.max_runtime_seconds, j.max_output_bytes)
|
||||
&& j.not_before < j.start_before,
|
||||
"INVALID_JOB"
|
||||
);
|
||||
|
||||
@@ -201,6 +201,39 @@ fn exact_permit_bytes_time_and_all_identity_hash_bindings_are_required() {
|
||||
request.permit_bytes = encode(&permit).unwrap();
|
||||
request.signature = key.sign(&request.permit_bytes).to_bytes().to_vec();
|
||||
binding.verify(&request, now).unwrap();
|
||||
// The exact fixed Event Log source/window/limits are original signed bytes.
|
||||
job.action = Action::QueryLogs {
|
||||
unit: rmm_domain::jobs::WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
||||
since: now - chrono::Duration::hours(1),
|
||||
until: now,
|
||||
max_lines: 1000,
|
||||
};
|
||||
request.job_bytes = encode(&job).unwrap();
|
||||
permit.action = job.action.name().into();
|
||||
permit.job_payload_hash = hash(&request.job_bytes);
|
||||
request.permit_bytes = encode(&permit).unwrap();
|
||||
request.signature = key.sign(&request.permit_bytes).to_bytes().to_vec();
|
||||
binding.verify(&request, now).unwrap();
|
||||
let mut wrong_source = job.clone();
|
||||
if let Action::QueryLogs { unit, .. } = &mut wrong_source.action {
|
||||
*unit = "Security".into();
|
||||
}
|
||||
let mut changed = request.clone();
|
||||
changed.job_bytes = encode(&wrong_source).unwrap();
|
||||
assert!(binding.verify(&changed, now).is_err());
|
||||
for (runtime, bytes) in [(9, 4096), (121, 4096), (10, 1023), (10, 65537)] {
|
||||
let mut changed_job = job.clone();
|
||||
changed_job.max_runtime_seconds = runtime;
|
||||
changed_job.max_output_bytes = bytes;
|
||||
let mut changed_permit = permit.clone();
|
||||
changed_permit.max_runtime_seconds = runtime;
|
||||
let mut changed = request.clone();
|
||||
changed.job_bytes = encode(&changed_job).unwrap();
|
||||
changed_permit.job_payload_hash = hash(&changed.job_bytes);
|
||||
changed.permit_bytes = encode(&changed_permit).unwrap();
|
||||
changed.signature = key.sign(&changed.permit_bytes).to_bytes().to_vec();
|
||||
assert!(binding.verify(&changed, now).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -39,4 +39,4 @@ rcgen = { version = "=0.14.10", default-features = false, features = ["crypto",
|
||||
cc = "=1.11.1"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Pipes", "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_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] }
|
||||
|
||||
@@ -71,10 +71,45 @@ pub fn supported(job: &JobPayload) -> bool {
|
||||
interpreter == "powershell" && powershell().is_ok()
|
||||
}
|
||||
Action::RefreshInventory { scope } => scope == "windows.base",
|
||||
Action::QueryLogs { .. } => crate::event_log::for_job(job).is_ok(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Each prepared operation retains its own typed binding; no non-script action
|
||||
/// can fall through to inventory or borrow the PowerShell execution profile.
|
||||
pub enum PreparedAction {
|
||||
Script(Script),
|
||||
Inventory,
|
||||
EventLog(crate::event_log_job::Prepared),
|
||||
}
|
||||
impl PreparedAction {
|
||||
pub fn prepare(
|
||||
job: &JobPayload,
|
||||
directory: &Path,
|
||||
grant: uuid::Uuid,
|
||||
request: &rmm_agent_core::auth::Request,
|
||||
boot: uuid::Uuid,
|
||||
) -> Result<Self> {
|
||||
ensure!(supported(job), "UNSUPPORTED_CAPABILITY");
|
||||
match &job.action {
|
||||
Action::RunScript { .. } => Ok(Self::Script(Script::prepare(job, directory, grant)?)),
|
||||
Action::RefreshInventory { scope } if scope == "windows.base" => Ok(Self::Inventory),
|
||||
Action::QueryLogs { .. } => Ok(Self::EventLog(
|
||||
crate::event_log_job::Prepared::prepare(job, directory, request, grant, boot)?,
|
||||
)),
|
||||
_ => anyhow::bail!("UNSUPPORTED_CAPABILITY"),
|
||||
}
|
||||
}
|
||||
pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result<Outcome> {
|
||||
match self {
|
||||
Self::Script(script) => script.run(job, cancel),
|
||||
Self::Inventory => inventory(job),
|
||||
Self::EventLog(log) => log.run(job, cancel),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Script {
|
||||
executable: PathBuf,
|
||||
path: PathBuf,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Bounded, local, fixture-only live Event Log query; not wired into any job.
|
||||
//! Bounded, local, fixture-only Event Log provider. Only the authorized native
|
||||
//! job worker may call the Windows provider; this module confers no authority.
|
||||
//!
|
||||
//! EvtQuery/EvtRender have no per-call timeout. The monotonic deadline below is
|
||||
//! cooperative between Win32 calls; the eventual executor must also supervise
|
||||
@@ -12,8 +13,9 @@ use chrono::{DateTime, SecondsFormat, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
pub const CHANNEL: &str = "Application";
|
||||
pub const PROVIDER: &str = "RustDiscovery-MVP-Test";
|
||||
pub use rmm_domain::jobs::{
|
||||
WINDOWS_EVENT_LOG_FIXTURE_CHANNEL as CHANNEL, WINDOWS_EVENT_LOG_FIXTURE_PROVIDER as PROVIDER,
|
||||
};
|
||||
const MAX_BYTES: usize = 256 * 1024;
|
||||
#[cfg(any(windows, test))]
|
||||
const REPORT_RESERVE: usize = 256;
|
||||
@@ -57,7 +59,42 @@ impl Query {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
/// Pure job-to-provider binding. Never opens a channel or touches a bookmark.
|
||||
pub fn for_job(job: &rmm_domain::jobs::JobPayload) -> Result<Query> {
|
||||
use rmm_domain::jobs::{Action, WINDOWS_EVENT_LOG_FIXTURE_SOURCE};
|
||||
let Action::QueryLogs {
|
||||
unit,
|
||||
since,
|
||||
until,
|
||||
max_lines,
|
||||
} = &job.action
|
||||
else {
|
||||
anyhow::bail!("EVENT_LOG_ACTION_REQUIRED")
|
||||
};
|
||||
ensure!(
|
||||
job.execution_identity == "agent_service"
|
||||
&& unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE
|
||||
&& job.action.validate()
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes),
|
||||
"EVENT_LOG_JOB_BINDING"
|
||||
);
|
||||
let q = Query {
|
||||
channel: CHANNEL.into(),
|
||||
provider: PROVIDER.into(),
|
||||
start_utc: *since,
|
||||
end_utc: *until,
|
||||
max_events: *max_lines,
|
||||
max_output_bytes: job.max_output_bytes,
|
||||
timeout_ms: 5000,
|
||||
};
|
||||
q.xpath()?;
|
||||
Ok(q)
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Event {
|
||||
pub channel: String,
|
||||
pub provider: String,
|
||||
@@ -501,6 +538,53 @@ mod tests {
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn job_mapping_is_only_fixed_unprivileged_live_logs_with_exact_limits() {
|
||||
use rmm_domain::jobs::{Action, JobPayload, WINDOWS_EVENT_LOG_FIXTURE_SOURCE};
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let now = DateTime::from_timestamp(1_700_000_000, 0).unwrap();
|
||||
let mut job = JobPayload {
|
||||
schema_version: 1,
|
||||
tenant_id: id,
|
||||
asset_id: id,
|
||||
agent_id: id,
|
||||
enrollment_generation: 1,
|
||||
assignment_version: 1,
|
||||
job_id: id,
|
||||
attempt_id: id,
|
||||
action: Action::QueryLogs {
|
||||
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
||||
since: now,
|
||||
until: now + chrono::Duration::hours(24),
|
||||
max_lines: 1000,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now,
|
||||
start_before: now + chrono::Duration::seconds(60),
|
||||
max_runtime_seconds: 10,
|
||||
max_output_bytes: 65536,
|
||||
};
|
||||
let q = for_job(&job).unwrap();
|
||||
assert_eq!(
|
||||
(q.channel.as_str(), q.provider.as_str()),
|
||||
(CHANNEL, PROVIDER)
|
||||
);
|
||||
assert_eq!(q.max_output_bytes, 65536);
|
||||
for identity in ["root", "system"] {
|
||||
job.execution_identity = identity.into();
|
||||
assert!(for_job(&job).is_err());
|
||||
}
|
||||
job.execution_identity = "agent_service".into();
|
||||
for bytes in [1023, 65537] {
|
||||
job.max_output_bytes = bytes;
|
||||
assert!(for_job(&job).is_err());
|
||||
}
|
||||
job.max_output_bytes = 65536;
|
||||
if let Action::QueryLogs { until, .. } = &mut job.action {
|
||||
*until += chrono::Duration::nanoseconds(1);
|
||||
}
|
||||
assert!(for_job(&job).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn serialized_byte_budget_includes_xml_escaping_and_metadata() {
|
||||
let q = request();
|
||||
let mut report = Report::new(&q);
|
||||
|
||||
@@ -0,0 +1,778 @@
|
||||
//! Fixed, authorized Event Log subprocess. A command-line mode is not a live
|
||||
//! query API: the child authenticates its real SCM parent, original signed
|
||||
//! request, protected public trust, and an already committed consumption/start.
|
||||
//! Request/grant bytes remain in a private, create-once job file, never argv.
|
||||
use crate::{event_log, native};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use chrono::{DateTime, Utc};
|
||||
use rmm_agent_core::auth::{Binding, Outcome, Request};
|
||||
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload, hash};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
fs::{File, OpenOptions},
|
||||
io::{Read, Write},
|
||||
mem::{size_of, size_of_val, zeroed},
|
||||
os::windows::{
|
||||
fs::OpenOptionsExt,
|
||||
io::{AsRawHandle, FromRawHandle, OwnedHandle},
|
||||
},
|
||||
path::{Path, PathBuf},
|
||||
ptr,
|
||||
sync::atomic::AtomicBool,
|
||||
time::Duration,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
use windows_sys::Win32::{
|
||||
Foundation::*,
|
||||
Security::{self, *},
|
||||
Storage::FileSystem::*,
|
||||
System::{Diagnostics::ToolHelp::*, Services::*, Threading::*},
|
||||
};
|
||||
|
||||
pub const MODE: &str = "--eventlog-worker";
|
||||
const CONFIG: &str = r"C:\ProgramData\RustDiscovery\config.json";
|
||||
const TICKET_LIMIT: u64 = 128 * 1024;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FileId {
|
||||
volume: u64,
|
||||
id: [u8; 16],
|
||||
}
|
||||
fn file_id(handle: HANDLE) -> Result<FileId> {
|
||||
let mut info: FILE_ID_INFO = unsafe { zeroed() };
|
||||
ensure!(
|
||||
unsafe {
|
||||
GetFileInformationByHandleEx(
|
||||
handle,
|
||||
FileIdInfo,
|
||||
(&mut info as *mut FILE_ID_INFO).cast(),
|
||||
size_of::<FILE_ID_INFO>() as u32,
|
||||
)
|
||||
} != 0,
|
||||
"EVENT_LOG_FILE_ID"
|
||||
);
|
||||
Ok(FileId {
|
||||
volume: info.VolumeSerialNumber,
|
||||
id: info.FileId.Identifier,
|
||||
})
|
||||
}
|
||||
fn owned(handle: HANDLE) -> Result<OwnedHandle> {
|
||||
ensure!(
|
||||
!handle.is_null() && handle != INVALID_HANDLE_VALUE,
|
||||
"EVENT_LOG_HANDLE"
|
||||
);
|
||||
Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
|
||||
}
|
||||
fn birth(handle: HANDLE) -> Result<u64> {
|
||||
let (mut c, mut e, mut k, mut u) = unsafe { (zeroed(), zeroed(), zeroed(), zeroed()) };
|
||||
ensure!(
|
||||
unsafe { GetProcessTimes(handle, &mut c, &mut e, &mut k, &mut u) } != 0,
|
||||
"EVENT_LOG_PROCESS_TIME"
|
||||
);
|
||||
Ok((u64::from(c.dwHighDateTime) << 32) | u64::from(c.dwLowDateTime))
|
||||
}
|
||||
fn text(value: *const u16) -> Result<String> {
|
||||
ensure!(!value.is_null(), "EVENT_LOG_NATIVE_STRING");
|
||||
let mut length = 0;
|
||||
while length < 32768 && unsafe { *value.add(length) } != 0 {
|
||||
length += 1;
|
||||
}
|
||||
ensure!(length < 32768, "EVENT_LOG_NATIVE_STRING_SIZE");
|
||||
Ok(String::from_utf16(unsafe {
|
||||
std::slice::from_raw_parts(value, length)
|
||||
})?)
|
||||
}
|
||||
fn process_image(handle: HANDLE) -> Result<PathBuf> {
|
||||
let mut buffer = vec![0u16; 32768];
|
||||
let mut len = buffer.len() as u32;
|
||||
ensure!(
|
||||
unsafe { QueryFullProcessImageNameW(handle, 0, buffer.as_mut_ptr(), &mut len) } != 0,
|
||||
"EVENT_LOG_PARENT_IMAGE"
|
||||
);
|
||||
Ok(String::from_utf16(&buffer[..len as usize])?.into())
|
||||
}
|
||||
struct Service(SC_HANDLE);
|
||||
impl Drop for Service {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
CloseServiceHandle(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn agent_pid(image: &Path) -> Result<u32> {
|
||||
let manager = Service(unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) });
|
||||
ensure!(!manager.0.is_null(), "EVENT_LOG_SCM");
|
||||
let service = Service(unsafe {
|
||||
OpenServiceW(
|
||||
manager.0,
|
||||
native::wide(crate::SERVICE_NAME).as_ptr(),
|
||||
SERVICE_QUERY_CONFIG | SERVICE_QUERY_STATUS,
|
||||
)
|
||||
});
|
||||
ensure!(!service.0.is_null(), "EVENT_LOG_AGENT_SERVICE");
|
||||
let mut bytes = 0;
|
||||
unsafe {
|
||||
QueryServiceConfigW(service.0, ptr::null_mut(), 0, &mut bytes);
|
||||
}
|
||||
ensure!((1..=32768).contains(&bytes), "EVENT_LOG_AGENT_CONFIG_SIZE");
|
||||
let mut storage = vec![0usize; (bytes as usize).div_ceil(size_of::<usize>())];
|
||||
ensure!(
|
||||
unsafe { QueryServiceConfigW(service.0, storage.as_mut_ptr().cast(), bytes, &mut bytes) }
|
||||
!= 0,
|
||||
"EVENT_LOG_AGENT_CONFIG"
|
||||
);
|
||||
let config = unsafe { &*storage.as_ptr().cast::<QUERY_SERVICE_CONFIGW>() };
|
||||
ensure!(
|
||||
config.dwServiceType == SERVICE_WIN32_OWN_PROCESS
|
||||
&& text(config.lpBinaryPathName)?
|
||||
== format!("\"{}\" --service --config \"{CONFIG}\"", image.display())
|
||||
&& text(config.lpServiceStartName)?.eq_ignore_ascii_case(r"NT AUTHORITY\LocalService"),
|
||||
"EVENT_LOG_AGENT_CONFIG_BINDING"
|
||||
);
|
||||
let mut status: SERVICE_STATUS_PROCESS = unsafe { zeroed() };
|
||||
ensure!(
|
||||
unsafe {
|
||||
QueryServiceStatusEx(
|
||||
service.0,
|
||||
SC_STATUS_PROCESS_INFO,
|
||||
(&mut status as *mut SERVICE_STATUS_PROCESS).cast(),
|
||||
size_of::<SERVICE_STATUS_PROCESS>() as u32,
|
||||
&mut bytes,
|
||||
)
|
||||
} != 0
|
||||
&& status.dwCurrentState == SERVICE_RUNNING
|
||||
&& status.dwProcessId > 0,
|
||||
"EVENT_LOG_AGENT_NOT_RUNNING"
|
||||
);
|
||||
Ok(status.dwProcessId)
|
||||
}
|
||||
fn token_info(token: HANDLE, class: TOKEN_INFORMATION_CLASS) -> Result<Vec<usize>> {
|
||||
let mut bytes = 0;
|
||||
unsafe {
|
||||
GetTokenInformation(token, class, ptr::null_mut(), 0, &mut bytes);
|
||||
}
|
||||
ensure!((1..=65536).contains(&bytes), "EVENT_LOG_TOKEN_SIZE");
|
||||
let mut data = vec![0usize; (bytes as usize).div_ceil(size_of::<usize>())];
|
||||
ensure!(
|
||||
unsafe { GetTokenInformation(token, class, data.as_mut_ptr().cast(), bytes, &mut bytes) }
|
||||
!= 0,
|
||||
"EVENT_LOG_TOKEN"
|
||||
);
|
||||
Ok(data)
|
||||
}
|
||||
fn service_token(process: HANDLE) -> Result<()> {
|
||||
let mut token = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) } != 0,
|
||||
"EVENT_LOG_TOKEN_OPEN"
|
||||
);
|
||||
let token = owned(token)?;
|
||||
let user = token_info(token.as_raw_handle(), TokenUser)?;
|
||||
let mut service_sid = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe {
|
||||
Security::Authorization::ConvertStringSidToSidW(
|
||||
native::wide(native::service_sid()?).as_ptr(),
|
||||
&mut service_sid,
|
||||
)
|
||||
} != 0,
|
||||
"EVENT_LOG_SERVICE_SID"
|
||||
);
|
||||
struct Sid(PSID);
|
||||
impl Drop for Sid {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
LocalFree(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
let service_sid = Sid(service_sid);
|
||||
let mut ls = [0usize; 16];
|
||||
let mut size = size_of_val(&ls) as u32;
|
||||
ensure!(
|
||||
unsafe {
|
||||
CreateWellKnownSid(
|
||||
WinLocalServiceSid,
|
||||
ptr::null_mut(),
|
||||
ls.as_mut_ptr().cast(),
|
||||
&mut size,
|
||||
)
|
||||
} != 0
|
||||
&& unsafe {
|
||||
EqualSid(
|
||||
(*user.as_ptr().cast::<TOKEN_USER>()).User.Sid,
|
||||
ls.as_ptr().cast_mut().cast(),
|
||||
)
|
||||
} != 0,
|
||||
"EVENT_LOG_LOCAL_SERVICE_REQUIRED"
|
||||
);
|
||||
let groups = token_info(token.as_raw_handle(), TokenGroups)?;
|
||||
let g = unsafe { &*groups.as_ptr().cast::<TOKEN_GROUPS>() };
|
||||
let offset = std::mem::offset_of!(TOKEN_GROUPS, Groups);
|
||||
ensure!(
|
||||
g.GroupCount <= 1024
|
||||
&& offset + g.GroupCount as usize * size_of::<SID_AND_ATTRIBUTES>()
|
||||
<= groups.len() * size_of::<usize>(),
|
||||
"EVENT_LOG_TOKEN_GROUPS_SIZE"
|
||||
);
|
||||
let entries = unsafe { std::slice::from_raw_parts(g.Groups.as_ptr(), g.GroupCount as usize) };
|
||||
let mut admins = [0usize; 16];
|
||||
let mut admin_bytes = size_of_val(&admins) as u32;
|
||||
ensure!(
|
||||
unsafe {
|
||||
CreateWellKnownSid(
|
||||
WinBuiltinAdministratorsSid,
|
||||
ptr::null_mut(),
|
||||
admins.as_mut_ptr().cast(),
|
||||
&mut admin_bytes,
|
||||
)
|
||||
} != 0,
|
||||
"EVENT_LOG_ADMIN_SID"
|
||||
);
|
||||
ensure!(
|
||||
!entries
|
||||
.iter()
|
||||
.any(|entry| entry.Attributes & 0x0000_0004 != 0
|
||||
&& unsafe { EqualSid(entry.Sid, admins.as_ptr().cast_mut().cast()) } != 0),
|
||||
"EVENT_LOG_ADMINISTRATOR_FORBIDDEN"
|
||||
);
|
||||
// TOKEN_GROUPS enabled/deny-only bits from winnt.h, as in the pipe peer proof.
|
||||
ensure!(
|
||||
entries
|
||||
.iter()
|
||||
.any(|entry| entry.Attributes & 0x0000_0004 != 0
|
||||
&& entry.Attributes & 0x0000_0010 == 0
|
||||
&& unsafe { EqualSid(entry.Sid, service_sid.0) } != 0),
|
||||
"EVENT_LOG_AGENT_SID_REQUIRED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn parent_pid() -> Result<u32> {
|
||||
let snapshot = owned(unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) })?;
|
||||
let mut entry: PROCESSENTRY32W = unsafe { zeroed() };
|
||||
entry.dwSize = size_of::<PROCESSENTRY32W>() as u32;
|
||||
let mut ok = unsafe { Process32FirstW(snapshot.as_raw_handle(), &mut entry) };
|
||||
while ok != 0 {
|
||||
if entry.th32ProcessID == std::process::id() {
|
||||
return Ok(entry.th32ParentProcessID);
|
||||
}
|
||||
ok = unsafe { Process32NextW(snapshot.as_raw_handle(), &mut entry) };
|
||||
}
|
||||
anyhow::bail!("EVENT_LOG_PARENT_UNVERIFIED")
|
||||
}
|
||||
fn open_private(path: &Path, share_write: bool) -> Result<File> {
|
||||
ensure!(
|
||||
path.is_absolute() && !path.to_string_lossy().starts_with(r"\\"),
|
||||
"EVENT_LOG_LOCAL_PATH"
|
||||
);
|
||||
for parent in path.ancestors().skip(1) {
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
ensure!(
|
||||
std::fs::symlink_metadata(parent)?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT
|
||||
== 0,
|
||||
"EVENT_LOG_REPARSE_ANCESTOR"
|
||||
);
|
||||
}
|
||||
native::private_path(path, false)?;
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.share_mode(FILE_SHARE_READ | if share_write { FILE_SHARE_WRITE } else { 0 })
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)?;
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
ensure!(
|
||||
file.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0,
|
||||
"EVENT_LOG_REPARSE_FILE"
|
||||
);
|
||||
Ok(file)
|
||||
}
|
||||
fn read(file: &mut File, limit: u64) -> Result<Vec<u8>> {
|
||||
ensure!(
|
||||
file.metadata()?.len() <= limit,
|
||||
"EVENT_LOG_PRIVATE_FILE_LIMIT"
|
||||
);
|
||||
let mut value = Vec::new();
|
||||
file.take(limit + 1).read_to_end(&mut value)?;
|
||||
ensure!(value.len() as u64 <= limit, "EVENT_LOG_PRIVATE_FILE_LIMIT");
|
||||
Ok(value)
|
||||
}
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Ticket {
|
||||
request: Request,
|
||||
parent_pid: u32,
|
||||
parent_birth: u64,
|
||||
boot: Uuid,
|
||||
ledger: FileId,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct WorkerConfig {
|
||||
state_directory: PathBuf,
|
||||
job_binding_file: PathBuf,
|
||||
enable_jobs: bool,
|
||||
}
|
||||
fn ticket_name(permit: &ExecutionPermitPayload) -> String {
|
||||
format!("eventlog-{}.json", hash(permit.grant_id.as_bytes()))
|
||||
}
|
||||
/// Prepared data only. No query, worker or Evt handle exists before run.
|
||||
pub struct Prepared {
|
||||
path: PathBuf,
|
||||
_file: File,
|
||||
ticket_hash: String,
|
||||
job_bytes: Vec<u8>,
|
||||
}
|
||||
impl Prepared {
|
||||
pub fn prepare(
|
||||
job: &JobPayload,
|
||||
directory: &Path,
|
||||
request: &Request,
|
||||
grant: Uuid,
|
||||
boot: Uuid,
|
||||
) -> Result<Self> {
|
||||
event_log::for_job(job)?;
|
||||
native::require_local_service()?;
|
||||
service_token(unsafe { GetCurrentProcess() })?;
|
||||
let image = std::env::current_exe()?;
|
||||
ensure!(
|
||||
agent_pid(&image)? == std::process::id(),
|
||||
"EVENT_LOG_REAL_AGENT_REQUIRED"
|
||||
);
|
||||
let permit: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
|
||||
ensure!(
|
||||
permit.grant_id == grant && !boot.is_nil(),
|
||||
"EVENT_LOG_GRANT_BINDING"
|
||||
);
|
||||
native::private_path(directory, true)?;
|
||||
let ledger = open_private(
|
||||
&directory
|
||||
.parent()
|
||||
.context("EVENT_LOG_STATE_DIRECTORY")?
|
||||
.join("consumption.sqlite"),
|
||||
true,
|
||||
)?;
|
||||
let ticket = Ticket {
|
||||
request: request.clone(),
|
||||
parent_pid: std::process::id(),
|
||||
parent_birth: birth(unsafe { GetCurrentProcess() })?,
|
||||
boot,
|
||||
ledger: file_id(ledger.as_raw_handle())?,
|
||||
};
|
||||
let bytes = serde_json::to_vec(&ticket)?;
|
||||
ensure!(bytes.len() as u64 <= TICKET_LIMIT, "EVENT_LOG_TICKET_LIMIT");
|
||||
let path = directory.join(ticket_name(&permit));
|
||||
let mut writer = OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.share_mode(0)
|
||||
.open(&path)?;
|
||||
writer.write_all(&bytes)?;
|
||||
writer.sync_all()?;
|
||||
drop(writer);
|
||||
let mut file = open_private(&path, false)?;
|
||||
ensure!(
|
||||
read(&mut file, TICKET_LIMIT)? == bytes,
|
||||
"EVENT_LOG_TICKET_CHANGED"
|
||||
);
|
||||
Ok(Self {
|
||||
path,
|
||||
_file: file,
|
||||
ticket_hash: hash(&bytes),
|
||||
job_bytes: request.job_bytes.clone(),
|
||||
})
|
||||
}
|
||||
pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result<Outcome> {
|
||||
event_log::for_job(job)?;
|
||||
ensure!(
|
||||
serde_json::from_slice::<serde_json::Value>(&self.job_bytes)?
|
||||
== serde_json::to_value(job)?,
|
||||
"EVENT_LOG_JOB_CHANGED"
|
||||
);
|
||||
let mut file = open_private(&self.path, false)?;
|
||||
ensure!(
|
||||
hash(&read(&mut file, TICKET_LIMIT)?) == self.ticket_hash,
|
||||
"EVENT_LOG_TICKET_CHANGED"
|
||||
);
|
||||
let output = crate::process::run(
|
||||
&std::env::current_exe()?,
|
||||
&[MODE.into(), self.path.as_os_str().into()],
|
||||
self.path.parent().context("EVENT_LOG_JOB_DIRECTORY")?,
|
||||
job.max_runtime_seconds,
|
||||
job.max_output_bytes as usize,
|
||||
cancel,
|
||||
)?;
|
||||
if output.interrupted {
|
||||
return Ok(Outcome::unknown(if output.cancelled {
|
||||
"EVENT_LOG_CANCELLED_RESULT_UNKNOWN"
|
||||
} else {
|
||||
"EVENT_LOG_TIMEOUT_RESULT_UNKNOWN"
|
||||
}));
|
||||
}
|
||||
ensure!(
|
||||
output.exit_code == Some(0) && !output.truncated && output.stderr.is_empty(),
|
||||
"EVENT_LOG_WORKER_RESULT_UNVERIFIED"
|
||||
);
|
||||
outcome(job, output.stdout)
|
||||
}
|
||||
}
|
||||
|
||||
fn consumed(
|
||||
db: &rusqlite::Connection,
|
||||
binding: &Binding,
|
||||
ticket: &Ticket,
|
||||
permit: &ExecutionPermitPayload,
|
||||
) -> Result<()> {
|
||||
let length: u64 = db.query_row("SELECT length(e.start) FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1", [permit.grant_id.to_string()], |r| r.get(0))?;
|
||||
ensure!(length <= TICKET_LIMIT, "EVENT_LOG_START_SIZE");
|
||||
type Row = (String, u64, String, String, bool, Vec<u8>, bool);
|
||||
let row: Row = db.query_row("SELECT c.agent,c.generation,c.job,c.attempt,c.result IS NULL,e.start,e.outcome IS NULL FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1",
|
||||
[permit.grant_id.to_string()], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?,r.get(6)?)))?;
|
||||
ensure!(
|
||||
row.0 == binding.agent_id.to_string()
|
||||
&& row.1 == binding.enrollment_generation
|
||||
&& row.2 == permit.job_id.to_string()
|
||||
&& row.3 == permit.attempt_id.to_string()
|
||||
&& row.4
|
||||
&& row.6,
|
||||
"EVENT_LOG_CONSUMPTION_BINDING"
|
||||
);
|
||||
let start: serde_json::Value = serde_json::from_slice(&row.5)?;
|
||||
ensure!(
|
||||
start["previous_boot_id"] == ticket.boot.to_string()
|
||||
&& serde_json::to_vec(&serde_json::from_value::<Request>(
|
||||
start["request"].clone()
|
||||
)?)? == serde_json::to_vec(&ticket.request)?,
|
||||
"EVENT_LOG_ORIGINAL_START_BINDING"
|
||||
);
|
||||
let identity: String = db.query_row(
|
||||
"SELECT identity FROM windows_binding WHERE length(identity)<=512",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(
|
||||
identity
|
||||
== format!(
|
||||
"{}:{}:{}:{}:{}",
|
||||
binding.tenant_id,
|
||||
binding.asset_id,
|
||||
binding.agent_id,
|
||||
binding.enrollment_generation,
|
||||
binding.assignment_version
|
||||
),
|
||||
"EVENT_LOG_LEDGER_BINDING"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn validate_ticket_path(path: &Path, directory: &Path) -> Result<()> {
|
||||
let name = path
|
||||
.file_name()
|
||||
.and_then(|s| s.to_str())
|
||||
.context("EVENT_LOG_TICKET_NAME")?;
|
||||
let hash_name = name
|
||||
.strip_prefix("eventlog-")
|
||||
.and_then(|s| s.strip_suffix(".json"))
|
||||
.context("EVENT_LOG_TICKET_NAME")?;
|
||||
ensure!(
|
||||
path.parent() == Some(directory)
|
||||
&& hash_name.len() == 64
|
||||
&& hash_name
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)),
|
||||
"EVENT_LOG_TICKET_PATH_BINDING"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Internal mode admission. Failure emits only the main executable's fixed
|
||||
/// initialization error; no request, query XML or private Win32 error is logged.
|
||||
pub fn worker(path: &Path) -> Result<()> {
|
||||
native::require_local_service()?;
|
||||
service_token(unsafe { GetCurrentProcess() })?;
|
||||
let image = std::env::current_exe()?;
|
||||
let actual_parent = parent_pid()?;
|
||||
ensure!(
|
||||
agent_pid(&image)? == actual_parent,
|
||||
"EVENT_LOG_REAL_PARENT_REQUIRED"
|
||||
);
|
||||
let parent = owned(unsafe {
|
||||
OpenProcess(
|
||||
PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE,
|
||||
0,
|
||||
actual_parent,
|
||||
)
|
||||
})?;
|
||||
let parent_birth = birth(parent.as_raw_handle())?;
|
||||
ensure!(
|
||||
process_image(parent.as_raw_handle())? == image
|
||||
&& unsafe { WaitForSingleObject(parent.as_raw_handle(), 0) } == WAIT_TIMEOUT,
|
||||
"EVENT_LOG_PARENT_INSTANCE"
|
||||
);
|
||||
service_token(parent.as_raw_handle())?;
|
||||
crate::job_binding::check_admin_readonly(Path::new(CONFIG))?;
|
||||
let mut config_file = open_private(Path::new(CONFIG), false)?;
|
||||
let config: WorkerConfig = serde_json::from_slice(&read(&mut config_file, 32768)?)?;
|
||||
ensure!(
|
||||
config.enable_jobs && config.state_directory.is_absolute(),
|
||||
"EVENT_LOG_JOBS_NOT_ENABLED"
|
||||
);
|
||||
let directory = config.state_directory.join("jobs");
|
||||
native::private_path(&directory, true)?;
|
||||
validate_ticket_path(path, &directory)?;
|
||||
// Only the exact jobs leaf is read; PKI/keys and arbitrary private files
|
||||
// cannot be passed to this mode, even by another LocalService process.
|
||||
let mut ticket_file = open_private(path, false)?;
|
||||
let ticket: Ticket = serde_json::from_slice(&read(&mut ticket_file, TICKET_LIMIT)?)?;
|
||||
ensure!(
|
||||
ticket.parent_pid == actual_parent && ticket.parent_birth == parent_birth,
|
||||
"EVENT_LOG_PARENT_INSTANCE"
|
||||
);
|
||||
let binding = crate::job_binding::readonly_binding(&config.job_binding_file)?;
|
||||
let clock = crate::clock::NativeClock::new();
|
||||
let now = clock.now()?;
|
||||
let (job, permit) = binding.verify(&ticket.request, now - chrono::Duration::seconds(2))?;
|
||||
binding.verify(&ticket.request, now + chrono::Duration::seconds(2))?;
|
||||
let query = event_log::for_job(&job)?;
|
||||
let expected = config
|
||||
.state_directory
|
||||
.join("jobs")
|
||||
.join(ticket_name(&permit));
|
||||
ensure!(path == expected, "EVENT_LOG_TICKET_PATH_BINDING");
|
||||
let runtime = tokio::runtime::Runtime::new()?;
|
||||
ensure!(
|
||||
Uuid::parse_str(&runtime.block_on(native::boot_id())?)? == ticket.boot,
|
||||
"EVENT_LOG_ORIGINAL_BOOT_REQUIRED"
|
||||
);
|
||||
let ledger_path = config.state_directory.join("consumption.sqlite");
|
||||
let ledger_file = open_private(&ledger_path, true)?;
|
||||
ensure!(
|
||||
file_id(ledger_file.as_raw_handle())? == ticket.ledger,
|
||||
"EVENT_LOG_LEDGER_FILE_CHANGED"
|
||||
);
|
||||
let db = rusqlite::Connection::open_with_flags(
|
||||
&ledger_path,
|
||||
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
||||
)?;
|
||||
db.busy_timeout(Duration::from_millis(100))?;
|
||||
let mut sqlite_handle: HANDLE = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe {
|
||||
rusqlite::ffi::sqlite3_file_control(
|
||||
db.handle(),
|
||||
c"main".as_ptr(),
|
||||
rusqlite::ffi::SQLITE_FCNTL_WIN32_GET_HANDLE,
|
||||
(&mut sqlite_handle as *mut HANDLE).cast(),
|
||||
)
|
||||
} == rusqlite::ffi::SQLITE_OK
|
||||
&& file_id(sqlite_handle)? == ticket.ledger,
|
||||
"EVENT_LOG_CONNECTED_LEDGER_FILE"
|
||||
);
|
||||
db.execute_batch("PRAGMA query_only=ON; BEGIN;")?;
|
||||
consumed(&db, &binding, &ticket, &permit)?;
|
||||
// Per-grant durable CAS prevents worker re-entry after a lost child reply.
|
||||
let marker = path.with_extension("started");
|
||||
let mut once = OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.share_mode(0)
|
||||
.open(&marker)?;
|
||||
once.write_all(b"event-log-dispatch-v1\n")?;
|
||||
once.sync_all()?;
|
||||
native::private_path(&marker, false)?;
|
||||
// File I/O, CIM and child scheduling cannot extend the signed start window.
|
||||
let now = clock.now()?;
|
||||
binding.verify(&ticket.request, now - chrono::Duration::seconds(2))?;
|
||||
binding.verify(&ticket.request, now + chrono::Duration::seconds(2))?;
|
||||
ensure!(
|
||||
agent_pid(&image)? == actual_parent
|
||||
&& birth(parent.as_raw_handle())? == ticket.parent_birth
|
||||
&& unsafe { WaitForSingleObject(parent.as_raw_handle(), 0) } == WAIT_TIMEOUT,
|
||||
"EVENT_LOG_PARENT_CHANGED"
|
||||
);
|
||||
consumed(&db, &binding, &ticket, &permit)?;
|
||||
let report = event_log::query(&query, &AtomicBool::new(false))?;
|
||||
let bytes = serde_json::to_vec(&report)?;
|
||||
ensure!(
|
||||
bytes.len() <= job.max_output_bytes as usize,
|
||||
"EVENT_LOG_OUTPUT_LIMIT"
|
||||
);
|
||||
std::io::stdout().lock().write_all(&bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct WireReport {
|
||||
channel: String,
|
||||
provider: String,
|
||||
start_utc: DateTime<Utc>,
|
||||
end_utc: DateTime<Utc>,
|
||||
quality: String,
|
||||
completeness: String,
|
||||
truncated: bool,
|
||||
error_code: Option<String>,
|
||||
win32_error: Option<u32>,
|
||||
events: Vec<event_log::Event>,
|
||||
bookmark_updated: bool,
|
||||
deadline_enforcement: String,
|
||||
}
|
||||
fn outcome(job: &JobPayload, bytes: Vec<u8>) -> Result<Outcome> {
|
||||
let q = event_log::for_job(job)?;
|
||||
ensure!(
|
||||
bytes.len() <= q.max_output_bytes as usize,
|
||||
"EVENT_LOG_OUTPUT_LIMIT"
|
||||
);
|
||||
let report: WireReport = serde_json::from_slice(&bytes)?;
|
||||
ensure!(
|
||||
report.channel == q.channel
|
||||
&& report.provider == q.provider
|
||||
&& report.start_utc == q.start_utc
|
||||
&& report.end_utc == q.end_utc
|
||||
&& !report.bookmark_updated
|
||||
&& report.events.len() <= q.max_events as usize
|
||||
&& report.deadline_enforcement == "cooperative_between_win32_calls",
|
||||
"EVENT_LOG_REPORT_BINDING"
|
||||
);
|
||||
let mut ids = std::collections::BTreeSet::new();
|
||||
for event in &report.events {
|
||||
ensure!(
|
||||
event.channel == q.channel
|
||||
&& event.provider == q.provider
|
||||
&& event.record_id > 0
|
||||
&& ids.insert(event.record_id)
|
||||
&& event.created_utc >= q.start_utc
|
||||
&& event.created_utc < q.end_utc
|
||||
&& event.xml.len() <= 64 * 1024
|
||||
&& !event.xml.contains('\0'),
|
||||
"EVENT_LOG_EVENT_BINDING"
|
||||
);
|
||||
}
|
||||
let complete =
|
||||
report.completeness == "complete" && !report.truncated && report.error_code.is_none();
|
||||
let partial = report.completeness == "partial"
|
||||
&& report.truncated
|
||||
&& matches!(
|
||||
report.error_code.as_deref(),
|
||||
Some("EVENT_LOG_EVENT_LIMIT" | "EVENT_LOG_BYTE_LIMIT" | "EVENT_LOG_EVENT_SIZE_LIMIT")
|
||||
);
|
||||
let success =
|
||||
report.quality == "valid" && report.win32_error.is_none() && (complete || partial);
|
||||
let error =
|
||||
report
|
||||
.error_code
|
||||
.as_deref()
|
||||
.unwrap_or(if success { "" } else { "EVENT_LOG_INCOMPLETE" });
|
||||
Ok(Outcome {
|
||||
state: if success { "succeeded" } else { "failed" }.into(),
|
||||
stdout: bytes,
|
||||
stderr: vec![],
|
||||
exit_code: None,
|
||||
output_truncated: report.truncated,
|
||||
reboot_required: false,
|
||||
error_code: if success { String::new() } else { error.into() },
|
||||
evidence: serde_json::json!({"postconditions_passed":success,
|
||||
"source_id":rmm_domain::jobs::WINDOWS_EVENT_LOG_FIXTURE_SOURCE,
|
||||
"channel":q.channel,"provider":q.provider,"start_utc":q.start_utc,"end_utc":q.end_utc,
|
||||
"max_events":q.max_events,"max_output_bytes":q.max_output_bytes,
|
||||
"quality":report.quality,"completeness":report.completeness,"truncated":report.truncated,
|
||||
"error_code":report.error_code,"win32_error":report.win32_error,
|
||||
"bookmark_updated":false,"execution_sid":"S-1-5-19","process_tree_bounded":true,
|
||||
"cursor_status":"not_advanced_no_ack_contract","observed_at":Utc::now()}),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn job() -> JobPayload {
|
||||
let id = Uuid::new_v4();
|
||||
let now = DateTime::from_timestamp(1_700_000_000, 0).unwrap();
|
||||
JobPayload {
|
||||
schema_version: 1,
|
||||
tenant_id: id,
|
||||
asset_id: id,
|
||||
agent_id: id,
|
||||
enrollment_generation: 1,
|
||||
assignment_version: 1,
|
||||
job_id: id,
|
||||
attempt_id: id,
|
||||
action: rmm_domain::jobs::Action::QueryLogs {
|
||||
unit: rmm_domain::jobs::WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
||||
since: now,
|
||||
until: now + chrono::Duration::minutes(5),
|
||||
max_lines: 2,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now,
|
||||
start_before: now + chrono::Duration::seconds(60),
|
||||
max_runtime_seconds: 10,
|
||||
max_output_bytes: 4096,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn ticket_pre_read_boundary_excludes_keys_siblings_and_noncanonical_leaves() {
|
||||
let directory = Path::new(r"C:\ProgramData\RustDiscovery\state\jobs");
|
||||
let leaf = format!("eventlog-{}.json", "a".repeat(64));
|
||||
assert!(validate_ticket_path(&directory.join(&leaf), directory).is_ok());
|
||||
for path in [
|
||||
PathBuf::from(r"C:\ProgramData\RustDiscovery\state\device-key.pem"),
|
||||
directory.join("..\\jobs").join(&leaf),
|
||||
directory.join(format!("eventlog-{}.json", "A".repeat(64))),
|
||||
directory.join(format!("eventlog-{}.json", "a".repeat(63))),
|
||||
directory.join(format!("eventlog-{}.json:stream", "a".repeat(64))),
|
||||
directory.join("other.json"),
|
||||
] {
|
||||
assert!(
|
||||
validate_ticket_path(&path, directory).is_err(),
|
||||
"{}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn event_log_outcome_never_equates_valid_quality_with_complete_or_authorized_success() {
|
||||
let job = job();
|
||||
let q = event_log::for_job(&job).unwrap();
|
||||
let mut report = serde_json::json!({"channel":q.channel,"provider":q.provider,
|
||||
"start_utc":q.start_utc,"end_utc":q.end_utc,"quality":"valid",
|
||||
"completeness":"complete","truncated":false,"error_code":null,"win32_error":null,
|
||||
"events":[],"bookmark_updated":false,"deadline_enforcement":"cooperative_between_win32_calls"});
|
||||
assert_eq!(
|
||||
outcome(&job, serde_json::to_vec(&report).unwrap())
|
||||
.unwrap()
|
||||
.state,
|
||||
"succeeded"
|
||||
);
|
||||
for code in [
|
||||
"EVENT_LOG_TIME_LIMIT",
|
||||
"EVENT_LOG_CANCELLED",
|
||||
"EVENT_LOG_API_ERROR",
|
||||
] {
|
||||
let mut partial = report.clone();
|
||||
partial["truncated"] = true.into();
|
||||
partial["completeness"] = "unknown".into();
|
||||
partial["error_code"] = code.into();
|
||||
assert_eq!(
|
||||
outcome(&job, serde_json::to_vec(&partial).unwrap())
|
||||
.unwrap()
|
||||
.state,
|
||||
"failed"
|
||||
);
|
||||
}
|
||||
report["truncated"] = true.into();
|
||||
report["completeness"] = "partial".into();
|
||||
report["error_code"] = "EVENT_LOG_BYTE_LIMIT".into();
|
||||
let bounded = outcome(&job, serde_json::to_vec(&report).unwrap()).unwrap();
|
||||
assert_eq!(bounded.state, "succeeded");
|
||||
assert!(bounded.output_truncated);
|
||||
report["quality"] = "permission_denied".into();
|
||||
report["win32_error"] = 5.into();
|
||||
assert_eq!(
|
||||
outcome(&job, serde_json::to_vec(&report).unwrap())
|
||||
.unwrap()
|
||||
.state,
|
||||
"failed"
|
||||
);
|
||||
report["provider"] = "another-provider".into();
|
||||
assert!(outcome(&job, serde_json::to_vec(&report).unwrap()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Shared protected public signing binding; never learns trust from a worker ticket.
|
||||
use crate::native;
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_agent_core::auth::Binding;
|
||||
use std::path::Path;
|
||||
fn read_private(path: &Path, limit: u64) -> Result<Vec<u8>> {
|
||||
use std::{fs::OpenOptions, io::Read, os::windows::fs::OpenOptionsExt};
|
||||
use windows_sys::Win32::Storage::FileSystem::{FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ};
|
||||
native::private_path(path, false)?;
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.share_mode(FILE_SHARE_READ)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)?;
|
||||
ensure!(file.metadata()?.len() <= limit, "BINDING_SIZE");
|
||||
let mut bytes = Vec::new();
|
||||
(&mut file).take(limit + 1).read_to_end(&mut bytes)?;
|
||||
ensure!(bytes.len() as u64 <= limit, "BINDING_SIZE");
|
||||
Ok(bytes)
|
||||
}
|
||||
pub fn check_admin_readonly(path: &Path) -> Result<()> {
|
||||
use std::ptr;
|
||||
use windows_sys::Win32::{
|
||||
Foundation::LocalFree,
|
||||
Security::{
|
||||
self, ACCESS_ALLOWED_ACE, ACL,
|
||||
Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT},
|
||||
DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
|
||||
},
|
||||
};
|
||||
unsafe fn sid(sid: Security::PSID) -> Result<String> {
|
||||
let mut raw = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { ConvertSidToStringSidW(sid, &mut raw) } != 0,
|
||||
"BINDING_SID"
|
||||
);
|
||||
let mut len = 0;
|
||||
while unsafe { *raw.add(len) } != 0 {
|
||||
len += 1;
|
||||
ensure!(len < 256, "BINDING_SID_LIMIT");
|
||||
}
|
||||
let value = String::from_utf16(unsafe { std::slice::from_raw_parts(raw, len) })?;
|
||||
unsafe {
|
||||
LocalFree(raw.cast());
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
ensure!(path.is_absolute(), "ABSOLUTE_JOB_BINDING_REQUIRED");
|
||||
// The immediate configuration directory must also deny agent replacement.
|
||||
for (item, directory) in [
|
||||
(path, false),
|
||||
(path.parent().context("BINDING_PARENT")?, true),
|
||||
] {
|
||||
native::private_path(item, directory)?;
|
||||
let mut owner = ptr::null_mut();
|
||||
let mut dacl: *mut ACL = ptr::null_mut();
|
||||
let mut descriptor = ptr::null_mut();
|
||||
let status = unsafe {
|
||||
GetNamedSecurityInfoW(
|
||||
native::wide(item).as_ptr(),
|
||||
SE_FILE_OBJECT,
|
||||
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
|
||||
&mut owner,
|
||||
ptr::null_mut(),
|
||||
&mut dacl,
|
||||
ptr::null_mut(),
|
||||
&mut descriptor,
|
||||
)
|
||||
};
|
||||
ensure!(status == 0, "BINDING_SECURITY");
|
||||
let check = (|| -> Result<()> {
|
||||
ensure!(!owner.is_null() && !dacl.is_null(), "BINDING_NULL_SECURITY");
|
||||
ensure!(
|
||||
matches!(unsafe { sid(owner) }?.as_str(), "S-1-5-18" | "S-1-5-32-544"),
|
||||
"BINDING_ADMIN_OWNER_REQUIRED"
|
||||
);
|
||||
for index in 0..unsafe { (*dacl).AceCount } {
|
||||
let mut raw = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { Security::GetAce(dacl, u32::from(index), &mut raw) } != 0,
|
||||
"BINDING_ACE"
|
||||
);
|
||||
let ace = unsafe { &*raw.cast::<ACCESS_ALLOWED_ACE>() };
|
||||
ensure!(
|
||||
ace.Header.AceType == 0
|
||||
&& usize::from(ace.Header.AceSize)
|
||||
>= std::mem::size_of::<ACCESS_ALLOWED_ACE>(),
|
||||
"BINDING_ACE_TYPE"
|
||||
);
|
||||
let who = unsafe { sid(ptr::addr_of!(ace.SidStart).cast_mut().cast()) }?;
|
||||
if !matches!(who.as_str(), "S-1-5-18" | "S-1-5-32-544") {
|
||||
// Generic write/all, owner/DACL/delete and all file/directory mutation bits.
|
||||
ensure!(ace.Mask & 0x500d_0156 == 0, "BINDING_AGENT_WRITE_FORBIDDEN");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
unsafe {
|
||||
LocalFree(descriptor.cast());
|
||||
}
|
||||
check?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn readonly_binding(path: &Path) -> Result<Binding> {
|
||||
check_admin_readonly(path)?;
|
||||
let binding: Binding = serde_json::from_slice(&read_private(path, 8192)?)?;
|
||||
ensure!(
|
||||
!binding.tenant_id.is_nil()
|
||||
&& !binding.agent_id.is_nil()
|
||||
&& !binding.asset_id.is_nil()
|
||||
&& binding.enrollment_generation > 0
|
||||
&& binding.assignment_version > 0
|
||||
&& binding.public_key_hex.len() == 64
|
||||
&& binding
|
||||
.public_key_hex
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_hexdigit()),
|
||||
"JOB_BINDING_PROFILE"
|
||||
);
|
||||
Ok(binding)
|
||||
}
|
||||
@@ -4,6 +4,9 @@
|
||||
pub mod actions;
|
||||
#[cfg(windows)]
|
||||
pub mod clock;
|
||||
pub mod event_log;
|
||||
#[cfg(windows)]
|
||||
pub mod event_log_job;
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
pub mod helper_ipc;
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
@@ -12,6 +15,8 @@ pub mod helper_runtime;
|
||||
pub mod helper_system;
|
||||
#[cfg(windows)]
|
||||
pub mod inventory;
|
||||
#[cfg(windows)]
|
||||
pub mod job_binding;
|
||||
pub mod journal;
|
||||
#[cfg(windows)]
|
||||
pub mod native;
|
||||
|
||||
@@ -7,7 +7,7 @@ use rmm_agent_core::{
|
||||
jobs, ledger,
|
||||
reconcile::{self, SyncClock},
|
||||
};
|
||||
use rmm_agent_windows::{CAPABILITIES, journal::Journal, native};
|
||||
use rmm_agent_windows::{CAPABILITIES, job_binding::readonly_binding, journal::Journal, native};
|
||||
use rmm_domain::jobs::{Action, ExecutionPermitPayload};
|
||||
use rmm_protocol::*;
|
||||
use rusqlite::{Connection, OptionalExtension};
|
||||
@@ -216,104 +216,6 @@ fn verified_window(
|
||||
binding.verify(request, now + chrono::Duration::seconds(2))?;
|
||||
Ok(result)
|
||||
}
|
||||
fn readonly_binding(path: &Path) -> Result<Binding> {
|
||||
use std::ptr;
|
||||
use windows_sys::Win32::{
|
||||
Foundation::LocalFree,
|
||||
Security::{
|
||||
self, ACCESS_ALLOWED_ACE, ACL,
|
||||
Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT},
|
||||
DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
|
||||
},
|
||||
};
|
||||
unsafe fn sid(sid: Security::PSID) -> Result<String> {
|
||||
let mut raw = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { ConvertSidToStringSidW(sid, &mut raw) } != 0,
|
||||
"BINDING_SID"
|
||||
);
|
||||
let mut len = 0;
|
||||
while unsafe { *raw.add(len) } != 0 {
|
||||
len += 1;
|
||||
ensure!(len < 256, "BINDING_SID_LIMIT");
|
||||
}
|
||||
let value = String::from_utf16(unsafe { std::slice::from_raw_parts(raw, len) })?;
|
||||
unsafe {
|
||||
LocalFree(raw.cast());
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
ensure!(path.is_absolute(), "ABSOLUTE_JOB_BINDING_REQUIRED");
|
||||
// The immediate configuration directory must also deny agent replacement.
|
||||
for (item, directory) in [
|
||||
(path, false),
|
||||
(path.parent().context("BINDING_PARENT")?, true),
|
||||
] {
|
||||
native::private_path(item, directory)?;
|
||||
let mut owner = ptr::null_mut();
|
||||
let mut dacl: *mut ACL = ptr::null_mut();
|
||||
let mut descriptor = ptr::null_mut();
|
||||
let status = unsafe {
|
||||
GetNamedSecurityInfoW(
|
||||
native::wide(item).as_ptr(),
|
||||
SE_FILE_OBJECT,
|
||||
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
|
||||
&mut owner,
|
||||
ptr::null_mut(),
|
||||
&mut dacl,
|
||||
ptr::null_mut(),
|
||||
&mut descriptor,
|
||||
)
|
||||
};
|
||||
ensure!(status == 0, "BINDING_SECURITY");
|
||||
let check = (|| -> Result<()> {
|
||||
ensure!(!owner.is_null() && !dacl.is_null(), "BINDING_NULL_SECURITY");
|
||||
ensure!(
|
||||
matches!(unsafe { sid(owner) }?.as_str(), "S-1-5-18" | "S-1-5-32-544"),
|
||||
"BINDING_ADMIN_OWNER_REQUIRED"
|
||||
);
|
||||
for index in 0..unsafe { (*dacl).AceCount } {
|
||||
let mut raw = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { Security::GetAce(dacl, u32::from(index), &mut raw) } != 0,
|
||||
"BINDING_ACE"
|
||||
);
|
||||
let ace = unsafe { &*raw.cast::<ACCESS_ALLOWED_ACE>() };
|
||||
ensure!(
|
||||
ace.Header.AceType == 0
|
||||
&& usize::from(ace.Header.AceSize)
|
||||
>= std::mem::size_of::<ACCESS_ALLOWED_ACE>(),
|
||||
"BINDING_ACE_TYPE"
|
||||
);
|
||||
let who = unsafe { sid(ptr::addr_of!(ace.SidStart).cast_mut().cast()) }?;
|
||||
if !matches!(who.as_str(), "S-1-5-18" | "S-1-5-32-544") {
|
||||
// Generic write/all, owner/DACL/delete and all file/directory mutation bits.
|
||||
ensure!(ace.Mask & 0x500d_0156 == 0, "BINDING_AGENT_WRITE_FORBIDDEN");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
unsafe {
|
||||
LocalFree(descriptor.cast());
|
||||
}
|
||||
check?;
|
||||
}
|
||||
let binding: Binding = serde_json::from_slice(&protected_read(path, 8192)?)?;
|
||||
ensure!(
|
||||
!binding.tenant_id.is_nil()
|
||||
&& !binding.agent_id.is_nil()
|
||||
&& !binding.asset_id.is_nil()
|
||||
&& binding.enrollment_generation > 0
|
||||
&& binding.assignment_version > 0
|
||||
&& binding.public_key_hex.len() == 64
|
||||
&& binding
|
||||
.public_key_hex
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_hexdigit()),
|
||||
"JOB_BINDING_PROFILE"
|
||||
);
|
||||
Ok(binding)
|
||||
}
|
||||
fn import_legacy_inventory(journal: &mut Journal) -> Result<()> {
|
||||
let original = {
|
||||
let mut q = journal
|
||||
@@ -1164,6 +1066,7 @@ impl Agent {
|
||||
let directory = self.config.state_directory.join("jobs");
|
||||
let work_offer = offer.clone();
|
||||
let work_grant = grant.clone();
|
||||
let original_boot = Uuid::parse_str(&self.boot)?;
|
||||
let worker = tokio::task::spawn_blocking(move || {
|
||||
let outcome = (|| -> Result<Outcome> {
|
||||
if !fence.allows(generation, &clock)
|
||||
@@ -1174,17 +1077,24 @@ impl Agent {
|
||||
"START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT",
|
||||
));
|
||||
}
|
||||
let script = if matches!(job.action, Action::RunScript { .. }) {
|
||||
match rmm_agent_windows::actions::Script::prepare(
|
||||
&job,
|
||||
&directory,
|
||||
work_grant.grant_id,
|
||||
) {
|
||||
Ok(script) => Some(script),
|
||||
Err(_) => return Ok(jobs::no_start("failed", "SCRIPT_PREPARATION_FAILED")),
|
||||
let prepared = match rmm_agent_windows::actions::PreparedAction::prepare(
|
||||
&job,
|
||||
&directory,
|
||||
work_grant.grant_id,
|
||||
&request,
|
||||
original_boot,
|
||||
) {
|
||||
Ok(prepared) => prepared,
|
||||
Err(_) => {
|
||||
return Ok(jobs::no_start(
|
||||
"failed",
|
||||
if matches!(job.action, Action::RunScript { .. }) {
|
||||
"SCRIPT_PREPARATION_FAILED"
|
||||
} else {
|
||||
"ACTION_PREPARATION_FAILED"
|
||||
},
|
||||
));
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// File creation, pool scheduling and fsync never extend a start window.
|
||||
if worker_cancel.load(Ordering::SeqCst) {
|
||||
@@ -1198,11 +1108,7 @@ impl Agent {
|
||||
"START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT",
|
||||
));
|
||||
}
|
||||
if let Some(script) = script {
|
||||
script.run(&job, &worker_cancel)
|
||||
} else {
|
||||
rmm_agent_windows::actions::inventory(&job)
|
||||
}
|
||||
prepared.run(&job, &worker_cancel)
|
||||
})()
|
||||
.unwrap_or_else(|_| Outcome::unknown("WINDOWS_EXECUTOR_EFFECT_UNKNOWN"));
|
||||
let _ = completed.blocking_send((work_offer, work_grant, outcome));
|
||||
@@ -1549,6 +1455,10 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
}
|
||||
pub fn main() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if args.first().map(String::as_str) == Some(rmm_agent_windows::event_log_job::MODE) {
|
||||
ensure!(args.len() == 2, "EVENT_LOG_WORKER_ARGUMENTS");
|
||||
return rmm_agent_windows::event_log_job::worker(Path::new(&args[1]));
|
||||
}
|
||||
if args == ["--help"] {
|
||||
println!(
|
||||
"Development Windows service. --service --config ABSOLUTE_PATH. Jobs disabled by default; require qualified clock, provisioned signing binding, signed Sync and WebUI-authorized grant. No approval bypass."
|
||||
|
||||
+135
-1
@@ -14,6 +14,13 @@ pub fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, serde_json::Error> {
|
||||
serde_json::to_vec(value)
|
||||
}
|
||||
|
||||
/// One explicitly qualified Event Log source, not an arbitrary channel/XPath.
|
||||
pub const WINDOWS_EVENT_LOG_FIXTURE_SOURCE: &str =
|
||||
"windows.eventlog.application.rustdiscovery-mvp-test";
|
||||
pub const WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY: &str = "logs.windows.eventlog.fixture/1";
|
||||
pub const WINDOWS_EVENT_LOG_FIXTURE_CHANNEL: &str = "Application";
|
||||
pub const WINDOWS_EVENT_LOG_FIXTURE_PROVIDER: &str = "RustDiscovery-MVP-Test";
|
||||
|
||||
/// Fixed per-job Windows PowerShell 5.1 option, never a machine/GPO policy.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
|
||||
pub enum WindowsExecutionProfile {
|
||||
@@ -54,6 +61,7 @@ pub enum Action {
|
||||
deserialize_with = "deserialize_windows_execution_profile",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
#[schemars(with = "WindowsExecutionProfile")]
|
||||
windows_execution_profile: Option<WindowsExecutionProfile>,
|
||||
},
|
||||
RefreshInventory {
|
||||
@@ -160,7 +168,8 @@ impl Action {
|
||||
} => {
|
||||
unit(u)
|
||||
&& since < until
|
||||
&& (*until - *since).num_hours() <= 24
|
||||
&& *until - *since <= chrono::Duration::hours(24)
|
||||
&& (u != WINDOWS_EVENT_LOG_FIXTURE_SOURCE || since.timestamp() >= 0)
|
||||
&& *max_lines > 0
|
||||
&& *max_lines <= 1000
|
||||
}
|
||||
@@ -234,6 +243,18 @@ impl Action {
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn is_windows_event_log_fixture(&self) -> bool {
|
||||
matches!(self, Self::QueryLogs { unit, .. } if unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE)
|
||||
}
|
||||
/// The outer process budget includes authenticated worker startup/cleanup;
|
||||
/// its inner Event Log calls retain their own cooperative <=5s deadline.
|
||||
pub fn valid_job_limits(&self, runtime_seconds: u32, output_bytes: u32) -> bool {
|
||||
(1..=3600).contains(&runtime_seconds)
|
||||
&& (1..=262144).contains(&output_bytes)
|
||||
&& (!self.is_windows_event_log_fixture()
|
||||
|| ((10..=120).contains(&runtime_seconds)
|
||||
&& (1024..=65536).contains(&output_bytes)))
|
||||
}
|
||||
/// Interpreter identity is part of the immutable action, never inferred at execution.
|
||||
pub fn script_platform(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
@@ -283,6 +304,16 @@ impl Action {
|
||||
&& !(has("linux.base/1") && has("windows.base/1"))
|
||||
&& (scope != "windows.base" || has("rmm.sync.v1"))
|
||||
}
|
||||
Self::QueryLogs { unit, .. }
|
||||
if unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE || has("windows.base/1") =>
|
||||
{
|
||||
identity == "agent_service"
|
||||
&& unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE
|
||||
&& has("windows.base/1")
|
||||
&& !has("linux.base/1")
|
||||
&& has("rmm.sync.v1")
|
||||
&& has(WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY)
|
||||
}
|
||||
Self::SetServiceState { state, .. }
|
||||
if identity == "system" || has("windows.base/1") =>
|
||||
{
|
||||
@@ -664,6 +695,28 @@ mod tests {
|
||||
}
|
||||
#[test]
|
||||
fn windows_remote_signed_profile_is_optional_exact_and_capability_bound() {
|
||||
let schema = schemars::schema_for!(Action).to_value();
|
||||
let script_schema = schema["oneOf"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|variant| {
|
||||
variant["properties"]
|
||||
.get("windows_execution_profile")
|
||||
.is_some()
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
script_schema["properties"]["windows_execution_profile"],
|
||||
serde_json::json!({"$ref":"#/$defs/WindowsExecutionProfile"})
|
||||
);
|
||||
assert!(
|
||||
!script_schema["required"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&serde_json::json!("windows_execution_profile"))
|
||||
);
|
||||
assert_eq!(schema["$defs"]["WindowsExecutionProfile"]["type"], "string");
|
||||
let legacy = br#"{"action":"run_script","interpreter":"powershell","script_utf8":"Write-Output 'hi'\r\n","arguments":[],"expected_stdout":null}"#;
|
||||
let mut action: Action = serde_json::from_slice(legacy).unwrap();
|
||||
assert_eq!(encode(&action).unwrap(), legacy);
|
||||
@@ -740,6 +793,87 @@ mod tests {
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn windows_event_log_fixture_scope_limits_and_exact_24h_preserve_linux_bytes() {
|
||||
let since = DateTime::parse_from_rfc3339("2026-11-14T00:00:00Z")
|
||||
.unwrap()
|
||||
.with_timezone(&Utc);
|
||||
let mut action = Action::QueryLogs {
|
||||
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
||||
since,
|
||||
until: since + chrono::Duration::hours(24),
|
||||
max_lines: 1000,
|
||||
};
|
||||
let caps: Vec<String> = [
|
||||
"windows.base/1",
|
||||
"rmm.sync.v1",
|
||||
"query_logs",
|
||||
WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY,
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
assert!(action.validate());
|
||||
assert!(action.available_for("agent_service", &caps));
|
||||
assert!(action.valid_job_limits(10, 1024));
|
||||
assert!(action.valid_job_limits(120, 65536));
|
||||
for (runtime, bytes) in [(9, 1024), (121, 1024), (10, 1023), (10, 65537)] {
|
||||
assert!(!action.valid_job_limits(runtime, bytes));
|
||||
}
|
||||
for i in 0..caps.len() {
|
||||
let mut short = caps.clone();
|
||||
short.remove(i);
|
||||
assert!(!action.available_for("agent_service", &short));
|
||||
}
|
||||
for identity in ["root", "system", "SYSTEM"] {
|
||||
assert!(!action.available_for(identity, &caps));
|
||||
}
|
||||
let mut mixed = caps.clone();
|
||||
mixed.push("linux.base/1".into());
|
||||
assert!(!action.available_for("agent_service", &mixed));
|
||||
assert!(!action.available_for("root", &["linux.base/1".into(), "query_logs".into()]));
|
||||
for unit in [
|
||||
"Application",
|
||||
"Security",
|
||||
"windows.eventlog.application.other",
|
||||
] {
|
||||
let mut wrong = action.clone();
|
||||
if let Action::QueryLogs { unit: u, .. } = &mut wrong {
|
||||
*u = unit.into();
|
||||
}
|
||||
assert!(!wrong.available_for("agent_service", &caps));
|
||||
}
|
||||
if let Action::QueryLogs { until, .. } = &mut action {
|
||||
*until += chrono::Duration::nanoseconds(1);
|
||||
}
|
||||
assert!(!action.validate());
|
||||
let linux = Action::QueryLogs {
|
||||
unit: "rmm-test.service".into(),
|
||||
since,
|
||||
until: since + chrono::Duration::hours(24),
|
||||
max_lines: 1000,
|
||||
};
|
||||
assert_eq!(
|
||||
String::from_utf8(encode(&linux).unwrap()).unwrap(),
|
||||
r#"{"action":"query_logs","unit":"rmm-test.service","since":"2026-11-14T00:00:00Z","until":"2026-11-15T00:00:00Z","max_lines":1000}"#
|
||||
);
|
||||
assert!(linux.validate());
|
||||
for identity in ["root", "agent_service"] {
|
||||
assert!(linux.available_for(identity, &["linux.base/1".into(), "query_logs".into()]));
|
||||
}
|
||||
let mut too_long = linux;
|
||||
if let Action::QueryLogs { until, .. } = &mut too_long {
|
||||
*until += chrono::Duration::minutes(59);
|
||||
}
|
||||
assert!(!too_long.validate());
|
||||
let pre_epoch = Action::QueryLogs {
|
||||
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
||||
since: DateTime::from_timestamp(-1, 0).unwrap(),
|
||||
until: DateTime::from_timestamp(0, 0).unwrap(),
|
||||
max_lines: 1,
|
||||
};
|
||||
assert!(!pre_epoch.validate());
|
||||
}
|
||||
#[test]
|
||||
fn no_terminal_replay_or_unknown_restart() {
|
||||
assert!(!JobState::Succeeded.allows(JobState::Running));
|
||||
assert!(!JobState::Unknown.allows(JobState::Running));
|
||||
|
||||
@@ -192,6 +192,7 @@ pub async fn event(
|
||||
}
|
||||
}
|
||||
script_profile_evidence(&payload.action, &evidence)?;
|
||||
windows_event_log_success_evidence(&payload, r, &evidence)?;
|
||||
if matches!(payload.action, Action::Reboot { .. }) {
|
||||
crate::synchronization::verify_reboot_success(
|
||||
tx, tenant, agent, e, &payload, r, &evidence,
|
||||
@@ -225,6 +226,70 @@ pub async fn event(
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
fn windows_event_log_success_evidence(
|
||||
job: &JobPayload,
|
||||
result: &JobResult,
|
||||
evidence: &Value,
|
||||
) -> Result<()> {
|
||||
if !job.action.is_windows_event_log_fixture() {
|
||||
return Ok(());
|
||||
}
|
||||
let Action::QueryLogs {
|
||||
unit,
|
||||
since,
|
||||
until,
|
||||
max_lines,
|
||||
} = &job.action
|
||||
else {
|
||||
anyhow::bail!("fixed event log action required")
|
||||
};
|
||||
let observed_since: chrono::DateTime<Utc> = serde_json::from_value(
|
||||
evidence
|
||||
.get("start_utc")
|
||||
.cloned()
|
||||
.context("event log start missing")?,
|
||||
)?;
|
||||
let observed_until: chrono::DateTime<Utc> = serde_json::from_value(
|
||||
evidence
|
||||
.get("end_utc")
|
||||
.cloned()
|
||||
.context("event log end missing")?,
|
||||
)?;
|
||||
let complete = evidence.get("completeness") == Some(&json!("complete"))
|
||||
&& evidence.get("truncated") == Some(&json!(false))
|
||||
&& evidence.get("error_code") == Some(&Value::Null);
|
||||
let partial = evidence.get("completeness") == Some(&json!("partial"))
|
||||
&& evidence.get("truncated") == Some(&json!(true))
|
||||
&& matches!(
|
||||
evidence.get("error_code").and_then(Value::as_str),
|
||||
Some("EVENT_LOG_EVENT_LIMIT" | "EVENT_LOG_BYTE_LIMIT" | "EVENT_LOG_EVENT_SIZE_LIMIT")
|
||||
);
|
||||
ensure!(
|
||||
!result.reboot_required
|
||||
&& evidence.get("truncated") == Some(&json!(result.output_truncated))
|
||||
&& job.execution_identity == "agent_service"
|
||||
&& job.action.validate()
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
||||
&& evidence.get("source_id") == Some(&json!(unit))
|
||||
&& evidence.get("channel") == Some(&json!(WINDOWS_EVENT_LOG_FIXTURE_CHANNEL))
|
||||
&& evidence.get("provider") == Some(&json!(WINDOWS_EVENT_LOG_FIXTURE_PROVIDER))
|
||||
&& observed_since == *since
|
||||
&& observed_until == *until
|
||||
&& evidence.get("max_events") == Some(&json!(max_lines))
|
||||
&& evidence.get("max_output_bytes") == Some(&json!(job.max_output_bytes))
|
||||
&& evidence.get("quality") == Some(&json!("valid"))
|
||||
&& evidence.get("win32_error") == Some(&Value::Null)
|
||||
&& evidence.get("bookmark_updated") == Some(&json!(false))
|
||||
&& evidence.get("process_tree_bounded") == Some(&json!(true))
|
||||
&& evidence.get("execution_sid") == Some(&json!("S-1-5-19"))
|
||||
&& (complete || partial),
|
||||
"fixed Windows Event Log evidence mismatch"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// The profile records the requested process option, never an effective GPO policy.
|
||||
fn script_profile_evidence(action: &Action, evidence: &Value) -> Result<()> {
|
||||
if let Action::RunScript {
|
||||
@@ -251,6 +316,94 @@ fn script_profile_evidence(action: &Action, evidence: &Value) -> Result<()> {
|
||||
mod script_profile_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn windows_event_log_success_binds_request_and_keeps_limit_partial_honest() {
|
||||
let id = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
let job = JobPayload {
|
||||
schema_version: 1,
|
||||
tenant_id: id,
|
||||
asset_id: id,
|
||||
agent_id: id,
|
||||
enrollment_generation: 1,
|
||||
assignment_version: 1,
|
||||
job_id: id,
|
||||
attempt_id: id,
|
||||
action: Action::QueryLogs {
|
||||
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
||||
since: now - Duration::hours(1),
|
||||
until: now,
|
||||
max_lines: 1000,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now,
|
||||
start_before: now + Duration::minutes(1),
|
||||
max_runtime_seconds: 30,
|
||||
max_output_bytes: 4096,
|
||||
};
|
||||
let evidence = json!({"source_id":WINDOWS_EVENT_LOG_FIXTURE_SOURCE,"channel":"Application","provider":"RustDiscovery-MVP-Test","start_utc":now-Duration::hours(1),"end_utc":now,"max_events":1000,"max_output_bytes":4096,"quality":"valid","completeness":"complete","truncated":false,"error_code":null,"win32_error":null,"bookmark_updated":false,"process_tree_bounded":true,"execution_sid":"S-1-5-19"});
|
||||
let result = JobResult::default();
|
||||
windows_event_log_success_evidence(&job, &result, &evidence).unwrap();
|
||||
for conflicting in [
|
||||
JobResult {
|
||||
reboot_required: true,
|
||||
..Default::default()
|
||||
},
|
||||
JobResult {
|
||||
output_truncated: true,
|
||||
..Default::default()
|
||||
},
|
||||
] {
|
||||
assert!(windows_event_log_success_evidence(&job, &conflicting, &evidence).is_err());
|
||||
}
|
||||
for field in [
|
||||
"source_id",
|
||||
"channel",
|
||||
"provider",
|
||||
"start_utc",
|
||||
"end_utc",
|
||||
"max_events",
|
||||
"max_output_bytes",
|
||||
"quality",
|
||||
"win32_error",
|
||||
"bookmark_updated",
|
||||
"process_tree_bounded",
|
||||
"execution_sid",
|
||||
] {
|
||||
let mut bad = evidence.clone();
|
||||
bad[field] = json!("different");
|
||||
assert!(
|
||||
windows_event_log_success_evidence(&job, &result, &bad).is_err(),
|
||||
"{field}"
|
||||
);
|
||||
}
|
||||
for code in [
|
||||
"EVENT_LOG_EVENT_LIMIT",
|
||||
"EVENT_LOG_BYTE_LIMIT",
|
||||
"EVENT_LOG_EVENT_SIZE_LIMIT",
|
||||
] {
|
||||
let mut partial = evidence.clone();
|
||||
partial["completeness"] = json!("partial");
|
||||
partial["truncated"] = json!(true);
|
||||
partial["error_code"] = json!(code);
|
||||
let partial_result = JobResult {
|
||||
output_truncated: true,
|
||||
..Default::default()
|
||||
};
|
||||
windows_event_log_success_evidence(&job, &partial_result, &partial).unwrap();
|
||||
assert!(windows_event_log_success_evidence(&job, &result, &partial).is_err());
|
||||
partial["error_code"] = json!("EVENT_LOG_TIMEOUT");
|
||||
assert!(windows_event_log_success_evidence(&job, &partial_result, &partial).is_err());
|
||||
partial["quality"] = json!("permission_denied");
|
||||
assert!(windows_event_log_success_evidence(&job, &partial_result, &partial).is_err());
|
||||
}
|
||||
let mut permission_denied = evidence.clone();
|
||||
permission_denied["win32_error"] = json!(5);
|
||||
assert!(windows_event_log_success_evidence(&job, &result, &permission_denied).is_err());
|
||||
let mut false_complete = evidence.clone();
|
||||
false_complete["truncated"] = json!(true);
|
||||
assert!(windows_event_log_success_evidence(&job, &result, &false_complete).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn requested_profile_success_evidence_is_exact_without_effective_policy_claim() {
|
||||
let mut action = Action::RunScript {
|
||||
interpreter: "powershell".into(),
|
||||
@@ -383,6 +536,12 @@ pub async fn permit(
|
||||
return Ok(denied("BINDING_MISMATCH"));
|
||||
}
|
||||
let now = Utc::now();
|
||||
if !payload
|
||||
.action
|
||||
.valid_job_limits(payload.max_runtime_seconds, payload.max_output_bytes)
|
||||
{
|
||||
return Ok(denied("INVALID_JOB_LIMITS"));
|
||||
}
|
||||
if !payload.action.validate() {
|
||||
return Ok(denied("APT_MANIFEST_REQUIRED"));
|
||||
}
|
||||
@@ -580,6 +739,9 @@ pub async fn next(
|
||||
if !payload
|
||||
.action
|
||||
.available_for(&payload.execution_identity, &caps)
|
||||
|| !payload
|
||||
.action
|
||||
.valid_job_limits(payload.max_runtime_seconds, payload.max_output_bytes)
|
||||
{
|
||||
tx.commit().await?;
|
||||
return Ok(None);
|
||||
|
||||
@@ -156,6 +156,7 @@ pub struct Variant {
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_windows_execution_profile",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
#[schemars(with = "WindowsExecutionProfile")]
|
||||
windows_execution_profile: Option<WindowsExecutionProfile>,
|
||||
}
|
||||
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
|
||||
@@ -471,6 +472,9 @@ pub async fn plan(
|
||||
let row = &rows[0];
|
||||
let caps = capabilities(row.get("capabilities"))?;
|
||||
let action = target_action(&input, &caps)?;
|
||||
if !action.valid_job_limits(input.max_runtime_seconds, input.max_output_bytes) {
|
||||
return Err(fail("VALIDATION_ERROR"));
|
||||
}
|
||||
if !action.available_for(&input.execution_identity, &caps) {
|
||||
return Err(fail("UNSUPPORTED_CAPABILITY"));
|
||||
}
|
||||
@@ -598,6 +602,12 @@ async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Resu
|
||||
}
|
||||
let mut references = Vec::new();
|
||||
for job in &plan.jobs {
|
||||
if !job.payload.action.valid_job_limits(
|
||||
job.payload.max_runtime_seconds,
|
||||
job.payload.max_output_bytes,
|
||||
) {
|
||||
return Err(fail("VALIDATION_ERROR"));
|
||||
}
|
||||
if !job.payload.action.validate() {
|
||||
return Err(Error(StatusCode::CONFLICT, "APT_MANIFEST_REQUIRED"));
|
||||
}
|
||||
@@ -1022,6 +1032,7 @@ async fn operations_http(
|
||||
#[cfg(test)]
|
||||
mod windows_contract_tests {
|
||||
use super::*;
|
||||
use chrono::Duration;
|
||||
fn input() -> PlanInput {
|
||||
let tenant = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
@@ -1054,6 +1065,33 @@ mod windows_contract_tests {
|
||||
assert!(target_action(&i, &["windows.base/1".into()]).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn fixed_windows_log_web_contract_denies_extra_source_parameters() {
|
||||
let tenant = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
let value = json!({"tenant_id":tenant,"action":"query_logs","targets":{"asset_ids":[Uuid::new_v4()]},"parameters":{"execution_identity":"agent_service","timeout_seconds":30,"max_output_bytes":4096,"unit":WINDOWS_EVENT_LOG_FIXTURE_SOURCE,"since":now-Duration::hours(1),"until":now,"max_lines":1000},"schedule":{"not_before":now,"start_before":now+Duration::minutes(10),"offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"fixed source"});
|
||||
let input = serde_json::from_value::<PlanRequest>(value.clone())
|
||||
.unwrap()
|
||||
.resolve(tenant)
|
||||
.unwrap();
|
||||
assert!(input.action.is_windows_event_log_fixture());
|
||||
assert!(input.action.validate());
|
||||
assert!(
|
||||
input
|
||||
.action
|
||||
.valid_job_limits(input.max_runtime_seconds, input.max_output_bytes)
|
||||
);
|
||||
assert!(input.script_variants.is_empty());
|
||||
for field in ["channel", "provider", "xpath", "bookmark"] {
|
||||
let mut bad = value.clone();
|
||||
bad["parameters"][field] = json!("arbitrary");
|
||||
assert!(
|
||||
serde_json::from_value::<PlanRequest>(bad)
|
||||
.map(|request| request.resolve(tenant).is_err())
|
||||
.unwrap_or(true)
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn remote_signed_fixed_variants_bind_profile_without_linux_inheritance() {
|
||||
let mut i = input();
|
||||
let legacy_linux = encode(&i.action).unwrap();
|
||||
@@ -1100,6 +1138,18 @@ mod windows_contract_tests {
|
||||
i.script_variants[1].windows_execution_profile =
|
||||
Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
|
||||
assert!(validate_variants(&i.script_variants).is_err());
|
||||
let schema = schemars::schema_for!(Variant).to_value();
|
||||
assert_eq!(
|
||||
schema["properties"]["windows_execution_profile"],
|
||||
json!({"$ref":"#/$defs/WindowsExecutionProfile"})
|
||||
);
|
||||
assert!(
|
||||
!schema["required"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("windows_execution_profile"))
|
||||
);
|
||||
assert_eq!(schema["$defs"]["WindowsExecutionProfile"]["type"], "string");
|
||||
let legacy = json!({"os_family":"windows", "interpreter":"powershell", "encoding":"utf-8", "script_utf8":"hi"});
|
||||
let inherited: Variant = serde_json::from_value(legacy.clone()).unwrap();
|
||||
assert!(inherited.windows_execution_profile.is_none());
|
||||
@@ -1351,6 +1401,116 @@ mod windows_contract_tests {
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
let now = Utc::now();
|
||||
let mut logs = input();
|
||||
logs.targets.asset_ids = vec![assets[1]];
|
||||
logs.script_variants.clear();
|
||||
logs.max_runtime_seconds = 30;
|
||||
logs.action = Action::QueryLogs {
|
||||
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
||||
since: now - Duration::hours(1),
|
||||
until: now,
|
||||
max_lines: 1000,
|
||||
};
|
||||
assert_eq!(
|
||||
plan(&state, &principal, tenant, logs.clone())
|
||||
.await
|
||||
.unwrap_err()
|
||||
.1,
|
||||
"FORBIDDEN"
|
||||
);
|
||||
sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'logs:read') WHERE principal=$1").bind(&principal.name).execute(&admin).await.unwrap();
|
||||
assert_eq!(
|
||||
plan(&state, &principal, tenant, logs.clone())
|
||||
.await
|
||||
.unwrap_err()
|
||||
.1,
|
||||
"UNSUPPORTED_CAPABILITY"
|
||||
);
|
||||
let mut log_caps = windows_caps.as_array().unwrap().clone();
|
||||
log_caps.extend([
|
||||
json!("query_logs"),
|
||||
json!(WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY),
|
||||
]);
|
||||
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
||||
.bind(agents[1])
|
||||
.bind(json!(log_caps))
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let view = plan(&state, &principal, tenant, logs).await.unwrap();
|
||||
let log_id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap();
|
||||
let bytes: Vec<u8> =
|
||||
sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1")
|
||||
.bind(log_id)
|
||||
.fetch_one(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let log_bound: PlanPayload = serde_json::from_slice(&bytes).unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
recheck(&mut tx, &log_bound).await.unwrap();
|
||||
tx.rollback().await.unwrap();
|
||||
let pending = submit(
|
||||
&state,
|
||||
&principal,
|
||||
tenant,
|
||||
log_id,
|
||||
Submit {
|
||||
idempotency_key: "fixed-event-log".into(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(pending["approval_state"], "pending_approval");
|
||||
assert_eq!(pending["job_count"], 0);
|
||||
let mut changed = log_bound.clone();
|
||||
if let Action::QueryLogs { max_lines, .. } = &mut changed.jobs[0].payload.action {
|
||||
*max_lines = 999;
|
||||
}
|
||||
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();
|
||||
let mut changed = log_bound.clone();
|
||||
changed.jobs[0].payload.max_output_bytes = 65537;
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
recheck(&mut tx, &changed).await.unwrap_err().1,
|
||||
"VALIDATION_ERROR"
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
log_caps.retain(|cap| cap != WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY);
|
||||
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
||||
.bind(agents[1])
|
||||
.bind(json!(log_caps))
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
recheck(&mut tx, &log_bound).await.unwrap_err().1,
|
||||
"UNSUPPORTED_CAPABILITY"
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
sqlx::query("UPDATE memberships SET permissions=array_remove(permissions,'logs:read') WHERE principal=$1").bind(&principal.name).execute(&admin).await.unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
recheck(&mut tx, &log_bound).await.unwrap_err().1,
|
||||
"FORBIDDEN"
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
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> =
|
||||
|
||||
@@ -0,0 +1,503 @@
|
||||
#!/usr/bin/env python3
|
||||
"""M3 Event Log pure contracts: Linux VM FIRST, then Windows VM.
|
||||
|
||||
Only two fixed test executables run in separate bootstrap scratch directories.
|
||||
No RMM job, daemon, live database, PKI, policy, enrollment or capability change.
|
||||
Native execution is explicit; any lost reply permits same-case readback only.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
import vm_access_check as access
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
STATE = ROOT / 'devstate/windows-eventlog-contracts'
|
||||
IMAGE = 'rust-discovery-durable-final-build:local'
|
||||
PROFILE = 'windows-eventlog-contracts-v1'
|
||||
LINUX_REMOTE = '/var/lib/rmm-windows-eventlog-contracts'
|
||||
KINDS = ('domain', 'contracts')
|
||||
REVIEWED_M3 = {'crates/agent-core/src/auth.rs': '360e6af153d7d5b31717e0f8fbc0e988850c7fa032eaa3a657962187f5a657e4',
|
||||
'crates/agent-core/tests/contracts.rs': '2482928f45e3236ae079329668849f5ccd2e01503e56cd3b8e37579af3f21e9c',
|
||||
'crates/agent-windows/Cargo.toml': '886f0ee1bc8b02133325bc1f1c4db76db3f0194435fba151eb1f3ca42e0660dc',
|
||||
'crates/agent-windows/src/actions.rs': 'a13e3746ee05619b993b6828e9c7b103fa5d3f9d47f1b52de595da3c57910180',
|
||||
'crates/agent-windows/src/event_log.rs': '00756bc178c5e67eca0de64fe55f6a1b3865e27d33f3e1c87fa575b5be81706d',
|
||||
'crates/agent-windows/src/event_log_job.rs': '08798cf194c405e93cd5874517857a06649aa47a0cc8c933fbd924018670113e',
|
||||
'crates/agent-windows/src/job_binding.rs': '488bab9f74b84023cf5b8f35f6f624903d98a82e886ef78d7ab93c8d99281e26',
|
||||
'crates/agent-windows/src/lib.rs': '391764708bfd6a8ab5546ef299d40f54dc4eefa02d4334dead7a16e46a22cd66',
|
||||
'crates/agent-windows/src/runtime.rs': '21c09cbc2a0b4caf5a4e273a20eac63dc870bb942a3683fb5b7ba6f7b36b4674',
|
||||
'crates/domain/src/jobs.rs': 'b9950270fc77086d06b3f7aa177aba2ad13155c10653b3ee73a2be436365cf1f',
|
||||
'crates/server/src/job_gateway.rs': '234542f4783c95cfcfd567495bfb7233f2c05a1b88dd87fb85a916d32eae5fc5',
|
||||
'crates/server/src/jobs.rs': '5bff6fe61fce601cd03721cebd82bca05b5af83d3640bf862ba6d603ceb7e3e9'}
|
||||
COUNTS = {'linux': {'domain': 17, 'contracts': 7}, 'windows': {'domain': 17, 'contracts': 6}}
|
||||
DOMAIN_NAMES = sorted(('apt_transaction::tests::closure_bytes_archives_and_code_are_bound',
|
||||
'apt_transaction::tests::helper_schema_two_roundtrip_and_strict_action_binding',
|
||||
'inventory_document::tests::additive_metadata_and_bounds',
|
||||
'inventory_document::tests::exact_linux_recovery_scope_does_not_admit_other_hyphens_or_windows',
|
||||
'inventory_document::tests::windows_scope_does_not_weaken_linux_or_accept_platform_spoofing',
|
||||
'jobs::tests::additive_recipe_refs_preserve_legacy_plan_bytes', 'jobs::tests::codec_golden_and_exact_script_bytes',
|
||||
'jobs::tests::no_terminal_replay_or_unknown_restart', 'jobs::tests::permit_codec_golden_all_bindings',
|
||||
'jobs::tests::updates_require_exact_versions_and_never_implicit_reboot',
|
||||
'jobs::tests::windows_event_log_fixture_scope_limits_and_exact_24h_preserve_linux_bytes',
|
||||
'jobs::tests::windows_interpreter_and_capability_contract',
|
||||
'jobs::tests::windows_remote_signed_profile_is_optional_exact_and_capability_bound',
|
||||
'jobs::tests::windows_system_scm_is_explicit_and_preserves_linux_service_bytes',
|
||||
'reconciliation::tests::outcome_codec_keeps_raw_output_and_sorts_evidence',
|
||||
'reconciliation::tests::reconciliation_cannot_be_a_permit_or_unbounded_ticket',
|
||||
'tests::production_never_accepts_development_auth'))
|
||||
CONTRACT_NAMES = sorted(('atomic_begin_execution_rolls_back_both_rows_on_missing_witness_or_start_insert_failure',
|
||||
'completion_cas_preserves_original_bytes_and_recovers_only_verified_bound_evidence',
|
||||
'consumed_attempt_and_unknown_lock_survive_reopen_without_reexecution',
|
||||
'exact_permit_bytes_time_and_all_identity_hash_bindings_are_required',
|
||||
'historical_request_and_binding_codecs_keep_field_order_arrays_and_strictness',
|
||||
'openssl_and_portable_ed25519_agree_on_current_keys_bytes_and_tampering',
|
||||
'portable_acceptance_requires_platform_capability_and_exact_redelivery'))
|
||||
UNIX_ONLY = 'openssl_and_portable_ed25519_agree_on_current_keys_bytes_and_tampering'
|
||||
EXPECTED = {'linux': {'domain': DOMAIN_NAMES, 'contracts': CONTRACT_NAMES},
|
||||
'windows': {'domain': DOMAIN_NAMES, 'contracts': [x for x in CONTRACT_NAMES if x != UNIX_ONLY]}}
|
||||
|
||||
|
||||
def require(value, code):
|
||||
if not value:
|
||||
raise RuntimeError(code)
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def object_pairs(items):
|
||||
value = {}
|
||||
for key, item in items:
|
||||
require(key not in value, 'duplicate JSON field')
|
||||
value[key] = item
|
||||
return value
|
||||
|
||||
|
||||
def private(path, directory=False):
|
||||
item = Path(path).lstat()
|
||||
require(not stat.S_ISLNK(item.st_mode) and item.st_uid == os.getuid()
|
||||
and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600)
|
||||
and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),
|
||||
'private owned regular path')
|
||||
|
||||
|
||||
def load(path):
|
||||
private(path)
|
||||
require(Path(path).stat().st_size <= 2 * 1024 * 1024, 'bounded private JSON')
|
||||
return json.loads(Path(path).read_bytes(), object_pairs_hook=object_pairs)
|
||||
|
||||
|
||||
def save(path, value):
|
||||
private(Path(path).parent, True)
|
||||
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
|
||||
with os.fdopen(fd, 'w') as stream:
|
||||
json.dump(value, stream, indent=2); stream.write('\n'); stream.flush(); os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def setup_state():
|
||||
os.umask(0o077)
|
||||
STATE.parent.mkdir(mode=0o700, exist_ok=True)
|
||||
metadata = STATE.parent.lstat()
|
||||
require(stat.S_ISDIR(metadata.st_mode) and metadata.st_uid == os.getuid() and not metadata.st_mode & 0o002,
|
||||
'owned non-world-writable devstate parent')
|
||||
STATE.mkdir(mode=0o700, exist_ok=True)
|
||||
private(STATE, True)
|
||||
|
||||
|
||||
def source_files():
|
||||
paths = [ROOT / p for p in ('Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml',
|
||||
'deploy/windows_eventlog_acceptance.py', 'deploy/remote_client_bootstrap.py',
|
||||
'deploy/vm_access_check.py', 'deploy/vm_mvp_acceptance.py', 'deploy/windows/client_bootstrap.py')]
|
||||
paths += list((ROOT / 'crates').rglob('Cargo.toml'))
|
||||
for name in ('domain', 'agent-core', 'protocol', 'server', 'agent-windows'):
|
||||
paths += [p for p in (ROOT / 'crates' / name).rglob('*') if p.is_file()]
|
||||
paths += [p for p in (ROOT / 'proto').rglob('*') if p.is_file()]
|
||||
for path in paths:
|
||||
require(not path.is_symlink() and path.is_file(), 'regular source inputs only')
|
||||
value = {str(p.relative_to(ROOT)): sha(p) for p in sorted(set(paths))}
|
||||
require(all(value[name] == digest for name, digest in REVIEWED_M3.items()), 'exact frozen reviewed M3 sources')
|
||||
return value
|
||||
|
||||
|
||||
def names(raw):
|
||||
return sorted(re.findall(r'^([A-Za-z0-9_:]+): test\r?$', raw, re.M))
|
||||
|
||||
|
||||
def check_list(raw, expected):
|
||||
require(names(raw) == expected and len(set(expected)) == len(expected), 'all exact test names before execution')
|
||||
require(all(not line.strip() or re.fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in raw.splitlines()),
|
||||
'terse list contains only exact tests, no benchmarks or extra entries')
|
||||
|
||||
|
||||
def check_output(raw, count):
|
||||
require(re.search(rb'^test result: ok\. ' + str(count).encode()
|
||||
+ rb' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;[^\r\n]*\r?$', raw, re.M),
|
||||
'all tests passed without skipped or filtered tests')
|
||||
|
||||
|
||||
def command(args, folder, timeout=300):
|
||||
index = len(list(folder.glob('command-*.json')))
|
||||
try:
|
||||
done = subprocess.run(args, capture_output=True, timeout=timeout)
|
||||
save(folder / ('command-%03d.json' % index), dict(returncode=done.returncode,
|
||||
stdout_b64=base64.b64encode(done.stdout).decode(), stderr_b64=base64.b64encode(done.stderr).decode()))
|
||||
require(done.returncode == 0, 'local qualification command failed; private output retained')
|
||||
return done.stdout
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('command-%03d.json' % index), dict(timed_out=True,
|
||||
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('local qualification timed out; no automatic retry') from None
|
||||
|
||||
|
||||
def scripts():
|
||||
return {'linux_case_sha256': hashlib.sha256(inspect.getsource(linux_case).encode()).hexdigest(),
|
||||
'windows_script_sha256': hashlib.sha256(WINDOWS.encode()).hexdigest()}
|
||||
|
||||
|
||||
def build():
|
||||
setup_state()
|
||||
folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700)
|
||||
before = source_files(); save(folder / 'source-before.json', before)
|
||||
image = command(['docker', 'image', 'inspect', '--format', '{{.Id}}', IMAGE], folder).decode().strip()
|
||||
require(re.fullmatch(r'sha256:[a-f0-9]{64}', image), 'immutable local build image')
|
||||
target = STATE / 'target'; target.mkdir(mode=0o700, exist_ok=True); private(target, True)
|
||||
common = ['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,size=512m',
|
||||
'-v', str(ROOT) + ':/src:ro', '-v', str(target) + ':/target', '-e', 'CARGO_TARGET_DIR=/target', '--entrypoint', 'cargo', image]
|
||||
artifacts = {'linux': {}, 'windows': {}}
|
||||
for platform, triple in [('linux', 'x86_64-unknown-linux-gnu'), ('windows', 'x86_64-pc-windows-gnu')]:
|
||||
for kind in KINDS:
|
||||
package, selection = ('rmm-domain', ['--lib']) if kind == 'domain' else ('rmm-agent-core', ['--test', 'contracts'])
|
||||
options = ['--manifest-path', '/src/Cargo.toml', '--locked', '--offline', '--target', triple, '-p', package]
|
||||
command(common + ['clippy'] + options + selection + ['--', '-D', 'warnings'], folder)
|
||||
raw = command(common + ['test'] + options + selection + ['--release', '--no-run', '--message-format=json'], folder)
|
||||
linked = []
|
||||
for line in raw.splitlines():
|
||||
try: item = json.loads(line)
|
||||
except ValueError: continue
|
||||
expected_name = 'rmm_domain' if kind == 'domain' else 'contracts'
|
||||
if item.get('reason') == 'compiler-artifact' and item.get('executable') and item.get('profile', {}).get('test') and item['target']['name'] == expected_name:
|
||||
linked.append(target / Path(item['executable']).relative_to('/target'))
|
||||
require(len(linked) == 1, 'exact selected unit executable')
|
||||
destination = folder / platform; destination.mkdir(mode=0o700, exist_ok=True)
|
||||
original = destination / (kind + '.linked')
|
||||
delivery = destination / (kind + ('.exe' if platform == 'windows' else ''))
|
||||
for path in (original, delivery): shutil.copyfile(linked[0], path); path.chmod(0o600)
|
||||
linked_sha = sha(original)
|
||||
tool = 'x86_64-w64-mingw32-strip' if platform == 'windows' else 'strip'
|
||||
command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', str(destination) + ':/artifacts',
|
||||
'--entrypoint', tool, image, '--strip-debug', '/artifacts/' + delivery.name], folder)
|
||||
require(sha(linked[0]) == sha(original) == linked_sha, 'unstripped original link preserved')
|
||||
data = delivery.read_bytes()
|
||||
if platform == 'linux':
|
||||
require(data[:6] == b'\x7fELF\x02\x01' and data[18:20] == b'\x3e\0', 'Linux x64 ELF')
|
||||
else:
|
||||
offset = int.from_bytes(data[60:64], 'little')
|
||||
require(data[:2] == b'MZ' and data[offset:offset + 6] == b'PE\0\0\x64\x86', 'Windows x64 PE')
|
||||
artifacts[platform][kind] = dict(path=str(delivery.resolve()), sha256=sha(delivery), bytes=len(data),
|
||||
original_link_path=str(original.resolve()), original_link_sha256=linked_sha, debug_stripped_delivery=True)
|
||||
# Run exactly the deliverable Linux bytes in an offline disposable container.
|
||||
for kind, item in artifacts['linux'].items():
|
||||
invoke = ['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,exec,size=128m',
|
||||
'-v', item['path'] + ':/unit:ro', '--entrypoint', 'python3', image, '-c']
|
||||
for mode in ('list', 'run'):
|
||||
args = ['--list', '--format', 'terse'] if mode == 'list' else ['--test-threads=1']
|
||||
script = 'import shutil,os,subprocess;shutil.copyfile("/unit","/tmp/unit");os.chmod("/tmp/unit",0o500);subprocess.run(["/tmp/unit"]+' + repr(args) + ',check=True,cwd="/tmp",env={"PATH":"/usr/bin:/bin","LANG":"C.UTF-8","TMPDIR":"/tmp","RUST_BACKTRACE":"0"})'
|
||||
raw = command(invoke + [script], folder)
|
||||
save(folder / ('local-linux-' + kind + '-' + mode + '.json'), dict(stdout_b64=base64.b64encode(raw).decode()))
|
||||
if mode == 'list': check_list(raw.decode(), EXPECTED['linux'][kind])
|
||||
else: check_output(raw, COUNTS['linux'][kind])
|
||||
dynamic = command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', item['path'] + ':/unit:ro',
|
||||
'--entrypoint', 'readelf', image, '-d', '/unit'], folder).decode()
|
||||
versions = command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', item['path'] + ':/unit:ro',
|
||||
'--entrypoint', 'readelf', image, '--version-info', '/unit'], folder).decode()
|
||||
glibc = sorted(set(re.findall(r'GLIBC_(\d+\.\d+)', versions)), key=lambda x: tuple(map(int, x.split('.'))))
|
||||
require(glibc and tuple(map(int, glibc[-1].split('.'))) <= (2, 39), 'VM-compatible glibc requirement')
|
||||
item['glibc_max'] = glibc[-1]; item['needed'] = sorted(re.findall(r'Shared library: \[([^\]]+)\]', dynamic))
|
||||
require(source_files() == before, 'source and runner unchanged through qualification')
|
||||
manifest = dict(schema_version=1, profile=PROFILE, source_files=before, source_before_after_equal=True,
|
||||
reviewed_m3_source_pins=REVIEWED_M3, m3_adapter_sources_hash_bound_only=True, live_eventlog_query=False,
|
||||
runner_sha256=sha(__file__), scripts=scripts(), test_names=EXPECTED, test_counts=COUNTS, artifacts=artifacts,
|
||||
build_image_id=image, both_targets_clippy_D_warnings=True, linux_lists_actual=True,
|
||||
windows_lists_expected_until_native=True, local_linux_tests_passed=24, native_linux_executed=False,
|
||||
native_windows_executed=False, product_state_writes=False, rmm_jobs=False)
|
||||
save(folder / 'manifest.json', manifest)
|
||||
print(json.dumps(dict(manifest=str((folder / 'manifest.json').resolve()), manifest_sha256=sha(folder / 'manifest.json'),
|
||||
linux_tests=24, windows_tests_expected=23, native_executed=False)))
|
||||
|
||||
|
||||
def verified(path, new_run):
|
||||
path = path.absolute(); private(path.parent, True)
|
||||
require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}', path.parent.name), 'fixed build manifest path')
|
||||
value = load(path)
|
||||
require(value['schema_version'] == 1 and value['profile'] == PROFILE and value['runner_sha256'] == sha(__file__)
|
||||
and value['scripts'] == scripts() and value['test_names'] == EXPECTED and value['test_counts'] == COUNTS
|
||||
and value['source_before_after_equal'] is True and value['both_targets_clippy_D_warnings'] is True
|
||||
and value['reviewed_m3_source_pins'] == REVIEWED_M3 and value['m3_adapter_sources_hash_bound_only'] is True
|
||||
and value['live_eventlog_query'] is False,
|
||||
'original manifest/runner/remote scripts/profile binding')
|
||||
if new_run: require(value['source_files'] == source_files(), 'new execution requires same current qualified source')
|
||||
for platform in COUNTS:
|
||||
require(set(value['artifacts'][platform]) == set(KINDS), 'exact two artifacts')
|
||||
for kind, item in value['artifacts'][platform].items():
|
||||
suffix = '.exe' if platform == 'windows' else ''
|
||||
require(Path(item['path']) == path.parent / platform / (kind + suffix)
|
||||
and Path(item['original_link_path']) == path.parent / platform / (kind + '.linked'), 'fixed private artifact paths')
|
||||
for field, digest in [('path', item['sha256']), ('original_link_path', item['original_link_sha256'])]:
|
||||
private(item[field]); require(sha(item[field]) == digest, 'immutable original/delivery bytes')
|
||||
require(Path(item['path']).stat().st_size == item['bytes'], 'artifact size unchanged')
|
||||
return value
|
||||
|
||||
|
||||
def access_settings(root, platform):
|
||||
"""Read strictly parsed existing access only when the parent executes native."""
|
||||
require(root is not None and not root.is_symlink(), 'explicit real access-root required')
|
||||
root = root.absolute(); require(root.is_dir() and root.resolve() == root, 'canonical access-root')
|
||||
if platform == 'linux':
|
||||
cfg = access.load_config(root / 'credentials/linux-vm.conf')
|
||||
require(cfg['address'] == '116.203.20.85' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
|
||||
and cfg.get('ssh_key_path'), 'fixed Cloud Linux bootstrap target')
|
||||
prefix = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), 'root@116.203.20.85']
|
||||
else:
|
||||
cfg = access.load_config(root / 'credentials/server.conf')
|
||||
require(cfg['address'] == '88.99.80.202' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
|
||||
and cfg.get('ssh_key_path'), 'fixed server reverse-jump only')
|
||||
credentials = root / 'credentials'; private(credentials, True)
|
||||
record = load(credentials / 'windows-dev-access.json')
|
||||
require(set(record) == {'ssh_prefix', 'expires_at'}, 'known Windows access schema')
|
||||
expires = dt.datetime.fromisoformat(record['expires_at'])
|
||||
require(expires.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expires, 'existing dev access still valid')
|
||||
key = str(Path(cfg['ssh_key_path']).expanduser())
|
||||
jump = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-i', key, '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'ForwardAgent=no', '-o', 'IdentitiesOnly=yes', '-W', '127.0.0.1:22240', 'root@88.99.80.202']
|
||||
prefix = ['ssh', '-F', '/dev/null', '-T', '-i', key, '-o', 'ProxyCommand=' + shlex.join(jump),
|
||||
'-o', 'HostKeyAlias=rmm-windows-dev', '-o', 'UserKnownHostsFile=' + str(credentials / 'windows-dev.known_hosts'),
|
||||
'-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', 'rmm-dev@127.0.0.1']
|
||||
require(record['ssh_prefix'] == prefix, 'exact registered pinned reverse SSH prefix')
|
||||
private(credentials / 'windows-dev.known_hosts')
|
||||
return prefix
|
||||
|
||||
|
||||
def transport(prefix, command_text, data, folder, timeout=60):
|
||||
"""No stdout/stderr escapes the private case directory on transport failure."""
|
||||
try:
|
||||
result = subprocess.run(prefix + [command_text], input=data, capture_output=True, timeout=timeout)
|
||||
save(folder / ('transport-' + str(uuid.uuid4()) + '.json'), dict(returncode=result.returncode,
|
||||
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
|
||||
require(result.returncode == 0, 'native transport incomplete; same-case readback only')
|
||||
value = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=object_pairs)
|
||||
require(isinstance(value, dict) and 'bootstrap_error' not in value, 'native bootstrap incomplete; private receipt retained')
|
||||
return value
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('transport-timeout-' + str(uuid.uuid4()) + '.json'), dict(timed_out=True,
|
||||
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('native reply lost; read original case only') from None
|
||||
|
||||
|
||||
def linux_rpc(prefix, payload, folder):
|
||||
code = 'import os,json,subprocess,base64,hashlib,uuid\nfrom pathlib import Path\n' + inspect.getsource(require) + '\n' + inspect.getsource(linux_case)
|
||||
code += '\ntry:\n print(json.dumps(linux_case(' + repr(payload) + ')))\nexcept Exception as e:\n print(json.dumps(dict(bootstrap_error=True,error_class=type(e).__name__)))\n'
|
||||
return transport(prefix, 'python3 -', code.encode(), folder)
|
||||
|
||||
|
||||
def windows_rpc(prefix, payload, folder):
|
||||
script = 'try {\n' + WINDOWS + '\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
|
||||
command_text = 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ' + base64.b64encode(script.encode('utf-16le')).decode()
|
||||
return transport(prefix, command_text, (json.dumps(payload) + '\n').encode(), folder)
|
||||
|
||||
|
||||
def upload(prefix, item, destination, folder, kind):
|
||||
args = ['sftp'] + [part for part in prefix[1:-1] if part != '-T'] + ['-b', '-', prefix[-1]]
|
||||
# Linux sftp uses uppercase -P; Windows prefix has no -p option.
|
||||
if '-p' in args: args[args.index('-p')] = '-P'
|
||||
batch = ('put ' + json.dumps(item['path']) + ' ' + json.dumps(destination) + '\n').encode()
|
||||
save(folder / ('transfer-' + kind + '-intent.json'), dict(sha256=item['sha256'], bytes=item['bytes']))
|
||||
try:
|
||||
result = subprocess.run(args, input=batch, capture_output=True, timeout=60)
|
||||
save(folder / ('transfer-' + kind + '-result.json'), dict(returncode=result.returncode,
|
||||
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
|
||||
require(result.returncode == 0, 'fixed artifact transfer failed; no retry')
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('transfer-' + kind + '-timeout.json'), dict(timed_out=True,
|
||||
stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('artifact transfer incomplete; no retry') from None
|
||||
|
||||
|
||||
def linux_case(p):
|
||||
import resource
|
||||
import stat
|
||||
ident = str(uuid.UUID(p['id']))
|
||||
require(ident == p['id'] and p['action'] in ('prepare', 'run', 'read') and p['profile'] == 'windows-eventlog-contracts-v1', 'fixed unit case')
|
||||
require(os.geteuid() == 0 and os.uname().machine == 'x86_64' and set(p['artifacts']) == {'domain', 'contracts'}, 'fixed Linux root qualification')
|
||||
root = Path('/var/lib/rmm-windows-eventlog-contracts')
|
||||
def safe(path, directory):
|
||||
s = path.lstat()
|
||||
require(s.st_uid == 0 and stat.S_IMODE(s.st_mode) == (0o700 if directory else 0o600)
|
||||
and (stat.S_ISDIR(s.st_mode) if directory else stat.S_ISREG(s.st_mode) and s.st_nlink == 1), 'private fixed unit path')
|
||||
def write(path, value):
|
||||
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, 'w') as out: json.dump(value, out); out.flush(); os.fsync(out.fileno())
|
||||
os.umask(0o077)
|
||||
case = root / ident
|
||||
if p['action'] == 'read' and not case.exists(): return dict(id=ident, status='remote_case_absent')
|
||||
if p['action'] == 'prepare':
|
||||
if not root.exists(): root.mkdir(mode=0o700)
|
||||
safe(root, True); case.mkdir(mode=0o700); write(case / 'intent.json', p)
|
||||
return dict(id=ident, prepared=True)
|
||||
safe(root, True); safe(case, True); safe(case / 'intent.json', False)
|
||||
original = json.loads((case / 'intent.json').read_bytes())
|
||||
require({k: v for k, v in p.items() if k != 'action'} == {k: v for k, v in original.items() if k != 'action'}, 'original complete unit intent')
|
||||
if p['action'] == 'read':
|
||||
if not (case / 'result.json').exists(): return dict(id=ident, status='started_without_result' if (case / 'started.json').exists() else 'prepared_without_start')
|
||||
safe(case / 'result.json', False); return json.loads((case / 'result.json').read_bytes())
|
||||
write(case / 'started.json', dict(manifest_sha256=p['manifest_sha256'], execute_once=True))
|
||||
temp = case / 'tmp'; temp.mkdir(mode=0o700)
|
||||
env = {'PATH': '/usr/bin:/bin', 'LANG': 'C.UTF-8', 'LC_ALL': 'C.UTF-8', 'TMPDIR': str(temp), 'RUST_BACKTRACE': '0'}
|
||||
def limits():
|
||||
resource.setrlimit(resource.RLIMIT_CORE, (0, 0)); resource.setrlimit(resource.RLIMIT_CPU, (15, 15)); resource.setrlimit(resource.RLIMIT_FSIZE, (1048576, 1048576))
|
||||
require(subprocess.run(['/usr/bin/unshare', '--net', '--', '/usr/bin/true'], env=env, capture_output=True, timeout=3).returncode == 0, 'network namespace required')
|
||||
listings = {}
|
||||
for kind in ('domain', 'contracts'):
|
||||
binary = case / kind; safe(binary, False)
|
||||
require(hashlib.sha256(binary.read_bytes()).hexdigest() == p['artifacts'][kind]['sha256'], 'exact Linux delivery')
|
||||
binary.chmod(0o500)
|
||||
listed = subprocess.run(['/usr/bin/unshare', '--net', '--', str(binary), '--list', '--format', 'terse'], cwd=case, env=env, capture_output=True, timeout=5, preexec_fn=limits)
|
||||
require(listed.returncode == 0 and len(listed.stdout) <= 65536 and len(listed.stderr) <= 65536, 'bounded actual listing')
|
||||
actual = sorted(line[:-6] for line in listed.stdout.decode().splitlines() if line.endswith(': test'))
|
||||
require(all(not line.strip() or __import__('re').fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in listed.stdout.decode().splitlines())
|
||||
and actual == p['names'][kind] and len(actual) == {'domain': 17, 'contracts': 7}[kind], 'exact native test names before ANY test execution')
|
||||
listings[kind] = actual
|
||||
reports = {}
|
||||
for kind in ('domain', 'contracts'):
|
||||
with (case / (kind + '-stdout.bin')).open('xb') as out, (case / (kind + '-stderr.bin')).open('xb') as err:
|
||||
timed = False
|
||||
try: code = subprocess.run(['/usr/bin/unshare', '--net', '--', str(case / kind), '--test-threads=1'], cwd=case, env=env,
|
||||
stdin=subprocess.DEVNULL, stdout=out, stderr=err, timeout=18, preexec_fn=limits).returncode
|
||||
except subprocess.TimeoutExpired: timed = True; code = None
|
||||
out.flush(); err.flush(); os.fsync(out.fileno()); os.fsync(err.fileno())
|
||||
raw, errors = [(case / (kind + '-' + stream + '.bin')).read_bytes() for stream in ('stdout', 'stderr')]
|
||||
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native output')
|
||||
reports[kind] = dict(sha256=p['artifacts'][kind]['sha256'], names=listings[kind], exit_code=code, timed_out=timed,
|
||||
stdout_b64=base64.b64encode(raw).decode(), stderr_b64=base64.b64encode(errors).decode())
|
||||
write(case / (kind + '-result.json'), reports[kind])
|
||||
value = dict(id=ident, platform='linux', profile=p['profile'], manifest_sha256=p['manifest_sha256'], runner_sha256=p['runner_sha256'],
|
||||
scripts=p['scripts'], reports=reports, network_namespace=True, environment_cleared=True, product_state_writes=False, rmm_jobs=False)
|
||||
write(case / 'result.json', value); return value
|
||||
|
||||
|
||||
WINDOWS = r'''
|
||||
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||
if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('prepare','run','read')-or$p.profile-cne'windows-eventlog-contracts-v1'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.linux_proof_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed Linux-first profile case'}
|
||||
$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('windows-eventlog-contracts-'+$p.id)
|
||||
function Safe($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Unit 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 unit owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private unit ACL'}}}
|
||||
function WriteNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||
function MatchIntent($old){if($old.id-cne$p.id-or$old.profile-cne$p.profile-or$old.manifest_sha256-cne$p.manifest_sha256-or$old.runner_sha256-cne$p.runner_sha256-or$old.linux_proof_sha256-cne$p.linux_proof_sha256-or$old.scripts.linux_case_sha256-cne$p.scripts.linux_case_sha256-or$old.scripts.windows_script_sha256-cne$p.scripts.windows_script_sha256){throw 'Original profile intent'};foreach($kind in @('domain','contracts')){if($old.artifacts.$kind.sha256-cne$p.artifacts.$kind.sha256-or$old.artifacts.$kind.bytes-ne$p.artifacts.$kind.bytes-or(@($old.names.$kind)-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'Original artifact/test tuple'}}}
|
||||
if($p.action-eq'read'-and!(Test-Path -LiteralPath $case)){@{id=$p.id;status='remote_case_absent'}|ConvertTo-Json -Compress;exit 0}
|
||||
Safe $root $true
|
||||
if($p.action-eq'prepare'){if(Test-Path -LiteralPath $case){throw 'Existing case retained'};New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p;@{id=$p.id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
|
||||
Safe $case $true;$intent=Join-Path $case 'intent.json';Safe $intent $false;MatchIntent (Get-Content -LiteralPath $intent -Raw|ConvertFrom-Json)
|
||||
if($p.action-eq'read'){$result=Join-Path $case 'result.json';if(!(Test-Path -LiteralPath $result)){$status=if(Test-Path -LiteralPath (Join-Path $case 'started.json')){'started_without_result'}else{'prepared_without_start'};@{id=$p.id;status=$status}|ConvertTo-Json -Compress;exit 0};Safe $result $false;Get-Content -LiteralPath $result -Raw;exit 0}
|
||||
function RunUnit($exe,[string]$arguments){$s=New-Object Diagnostics.ProcessStartInfo;$s.FileName=$exe;$s.Arguments=$arguments;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.WorkingDirectory=$case;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$systemRoot=$env:WINDIR;$s.EnvironmentVariables.Clear();$s.EnvironmentVariables['SystemRoot']=$systemRoot;$s.EnvironmentVariables['WINDIR']=$systemRoot;$s.EnvironmentVariables['PATH']=$systemRoot+'\System32';$s.EnvironmentVariables['TEMP']=$script:temp;$s.EnvironmentVariables['TMP']=$script:temp;$s.EnvironmentVariables['RUST_BACKTRACE']='0';$c=New-Object Diagnostics.Process;$c.StartInfo=$s;if(!$c.Start()){throw 'Unit start'};try{$o=$c.StandardOutput.ReadToEndAsync();$e=$c.StandardError.ReadToEndAsync();$timed=$false;if(!$c.WaitForExit(18000)){$timed=$true;$c.Kill();if(!$c.WaitForExit(2000)){throw 'Own unit process did not exit'}};if(!$o.Wait(2000)-or!$e.Wait(2000)-or$o.Result.Length-gt1048576-or$e.Result.Length-gt1048576){throw 'Bounded unit output'};return @{exit_code=$c.ExitCode;timed_out=$timed;stdout_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($o.Result));stderr_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($e.Result))}}finally{$c.Dispose()}}
|
||||
WriteNew (Join-Path $case 'started.json') @{execute_once=$true;manifest_sha256=$p.manifest_sha256};$script:temp=Join-Path $case 'tmp';New-Item -ItemType Directory -Path $script:temp|Out-Null;Safe $script:temp $true
|
||||
$lists=@{};$executables=@{}
|
||||
foreach($kind in @('domain','contracts')){$item=$p.artifacts.$kind;if($item.sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed unit hash'};$exe=Join-Path $case ($kind+'.exe');Safe $exe $false;if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$item.sha256-or(Get-Item -LiteralPath $exe).Length-ne$item.bytes){throw 'Exact unit bytes'};$list=RunUnit $exe '--list --format terse';if($list.exit_code-ne0-or$list.timed_out){throw 'Actual Windows listing'};$text=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($list.stdout_b64));$unexpected=@($text-split'\r?\n'|Where-Object{$_.Trim()-and$_-notmatch'^[A-Za-z0-9_:]+: test$'});if($unexpected.Count){throw 'Only exact terse test entries'};$actual=@($text-split'\r?\n'|Where-Object{$_-match': test$'}|ForEach-Object{$_-replace': test$',''}|Sort-Object);$count=if($kind-eq'domain'){17}else{6};if($actual.Count-ne$count-or($actual-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'All exact names BEFORE any tests'};$lists[$kind]=$actual;$executables[$kind]=$exe}
|
||||
$reports=@{};foreach($kind in @('domain','contracts')){$value=RunUnit $executables[$kind] '--test-threads=1';$value.sha256=$p.artifacts.$kind.sha256;$value.names=$lists[$kind];WriteNew (Join-Path $case ($kind+'-result.json')) $value;$reports[$kind]=$value}
|
||||
$value=@{id=$p.id;platform='windows';profile=$p.profile;manifest_sha256=$p.manifest_sha256;runner_sha256=$p.runner_sha256;scripts=$p.scripts;linux_proof_sha256=$p.linux_proof_sha256;reports=$reports;bootstrap_administrator_units=$true;local_service_proof=$false;environment_cleared=$true;product_state_writes=$false;rmm_jobs=$false};WriteNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 16 -Compress
|
||||
'''
|
||||
|
||||
|
||||
def check_result(manifest, platform, value, payload):
|
||||
require(value.get('id') == payload['id'] and value.get('platform') == platform and value.get('profile') == PROFILE
|
||||
and value.get('manifest_sha256') == payload['manifest_sha256'] and value.get('runner_sha256') == manifest['runner_sha256']
|
||||
and value.get('scripts') == manifest['scripts'] and value.get('product_state_writes') is False and value.get('rmm_jobs') is False
|
||||
and value.get('environment_cleared') is True and set(value['reports']) == set(KINDS), 'complete native original binding')
|
||||
if platform == 'linux': require(value.get('network_namespace') is True, 'actual Linux netns proof')
|
||||
else: require(value.get('linux_proof_sha256') == payload['linux_proof_sha256'] and value.get('local_service_proof') is False, 'original Linux proof and honest account scope')
|
||||
for kind, item in value['reports'].items():
|
||||
require(item['names'] == EXPECTED[platform][kind] and item['sha256'] == manifest['artifacts'][platform][kind]['sha256']
|
||||
and item['exit_code'] == 0 and item['timed_out'] is False, 'all native exact test names/artifacts/exits')
|
||||
raw = base64.b64decode(item['stdout_b64'], validate=True); errors = base64.b64decode(item['stderr_b64'], validate=True)
|
||||
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native outputs')
|
||||
check_output(raw, COUNTS[platform][kind])
|
||||
|
||||
|
||||
def execute(path, platform, access_root, case_id=None):
|
||||
setup_state(); path = path.absolute(); manifest = verified(path, new_run=case_id is None)
|
||||
prefix = access_settings(access_root, platform)
|
||||
if case_id is None:
|
||||
case_id = str(uuid.uuid4()); folder = STATE / case_id; folder.mkdir(mode=0o700)
|
||||
payload = dict(id=case_id, profile=PROFILE, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], scripts=manifest['scripts'],
|
||||
artifacts={kind: {k: manifest['artifacts'][platform][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS}, names=EXPECTED[platform])
|
||||
if platform == 'windows':
|
||||
proof_path = path.parent / 'linux-passed.json'; proof = load(proof_path)
|
||||
require(proof['verified'] is True and proof['manifest_sha256'] == sha(path), 'same-manifest real Linux proof FIRST')
|
||||
linux_payload = dict(payload, id=proof['case_id'], artifacts={kind: {k: manifest['artifacts']['linux'][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS}, names=EXPECTED['linux'])
|
||||
check_result(manifest, 'linux', proof['native'], linux_payload)
|
||||
payload['linux_proof_sha256'] = sha(proof_path)
|
||||
intent = dict(id=case_id, platform=platform, manifest_path=str(path), manifest_sha256=sha(path), runner_sha256=sha(__file__),
|
||||
scripts=scripts(), access_root_sha256=hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), payload=payload)
|
||||
save(folder / 'intent.json', intent)
|
||||
save(folder / 'started-local.json', dict(create_once=True, no_retry=True))
|
||||
run_read = False
|
||||
else:
|
||||
require(str(uuid.UUID(case_id)) == case_id, 'original canonical case id')
|
||||
folder = STATE / case_id; private(folder, True); intent = load(folder / 'intent.json'); load(folder / 'started-local.json')
|
||||
require(intent['id'] == case_id and intent['platform'] == platform and intent['manifest_path'] == str(path)
|
||||
and intent['manifest_sha256'] == sha(path) and intent['runner_sha256'] == sha(__file__) and intent['scripts'] == scripts()
|
||||
and intent['access_root_sha256'] == hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), 'immutable same-case readback')
|
||||
payload = intent['payload']; run_read = True
|
||||
rpc = linux_rpc if platform == 'linux' else windows_rpc
|
||||
if not run_read:
|
||||
result = rpc(prefix, dict(payload, action='prepare'), folder)
|
||||
save(folder / 'prepared-remote.json', result); require(result == dict(id=case_id, prepared=True), 'fresh fixed case prepared')
|
||||
for kind in KINDS:
|
||||
destination = LINUX_REMOTE + '/' + case_id + '/' + kind if platform == 'linux' else '/C:/ProgramData/RustDiscoveryBootstrap/windows-eventlog-contracts-' + case_id + '/' + kind + '.exe'
|
||||
upload(prefix, manifest['artifacts'][platform][kind], destination, folder, kind)
|
||||
result = rpc(prefix, dict(payload, action='read' if run_read else 'run'), folder)
|
||||
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), result)
|
||||
if result.get('status'):
|
||||
require(run_read and result.get('id') == case_id and result['status'] in ('remote_case_absent', 'prepared_without_start', 'started_without_result'), 'fixed read-only incomplete status')
|
||||
print(json.dumps(dict(verified=False, platform=platform, case_id=case_id, status=result['status'], retry_allowed=False))); return
|
||||
check_result(manifest, platform, result, payload)
|
||||
proof = dict(verified=True, case_id=case_id, platform=platform, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], native=result)
|
||||
destination = path.parent / (platform + '-passed.json')
|
||||
if destination.exists(): require(load(destination) == proof, 'preserve identical native proof')
|
||||
else: save(destination, proof)
|
||||
save(folder / 'verified.json', dict(verified=True, proof_sha256=sha(destination))) if not (folder / 'verified.json').exists() else require(load(folder / 'verified.json') == dict(verified=True, proof_sha256=sha(destination)), 'same verified receipt')
|
||||
print(json.dumps(dict(verified=True, platform=platform, case_id=case_id, tests=sum(COUNTS[platform].values()),
|
||||
manifest_sha256=sha(path), proof_sha256=sha(destination))))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('build-local', 'linux', 'windows', 'readback-linux', 'readback-windows'))
|
||||
parser.add_argument('--manifest', type=Path); parser.add_argument('--case'); parser.add_argument('--access-root', type=Path)
|
||||
parser.add_argument('--execute-native-tests', action='store_true'); args = parser.parse_args()
|
||||
if args.action == 'build-local':
|
||||
require(not (args.manifest or args.case or args.access_root or args.execute_native_tests), 'local build only'); build()
|
||||
elif args.action.startswith('readback-'):
|
||||
require(args.manifest and args.case and args.access_root and not args.execute_native_tests, 'original case readback only')
|
||||
execute(args.manifest, args.action.removeprefix('readback-'), args.access_root, args.case)
|
||||
else:
|
||||
require(args.manifest and args.access_root and args.execute_native_tests and not args.case, 'explicit new native platform run')
|
||||
execute(args.manifest, args.action, args.access_root)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try: main()
|
||||
except Exception as error:
|
||||
print(json.dumps(dict(error='WINDOWS_EVENTLOG_CONTRACT_QUALIFICATION_INCOMPLETE', error_class=type(error).__name__, details_suppressed=True)))
|
||||
raise SystemExit(2) from None
|
||||
@@ -0,0 +1,61 @@
|
||||
# Native M3-Eventlog-Vertragsprüfung
|
||||
|
||||
`deploy/windows_eventlog_acceptance.py` ist ein neuer, separater Bootstraprunner.
|
||||
Der unveränderte Profilrunner und dessen16/7- beziehungsweise16/6-Belege bleiben
|
||||
readbackfähig. Neuer Namespace: `windows-eventlog-contracts`.
|
||||
|
||||
Der neue Pack enthält ausschließlich Domain-Lib17 und Core-Contracts7 auf Linux,
|
||||
danach Domain-Lib17 und Core-Contracts6 auf Windows. Der Unix-OpenSSL-Paritätstest
|
||||
entfällt unter Windows. Server-/Windows-M3-Quellen werden zusätzlich exakt an den
|
||||
geprüften Stand gebunden, einschließlich Schemars-Metadatenfix und Gateway-
|
||||
Ergebnisprüfung. Diese Adapterquellen werden durch die beiden Vertrags-EXEs
|
||||
**nicht** als native Eventlogprovider qualifiziert. Es gibt weder Liveabfrage
|
||||
noch RMM-Job, Capabilityaktivierung, Dienst-/Produktdatenbank-/PKIänderung.
|
||||
|
||||
Tatsächlich auf Cloud-Linux bestanden:24Prüfungen ohne Skips, Fall
|
||||
`6f9bdfb7-3902-462e-a08f-ec612e36c635`. Gemeinsamer Build
|
||||
`afb44f9b-8040-4efa-ac2c-fd6c3a43f8a6`, Manifest-SHA256
|
||||
`ed1371e9b058f8e7f874b071fcfce1bc409769546d5e63235295adadb5ec1de7`,
|
||||
Linuxproof-SHA256
|
||||
`d37ce1644dd169c932176e3e9bd33cee22b9fa4698e9faa0f5aea0f2de09f7d4`.
|
||||
Windows23 weiterhin geplant, nicht nativ ausgeführt. Der lokale Build mit
|
||||
98identischen Vorher-/Nachher-Inputs, vier erhaltenen Original-Linkdateien,
|
||||
beiden Ziel-Clippyprüfungen und24lokalen Linux-Vertragstests ist bestanden.
|
||||
|
||||
Der lokale Offlinebuild erhält Original-Linkdateien neben gestrippten
|
||||
Lieferkopien, prüft Clippy für beide Vertragsziele und führt die tatsächlichen
|
||||
Linux-Lieferbytes mit exakter Liste und ungefiltert aus. Windowslisten bleiben
|
||||
bis zur tatsächlichen Windowsausgabe erwartet. Vor/nach müssen sämtliche
|
||||
gebundenen Cargo-/Toolchain-/Domain-/Core-/Protocol-/Proto-/Server-/Windows- und
|
||||
Runner-/Bootstrapquellen gleich sein. Ein weiterer Backend-/PG-Testlauf ist
|
||||
nicht Bestandteil dieses Runners.
|
||||
|
||||
**Aufrufschema; Linuxfall oben tatsächlich ausgeführt, Windows noch geplant:**
|
||||
|
||||
```sh
|
||||
python3 deploy/windows_eventlog_acceptance.py build-local
|
||||
python3 deploy/windows_eventlog_acceptance.py linux --manifest devstate/windows-eventlog-contracts/build-UUID/manifest.json --access-root /ABSOLUTER/PFAD/ZUM/HAUPTREPO --execute-native-tests
|
||||
python3 deploy/windows_eventlog_acceptance.py windows --manifest devstate/windows-eventlog-contracts/build-UUID/manifest.json --access-root /ABSOLUTER/PFAD/ZUM/HAUPTREPO --execute-native-tests
|
||||
```
|
||||
|
||||
Artefakte und lokale Belege bleiben im isolierten Eventlogworktree. Ausschließlich
|
||||
`--access-root` liest bei ausdrücklicher nativer Ausführung streng geparste
|
||||
bestehende SSH-Konfigurationen für Cloud-Linux116.203.20.85 beziehungsweise den
|
||||
bekannten gepinnten Windows-Reversezugang. Keine Credentialkopie oder neue
|
||||
Hostkeyannahme. Windows bindet den SHA256 des zuvor tatsächlich verifizierten
|
||||
Linuxbelegs desselben Manifests.
|
||||
|
||||
Jeder native Fall hat eigene Create-once-Intents und Startbelege. Linux nutzt
|
||||
privaten Rootscratch, geleerte Umgebung und eigene Netzwerknamespace. Beide
|
||||
Plattformen prüfen vor dem ersten Teststart die vollständigen Testnamen beider
|
||||
Programme. Windows läuft als Bootstrapadministrator, kein LocalService-Nachweis.
|
||||
Ausgaben und Transportfehler bleiben privat; stdout enthält nur Status und
|
||||
Nachweishashes.
|
||||
|
||||
Nach Antwortverlust ausschließlich `readback-linux` beziehungsweise
|
||||
`readback-windows` mit ursprünglichem Manifest, `--case UUID` und `--access-root`.
|
||||
Readback lädt nichts hoch und startet nichts neu. Er bindet unveränderliche
|
||||
Originalintents, Manifest sowie Runner-/Remotescripthashes; spätere
|
||||
Produktquellenänderungen erzwingen keinen neuen Lauf. Nur neue Starts benötigen
|
||||
den aktuellen exakt qualifizierten Quellstand. Unvollständige Fälle bleiben
|
||||
unvollständig; kein automatischer zweiter Versuch.
|
||||
@@ -0,0 +1,53 @@
|
||||
# Windows-M3: begrenztes Ereignisprotokoll
|
||||
|
||||
Stand2026-11-14: Quelle implementiert und unabhängig gegenseitig geprüft,
|
||||
noch nicht auf dem Windowsgast installiert oder als RMM-Aktion ausgeführt.
|
||||
Der isolierte Branch enthält auch das bereits separat nativ qualifizierte
|
||||
optionale PowerShell-Prozessprofil. Keine Capability wurde veröffentlicht.
|
||||
|
||||
`query_logs` bindet ausschließlich Quelle
|
||||
`windows.eventlog.application.rustdiscovery-mvp-test`, Kanal `Application`
|
||||
und Provider `RustDiscovery-MVP-Test`. Erforderlich sind Windows-/Sync- und
|
||||
eigene Fixturecapability, `logs:read` und `agent_service`. Kein SYSTEM-Logpfad,
|
||||
kein freies XPath, kein angeforderter Liveabruf als passives Inventar.
|
||||
UTC-Zeitfenster höchstens24Stunden, höchstens65536Ausgabebytes und feste
|
||||
innere5Sekunden-Grenze; äußerer Jobrahmen10–120Sekunden. Alle Werte stehen
|
||||
aus hashgeprüften gespeicherten Planbytes vor der WebUI-Genehmigung fest.
|
||||
|
||||
Die synchrone native Eventlog-API läuft im begrenzten eigenen Prozess innerhalb
|
||||
des vorhandenen atomaren JobObjects. Der Child prüft tatsächlichen LocalService-
|
||||
Token samt Agent-Service-SID, echten SCM-/Kernel-Elternprozess, geschützte
|
||||
Konfiguration, signierten Originalrequest, aktuelle qualifizierte Uhr und Boot,
|
||||
den bereits dauerhaft gebuchten Verbrauch/Start samt tatsächlichem SQLite-
|
||||
Dateihandle sowie einen einmaligen Startmarker. Der Aufruf über den festen
|
||||
CLI-Modus allein verleiht keine Berechtigung. Keine Schlüssel-/Requestbytes
|
||||
auf der Kommandozeile. Uhr-/Jobgates bleiben geschlossen.
|
||||
|
||||
Worker und Server prüfen konkrete Herkunft, Zeitfenster, Budget, Vollständigkeit
|
||||
und Fehler. Bekannte Ereignis-/Byte-/Einzelereignisgrenzen bleiben ausdrücklich
|
||||
partiell; Zeitüberschreitung oder Berechtigungsfehler werden kein vollständiger
|
||||
Erfolg. Eine im Review gefundene Lücke im serverseitigen Successguard wurde
|
||||
geschlossen: `win32_error` ausdrücklichnull, kein Neustartbedarf und generisches
|
||||
Kürzungsflag identisch zur konkreten Evidenz.
|
||||
|
||||
Lokal tatsächlich bestanden:238Rusttests, ein isolierter PostgreSQL-Fall und
|
||||
38Webtests samt Typecheck/Build/Clippy. Der PG-Fall prüfte unter anderem fehlendes
|
||||
`logs:read`, verlorene Capability und `pending_approval` mit0Jobs/Outbox/Grants.
|
||||
Nach dem Successguard-Fix wurden dessen bestehende Mutationsmatrix und
|
||||
Server-Clippy gezielt erneut ausgeführt. Drei portable Provider-/Ergebnistests
|
||||
liefen tatsächlich im Linux-Buildcontainer; zwei Windows-Workerprüfungen sind
|
||||
bisher nur crosskompiliert. Keine dieser Ebenen ersetzt den Nativepfad.
|
||||
|
||||
Private Quellenbelege: `devstate/windows-eventlog-backend/qualification.json`
|
||||
(`facab5cc…`), `qualification-success-flags.json` (`f5972644…`) und
|
||||
`devstate/windows-eventlog/windows-source-qualification.json` (`feb16e79…`).
|
||||
Die geplante gesonderte Vertragsabnahme umfasst zuerst Linux24, danach Windows23;
|
||||
die neue native Runnerdokumentation hält tatsächliche Ergebnisse getrennt fest.
|
||||
|
||||
Weiter offen: reale LocalService-Eventlog-API, eigene Fixtureereignisse,
|
||||
Filter-/Zeit-/Ausgabe-/Fehlergrenzen und vollständiger WebUI-genehmigter Job.
|
||||
Keine Registrierung oder Erhebung auf dem Ziel wurde durch diese Quellarbeiten
|
||||
ausgeführt. Der Schemars-Attributfix entfernt lediglich die irreführende
|
||||
Nullable-Angabe des optionalen Prozessprofils; strikte Deserialisierung und
|
||||
fehlendes Feld bleiben unverändert. Die vorherigen Nativebelege bleiben an
|
||||
ihre ursprünglichen Quellen gebunden.
|
||||
@@ -65,6 +65,13 @@ describe('JSON contract boundary', () => {
|
||||
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('bounds the fixed Event Log source and exact 24h interval without rewriting Linux queries', () => {
|
||||
const base: PlanInput = { tenant_id: 't', action: 'query_logs', targets: { asset_ids: ['a'] }, parameters: { execution_identity: 'agent_service', unit: 'windows.eventlog.application.rustdiscovery-mvp-test', since: '2026-11-14T00:00:00Z', until: '2026-11-15T00:00:00Z', max_lines: 1000, timeout_seconds: 30, 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 fixture logs' };
|
||||
const before = JSON.stringify(base); validateInput(base); expect(JSON.stringify(base)).toBe(before);
|
||||
for (const change of [{ execution_identity: 'root' }, { execution_identity: 'system' }, { unit: 'windows.eventlog.security.other' }, { timeout_seconds: 9 }, { timeout_seconds: 121 }, { max_output_bytes: 1023 }, { max_output_bytes: 65537 }, { max_lines: 1001 }, { until: '2026-11-15T00:00:00.000000001Z' }]) expect(() => validateInput({ ...base, parameters: { ...base.parameters, ...change } })).toThrow();
|
||||
const linux = { ...base, parameters: { ...base.parameters, unit: 'rmm-test.service', execution_identity: 'root', timeout_seconds: 1, max_output_bytes: 512 } }; const original=JSON.stringify(linux); validateInput(linux); expect(JSON.stringify(linux)).toBe(original);
|
||||
expect(() => validateInput({ ...linux, parameters: { ...linux.parameters, until: '2026-11-15T00:59:00Z' } })).toThrow('24Stunden');
|
||||
});
|
||||
it('accepts only the fixed Windows process profile without changing inherited variants', () => {
|
||||
const windows = { os_family: 'windows', interpreter: 'powershell', encoding: 'utf-8', script_utf8: "Write-Output 'fixed'\r\n" };
|
||||
const base: PlanInput = { tenant_id: 't', action: 'run_script', targets: { asset_ids: ['a'] }, parameters: { variants: [windows], execution_identity: 'agent_service', timeout_seconds: 30, 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 profile fixture' };
|
||||
|
||||
+27
-1
@@ -67,6 +67,27 @@ export function windowsScriptProfile(value: RecordValue): 'inherited' | typeof w
|
||||
|| (value.os_family !== undefined && value.os_family !== 'windows')) throw new Error('Windows-Ausführungsprofil nur powershell_51_remote_signed für Windows PowerShell5.1');
|
||||
return windowsPowerShellRemoteSignedProfile;
|
||||
}
|
||||
export const windowsEventLogFixtureSource = 'windows.eventlog.application.rustdiscovery-mvp-test';
|
||||
export const windowsEventLogFixtureChannel = 'Application';
|
||||
export const windowsEventLogFixtureProvider = 'RustDiscovery-MVP-Test';
|
||||
/** Preserve sub-millisecond bounds; Date.parse alone would admit 24h + 1ns. */
|
||||
export function logWindow(since: unknown, until: unknown): void {
|
||||
const instant = (value: unknown): bigint => {
|
||||
if (typeof value !== 'string') throw new Error('Exaktes UTC-Log-Zeitfenster erforderlich');
|
||||
const match = /^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d{1,9}))?(Z|[+-]\d\d:\d\d)$/.exec(value);
|
||||
if (!match) throw new Error('Exaktes UTC-Log-Zeitfenster erforderlich');
|
||||
const seconds = Date.parse(match[1]! + match[3]!);
|
||||
if (!Number.isFinite(seconds)) throw new Error('Exaktes UTC-Log-Zeitfenster erforderlich');
|
||||
return BigInt(seconds) * 1000000n + BigInt((match[2] ?? '').padEnd(9, '0'));
|
||||
};
|
||||
const start = instant(since), end = instant(until);
|
||||
if (end <= start || end - start > 86400000000000n) throw new Error('Exaktes Log-Zeitfenster höchstens24Stunden erforderlich');
|
||||
}
|
||||
export function validateWindowsLogLimits(identity: unknown, runtime: unknown, output: unknown, since: unknown): void {
|
||||
if (identity !== 'agent_service' || typeof runtime !== 'number' || !Number.isSafeInteger(runtime) || runtime < 10 || runtime > 120
|
||||
|| typeof output !== 'number' || !Number.isSafeInteger(output) || output < 1024 || output > 65536
|
||||
|| typeof since !== 'string' || Date.parse(since) < 0) throw new Error('Windows-Fixture-Eventlog nur agent_service,10–120s und1024–65536Bytes');
|
||||
}
|
||||
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 {
|
||||
@@ -103,7 +124,12 @@ export function validateInput(input: PlanInput): void {
|
||||
}
|
||||
const required = (key: string) => text(input.parameters[key], `parameters.${key}`);
|
||||
if (input.action === 'refresh_inventory') required('scope');
|
||||
if (input.action === 'query_logs') { required('unit'); const since = Date.parse(required('since')), until = Date.parse(required('until')); if (!Number.isFinite(since) || !Number.isFinite(until) || until <= since) throw new Error('Exaktes Log-Zeitfenster erforderlich'); if (typeof input.parameters.max_lines !== 'number' || !Number.isSafeInteger(input.parameters.max_lines) || input.parameters.max_lines < 1 || input.parameters.max_lines > 1000) throw new Error('Loglimit muss 1–1000 sein'); }
|
||||
if (input.action === 'query_logs') {
|
||||
const unit = required('unit'); logWindow(required('since'), required('until'));
|
||||
if (unit.startsWith('windows.eventlog.') && unit !== windowsEventLogFixtureSource) throw new Error('Nur die feste Windows-Fixture-Eventlogquelle ist konfiguriert');
|
||||
if (unit === windowsEventLogFixtureSource) validateWindowsLogLimits(input.parameters.execution_identity, input.parameters.timeout_seconds, input.parameters.max_output_bytes, input.parameters.since);
|
||||
if (typeof input.parameters.max_lines !== 'number' || !Number.isSafeInteger(input.parameters.max_lines) || input.parameters.max_lines < 1 || input.parameters.max_lines > 1000) throw new Error('Loglimit muss 1–1000 sein');
|
||||
}
|
||||
if (input.action === 'set_service_state') { required('unit'); if (!['running', 'stopped', 'restarted'].includes(required('state'))) throw new Error('Ungültiger Dienstzustand'); }
|
||||
if (input.action === 'ensure_package') { for (const key of ['provider', 'recipe_version', 'package', 'version', 'architecture', 'installation_context']) required(key); }
|
||||
if (input.action === 'apply_updates') { required('provider'); if (!Array.isArray(input.parameters.packages) || !input.parameters.packages.length || !input.parameters.packages.every(v => typeof v === 'string' && v.length > 0)) throw new Error('Feste Updatepakete erforderlich'); if (input.parameters.reboot_policy !== 'never') throw new Error('Kein impliziter Reboot; eigenen festen Plan erstellen'); }
|
||||
|
||||
@@ -5,6 +5,18 @@ import { sha256, verifyPlanIntegrity } from './safety';
|
||||
// Import the actual renderer without mounting the application's network effects.
|
||||
vi.mock('react-dom/client', () => ({ createRoot: () => ({ render: vi.fn() }) }));
|
||||
|
||||
it('shows fixed Event Log source, half-open UTC window and both runtime bounds before approval', async () => {
|
||||
const fetch=vi.fn();vi.stubGlobal('fetch',fetch);vi.stubGlobal('document',{getElementById:()=>({})});
|
||||
try{
|
||||
const {QueryLogsPlanNotice}=await import('./main');
|
||||
const payload={jobs:[{payload:{asset_id:'win-fixture',execution_identity:'agent_service',max_runtime_seconds:30,max_output_bytes:4096,action:{action:'query_logs',unit:'windows.eventlog.application.rustdiscovery-mvp-test',since:'2026-11-14T00:00:00Z',until:'2026-11-14T01:00:00Z',max_lines:1000}}}]};
|
||||
const raw=new TextEncoder().encode(JSON.stringify(payload)),plan={plan_payload_bytes:Array.from(raw),plan_hash:await sha256(raw),plan_payload:payload};
|
||||
expect(renderToStaticMarkup(<QueryLogsPlanNotice plan={plan}/>)).toContain('role="alert"');await verifyPlanIntegrity(plan);
|
||||
const html=renderToStaticMarkup(<QueryLogsPlanNotice plan={plan}/>);for(const expected of ['Application','RustDiscovery-MVP-Test','1000','4096','30s','5000ms','kooperativ','2026-11-14T01:00:00Z)','Keine Bookmark'])expect(html).toContain(expected);
|
||||
expect(html).not.toMatch(/<(button|input|form)\b/);expect(fetch).not.toHaveBeenCalled();
|
||||
}finally{vi.unstubAllGlobals();}
|
||||
});
|
||||
|
||||
it('shows the verified PowerShell process profile before approval without issuing requests', async () => {
|
||||
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) });
|
||||
try {
|
||||
|
||||
+11
-2
@@ -3,7 +3,7 @@ import { createRoot } from 'react-dom/client';
|
||||
import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput, windowsPowerShellRemoteSignedProfile } from './api';
|
||||
import './style.css';
|
||||
import { AdminControl, Catalog, TenantControls } from './management';
|
||||
import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity } from './safety';
|
||||
import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity, queryLogsApprovalBlockers, queryLogsPlanJobs } from './safety';
|
||||
import { Login } from './login';
|
||||
|
||||
const errorText = (error: unknown) => error instanceof Error ? error.message : 'Unbekannter Fehler';
|
||||
@@ -22,6 +22,13 @@ export function PowerShellPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
return <aside className="warning" aria-label="Feste PowerShell-Prozessprofile"><p>Diese Ausführungsoptionen sind an die hashgeprüften gespeicherten Planbytes gebunden.</p><ul>{jobs.map((job, i) => <li key={i}>Asset: {job.assetId} · Windows PowerShell5.1 · agent_service · {job.profile === windowsPowerShellRemoteSignedProfile ? 'RemoteSigned · nur Jobprozess' : 'Geerbte Richtlinie · kein ExecutionPolicy-Prozessparameter'}</li>)}</ul><p>Keine Maschinen-/CurrentUser-/GPO-Änderung durch den Executor. GPO-Vorgaben bleiben wirksam; die angeforderte Option ist kein Nachweis der effektiven Policy.</p></aside>;
|
||||
} catch { return <aside role="alert" className="error">PowerShell-Planprofil ist nicht verifiziert oder wurde verändert. Keine Genehmigung ohne gültige gespeicherte Planbytes.</aside>; }
|
||||
}
|
||||
export function QueryLogsPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
try {
|
||||
const jobs = queryLogsPlanJobs(plan);
|
||||
if (!jobs.length) return null;
|
||||
return <aside className="warning" aria-label="Feste Live-Logfenster"><p>UI-genehmigte Liveabfrage aus hashgeprüften gespeicherten Planbytes; kein passives Inventar, keine automatische Erhebung.</p><ul>{jobs.map((job, i) => <li key={i}>Asset: {job.assetId} · Quelle: {job.source}{job.windows ? <> · Kanal: {job.channel} · Provider: {job.provider} · agent_service</> : ' · Linux-Journal'} · UTC-Fenster: [{job.since}, {job.until}) · maximal {job.maxLines} {job.windows ? 'Events' : 'Zeilen'} · {job.outputBytes} Bytes · äußere Joblaufzeit {job.runtimeSeconds}s{job.windows && ' · inneres Abfragebudget höchstens5000ms, zwischen Win32-Aufrufen kooperativ geprüft'}</li>)}</ul><p>Grenzen, Abbruch, fehlende Rechte und Teilabdeckung bleiben sichtbar. Keine Bookmarkfortschreibung durch diesen Auftrag; die Abfrage behauptet keine vollständige Sammlung aller Systemlogs.</p></aside>;
|
||||
} catch { return <aside role="alert" className="error">Logfenster ist nicht verifiziert oder wurde verändert. Keine Genehmigung ohne gültige gespeicherte Planbytes.</aside>; }
|
||||
}
|
||||
function ErrorBox({ error }: { error: string | null }) { return error ? <div role="alert" className="error">{error}</div> : null; }
|
||||
function useResource<T>(load: (signal: AbortSignal) => Promise<T>, deps: React.DependencyList, poll = false) {
|
||||
const [data, setData] = useState<T | null>(null), [error, setError] = useState<string | null>(null), [revision, setRevision] = useState(0);
|
||||
@@ -63,6 +70,7 @@ function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; aut
|
||||
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); } }}>
|
||||
<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 === 'query_logs' && <p>Windows-MVP nur Quelle windows.eventlog.application.rustdiscovery-mvp-test, Kanal Application, Provider RustDiscovery-MVP-Test, agent_service. Festes UTC-Fenster höchstens24h,1–1000Events,1024–65536Bytes,äußere Joblaufzeit10–120s; inneres kooperatives Abfragebudget höchstens5000ms. Keine freie Kanal-/XPathauswahl und keine Bookmarkfortschreibung. Linux behält seine feste Journalunit.</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>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. Einzelne neue Windowspläne binden fest RemoteSigned nur für den Jobprozess. Bei gemischten Varianten ist powershell_51_remote_signed ausdrücklich an der Windowsvariante zu setzen; fehlendes Profil bleibt geerbt. Jede tatsächliche Prozessoption steht vor Genehmigung je Ziel im festen Plan. 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><option value="system" disabled={action !== 'set_service_state' || !allowed(auth, 'system:execute')}>system · system:execute und Windows-SYSTEM-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>
|
||||
@@ -79,11 +87,12 @@ function PlanDetail({ tenantId, id, auth, onOperation }: { tenantId: string; id:
|
||||
const plan = useResource(async signal => { const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}`), { signal })); await verifyPlanIntegrity(result); return result; }, [tenantId, id]);
|
||||
const [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false), [confirmed, setConfirmed] = useState(false), [submitted, setSubmitted] = useState(false), [pending, setPending] = useState(false);
|
||||
const [idempotency] = useState(() => crypto.randomUUID());
|
||||
const blockers = plan.data ? [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data)] : ['Plan noch nicht geladen'];
|
||||
const blockers = plan.data ? [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data), ...queryLogsApprovalBlockers(plan.data)] : ['Plan noch nicht geladen'];
|
||||
return <section><h2>Unveränderlicher Plan / Genehmigungsdetail</h2><ErrorBox error={plan.error}/><ErrorBox error={error}/>{plan.data && <>
|
||||
<p>Plan-ID: {id}</p><p>Exakter gespeicherter Planhash: <code>{stringField(plan.data, 'plan_hash')}</code></p><p>Feste Ziele: {Array.isArray(plan.data.resolved_targets) ? plan.data.resolved_targets.length : 'unknown'}. Die folgenden Zielpreviews sind unveränderliche Plandefinitionen, keine ausführbaren Jobs oder angelegten Versuche. Diese entstehen erst nach Genehmigung.</p>
|
||||
<SystemPlanNotice plan={plan.data}/>
|
||||
<PowerShellPlanNotice plan={plan.data}/>
|
||||
<QueryLogsPlanNotice plan={plan.data}/>
|
||||
<JsonView value={plan.data} label="Alle festen Zielpreviews, exakte Skriptinhalte/Hashes, Parameter, Rechte, Fristen, Rollout und Nachbedingungen"/>
|
||||
<p className="warning">Genehmigung bindet ausschließlich diesen unveränderlichen Plan. Kein pauschaler Retry, keine Wildcard, kein impliziter Reboot. Unbekannte Wirkung wird nicht automatisch wiederholt. Ein Exitcode allein beweist keine fachliche Wirkung.</p>
|
||||
{blockers.length > 0 && <div role="alert" className="error">Nicht genehmigungsfähig: {blockers.join('; ')}</div>}
|
||||
|
||||
+19
-1
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { actions, PlanInput, Session, request, session } from './api';
|
||||
import { adminIntent, allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, recipeInput, rootWarning, sha256, validateAptManifest, validateSensitiveInput, verifyAptManifest, verifyPlanIntegrity } from './safety';
|
||||
import { adminIntent, allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, queryLogsApprovalBlockers, queryLogsPlanJobs, recipeInput, rootWarning, sha256, validateAptManifest, validateSensitiveInput, verifyAptManifest, verifyPlanIntegrity } from './safety';
|
||||
import { AdminControl } from './management';
|
||||
|
||||
const auth: Session = { principal: { id: 'test', display_name: 'SIMULIERT', simulated: true }, csrf_token: 'csrf', tenants: [], permissions: ['root:execute', 'devices:revoke'] };
|
||||
@@ -40,6 +40,24 @@ describe('immutable PowerShell process profile', () => {
|
||||
value.plan_payload_bytes[0] = 0; expect(powerShellApprovalBlockers(value).length).toBeGreaterThan(0); expect(() => powerShellPlanJobs(value)).toThrow('verändert');
|
||||
});
|
||||
});
|
||||
describe('immutable live log window', () => {
|
||||
it('binds source/window/limits and every supplied view to stored bytes, preserving Linux and SYSTEM plans', async () => {
|
||||
const payload={asset_id:'windows-a',execution_identity:'agent_service',max_runtime_seconds:30,max_output_bytes:4096,action:{action:'query_logs',unit:'windows.eventlog.application.rustdiscovery-mvp-test',since:'2026-11-14T00:00:00Z',until:'2026-11-15T00:00:00Z',max_lines:1000}};
|
||||
const plan_payload={jobs:[{payload}]},raw=new TextEncoder().encode(JSON.stringify(plan_payload));
|
||||
const plan={plan_payload,plan_payload_bytes:Array.from(raw),plan_hash:await sha256(raw),jobs:plan_payload.jobs,resolved_targets:['windows-a']};
|
||||
expect(()=>queryLogsPlanJobs(plan)).toThrow();await verifyPlanIntegrity(plan);
|
||||
expect(queryLogsApprovalBlockers(plan)).toEqual([]);expect(queryLogsPlanJobs(plan)[0]).toMatchObject({source:payload.action.unit,channel:'Application',provider:'RustDiscovery-MVP-Test',maxLines:1000,outputBytes:4096,runtimeSeconds:30});
|
||||
await expect(verifyPlanIntegrity({...plan,plan_payload_bytes:undefined})).rejects.toThrow('gespeicherte');
|
||||
for(const action of [{...payload.action,max_lines:999},{...payload.action,until:'2026-11-14T23:59:59Z'}]){
|
||||
const bad={...plan,payloads:[{payload:{...payload,action}}]};await expect(verifyPlanIntegrity(bad)).rejects.toThrow('widerspricht');
|
||||
}
|
||||
const changed={...plan,jobs:[{payload:{...payload,max_output_bytes:2048}}]};await expect(verifyPlanIntegrity(changed)).rejects.toThrow('widerspricht');
|
||||
const cached={...plan};await verifyPlanIntegrity(cached);cached.jobs=[{payload:{...payload,max_runtime_seconds:31}}];expect(queryLogsApprovalBlockers(cached).length).toBeGreaterThan(0);
|
||||
for(const execution_identity of ['root','system']){const p={jobs:[{payload:{...payload,execution_identity}}]};const b=new TextEncoder().encode(JSON.stringify(p));await expect(verifyPlanIntegrity({plan_payload_bytes:Array.from(b),plan_hash:await sha256(b)})).rejects.toThrow('agent_service');}
|
||||
const linux={jobs:[{payload:{...payload,execution_identity:'root',action:{...payload.action,unit:'rmm-test.service'}}}]};const linuxBytes=new TextEncoder().encode(JSON.stringify(linux));const linuxPlan={plan_payload_bytes:Array.from(linuxBytes),plan_hash:await sha256(linuxBytes)};await verifyPlanIntegrity(linuxPlan);expect(queryLogsPlanJobs(linuxPlan)[0]?.windows).toBe(false);
|
||||
const system={jobs:[{payload:{...payload,execution_identity:'system',action:{action:'set_service_state',unit:'RmmDiscoveryFixtureService',state:'running'}}}]};const systemBytes=new TextEncoder().encode(JSON.stringify(system));const systemPlan={plan_payload_bytes:Array.from(systemBytes),plan_hash:await sha256(systemBytes)};await verifyPlanIntegrity(systemPlan);expect(queryLogsPlanJobs(systemPlan)).toEqual([]);
|
||||
});
|
||||
});
|
||||
async function manifest(acceptance = true) {
|
||||
const transaction = { schema_version: 1, recipe_id: 'rmm-apt-fixture-install-1.0', recipe_version: '1', platform: 'ubuntu-24.04-amd64', resolver_config_version: 'rmm-apt-local-v1', no_reboot: true, status_fingerprint: 'a'.repeat(64), baseline_sha256: 'b'.repeat(64), packages: [{ name: 'rmm-mvp-test', architecture: 'all', old_version: null, new_version: '1.0', origin: 'rmm-test', sha256: '74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867', size: 20672, archive_path: '/var/lib/rmm-apt-transaction/archives/74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867.deb' }] };
|
||||
const raw = new TextEncoder().encode(JSON.stringify(transaction));
|
||||
|
||||
+58
-10
@@ -1,4 +1,4 @@
|
||||
import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, windowsScriptProfile } from './api';
|
||||
import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, windowsScriptProfile, logWindow, validateWindowsLogLimits, windowsEventLogFixtureSource, windowsEventLogFixtureChannel, windowsEventLogFixtureProvider } from './api';
|
||||
|
||||
export const hashPattern = /^[0-9a-f]{64}$/;
|
||||
export const rootWarning = 'HOHES RISIKO: root kann das Zielsystem verändern. Keine automatische Rechteerhöhung; eigener expliziter Plan, Scope, Helper und Genehmigung erforderlich.';
|
||||
@@ -104,7 +104,7 @@ export function systemPlanJobs(plan: RecordValue): RecordValue[] {
|
||||
export interface PowerShellPlanJob { readonly assetId: string; readonly profile: 'inherited' | 'powershell_51_remote_signed' }
|
||||
// Only successful verification writes this cache. Projection is copied from the
|
||||
// verified bytes; later mutations of API views cannot change the displayed plan.
|
||||
interface VerifiedPowerShellPlan { readonly jobs: readonly PowerShellPlanJob[]; readonly planHash: unknown; readonly planBytes: readonly number[] }
|
||||
interface VerifiedPowerShellPlan { readonly jobs: readonly PowerShellPlanJob[]; readonly logJobs: readonly QueryLogsPlanJob[]; readonly planHash: unknown; readonly planBytes: readonly number[] }
|
||||
const verifiedPowerShellPlans = new WeakMap<RecordValue, VerifiedPowerShellPlan>();
|
||||
export function powerShellPlanJobs(plan: RecordValue): readonly PowerShellPlanJob[] {
|
||||
const verified = verifiedPowerShellPlans.get(plan);
|
||||
@@ -115,6 +115,7 @@ export function powerShellPlanJobs(plan: RecordValue): readonly PowerShellPlanJo
|
||||
const parsed = record(parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(current)));
|
||||
validatePlanAliases(plan, parsed);
|
||||
validatePowerShellViews(plan, parsed.jobs);
|
||||
validateQueryLogsViews(plan, parsed.jobs);
|
||||
} else if (scriptPayloads(planTargetPreviews(plan)).some(hasPowerShellProfile)) {
|
||||
throw new Error('PowerShell-Plan benötigt exakte gespeicherte Planbytes');
|
||||
}
|
||||
@@ -153,25 +154,66 @@ function projectPowerShellJobs(jobs: unknown): PowerShellPlanJob[] {
|
||||
function validatePlanAliases(plan: RecordValue, parsed: unknown): void {
|
||||
for (const alias of ['plan_payload', 'payload']) if (plan[alias] !== undefined && canonical(parsed) !== canonical(plan[alias])) throw new Error('Planansicht widerspricht gespeicherten Bytes');
|
||||
}
|
||||
function validatePowerShellViews(plan: RecordValue, rawJobs: unknown): void {
|
||||
function validateFixedViews(plan: RecordValue, rawJobs: unknown, selected: (payload: RecordValue) => boolean, label: string, fields = ['action', 'execution_identity']): void {
|
||||
const rawPayloads = scriptPayloads(rawJobs), views = [planTargetPreviews(plan)];
|
||||
for (const alias of ['jobs', 'payloads', 'resolved_targets']) {
|
||||
if (plan[alias] !== undefined && !Array.isArray(plan[alias])) throw new Error('PowerShell-Zielpreview ist keine vollständige Liste');
|
||||
if (plan[alias] !== undefined && !Array.isArray(plan[alias])) throw new Error(`${label}-Zielpreview ist keine vollständige Liste`);
|
||||
if (Array.isArray(plan[alias])) views.push(plan[alias]);
|
||||
}
|
||||
for (const collection of new Set(views)) if (collection !== null) {
|
||||
// IDs-only target lists remain metadata. Every supplied payload-bearing
|
||||
// alias, however, must describe the same complete fixed PowerShell jobs.
|
||||
if (!collection.some(value => value !== null && typeof value === 'object' && !Array.isArray(value) && 'payload' in value)) continue;
|
||||
const viewPayloads = scriptPayloads(collection);
|
||||
for (const fixed of rawPayloads.filter(hasPowerShellProfile)) if (!viewPayloads.some(view => view.asset_id === fixed.asset_id)) throw new Error('PowerShell-Zielpreview fehlt im festen Plan');
|
||||
for (const fixed of rawPayloads.filter(selected)) if (!viewPayloads.some(view => view.asset_id === fixed.asset_id)) throw new Error(`${label}-Zielpreview fehlt im festen Plan`);
|
||||
for (const view of viewPayloads) {
|
||||
const raw = rawPayloads.find(payload => payload.asset_id === view.asset_id);
|
||||
if ((hasPowerShellProfile(view) || (raw && hasPowerShellProfile(raw))) && (!raw || canonical(raw.action) !== canonical(view.action)
|
||||
|| raw.execution_identity !== view.execution_identity)) throw new Error('PowerShell-Zielpreview widerspricht gespeicherten Planbytes');
|
||||
if ((selected(view) || (raw && selected(raw))) && (!raw || fields.some(field => canonical(raw[field]) !== canonical(view[field])))) throw new Error(`${label}-Zielpreview widerspricht gespeicherten Planbytes`);
|
||||
}
|
||||
}
|
||||
}
|
||||
function validatePowerShellViews(plan: RecordValue, rawJobs: unknown): void {
|
||||
validateFixedViews(plan, rawJobs, hasPowerShellProfile, 'PowerShell');
|
||||
}
|
||||
function isQueryLogs(payload: RecordValue): boolean {
|
||||
return payload.action !== null && typeof payload.action === 'object' && record(payload.action).action === 'query_logs';
|
||||
}
|
||||
function validateQueryLogsViews(plan: RecordValue, rawJobs: unknown): void {
|
||||
validateFixedViews(plan, rawJobs, isQueryLogs, 'Log', ['action', 'execution_identity', 'max_runtime_seconds', 'max_output_bytes']);
|
||||
}
|
||||
export interface QueryLogsPlanJob {
|
||||
readonly assetId: string; readonly source: string; readonly since: string; readonly until: string;
|
||||
readonly maxLines: number; readonly runtimeSeconds: number; readonly outputBytes: number; readonly windows: boolean;
|
||||
readonly channel: string | null; readonly provider: string | null;
|
||||
}
|
||||
function projectQueryLogsJobs(jobs: unknown): QueryLogsPlanJob[] {
|
||||
return scriptPayloads(jobs).filter(isQueryLogs).map(payload => {
|
||||
const action = record(payload.action);
|
||||
exact(action, ['action', 'unit', 'since', 'until', 'max_lines']);
|
||||
const source = text(action.unit, 'Logquelle'), since = text(action.since, 'since'), until = text(action.until, 'until');
|
||||
logWindow(since, until);
|
||||
if (typeof action.max_lines !== 'number' || !Number.isSafeInteger(action.max_lines) || action.max_lines < 1 || action.max_lines > 1000
|
||||
|| typeof payload.max_runtime_seconds !== 'number' || !Number.isSafeInteger(payload.max_runtime_seconds) || payload.max_runtime_seconds < 1 || payload.max_runtime_seconds > 3600
|
||||
|| typeof payload.max_output_bytes !== 'number' || !Number.isSafeInteger(payload.max_output_bytes) || payload.max_output_bytes < 1 || payload.max_output_bytes > 262144) throw new Error('Vollständige feste Loglimits erforderlich');
|
||||
const windows = source === windowsEventLogFixtureSource;
|
||||
if (source.startsWith('windows.eventlog.') && !windows) throw new Error('Unbekannte Windows-Eventlogquelle');
|
||||
if (windows) validateWindowsLogLimits(payload.execution_identity, payload.max_runtime_seconds, payload.max_output_bytes, since);
|
||||
else if (!['agent_service', 'root'].includes(String(payload.execution_identity))) throw new Error('Unbekannte Log-Ausführungsidentität');
|
||||
return { assetId: text(payload.asset_id, 'Log-Zielasset'), source, since, until, maxLines: action.max_lines,
|
||||
runtimeSeconds: payload.max_runtime_seconds, outputBytes: payload.max_output_bytes, windows,
|
||||
channel: windows ? windowsEventLogFixtureChannel : null, provider: windows ? windowsEventLogFixtureProvider : null };
|
||||
});
|
||||
}
|
||||
export function queryLogsPlanJobs(plan: RecordValue): readonly QueryLogsPlanJob[] {
|
||||
// Reuse the same verified-object/immutable-byte gate as the PowerShell view.
|
||||
powerShellPlanJobs(plan);
|
||||
const verified = verifiedPowerShellPlans.get(plan)!;
|
||||
if (!verified.planBytes.length && ['jobs', 'payloads', 'resolved_targets'].some(alias => scriptPayloads(plan[alias]).some(isQueryLogs))) throw new Error('Logplan benötigt exakte gespeicherte Planbytes');
|
||||
return verified.logJobs.map(job => ({ ...job }));
|
||||
}
|
||||
export function queryLogsApprovalBlockers(plan: RecordValue): string[] {
|
||||
try { queryLogsPlanJobs(plan); return []; }
|
||||
catch (error) { return [error instanceof Error ? error.message : 'Logplan ist nicht verifiziert']; }
|
||||
}
|
||||
|
||||
export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
verifiedPowerShellPlans.delete(plan);
|
||||
const views = planTargetPreviews(plan), hasScriptView = scriptPayloads(views).some(hasPowerShellProfile)
|
||||
@@ -180,6 +222,10 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
|| scriptPayloads(record(plan.plan_payload ?? {}).jobs).some(hasPowerShellProfile)
|
||||
|| scriptPayloads(record(plan.payload ?? {}).jobs).some(hasPowerShellProfile);
|
||||
if (hasScriptView && plan.plan_payload_bytes === undefined) throw new Error('PowerShell-Plan benötigt exakte gespeicherte Planbytes');
|
||||
const hasLogView = ['jobs', 'payloads', 'resolved_targets'].some(alias => scriptPayloads(plan[alias]).some(isQueryLogs))
|
||||
|| scriptPayloads(record(plan.plan_payload ?? {}).jobs).some(isQueryLogs) || scriptPayloads(record(plan.payload ?? {}).jobs).some(isQueryLogs);
|
||||
if (hasLogView && plan.plan_payload_bytes === undefined) throw new Error('Logplan benötigt exakte gespeicherte Planbytes');
|
||||
let logJobs: QueryLogsPlanJob[] = [];
|
||||
let powerShellJobs: PowerShellPlanJob[] = [];
|
||||
let verifiedBytes: readonly number[] = [];
|
||||
if (plan.plan_payload_bytes === undefined && Array.isArray(plan.jobs) && plan.jobs.some(value => {
|
||||
@@ -194,6 +240,8 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
validatePlanAliases(plan, parsed);
|
||||
const rawJobs = record(parsed).jobs;
|
||||
powerShellJobs = projectPowerShellJobs(rawJobs);
|
||||
logJobs = projectQueryLogsJobs(rawJobs);
|
||||
if (hasLogView || logJobs.length) validateQueryLogsViews(plan, rawJobs);
|
||||
if (hasScriptView || powerShellJobs.length) {
|
||||
if (!Array.isArray(rawJobs)) throw new Error('Vollständige feste PowerShell-Zielpayloads fehlen');
|
||||
validatePowerShellViews(plan, rawJobs);
|
||||
@@ -209,7 +257,7 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
for (const value of jobs) { if (!value || typeof value !== 'object') continue; const p = record(value).payload; if (!p || typeof p !== 'object') continue; const action = record(p).action;
|
||||
if (action && typeof action === 'object' && record(action).apt_manifest !== undefined && record(action).apt_manifest !== null) await verifyAptManifest(record(action).apt_manifest, record(action).action === 'apt_native_acceptance');
|
||||
}
|
||||
verifiedPowerShellPlans.set(plan, { jobs: powerShellJobs.map(job => Object.freeze({ ...job })), planHash: plan.plan_hash, planBytes: verifiedBytes });
|
||||
verifiedPowerShellPlans.set(plan, { jobs: powerShellJobs.map(job => Object.freeze({ ...job })), logJobs: logJobs.map(job => Object.freeze({ ...job })), planHash: plan.plan_hash, planBytes: verifiedBytes });
|
||||
}
|
||||
export function recipeInput(value: unknown): RecordValue {
|
||||
const r = record(value); exact(r, ['schema_version', 'provider', 'package', 'version', 'architecture', 'recipe_version', 'installation_context', 'reboot_policy']);
|
||||
|
||||
Reference in New Issue
Block a user