381 lines
14 KiB
Rust
381 lines
14 KiB
Rust
//! 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());
|
|
}
|
|
}
|
|
}
|