134 lines
5.6 KiB
Rust
134 lines
5.6 KiB
Rust
use crate::{artifact_store::ArtifactStore, jobs::Error};
|
|
use axum::{
|
|
Extension,
|
|
extract::{Path, Query, State},
|
|
http::{HeaderMap, HeaderValue, StatusCode},
|
|
response::{IntoResponse, Response},
|
|
};
|
|
use rmm_domain::jobs::{JobPayload, PlanPayload};
|
|
use serde::Deserialize;
|
|
use sqlx::Row;
|
|
use uuid::Uuid;
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Chunk {
|
|
job_id: Uuid,
|
|
attempt_id: Uuid,
|
|
#[serde(default)]
|
|
offset: u64,
|
|
length: Option<u32>,
|
|
}
|
|
pub async fn download(
|
|
State(s): State<crate::State>,
|
|
Extension(peer): Extension<crate::Peer>,
|
|
h: HeaderMap,
|
|
Path(id): Path<Uuid>,
|
|
Query(q): Query<Chunk>,
|
|
) -> Result<Response, Error> {
|
|
if h.contains_key("authorization") {
|
|
return Err(Error(StatusCode::UNAUTHORIZED, "DEVICE_MTLS_REQUIRED"));
|
|
}
|
|
let (t, a) = crate::agent_http::identity(&s, peer)
|
|
.await
|
|
.map_err(|status| Error(status, "UNAUTHENTICATED"))?;
|
|
let length = q.length.unwrap_or(512 * 1024);
|
|
if length == 0 || length > 512 * 1024 {
|
|
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,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
|
|
{
|
|
return Err(Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
|
|
}
|
|
let reference = plan
|
|
.artifact_references
|
|
.iter()
|
|
.find(|r| {
|
|
r.job_id == q.job_id && r.attempt_id == q.attempt_id && r.artifact.artifact_id == id
|
|
})
|
|
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
|
|
let metadata = sqlx::query("SELECT sha256,size_bytes FROM artifacts WHERE artifact_id=$1")
|
|
.bind(id)
|
|
.fetch_optional(&mut *tx)
|
|
.await?
|
|
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
|
|
if reference.artifact.sha256 != metadata.get::<String, _>("sha256")
|
|
|| reference.artifact.size_bytes != metadata.get::<i64, _>("size_bytes") as u64
|
|
{
|
|
return Err(Error(StatusCode::CONFLICT, "ARTIFACT_BINDING_MISMATCH"));
|
|
}
|
|
tx.commit().await?;
|
|
let bytes = crate::catalog::store()?.get(t, &reference.artifact.sha256)?;
|
|
if bytes.len() as u64 != reference.artifact.size_bytes {
|
|
return Err(Error(
|
|
StatusCode::SERVICE_UNAVAILABLE,
|
|
"ARTIFACT_INTEGRITY_FAILURE",
|
|
));
|
|
}
|
|
if q.offset >= bytes.len() as u64 {
|
|
return Err(Error(
|
|
StatusCode::RANGE_NOT_SATISFIABLE,
|
|
"INVALID_ARTIFACT_RANGE",
|
|
));
|
|
}
|
|
let start = q.offset as usize;
|
|
let end = (start + length as usize).min(bytes.len());
|
|
let partial = start > 0 || end < bytes.len();
|
|
let mut response = (
|
|
if partial {
|
|
StatusCode::PARTIAL_CONTENT
|
|
} else {
|
|
StatusCode::OK
|
|
},
|
|
bytes[start..end].to_vec(),
|
|
)
|
|
.into_response();
|
|
let headers = response.headers_mut();
|
|
headers.insert(
|
|
"content-type",
|
|
HeaderValue::from_static("application/octet-stream"),
|
|
);
|
|
headers.insert(
|
|
"content-disposition",
|
|
HeaderValue::from_static("attachment"),
|
|
);
|
|
headers.insert(
|
|
"x-content-type-options",
|
|
HeaderValue::from_static("nosniff"),
|
|
);
|
|
headers.insert("accept-ranges", HeaderValue::from_static("bytes"));
|
|
headers.insert(
|
|
"x-artifact-sha256",
|
|
HeaderValue::from_str(&reference.artifact.sha256).map_err(|_| {
|
|
Error(
|
|
StatusCode::INTERNAL_SERVER_ERROR,
|
|
"ARTIFACT_INTEGRITY_FAILURE",
|
|
)
|
|
})?,
|
|
);
|
|
if partial {
|
|
headers.insert(
|
|
"content-range",
|
|
HeaderValue::from_str(&format!("bytes {}-{}/{}", start, end - 1, bytes.len()))
|
|
.map_err(|_| Error(StatusCode::INTERNAL_SERVER_ERROR, "VALIDATION_ERROR"))?,
|
|
);
|
|
}
|
|
Ok(response)
|
|
}
|