Integrate strict Windows MSI manifests tenant catalog and SYSTEM package policy
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -36,13 +36,20 @@ pub async fn download(
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
|
||||
let row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,i.asset_id,i.enrollment_generation,i.assignment_version FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.job_id=$2 AND j.attempt_id=$3 AND j.state IN ('queued','accepted','running','verifying','awaiting_reboot') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL").bind(a).bind(q.job_id).bind(q.attempt_id).fetch_optional(&mut *tx).await?.ok_or(Error(StatusCode::NOT_FOUND,"NOT_FOUND"))?;
|
||||
let row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,z.principal AS approver,i.asset_id,i.enrollment_generation,i.assignment_version FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.job_id=$2 AND j.attempt_id=$3 AND j.state IN ('queued','accepted','running','verifying','awaiting_reboot') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL").bind(a).bind(q.job_id).bind(q.attempt_id).fetch_optional(&mut *tx).await?.ok_or(Error(StatusCode::NOT_FOUND,"NOT_FOUND"))?;
|
||||
let job: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
|
||||
let plan_bytes: Vec<u8> = row.get("plan_payload");
|
||||
if rmm_domain::jobs::hash(&plan_bytes) != row.get::<String, _>("plan_hash") {
|
||||
return Err(Error(StatusCode::CONFLICT, "PLAN_HASH_MISMATCH"));
|
||||
}
|
||||
let plan: PlanPayload = serde_json::from_slice(&plan_bytes)?;
|
||||
if job.action.windows_msi().is_some() {
|
||||
crate::windows_msi_catalog::validate_job_binding(&plan, &job)?;
|
||||
crate::catalog::check(&mut tx, &job.action).await?;
|
||||
crate::root_policy::authorize(&mut tx, &plan.principal, &job).await?;
|
||||
crate::root_policy::authorize(&mut tx, &row.get::<String, _>("approver"), &job).await?;
|
||||
}
|
||||
|
||||
if job.asset_id != row.get::<Uuid, _>("asset_id")
|
||||
|| job.enrollment_generation != row.get::<i64, _>("enrollment_generation") as u64
|
||||
|| job.assignment_version != row.get::<i64, _>("assignment_version") as u64
|
||||
|
||||
@@ -24,6 +24,10 @@ pub struct AptRecipe {
|
||||
}
|
||||
pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
|
||||
r.route(
|
||||
"/api/v1/tenants/{tenant}/windows-msi-recipes",
|
||||
get(crate::windows_msi_catalog::list).post(crate::windows_msi_catalog::import),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/package-recipes",
|
||||
get(list).post(import),
|
||||
)
|
||||
@@ -43,6 +47,15 @@ pub async fn references(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
action: &rmm_domain::jobs::Action,
|
||||
) -> Result<Vec<rmm_domain::jobs::RecipeReference>, Error> {
|
||||
if let Some(manifest) = action.windows_msi() {
|
||||
if !action.validate() {
|
||||
return Err(Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"INVALID_WINDOWS_MSI_MANIFEST",
|
||||
));
|
||||
}
|
||||
return crate::windows_msi_catalog::references(tx, manifest).await;
|
||||
}
|
||||
let manifest = match action {
|
||||
rmm_domain::jobs::Action::EnsurePackage {
|
||||
apt_manifest: Some(m),
|
||||
@@ -138,7 +151,7 @@ pub async fn references(
|
||||
references.dedup();
|
||||
Ok(references)
|
||||
}
|
||||
async fn context<'a>(
|
||||
pub(crate) async fn context<'a>(
|
||||
s: &'a crate::State,
|
||||
h: &HeaderMap,
|
||||
t: Uuid,
|
||||
@@ -182,6 +195,7 @@ pub async fn import(
|
||||
installation_context: recipe.installation_context.clone(),
|
||||
recipe_id: None,
|
||||
apt_manifest: None,
|
||||
windows_msi_manifest: None,
|
||||
};
|
||||
if recipe.schema_version != 1
|
||||
|| recipe.reboot_policy != "never"
|
||||
|
||||
@@ -491,6 +491,9 @@ pub async fn permit(
|
||||
let payload: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
|
||||
let plan: PlanPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("plan_payload"))?;
|
||||
let capabilities: Vec<String> = serde_json::from_value(row.get("capabilities"))?;
|
||||
if crate::windows_msi_catalog::validate_job_binding(&plan, &payload).is_err() {
|
||||
return Ok(denied("WINDOWS_MSI_BINDING_MISMATCH"));
|
||||
}
|
||||
if row.get::<Uuid, _>("bound_asset") != payload.asset_id
|
||||
|| !payload
|
||||
.action
|
||||
@@ -736,6 +739,20 @@ pub async fn next(
|
||||
};
|
||||
let payload: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
|
||||
let caps: Vec<String> = serde_json::from_value(row.get("capabilities"))?;
|
||||
if payload.action.windows_msi().is_some() {
|
||||
let raw: Vec<u8> = row.get("plan_payload");
|
||||
let plan: PlanPayload = serde_json::from_slice(&raw)?;
|
||||
if hash(&raw) != row.get::<String, _>("plan_hash")
|
||||
|| crate::windows_msi_catalog::validate_job_binding(&plan, &payload).is_err()
|
||||
|| crate::catalog::check(&mut tx, &payload.action)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tx.commit().await?;
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
|
||||
if !payload
|
||||
.action
|
||||
.available_for(&payload.execution_identity, &caps)
|
||||
|
||||
+207
-1
@@ -181,6 +181,12 @@ struct WebParameters {
|
||||
recipe_version: Option<String>,
|
||||
recipe_id: Option<String>,
|
||||
apt_manifest: Option<rmm_domain::apt_transaction::AptExecutionManifest>,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_windows_msi_manifest"
|
||||
)]
|
||||
#[schemars(with = "rmm_domain::windows_execution::ResolvedWindowsMsi")]
|
||||
windows_msi_manifest: Option<Box<rmm_domain::windows_execution::ResolvedWindowsMsi>>,
|
||||
installation_context: Option<String>,
|
||||
packages: Option<Vec<String>>,
|
||||
reboot_policy: Option<String>,
|
||||
@@ -205,6 +211,9 @@ impl PlanRequest {
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
let p = w.parameters;
|
||||
if p.windows_msi_manifest.is_some() && w.action != "ensure_package" {
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
let required =
|
||||
|value: Option<String>| value.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
let action = match w.action.as_str() {
|
||||
@@ -251,6 +260,7 @@ impl PlanRequest {
|
||||
installation_context: required(p.installation_context)?,
|
||||
recipe_id: p.recipe_id,
|
||||
apt_manifest: p.apt_manifest,
|
||||
windows_msi_manifest: p.windows_msi_manifest,
|
||||
},
|
||||
"apply_updates" => Action::ApplyUpdates {
|
||||
provider: required(p.provider)?,
|
||||
@@ -435,6 +445,14 @@ pub async fn plan(
|
||||
{
|
||||
return Err(Error(StatusCode::FORBIDDEN, "ROOT_IDENTITY_REQUIRED"));
|
||||
}
|
||||
if input.action.windows_msi().is_some()
|
||||
&& (input.execution_identity != "system" || !input.artifact_ids.is_empty())
|
||||
{
|
||||
return Err(Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"WINDOWS_MSI_EXACT_ARTIFACT_REQUIRED",
|
||||
));
|
||||
}
|
||||
// Conservative policy: reboot is always serial, no provider-triggered reboot.
|
||||
if matches!(input.action, Action::Reboot { .. }) && input.rollout.max_parallel != 1 {
|
||||
return Err(fail("POLICY_DENIED"));
|
||||
@@ -458,7 +476,11 @@ pub async fn plan(
|
||||
crate::permissions::require_principal(&mut tx, p, "logs:read").await?;
|
||||
}
|
||||
let recipe_references = crate::catalog::references(&mut tx, &input.action).await?;
|
||||
let artifacts = crate::catalog::resolve_artifacts(&mut tx, tenant, &input.artifact_ids).await?;
|
||||
let artifacts = if input.action.windows_msi().is_some() {
|
||||
crate::windows_msi_catalog::automatic_artifacts(&mut tx, tenant, &input.action).await?
|
||||
} else {
|
||||
crate::catalog::resolve_artifacts(&mut tx, tenant, &input.artifact_ids).await?
|
||||
};
|
||||
let mut jobs = Vec::new();
|
||||
for asset in ids {
|
||||
let rows=sqlx::query("SELECT agent_id,enrollment_generation,assignment_version,capabilities FROM agent_installations WHERE asset_id=$1 AND revoked_at IS NULL ORDER BY agent_id FOR SHARE").bind(asset).fetch_all(&mut *tx).await?;
|
||||
@@ -531,6 +553,7 @@ pub async fn plan(
|
||||
recipe_references,
|
||||
artifact_references,
|
||||
};
|
||||
crate::windows_msi_catalog::validate_plan_bindings(&payload)?;
|
||||
let bytes = encode(&payload)?;
|
||||
let plan_hash = hash(&bytes);
|
||||
sqlx::query("INSERT INTO operation_plans(tenant_id,plan_id,principal,payload,plan_hash,expires_at) VALUES($1,$2,$3,$4,$5,$6)").bind(tenant).bind(payload.plan_id).bind(&p.name).bind(&bytes).bind(&plan_hash).bind(input.schedule.start_before).execute(&mut *tx).await?;
|
||||
@@ -565,6 +588,7 @@ async fn load_plan(
|
||||
Ok((serde_json::from_slice(&bytes)?, h, bytes))
|
||||
}
|
||||
async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Result<()> {
|
||||
crate::windows_msi_catalog::validate_plan_bindings(plan)?;
|
||||
policy(tx).await?;
|
||||
let current_artifacts = crate::catalog::resolve_artifacts(
|
||||
tx,
|
||||
@@ -1511,6 +1535,188 @@ mod windows_contract_tests {
|
||||
"FORBIDDEN"
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
// MSI metadata only: real migration/RLS/FKs and pending-only planning.
|
||||
// This ignored test runs alone in the dedicated isolated PostgreSQL process.
|
||||
// Opaque bytes deliberately are NOT an authored/installed MSI fixture.
|
||||
use crate::artifact_store::ArtifactStore;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let key_path = temp.join("key.pem");
|
||||
let policy_path = temp.join("system-msi.json");
|
||||
let settings = [
|
||||
("RMM_PROFILE", "development".to_string()),
|
||||
("RMM_JOB_KEY_FILE", key_path.display().to_string()),
|
||||
("RMM_DEV_SYSTEM_ENABLED", "true".to_string()),
|
||||
(
|
||||
"RMM_DEV_SYSTEM_POLICY_FILE",
|
||||
policy_path.display().to_string(),
|
||||
),
|
||||
];
|
||||
let previous = settings
|
||||
.iter()
|
||||
.map(|(key, _)| (*key, std::env::var_os(key)))
|
||||
.collect::<Vec<_>>();
|
||||
for (key, value) in &settings {
|
||||
unsafe {
|
||||
std::env::set_var(key, value);
|
||||
}
|
||||
}
|
||||
let artifact_id = Uuid::new_v4();
|
||||
let opaque = b"metadata-contract-not-an-executable-msi";
|
||||
let artifact_sha = crate::catalog::store()
|
||||
.unwrap()
|
||||
.put(tenant, opaque)
|
||||
.unwrap();
|
||||
let manifest = crate::windows_msi_catalog::test_manifest(
|
||||
artifact_id,
|
||||
&artifact_sha,
|
||||
opaque.len() as u64,
|
||||
);
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO artifacts(tenant_id,artifact_id,sha256,size_bytes,media_type) VALUES($1,$2,$3,$4,'application/octet-stream')")
|
||||
.bind(tenant).bind(artifact_id).bind(&artifact_sha).bind(opaque.len() as i64).execute(&mut *tx).await.unwrap();
|
||||
let catalog_id = crate::windows_msi_catalog::store_recipe(&mut tx, tenant, &manifest)
|
||||
.await
|
||||
.unwrap();
|
||||
tx.commit().await.unwrap();
|
||||
let other = Uuid::new_v4();
|
||||
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'other MSI tenant')")
|
||||
.bind(other)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut foreign = rmm_persistence::tenant_tx(&state.pool, other)
|
||||
.await
|
||||
.unwrap();
|
||||
let count: i64 = sqlx::query_scalar("SELECT count(*) FROM windows_msi_recipes")
|
||||
.fetch_one(&mut *foreign)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, 0);
|
||||
assert!(
|
||||
crate::windows_msi_catalog::references(&mut foreign, &manifest)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
foreign.rollback().await.unwrap();
|
||||
let row=sqlx::query("INSERT INTO windows_msi_recipes(tenant_id,catalog_id,recipe_id,recipe_version,recipe_sha256,artifact_id,artifact_sha256,artifact_bytes,payload) VALUES($1,$2,$3,'1',$4,$5,$6,$7,$8)")
|
||||
.bind(other).bind(Uuid::new_v4()).bind(&manifest.recipe.recipe_id).bind(&manifest.recipe_sha256)
|
||||
.bind(artifact_id).bind(&artifact_sha).bind(opaque.len() as i64).bind(encode(&manifest.recipe).unwrap()).execute(&admin).await;
|
||||
assert!(row.is_err()); // database-level composite tenant/artifact FK
|
||||
assert!(
|
||||
sqlx::query("UPDATE windows_msi_recipes SET recipe_sha256=$2 WHERE catalog_id=$1")
|
||||
.bind(catalog_id)
|
||||
.bind("cd".repeat(32))
|
||||
.execute(&admin)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
sqlx::query("DELETE FROM windows_msi_recipes WHERE catalog_id=$1")
|
||||
.bind(catalog_id)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'system:execute') WHERE tenant_id=$1 AND principal=$2").bind(tenant).bind(&principal.name).execute(&admin).await.unwrap();
|
||||
let caps = json!([
|
||||
"windows.base/1",
|
||||
"rmm.sync.v1",
|
||||
"helper.system.v1",
|
||||
"ensure_package",
|
||||
"system:ensure_package",
|
||||
rmm_domain::windows_execution::MSI_CAPABILITY,
|
||||
format!("helper.policy.sha256:{}", "ab".repeat(32)),
|
||||
format!("helper.binary.sha256:{}", "cd".repeat(32))
|
||||
]);
|
||||
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
||||
.bind(agents[1])
|
||||
.bind(&caps)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let system = json!({"schema_version":2,"profile":"development","expires_at":Utc::now()+Duration::minutes(10),"scopes":[{
|
||||
"tenant_id":tenant,"asset_id":assets[1],"agent_id":agents[1],"enrollment_generation":1,"assignment_version":1,
|
||||
"principals":[principal.name],"helper_policy_sha256":"ab".repeat(32),"helper_binary_sha256":"cd".repeat(32),
|
||||
"acceptance_evidence_id":Uuid::new_v4(),"allowed_services":[],"max_runtime_seconds":120,"allowed_msi_recipe_sha256":[manifest.recipe_sha256]}]});
|
||||
std::fs::write(&policy_path, encode(&system).unwrap()).unwrap();
|
||||
std::fs::set_permissions(&policy_path, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
let mut package = input();
|
||||
package.targets.asset_ids = vec![assets[1]];
|
||||
package.script_variants.clear();
|
||||
package.execution_identity = "system".into();
|
||||
package.action = crate::windows_msi_catalog::test_action(manifest.clone());
|
||||
package.max_runtime_seconds = 30;
|
||||
package.max_output_bytes = 4096;
|
||||
let mut extra = package.clone();
|
||||
extra.artifact_ids = vec![artifact_id];
|
||||
assert_eq!(
|
||||
plan(&state, &principal, tenant, extra).await.unwrap_err().1,
|
||||
"WINDOWS_MSI_EXACT_ARTIFACT_REQUIRED"
|
||||
);
|
||||
let view = plan(&state, &principal, tenant, package).await.unwrap();
|
||||
let package_id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap();
|
||||
let raw: Vec<u8> =
|
||||
sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1")
|
||||
.bind(package_id)
|
||||
.fetch_one(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let fixed: PlanPayload = serde_json::from_slice(&raw).unwrap();
|
||||
assert_eq!(fixed.artifact_references.len(), 1);
|
||||
assert_eq!(
|
||||
fixed.artifact_references[0].artifact.artifact_id,
|
||||
artifact_id
|
||||
);
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
recheck(&mut tx, &fixed).await.unwrap();
|
||||
tx.rollback().await.unwrap();
|
||||
for case in 0..4 {
|
||||
let mut bad = fixed.clone();
|
||||
match case {
|
||||
0 => bad.artifact_references.clear(),
|
||||
1 => bad
|
||||
.artifact_references
|
||||
.push(bad.artifact_references[0].clone()),
|
||||
2 => bad.artifact_references[0].artifact.size_bytes += 1,
|
||||
_ => bad.artifact_references[0].artifact.artifact_id = Uuid::new_v4(),
|
||||
};
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(recheck(&mut tx, &bad).await.is_err());
|
||||
tx.rollback().await.unwrap();
|
||||
}
|
||||
let pending = submit(
|
||||
&state,
|
||||
&principal,
|
||||
tenant,
|
||||
package_id,
|
||||
Submit {
|
||||
idempotency_key: "fixed-msi-metadata".into(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(pending["approval_state"], "pending_approval");
|
||||
assert_eq!(pending["job_count"], 0);
|
||||
sqlx::query("UPDATE memberships SET permissions=array_remove(permissions,'system:execute') WHERE tenant_id=$1 AND principal=$2").bind(tenant).bind(&principal.name).execute(&admin).await.unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(recheck(&mut tx, &fixed).await.unwrap_err().1, "FORBIDDEN");
|
||||
tx.rollback().await.unwrap();
|
||||
for (key, value) in previous {
|
||||
unsafe {
|
||||
match value {
|
||||
Some(value) => std::env::set_var(key, value),
|
||||
None => std::env::remove_var(key),
|
||||
}
|
||||
}
|
||||
}
|
||||
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> =
|
||||
|
||||
@@ -21,6 +21,7 @@ mod root_policy;
|
||||
mod scheduler;
|
||||
mod synchronization;
|
||||
mod tls;
|
||||
mod windows_msi_catalog;
|
||||
mod windows_policy;
|
||||
|
||||
use anyhow::{Context, Result, ensure};
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
//! Immutable tenant MSI recipe/one-artifact binding. Catalog import is metadata,
|
||||
//! never job approval, helper provisioning, an installer, or a capability grant.
|
||||
use crate::{jobs::Error, pagination};
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, Query, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
};
|
||||
use rmm_domain::{
|
||||
jobs::{Action, ArtifactReference, JobPayload, PlanPayload, RecipeReference, encode, hash},
|
||||
windows_execution::{MSI_PACKAGE_ID, ResolvedWindowsMsi, WindowsMsiRecipe},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
use uuid::Uuid;
|
||||
fn conflict() -> Error {
|
||||
Error(StatusCode::CONFLICT, "WINDOWS_MSI_BINDING_MISMATCH")
|
||||
}
|
||||
fn reference(m: &ResolvedWindowsMsi) -> RecipeReference {
|
||||
RecipeReference {
|
||||
package: MSI_PACKAGE_ID.into(),
|
||||
version: m.recipe.postcondition.product_version.clone(),
|
||||
architecture: "x64".into(),
|
||||
recipe_version: m.recipe.recipe_version.clone(),
|
||||
sha256: m.recipe_sha256.clone(),
|
||||
}
|
||||
}
|
||||
fn artifact(m: &ResolvedWindowsMsi) -> ArtifactReference {
|
||||
ArtifactReference {
|
||||
artifact_id: m.recipe.artifact.artifact_id,
|
||||
sha256: m.recipe.artifact.sha256.clone(),
|
||||
size_bytes: m.recipe.artifact.bytes,
|
||||
}
|
||||
}
|
||||
async fn checked(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
m: &ResolvedWindowsMsi,
|
||||
) -> Result<(Uuid, ArtifactReference), Error> {
|
||||
if !m.validate() {
|
||||
return Err(Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"INVALID_WINDOWS_MSI_MANIFEST",
|
||||
));
|
||||
}
|
||||
// Catalog rows cannot be updated/deleted. Avoid a row lock here: PostgreSQL
|
||||
// requires UPDATE privilege for FOR SHARE, which this immutable reader lacks.
|
||||
let row=sqlx::query("SELECT tenant_id,payload,recipe_sha256,artifact_id,artifact_sha256,artifact_bytes FROM windows_msi_recipes WHERE recipe_id=$1 AND recipe_version=$2")
|
||||
.bind(&m.recipe.recipe_id).bind(&m.recipe.recipe_version).fetch_optional(&mut **tx).await?
|
||||
.ok_or(Error(StatusCode::CONFLICT,"WINDOWS_MSI_RECIPE_NOT_CONFIGURED"))?;
|
||||
let bytes: Vec<u8> = row.get("payload");
|
||||
let a = artifact(m);
|
||||
if encode(&m.recipe)? != bytes
|
||||
|| hash(&bytes) != m.recipe_sha256
|
||||
|| row.get::<String, _>("recipe_sha256") != m.recipe_sha256
|
||||
|| row.get::<Uuid, _>("artifact_id") != a.artifact_id
|
||||
|| row.get::<String, _>("artifact_sha256") != a.sha256
|
||||
|| row.get::<i64, _>("artifact_bytes") as u64 != a.size_bytes
|
||||
{
|
||||
return Err(conflict());
|
||||
}
|
||||
let tenant: Uuid = row.get("tenant_id");
|
||||
let actual = crate::catalog::resolve_artifacts(tx, tenant, &[a.artifact_id]).await?;
|
||||
if actual != [a.clone()] {
|
||||
return Err(conflict());
|
||||
}
|
||||
Ok((tenant, a))
|
||||
}
|
||||
pub async fn references(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
m: &ResolvedWindowsMsi,
|
||||
) -> Result<Vec<RecipeReference>, Error> {
|
||||
checked(tx, m).await?;
|
||||
Ok(vec![reference(m)])
|
||||
}
|
||||
pub async fn automatic_artifacts(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
action: &Action,
|
||||
) -> Result<Vec<ArtifactReference>, Error> {
|
||||
let m = action.windows_msi().ok_or_else(conflict)?;
|
||||
if !action.validate() {
|
||||
return Err(conflict());
|
||||
}
|
||||
let (actual, a) = checked(tx, m).await?;
|
||||
if actual != tenant {
|
||||
return Err(conflict());
|
||||
}
|
||||
Ok(vec![a])
|
||||
}
|
||||
/// Set equality/count checks are deliberate. contains()/dedup() would accept
|
||||
/// missing, additional, or duplicate per-attempt Windows artifact authorizations.
|
||||
pub fn validate_plan_bindings(plan: &PlanPayload) -> Result<(), Error> {
|
||||
let mut has_msi = false;
|
||||
let mut recipes = Vec::new();
|
||||
for job in &plan.jobs {
|
||||
let Some(m) = job.payload.action.windows_msi() else {
|
||||
continue;
|
||||
};
|
||||
has_msi = true;
|
||||
recipes.push(reference(m));
|
||||
if !job.payload.action.validate()
|
||||
|| job.payload.execution_identity != "system"
|
||||
|| !job.payload.action.valid_job_limits(
|
||||
job.payload.max_runtime_seconds,
|
||||
job.payload.max_output_bytes,
|
||||
)
|
||||
|| plan.tenant_id != job.payload.tenant_id
|
||||
|| plan
|
||||
.jobs
|
||||
.iter()
|
||||
.filter(|other| {
|
||||
other.payload.job_id == job.payload.job_id
|
||||
&& other.payload.attempt_id == job.payload.attempt_id
|
||||
})
|
||||
.count()
|
||||
!= 1
|
||||
{
|
||||
return Err(conflict());
|
||||
}
|
||||
let refs = plan
|
||||
.artifact_references
|
||||
.iter()
|
||||
.filter(|r| r.job_id == job.payload.job_id && r.attempt_id == job.payload.attempt_id)
|
||||
.collect::<Vec<_>>();
|
||||
if refs.len() != 1
|
||||
|| refs[0].artifact != artifact(m)
|
||||
|| plan
|
||||
.recipe_references
|
||||
.iter()
|
||||
.filter(|r| **r == reference(m))
|
||||
.count()
|
||||
!= 1
|
||||
{
|
||||
return Err(conflict());
|
||||
}
|
||||
}
|
||||
if has_msi {
|
||||
recipes.sort();
|
||||
recipes.dedup();
|
||||
// A package plan resolves one common MSI action for all its targets.
|
||||
// Never accept extra recipe authority or a mixed-action plan at a later
|
||||
// delivery/permit/download boundary merely because contains() succeeds.
|
||||
if recipes != plan.recipe_references
|
||||
|| plan
|
||||
.jobs
|
||||
.iter()
|
||||
.any(|j| j.payload.action.windows_msi().is_none())
|
||||
|| plan.artifact_references.iter().any(|r| {
|
||||
!plan
|
||||
.jobs
|
||||
.iter()
|
||||
.any(|j| j.payload.job_id == r.job_id && j.payload.attempt_id == r.attempt_id)
|
||||
})
|
||||
{
|
||||
return Err(conflict());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn validate_job_binding(plan: &PlanPayload, job: &JobPayload) -> Result<(), Error> {
|
||||
if job.action.windows_msi().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
validate_plan_bindings(plan)?;
|
||||
let bytes = encode(job)?;
|
||||
let matches = plan
|
||||
.jobs
|
||||
.iter()
|
||||
.filter(|j| j.payload.job_id == job.job_id && j.payload.attempt_id == job.attempt_id)
|
||||
.collect::<Vec<_>>();
|
||||
if matches.len() != 1
|
||||
|| matches[0].job_payload_hash != hash(&bytes)
|
||||
|| encode(&matches[0].payload)? != bytes
|
||||
{
|
||||
return Err(conflict());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) async fn store_recipe(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
t: Uuid,
|
||||
m: &ResolvedWindowsMsi,
|
||||
) -> Result<Uuid, Error> {
|
||||
if !m.validate() {
|
||||
return Err(Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"INVALID_WINDOWS_MSI_MANIFEST",
|
||||
));
|
||||
}
|
||||
let actual = crate::catalog::resolve_artifacts(tx, t, &[m.recipe.artifact.artifact_id]).await?;
|
||||
if actual != [artifact(m)] {
|
||||
return Err(conflict());
|
||||
}
|
||||
let bytes = encode(&m.recipe)?;
|
||||
if bytes.len() > 65536 {
|
||||
return Err(Error(StatusCode::PAYLOAD_TOO_LARGE, "QUOTA_EXCEEDED"));
|
||||
}
|
||||
let id = Uuid::new_v4();
|
||||
sqlx::query("INSERT INTO windows_msi_recipes(tenant_id,catalog_id,recipe_id,recipe_version,recipe_sha256,artifact_id,artifact_sha256,artifact_bytes,payload) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)")
|
||||
.bind(t).bind(id).bind(&m.recipe.recipe_id).bind(&m.recipe.recipe_version).bind(&m.recipe_sha256)
|
||||
.bind(m.recipe.artifact.artifact_id).bind(&m.recipe.artifact.sha256).bind(m.recipe.artifact.bytes as i64).bind(bytes).execute(&mut **tx).await?;
|
||||
Ok(id)
|
||||
}
|
||||
pub async fn import(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path(t): Path<Uuid>,
|
||||
Json(m): Json<ResolvedWindowsMsi>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let (p, mut tx) = crate::catalog::context(&s, &h, t, true).await?;
|
||||
let id = store_recipe(&mut tx, t, &m).await?;
|
||||
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'windows_msi_recipe_imported',$4,now())")
|
||||
.bind(t)
|
||||
.bind(Uuid::new_v4())
|
||||
.bind(p.name)
|
||||
.bind(
|
||||
json!({"catalog_id":id,"recipe_id":m.recipe.recipe_id,"recipe_sha256":m.recipe_sha256,
|
||||
"artifact_id":m.recipe.artifact.artifact_id,"testsimulation":p.testsimulation}),
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(
|
||||
json!({"catalog_id":id,"recipe_id":m.recipe.recipe_id,"sha256":m.recipe_sha256,"manifest":m}),
|
||||
))
|
||||
}
|
||||
pub async fn list(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path(t): Path<Uuid>,
|
||||
Query(query): Query<pagination::PageQuery>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let (p, mut tx) = crate::catalog::context(&s, &h, t, false).await?;
|
||||
let mut page = pagination::Cursor::parse(&s, &p, "catalog:windows-msi:catalog_id:asc", query)
|
||||
.map_err(|status| Error(status, "VALIDATION_ERROR"))?;
|
||||
let rows=sqlx::query("SELECT catalog_id,payload,recipe_sha256 FROM windows_msi_recipes WHERE catalog_id>$1 AND created_at<=$2 ORDER BY catalog_id LIMIT $3")
|
||||
.bind(page.last).bind(page.as_of).bind(i64::from(page.limit)+1).fetch_all(&mut *tx).await?;
|
||||
let truncated = rows.len() > usize::from(page.limit);
|
||||
let next = if truncated {
|
||||
Some(
|
||||
page.next(&s, rows[usize::from(page.limit) - 1].get("catalog_id"))
|
||||
.map_err(|status| Error(status, "VALIDATION_ERROR"))?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut items = Vec::new();
|
||||
for row in rows.iter().take(usize::from(page.limit)) {
|
||||
let bytes: Vec<u8> = row.get("payload");
|
||||
let m = ResolvedWindowsMsi {
|
||||
recipe: serde_json::from_slice::<WindowsMsiRecipe>(&bytes)?,
|
||||
recipe_sha256: row.get("recipe_sha256"),
|
||||
};
|
||||
if !m.validate() || encode(&m.recipe)? != bytes {
|
||||
return Err(conflict());
|
||||
}
|
||||
items.push(json!({"catalog_id":row.get::<Uuid,_>("catalog_id"),"recipe_id":m.recipe.recipe_id,"sha256":m.recipe_sha256,"manifest":m}));
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Json(
|
||||
json!({"items":items,"next_cursor":next,"completeness":if truncated{"partial"}else{"complete"},"truncated":truncated,"as_of":page.as_of}),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_manifest(id: Uuid, sha: &str, bytes: u64) -> ResolvedWindowsMsi {
|
||||
use rmm_domain::windows_execution::*;
|
||||
let recipe = WindowsMsiRecipe {
|
||||
schema_version: 1,
|
||||
recipe_id: MSI_RECIPE_ID.into(),
|
||||
recipe_version: "1".into(),
|
||||
platform: "windows".into(),
|
||||
upgrade_code: MSI_UPGRADE_CODE.into(),
|
||||
architecture: Architecture::X64,
|
||||
context: InstallContext::Machine,
|
||||
command_profile: MsiCommandProfile::FixtureQuietNoRebootV1,
|
||||
artifact: MsiArtifact {
|
||||
artifact_id: id,
|
||||
sha256: sha.into(),
|
||||
bytes,
|
||||
},
|
||||
postcondition: MsiPostcondition {
|
||||
product_code: MSI_PRODUCT_CODE.into(),
|
||||
product_version: MSI_VERSION.into(),
|
||||
payload_path: MSI_PAYLOAD.into(),
|
||||
payload_sha256: MSI_PAYLOAD_10_SHA256.into(),
|
||||
payload_bytes: MSI_PAYLOAD_BYTES,
|
||||
},
|
||||
no_reboot: true,
|
||||
package_code: None,
|
||||
predecessor: None,
|
||||
};
|
||||
ResolvedWindowsMsi {
|
||||
recipe_sha256: recipe.sha256().unwrap(),
|
||||
recipe,
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_action(m: ResolvedWindowsMsi) -> Action {
|
||||
Action::EnsurePackage {
|
||||
provider: "msi".into(),
|
||||
package: MSI_PACKAGE_ID.into(),
|
||||
version: m.recipe.postcondition.product_version.clone(),
|
||||
architecture: "x64".into(),
|
||||
recipe_version: m.recipe.recipe_version.clone(),
|
||||
installation_context: "machine".into(),
|
||||
recipe_id: Some(m.recipe.recipe_id.clone()),
|
||||
apt_manifest: None,
|
||||
windows_msi_manifest: Some(Box::new(m)),
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn exact_per_attempt_artifact_set_never_deduplicates_missing_extra_or_foreign_authority() {
|
||||
use rmm_domain::jobs::{JobArtifactReference, PlannedJob};
|
||||
let id = Uuid::new_v4();
|
||||
let now = chrono::Utc::now();
|
||||
let m = test_manifest(Uuid::new_v4(), &"ab".repeat(32), 32);
|
||||
let job = JobPayload {
|
||||
schema_version: 1,
|
||||
tenant_id: id,
|
||||
asset_id: id,
|
||||
agent_id: id,
|
||||
enrollment_generation: 1,
|
||||
assignment_version: 1,
|
||||
job_id: Uuid::new_v4(),
|
||||
attempt_id: Uuid::new_v4(),
|
||||
action: test_action(m.clone()),
|
||||
execution_identity: "system".into(),
|
||||
not_before: now,
|
||||
start_before: now + chrono::Duration::minutes(1),
|
||||
max_runtime_seconds: 30,
|
||||
max_output_bytes: 4096,
|
||||
};
|
||||
let plan = PlanPayload {
|
||||
schema_version: 1,
|
||||
plan_id: Uuid::new_v4(),
|
||||
tenant_id: id,
|
||||
principal: "test".into(),
|
||||
reason: "metadata only".into(),
|
||||
jobs: vec![PlannedJob {
|
||||
job_payload_hash: hash(&encode(&job).unwrap()),
|
||||
payload: job.clone(),
|
||||
script_sha256: None,
|
||||
}],
|
||||
max_parallel: 1,
|
||||
halt_after_failures: 1,
|
||||
recipe_references: vec![reference(&m)],
|
||||
artifact_references: vec![JobArtifactReference {
|
||||
job_id: job.job_id,
|
||||
attempt_id: job.attempt_id,
|
||||
artifact: artifact(&m),
|
||||
}],
|
||||
};
|
||||
validate_job_binding(&plan, &job).unwrap();
|
||||
for case in 0..9 {
|
||||
let mut bad = plan.clone();
|
||||
match case {
|
||||
0 => bad.artifact_references.clear(),
|
||||
1 => bad
|
||||
.artifact_references
|
||||
.push(bad.artifact_references[0].clone()),
|
||||
2 => bad.artifact_references[0].artifact.artifact_id = Uuid::new_v4(),
|
||||
3 => bad.artifact_references[0].artifact.size_bytes += 1,
|
||||
4 => bad.artifact_references[0].attempt_id = Uuid::new_v4(),
|
||||
5 => bad.jobs[0].payload.max_output_bytes += 1,
|
||||
6 => bad.recipe_references.clear(),
|
||||
7 => bad.recipe_references.push(bad.recipe_references[0].clone()),
|
||||
_ => {
|
||||
let mut extra = bad.recipe_references[0].clone();
|
||||
extra.sha256 = "ef".repeat(32);
|
||||
bad.recipe_references.push(extra);
|
||||
}
|
||||
}
|
||||
assert!(validate_job_binding(&bad, &job).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,8 +37,16 @@ struct SystemScope {
|
||||
// Administrative evidence pin, never an approval or authorization ID.
|
||||
acceptance_evidence_id: Uuid,
|
||||
allowed_services: Vec<String>,
|
||||
#[serde(default, deserialize_with = "strict_optional_hashes")]
|
||||
allowed_msi_recipe_sha256: Option<Vec<String>>,
|
||||
max_runtime_seconds: u32,
|
||||
}
|
||||
fn strict_optional_hashes<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
Vec::<String>::deserialize(deserializer).map(Some)
|
||||
}
|
||||
fn digest(value: &str) -> bool {
|
||||
value.len() == 64
|
||||
&& value
|
||||
@@ -86,9 +94,27 @@ impl SystemScope {
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.len()
|
||||
== self.allowed_services.len()
|
||||
&& self
|
||||
.allowed_msi_recipe_sha256
|
||||
.as_ref()
|
||||
.is_none_or(|hashes| {
|
||||
hashes.len() <= 2
|
||||
&& hashes.iter().all(|h| digest(h))
|
||||
&& hashes
|
||||
.iter()
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.len()
|
||||
== hashes.len()
|
||||
})
|
||||
&& (1..=120).contains(&self.max_runtime_seconds)
|
||||
}
|
||||
fn permits(&self, principal: &str, job: &JobPayload, capabilities: &[String]) -> bool {
|
||||
fn permits(
|
||||
&self,
|
||||
principal: &str,
|
||||
job: &JobPayload,
|
||||
capabilities: &[String],
|
||||
allow_msi: bool,
|
||||
) -> bool {
|
||||
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
|
||||
self.valid()
|
||||
&& job.execution_identity == "system"
|
||||
@@ -110,17 +136,40 @@ impl SystemScope {
|
||||
"helper.binary.sha256:{}",
|
||||
self.helper_binary_sha256
|
||||
))
|
||||
&& has("system:set_service_state")
|
||||
&& has("set_service_state")
|
||||
&& (1..=self.max_runtime_seconds).contains(&job.max_runtime_seconds)
|
||||
&& (1..=65536).contains(&job.max_output_bytes)
|
||||
&& matches!(&job.action,Action::SetServiceState{unit,state}
|
||||
if self.allowed_services.contains(unit) && matches!(state.as_str(),"running"|"stopped"))
|
||||
&& match &job.action {
|
||||
Action::SetServiceState { unit, state } => {
|
||||
self.allowed_services.contains(unit)
|
||||
&& matches!(state.as_str(), "running" | "stopped")
|
||||
&& has("system:set_service_state")
|
||||
&& has("set_service_state")
|
||||
}
|
||||
_ if allow_msi => job.action.windows_msi().is_some_and(|m| {
|
||||
job.action.validate()
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
||||
&& self
|
||||
.allowed_msi_recipe_sha256
|
||||
.as_ref()
|
||||
.is_some_and(|hashes| hashes.contains(&m.recipe_sha256))
|
||||
&& has("ensure_package")
|
||||
&& has("system:ensure_package")
|
||||
&& has(rmm_domain::windows_execution::MSI_CAPABILITY)
|
||||
}),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl SystemPolicy {
|
||||
fn valid(&self, now: DateTime<Utc>) -> bool {
|
||||
self.schema_version == 1
|
||||
matches!(self.schema_version, 1 | 2)
|
||||
&& (self.schema_version == 2
|
||||
|| self
|
||||
.scopes
|
||||
.iter()
|
||||
.all(|scope| scope.allowed_msi_recipe_sha256.is_none()))
|
||||
&& self.profile == "development"
|
||||
&& self.expires_at > now
|
||||
&& !self.scopes.is_empty()
|
||||
@@ -138,7 +187,7 @@ impl SystemPolicy {
|
||||
&& self
|
||||
.scopes
|
||||
.iter()
|
||||
.any(|scope| scope.permits(principal, job, capabilities))
|
||||
.any(|scope| scope.permits(principal, job, capabilities, self.schema_version == 2))
|
||||
}
|
||||
}
|
||||
fn disabled() -> Error {
|
||||
@@ -410,6 +459,29 @@ mod tests {
|
||||
assert!(serde_json::from_value::<SystemPolicy>(invalid).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn only_explicit_v2_hash_scope_and_package_caps_allow_fixed_msi() {
|
||||
let (mut policy, mut job, mut caps) = fixture();
|
||||
let m = crate::windows_msi_catalog::test_manifest(Uuid::new_v4(), &"ab".repeat(32), 32);
|
||||
job.action = crate::windows_msi_catalog::test_action(m.clone());
|
||||
caps.extend([
|
||||
"ensure_package".into(),
|
||||
"system:ensure_package".into(),
|
||||
rmm_domain::windows_execution::MSI_CAPABILITY.into(),
|
||||
]);
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
policy.scopes[0].allowed_msi_recipe_sha256 = Some(vec![m.recipe_sha256.clone()]);
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now())); // v1 remains SCM-only
|
||||
policy.schema_version = 2;
|
||||
assert!(policy.permits("selected", &job, &caps, Utc::now()));
|
||||
for index in caps.len() - 3..caps.len() {
|
||||
let mut short = caps.clone();
|
||||
short.remove(index);
|
||||
assert!(!policy.permits("selected", &job, &short, Utc::now()));
|
||||
}
|
||||
policy.scopes[0].allowed_msi_recipe_sha256 = Some(vec!["cd".repeat(32)]);
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
}
|
||||
#[test]
|
||||
fn policy_file_refuses_symlinks_public_mode_wrong_owner_and_writable_parent() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let directory = std::env::temp_dir().join(format!("rmm-windows-policy-{}", Uuid::new_v4()));
|
||||
|
||||
Reference in New Issue
Block a user