Recheck the submitting principal and protect stored log output
This commit is contained in:
@@ -36,7 +36,7 @@ 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,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 row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,z.principal AS approver,r.principal AS submitter,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") {
|
||||
@@ -46,8 +46,7 @@ pub async fn download(
|
||||
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?;
|
||||
crate::jobs::authorize_approved_job(&s, &mut tx, t, &plan, &job, &row).await?;
|
||||
}
|
||||
|
||||
if job.asset_id != row.get::<Uuid, _>("asset_id")
|
||||
|
||||
@@ -736,7 +736,7 @@ async fn download(
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).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') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL")
|
||||
let row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,z.principal AS approver,r.principal AS submitter,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') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL")
|
||||
.bind(agent).bind(q.job_id).bind(q.attempt_id).fetch_optional(&mut *tx).await?.ok_or_else(missing)?;
|
||||
let job: rmm_domain::jobs::JobPayload =
|
||||
serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
|
||||
@@ -749,8 +749,7 @@ async fn download(
|
||||
let rmm_domain::jobs::Action::UpdateAgent { update } = &job.action else {
|
||||
return Err(missing());
|
||||
};
|
||||
crate::root_policy::authorize(&mut tx, &plan.principal, &job).await?;
|
||||
crate::root_policy::authorize(&mut tx, &row.get::<String, _>("approver"), &job).await?;
|
||||
crate::jobs::authorize_approved_job(&s, &mut tx, tenant, &plan, &job, &row).await?;
|
||||
check_update(&mut tx, update).await?;
|
||||
if job.tenant_id != tenant
|
||||
|| job.agent_id != agent
|
||||
|
||||
@@ -528,7 +528,7 @@ pub async fn permit(
|
||||
denial_code: code.into(),
|
||||
unreserved_request: None,
|
||||
};
|
||||
let row=sqlx::query("SELECT j.*,a.authorization_id,a.revoked_at,a.principal AS approver,p.plan_hash,p.payload AS plan_payload,r.approval_state,i.enrollment_generation,i.assignment_version,i.asset_id AS bound_asset,i.capabilities,i.revoked_at AS device_revoked,i.connection_generation,t.changes_stopped FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=j.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id JOIN tenants t ON t.tenant_id=j.tenant_id WHERE j.job_id=$1 AND j.attempt_id=$2 AND j.agent_id=$3 FOR UPDATE OF j").bind(Uuid::parse_str(&r.job_id)?).bind(Uuid::parse_str(&r.attempt_id)?).bind(agent).fetch_optional(&mut *tx).await?;
|
||||
let row=sqlx::query("SELECT j.*,a.authorization_id,a.revoked_at,a.principal AS approver,r.principal AS submitter,p.plan_hash,p.payload AS plan_payload,r.approval_state,i.enrollment_generation,i.assignment_version,i.asset_id AS bound_asset,i.capabilities,i.revoked_at AS device_revoked,i.connection_generation,t.changes_stopped FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=j.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id JOIN tenants t ON t.tenant_id=j.tenant_id WHERE j.job_id=$1 AND j.attempt_id=$2 AND j.agent_id=$3 FOR UPDATE OF j").bind(Uuid::parse_str(&r.job_id)?).bind(Uuid::parse_str(&r.attempt_id)?).bind(agent).fetch_optional(&mut *tx).await?;
|
||||
let Some(row) = row else {
|
||||
return Ok(denied("NOT_FOUND"));
|
||||
};
|
||||
@@ -571,8 +571,6 @@ pub async fn permit(
|
||||
|| row
|
||||
.get::<Option<chrono::DateTime<Utc>>, _>("device_revoked")
|
||||
.is_some()
|
||||
|| !crate::jobs::requester_enabled(state, &mut tx, &plan.principal, tenant).await?
|
||||
|| !crate::jobs::requester_enabled(state, &mut tx, &row.get::<String, _>("approver"), tenant).await?
|
||||
{
|
||||
return Ok(denied("AUTHORIZATION_REVOKED"));
|
||||
}
|
||||
@@ -609,14 +607,7 @@ pub async fn permit(
|
||||
.bind(agent)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if !helper_ready
|
||||
|| crate::root_policy::authorize(&mut tx, &plan.principal, &payload)
|
||||
.await
|
||||
.is_err()
|
||||
|| crate::root_policy::authorize(&mut tx, &row.get::<String, _>("approver"), &payload)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
if !helper_ready {
|
||||
return Ok(denied(if payload.execution_identity == "system" {
|
||||
"SYSTEM_SCOPE_OR_HELPER_SYNC_REQUIRED"
|
||||
} else {
|
||||
@@ -684,23 +675,6 @@ pub async fn permit(
|
||||
{
|
||||
return Ok(denied("ARTIFACT_BINDING_MISMATCH"));
|
||||
}
|
||||
let approver: String = row.get("approver");
|
||||
if matches!(payload.action, Action::QueryLogs { .. })
|
||||
&& !crate::permissions::allowed(&mut tx, &plan.principal, "logs:read").await?
|
||||
{
|
||||
return Ok(denied("AUTHORIZATION_REVOKED"));
|
||||
}
|
||||
if !crate::permissions::allowed(&mut tx, &approver, "plans:approve").await?
|
||||
|| !crate::permissions::allowed(&mut tx, &plan.principal, "operations:submit").await?
|
||||
|| (matches!(payload.action, Action::RunScript { .. })
|
||||
&& (!crate::permissions::allowed(&mut tx, &plan.principal, "scripts:execute").await?
|
||||
|| !crate::permissions::allowed(&mut tx, &approver, "scripts:execute").await?))
|
||||
|| (matches!(payload.action, Action::UpdateAgent { .. })
|
||||
&& (!crate::permissions::allowed(&mut tx, &plan.principal, "updates:apply").await?
|
||||
|| !crate::permissions::allowed(&mut tx, &approver, "updates:apply").await?))
|
||||
{
|
||||
return Ok(denied("AUTHORIZATION_REVOKED"));
|
||||
}
|
||||
let limits: (i32, i32) =
|
||||
sqlx::query_as("SELECT starts_per_hour,max_parallel FROM tenant_limits")
|
||||
.fetch_one(&mut *tx)
|
||||
@@ -743,6 +717,21 @@ pub async fn permit(
|
||||
if locked {
|
||||
return Ok(denied("RESOURCE_LOCKED"));
|
||||
}
|
||||
let log_sensitive = crate::root_policy::stored_log_sensitivity(&payload);
|
||||
if let Err(error) =
|
||||
crate::jobs::authorize_approved_job(state, &mut tx, tenant, &plan, &payload, &row).await
|
||||
{
|
||||
if error.0.is_server_error() {
|
||||
anyhow::bail!("job authorization unavailable");
|
||||
}
|
||||
let code = match (error.1, payload.execution_identity.as_str()) {
|
||||
("AUTHORIZATION_REVOKED" | "FORBIDDEN", _) => "AUTHORIZATION_REVOKED",
|
||||
(_, "system") => "SYSTEM_SCOPE_OR_HELPER_SYNC_REQUIRED",
|
||||
(_, "root") => "ROOT_SCOPE_OR_HELPER_SYNC_REQUIRED",
|
||||
_ => "AUTHORIZATION_REVOKED",
|
||||
};
|
||||
return Ok(denied(code));
|
||||
}
|
||||
let grant = ExecutionPermitPayload {
|
||||
agent_update_plan_id: matches!(payload.action, Action::UpdateAgent { .. })
|
||||
.then_some(plan.plan_id),
|
||||
@@ -769,8 +758,9 @@ pub async fn permit(
|
||||
let bytes = encode(&grant)?;
|
||||
let signature = state.job_signer.sign(&bytes)?;
|
||||
sqlx::query("INSERT INTO execution_permits(tenant_id,grant_id,job_id,attempt_id,payload,signature) VALUES($1,$2,$3,$4,$5,$6)").bind(tenant).bind(grant.grant_id).bind(grant.job_id).bind(grant.attempt_id).bind(&bytes).bind(&signature).execute(&mut *tx).await?;
|
||||
sqlx::query("UPDATE jobs SET start_reserved=true WHERE job_id=$1")
|
||||
sqlx::query("UPDATE jobs SET start_reserved=true, log_sensitive=$2 WHERE job_id=$1")
|
||||
.bind(grant.job_id)
|
||||
.bind(log_sensitive)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query("INSERT INTO audit_events VALUES($1,$2,'job-service','start_reserved',$3,now())")
|
||||
@@ -804,54 +794,56 @@ pub async fn next(
|
||||
if let Some(r)=sqlx::query("SELECT job_id,attempt_id FROM jobs WHERE agent_id=$1 AND cancel_requested AND state IN ('accepted','running','verifying','awaiting_reboot') ORDER BY job_id LIMIT 1").bind(agent).fetch_optional(&mut *tx).await?{
|
||||
tx.commit().await?;return Ok(Some(Payload::CancelRequest(CancelRequest{job_id:r.get::<Uuid,_>("job_id").to_string(),attempt_id:r.get::<Uuid,_>("attempt_id").to_string(),reason:"operator_cancel_requested".into()})))
|
||||
}
|
||||
let row=sqlx::query("SELECT j.job_id,j.attempt_id,j.payload,j.payload_hash,a.authorization_id,a.principal AS approver,p.plan_hash,p.payload AS plan_payload,i.capabilities FROM outbox b JOIN jobs j USING(tenant_id,job_id,attempt_id) JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=j.tenant_id AND p.plan_id=r.plan_id JOIN tenants t ON t.tenant_id=j.tenant_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.state='queued' AND NOT j.cancel_requested AND NOT t.changes_stopped AND a.revoked_at IS NULL AND r.approval_state='approved' AND p.expires_at>now() AND b.acknowledged_at IS NULL AND (b.lease_until IS NULL OR b.lease_until<now()) ORDER BY j.job_id FOR UPDATE OF b SKIP LOCKED LIMIT 1").bind(agent).fetch_optional(&mut *tx).await?;
|
||||
let Some(row) = row else {
|
||||
tx.commit().await?;
|
||||
return Ok(None);
|
||||
};
|
||||
let payload: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
|
||||
let caps: Vec<String> = serde_json::from_value(row.get("capabilities"))?;
|
||||
if payload.action.windows_msi().is_some()
|
||||
|| matches!(payload.action, Action::UpdateAgent { .. })
|
||||
{
|
||||
// A revoked participant can leave a queued job behind. Skip that job
|
||||
// without leasing it so later eligible work on the same device can proceed.
|
||||
let mut after = None;
|
||||
let row = loop {
|
||||
let row=sqlx::query("SELECT j.job_id,j.attempt_id,j.payload,j.payload_hash,a.authorization_id,a.principal AS approver,r.principal AS submitter,p.plan_hash,p.payload AS plan_payload,i.capabilities FROM outbox b JOIN jobs j USING(tenant_id,job_id,attempt_id) JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=j.tenant_id AND p.plan_id=r.plan_id JOIN tenants t ON t.tenant_id=j.tenant_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND ($2::uuid IS NULL OR j.job_id>$2) AND j.state='queued' AND NOT j.cancel_requested AND NOT t.changes_stopped AND a.revoked_at IS NULL AND r.approval_state='approved' AND p.expires_at>now() AND b.acknowledged_at IS NULL AND (b.lease_until IS NULL OR b.lease_until<now()) ORDER BY j.job_id FOR UPDATE OF b SKIP LOCKED LIMIT 1").bind(agent).bind(after).fetch_optional(&mut *tx).await?;
|
||||
let Some(row) = row else {
|
||||
tx.commit().await?;
|
||||
return Ok(None);
|
||||
};
|
||||
after = Some(row.get::<Uuid, _>("job_id"));
|
||||
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()
|
||||
|| (matches!(payload.action, Action::UpdateAgent { .. })
|
||||
&& crate::agent_updates::validate_job_binding(&plan, &payload).is_err())
|
||||
|| crate::catalog::check(&mut tx, &payload.action)
|
||||
.await
|
||||
.is_err()
|
||||
if hash(&raw) != row.get::<String, _>("plan_hash") {
|
||||
continue;
|
||||
}
|
||||
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()
|
||||
|| matches!(payload.action, Action::UpdateAgent { .. })
|
||||
{
|
||||
tx.commit().await?;
|
||||
return Ok(None);
|
||||
if crate::windows_msi_catalog::validate_job_binding(&plan, &payload).is_err()
|
||||
|| (matches!(payload.action, Action::UpdateAgent { .. })
|
||||
&& crate::agent_updates::validate_job_binding(&plan, &payload).is_err())
|
||||
|| crate::catalog::check(&mut tx, &payload.action)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !payload
|
||||
.action
|
||||
.available_for(&payload.execution_identity, &caps)
|
||||
|| !payload
|
||||
if !payload
|
||||
.action
|
||||
.valid_job_limits(payload.max_runtime_seconds, payload.max_output_bytes)
|
||||
{
|
||||
tx.commit().await?;
|
||||
return Ok(None);
|
||||
}
|
||||
if crate::root_policy::needs_helper(&payload.execution_identity) {
|
||||
let plan: PlanPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("plan_payload"))?;
|
||||
if crate::root_policy::authorize(&mut tx, &plan.principal, &payload)
|
||||
.await
|
||||
.is_err()
|
||||
|| crate::root_policy::authorize(&mut tx, &row.get::<String, _>("approver"), &payload)
|
||||
.await
|
||||
.is_err()
|
||||
.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);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Err(error) =
|
||||
crate::jobs::authorize_approved_job(state, &mut tx, tenant, &plan, &payload, &row).await
|
||||
{
|
||||
if error.0.is_server_error() {
|
||||
anyhow::bail!("job authorization unavailable");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
break row;
|
||||
};
|
||||
sqlx::query("UPDATE outbox SET lease_until=now()+interval '30 seconds' WHERE job_id=$1")
|
||||
.bind(row.get::<Uuid, _>("job_id"))
|
||||
.execute(&mut *tx)
|
||||
|
||||
+138
-79
@@ -13,6 +13,7 @@ use rmm_domain::jobs::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
use std::collections::BTreeSet;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -606,21 +607,9 @@ pub(crate) async fn plan_resolved(
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
||||
policy(&mut tx).await?;
|
||||
crate::permissions::require_principal(&mut tx, p, "operations:plan").await?;
|
||||
if let Some(permission) = crate::root_policy::execution_permission(&input.execution_identity) {
|
||||
for permission in execution_permissions(&input.action, &input.execution_identity) {
|
||||
crate::permissions::require_principal(&mut tx, p, permission).await?;
|
||||
}
|
||||
if matches!(input.action, Action::AptNativeAcceptance { .. }) {
|
||||
crate::permissions::require_principal(&mut tx, p, "apt:native_acceptance").await?;
|
||||
}
|
||||
if matches!(input.action, Action::RunScript { .. }) {
|
||||
crate::permissions::require_principal(&mut tx, p, "scripts:execute").await?;
|
||||
}
|
||||
if matches!(input.action, Action::UpdateAgent { .. }) {
|
||||
crate::permissions::require_principal(&mut tx, p, "updates:apply").await?;
|
||||
}
|
||||
if matches!(input.action, Action::QueryLogs { .. }) {
|
||||
crate::permissions::require_principal(&mut tx, p, "logs:read").await?;
|
||||
}
|
||||
let recipe_references = crate::catalog::references(&mut tx, &input.action).await?;
|
||||
let artifacts = if let Action::UpdateAgent { update } = &input.action {
|
||||
if !input.artifact_ids.is_empty() {
|
||||
@@ -760,7 +749,99 @@ async fn load_plan(
|
||||
}
|
||||
Ok((serde_json::from_slice(&bytes)?, h, bytes))
|
||||
}
|
||||
fn execution_permissions(action: &Action, identity: &str) -> impl Iterator<Item = &'static str> {
|
||||
let action_permission = match action {
|
||||
Action::RunScript { .. } => Some("scripts:execute"),
|
||||
Action::UpdateAgent { .. } => Some("updates:apply"),
|
||||
Action::QueryLogs { .. } => Some("logs:read"),
|
||||
Action::AptNativeAcceptance { .. } => Some("apt:native_acceptance"),
|
||||
_ => None,
|
||||
};
|
||||
[
|
||||
action_permission,
|
||||
crate::root_policy::execution_permission(identity),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
struct JobParticipants<'a> {
|
||||
planner: &'a str,
|
||||
submitter: &'a str,
|
||||
approver: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> JobParticipants<'a> {
|
||||
fn distinct(&self) -> BTreeSet<&'a str> {
|
||||
[self.planner, self.submitter, self.approver].into()
|
||||
}
|
||||
|
||||
async fn require_roles(
|
||||
&self,
|
||||
state: &crate::State,
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
) -> Result<()> {
|
||||
for name in self.distinct() {
|
||||
if !requester_enabled(state, tx, name, tenant).await? {
|
||||
return Err(fail("AUTHORIZATION_REVOKED"));
|
||||
}
|
||||
}
|
||||
for (name, permission) in [
|
||||
(self.planner, "operations:plan"),
|
||||
(self.submitter, "operations:submit"),
|
||||
(self.submitter, "operations:read"),
|
||||
(self.approver, "plans:approve"),
|
||||
] {
|
||||
crate::permissions::require(tx, name, permission).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn authorize_approved_job(
|
||||
state: &crate::State,
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
plan: &PlanPayload,
|
||||
job: &JobPayload,
|
||||
row: &sqlx::postgres::PgRow,
|
||||
) -> Result<()> {
|
||||
let participants = JobParticipants {
|
||||
planner: &plan.principal,
|
||||
submitter: row.get("submitter"),
|
||||
approver: row.get("approver"),
|
||||
};
|
||||
if job.tenant_id != tenant || plan.tenant_id != tenant {
|
||||
return Err(fail("BINDING_MISMATCH"));
|
||||
}
|
||||
participants.require_roles(state, tx, tenant).await?;
|
||||
authorize_execution(tx, &participants.distinct(), job).await
|
||||
}
|
||||
|
||||
async fn authorize_execution(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
actors: &BTreeSet<&str>,
|
||||
job: &JobPayload,
|
||||
) -> Result<()> {
|
||||
for &name in actors {
|
||||
for permission in execution_permissions(&job.action, &job.execution_identity) {
|
||||
crate::permissions::require(tx, name, permission).await?;
|
||||
}
|
||||
crate::root_policy::authorize(tx, name, job).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Result<()> {
|
||||
recheck_for(tx, plan, &[plan.principal.as_str()].into()).await
|
||||
}
|
||||
|
||||
async fn recheck_for(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
plan: &PlanPayload,
|
||||
actors: &BTreeSet<&str>,
|
||||
) -> Result<()> {
|
||||
crate::script_library::validate_plan_bindings(plan)?;
|
||||
crate::windows_msi_catalog::validate_plan_bindings(plan)?;
|
||||
crate::agent_updates::validate_plan_bindings(plan)?;
|
||||
@@ -799,27 +880,6 @@ async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Resu
|
||||
}
|
||||
}
|
||||
crate::permissions::require(tx, &plan.principal, "operations:plan").await?;
|
||||
if plan
|
||||
.jobs
|
||||
.iter()
|
||||
.any(|j| matches!(j.payload.action, Action::RunScript { .. }))
|
||||
{
|
||||
crate::permissions::require(tx, &plan.principal, "scripts:execute").await?;
|
||||
}
|
||||
if plan
|
||||
.jobs
|
||||
.iter()
|
||||
.any(|j| matches!(j.payload.action, Action::UpdateAgent { .. }))
|
||||
{
|
||||
crate::permissions::require(tx, &plan.principal, "updates:apply").await?;
|
||||
}
|
||||
if plan
|
||||
.jobs
|
||||
.iter()
|
||||
.any(|j| matches!(j.payload.action, Action::QueryLogs { .. }))
|
||||
{
|
||||
crate::permissions::require(tx, &plan.principal, "logs:read").await?;
|
||||
}
|
||||
let mut references = Vec::new();
|
||||
for job in &plan.jobs {
|
||||
if !job.payload.action.valid_job_limits(
|
||||
@@ -831,7 +891,7 @@ async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Resu
|
||||
if !job.payload.action.validate() {
|
||||
return Err(Error(StatusCode::CONFLICT, "APT_MANIFEST_REQUIRED"));
|
||||
}
|
||||
crate::root_policy::authorize(tx, &plan.principal, &job.payload).await?;
|
||||
authorize_execution(tx, actors, &job.payload).await?;
|
||||
crate::catalog::check(tx, &job.payload.action).await?;
|
||||
references.extend(crate::catalog::references(tx, &job.payload.action).await?);
|
||||
if job.payload.start_before <= Utc::now() {
|
||||
@@ -906,24 +966,10 @@ pub async fn submit(
|
||||
let request_hash = hash(id.as_bytes());
|
||||
let (plan, _, _) = load_plan(&mut tx, id).await?;
|
||||
for job in &plan.jobs {
|
||||
if matches!(job.payload.action, Action::RunScript { .. }) {
|
||||
crate::permissions::require_principal(&mut tx, p, "scripts:execute").await?;
|
||||
}
|
||||
if matches!(job.payload.action, Action::UpdateAgent { .. }) {
|
||||
crate::permissions::require_principal(&mut tx, p, "updates:apply").await?;
|
||||
}
|
||||
if matches!(job.payload.action, Action::QueryLogs { .. }) {
|
||||
crate::permissions::require_principal(&mut tx, p, "logs:read").await?;
|
||||
}
|
||||
if let Some(permission) =
|
||||
crate::root_policy::execution_permission(&job.payload.execution_identity)
|
||||
{
|
||||
for permission in execution_permissions(&job.payload.action, &job.payload.execution_identity) {
|
||||
crate::permissions::require_principal(&mut tx, p, permission).await?;
|
||||
crate::root_policy::authorize(&mut tx, &p.name, &job.payload).await?;
|
||||
}
|
||||
if matches!(job.payload.action, Action::AptNativeAcceptance { .. }) {
|
||||
crate::permissions::require_principal(&mut tx, p, "apt:native_acceptance").await?;
|
||||
}
|
||||
crate::root_policy::authorize(&mut tx, &p.name, &job.payload).await?;
|
||||
}
|
||||
if let Some(row)=sqlx::query("SELECT request_hash,operation_id FROM operation_submissions WHERE principal=$1 AND idempotency_key=$2").bind(&p.name).bind(&input.idempotency_key).fetch_optional(&mut *tx).await? {
|
||||
if row.get::<String,_>("request_hash")!=request_hash{return Err(fail("IDEMPOTENCY_CONFLICT"))}
|
||||
@@ -970,6 +1016,28 @@ struct Authorize {
|
||||
fn approve_decision() -> String {
|
||||
"approve".into()
|
||||
}
|
||||
pub(crate) async fn recheck_approval(
|
||||
state: &crate::State,
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
plan: &PlanPayload,
|
||||
submitter: &str,
|
||||
approver: &Principal,
|
||||
) -> Result<()> {
|
||||
let participants = JobParticipants {
|
||||
planner: &plan.principal,
|
||||
submitter,
|
||||
approver: &approver.name,
|
||||
};
|
||||
participants.require_roles(state, tx, plan.tenant_id).await?;
|
||||
for job in &plan.jobs {
|
||||
if execution_permissions(&job.payload.action, &job.payload.execution_identity)
|
||||
.any(|permission| !approver.permits_scope(permission))
|
||||
{
|
||||
return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
|
||||
}
|
||||
}
|
||||
recheck_for(tx, plan, &participants.distinct()).await
|
||||
}
|
||||
async fn authorize_http(
|
||||
State(state): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
@@ -987,7 +1055,7 @@ async fn authorize_http(
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
||||
let row = sqlx::query(
|
||||
"SELECT operation_id,approval_state FROM approval_requests WHERE plan_id=$1 FOR UPDATE",
|
||||
"SELECT operation_id,approval_state,principal FROM approval_requests WHERE plan_id=$1 FOR UPDATE",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
@@ -1013,26 +1081,7 @@ async fn authorize_http(
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
} else {
|
||||
recheck(&mut tx, &plan).await?;
|
||||
// Both requester and approver retain explicit operator rights: the only
|
||||
// shipped dev principals are fixed-scope and cannot grant memberships.
|
||||
if !requester_enabled(&state, &mut tx, &plan.principal, tenant).await? {
|
||||
return Err(fail("AUTHORIZATION_REVOKED"));
|
||||
}
|
||||
for job in &plan.jobs {
|
||||
if matches!(job.payload.action, Action::RunScript { .. }) {
|
||||
crate::permissions::require_principal(&mut tx, &p, "scripts:execute").await?;
|
||||
}
|
||||
if matches!(job.payload.action, Action::UpdateAgent { .. }) {
|
||||
crate::permissions::require_principal(&mut tx, &p, "updates:apply").await?;
|
||||
}
|
||||
if let Some(permission) =
|
||||
crate::root_policy::execution_permission(&job.payload.execution_identity)
|
||||
{
|
||||
crate::permissions::require_principal(&mut tx, &p, permission).await?;
|
||||
}
|
||||
crate::root_policy::authorize(&mut tx, &p.name, &job.payload).await?;
|
||||
}
|
||||
recheck_approval(&state, &mut tx, &plan, row.get("principal"), &p).await?;
|
||||
let authorization = Uuid::new_v4();
|
||||
sqlx::query("INSERT INTO authorizations(tenant_id,authorization_id,operation_id,plan_id,plan_hash,principal,session_hash,approval_origin,testsimulation,policy_version) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,1)").bind(tenant).bind(authorization).bind(op).bind(id).bind(&ph).bind(&p.name).bind(session).bind(p.approval_origin()).bind(p.testsimulation).execute(&mut *tx).await?;
|
||||
sqlx::query("INSERT INTO operations VALUES($1,$2,$3)")
|
||||
@@ -1137,11 +1186,6 @@ pub async fn operation(
|
||||
tx.commit().await?;
|
||||
Ok(result)
|
||||
}
|
||||
fn job_view(r: &sqlx::postgres::PgRow) -> Value {
|
||||
let mut result = job_summary(r);
|
||||
result["result"] = r.get::<Option<Value>, _>("result").unwrap_or(Value::Null);
|
||||
result
|
||||
}
|
||||
fn job_summary(r: &sqlx::postgres::PgRow) -> Value {
|
||||
json!({"asset_id":r.get::<Uuid,_>("asset_id"),"agent_id":r.get::<Uuid,_>("agent_id"),"job_id":r.get::<Uuid,_>("job_id"),"attempt_id":r.get::<Uuid,_>("attempt_id"),"state":r.get::<String,_>("state"),"cancel_requested":r.get::<bool,_>("cancel_requested"),"revision":r.get::<i64,_>("revision"),"pending_reason":r.get::<Option<String>,_>("pending_reason")})
|
||||
}
|
||||
@@ -1150,14 +1194,29 @@ pub async fn job(state: &crate::State, p: &Principal, tenant: Uuid, id: Uuid) ->
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
|
||||
crate::permissions::require_principal(&mut tx, p, "operations:read").await?;
|
||||
let r = sqlx::query(
|
||||
"SELECT asset_id,agent_id,job_id,attempt_id,state,cancel_requested,revision,result,pending_reason FROM jobs WHERE job_id=$1",
|
||||
"SELECT asset_id,agent_id,job_id,attempt_id,state,cancel_requested,revision,result,pending_reason,
|
||||
convert_from(payload,'UTF8')::jsonb->'action'->>'action' AS action, log_sensitive
|
||||
FROM jobs WHERE job_id=$1",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or_else(missing)?;
|
||||
let mut view = job_summary(&r);
|
||||
let stored = r.get::<Option<Value>, _>("result");
|
||||
if let Some(result) = stored {
|
||||
if r.try_get::<String, _>("action")? == "query_logs"
|
||||
&& !crate::monitoring::LogReadAccess::for_principal(&mut tx, p).await?.permits(r.get("log_sensitive"))
|
||||
{
|
||||
view["result"] = json!({"output_restricted":true,"exit_code":result["exit_code"].as_i64()});
|
||||
} else {
|
||||
view["result"] = result;
|
||||
}
|
||||
} else {
|
||||
view["result"] = Value::Null;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(job_view(&r))
|
||||
Ok(view)
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
|
||||
@@ -316,6 +316,8 @@ async fn consume(pool: &PgPool, account: &Account, step: i64) -> Result<(), Stat
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
mod job_participants;
|
||||
|
||||
use super::*;
|
||||
use chrono::Utc;
|
||||
use serde_json::json;
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
use super::*;
|
||||
use crate::auth::Principal;
|
||||
use crate::jobs::{PlanInput, Rollout, Schedule, Submit, Targets};
|
||||
use rmm_domain::jobs::{Action, PlanPayload, encode};
|
||||
use rmm_protocol::{Envelope, ExecutionPermitRequest, Payload};
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
|
||||
async fn separate_roles_and_submitter_revocation_at_approval_and_start() {
|
||||
let admin = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let pool = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let tenant = Uuid::new_v4();
|
||||
let agent = Uuid::new_v4();
|
||||
let planner_name = format!("local:{}", Uuid::new_v4());
|
||||
let approver_name = format!("local:{}", Uuid::new_v4());
|
||||
let scopes = ["operations:submit", "operations:read", "scripts:execute"];
|
||||
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,$2)")
|
||||
.bind(tenant)
|
||||
.bind(format!("Participants {tenant}"))
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
for (actor, permissions) in [
|
||||
(&planner_name, vec!["operations:plan", "scripts:execute"]),
|
||||
(
|
||||
&approver_name,
|
||||
[scopes.as_slice(), &["plans:approve", "tokens:manage"]].concat(),
|
||||
),
|
||||
] {
|
||||
sqlx::query("INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES($1,$2,'human',$3)")
|
||||
.bind(tenant).bind(actor).bind(permissions).execute(&admin).await.unwrap();
|
||||
}
|
||||
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
|
||||
.bind(tenant)
|
||||
.bind(agent)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256,capabilities,connection_generation) VALUES($1,$2,$2,$3,$4,1)")
|
||||
.bind(tenant).bind(agent).bind(hash(agent.as_bytes())).bind(json!(["linux.base/1","run_script"]))
|
||||
.execute(&admin).await.unwrap();
|
||||
let mut accounts = sample(&planner_name, tenant, &"0".repeat(128));
|
||||
let mut reviewer = sample(&approver_name, tenant, &"0".repeat(128))["users"][0].clone();
|
||||
reviewer["username"] = json!("reviewer");
|
||||
accounts["users"].as_array_mut().unwrap().push(reviewer);
|
||||
let mut auth = crate::auth::Auth::from_env("development").await.unwrap();
|
||||
auth.local = Some(configured(&accounts));
|
||||
let key_dir = std::env::temp_dir().join(format!("rmm-roles-{tenant}"));
|
||||
let state = crate::State {
|
||||
auth: Arc::new(auth),
|
||||
pool: pool.clone(),
|
||||
signer: None,
|
||||
viewer_a: [0; 32],
|
||||
viewer_b: [1; 32],
|
||||
job_signer: Arc::new(
|
||||
crate::job_signer::JobSigner::load_or_create(&key_dir.join("test.key")).unwrap(),
|
||||
),
|
||||
};
|
||||
let planner = Principal {
|
||||
tenant,
|
||||
tenants: vec![tenant],
|
||||
name: planner_name,
|
||||
operator: true,
|
||||
scopes: None,
|
||||
session_hash: None,
|
||||
csrf: None,
|
||||
testsimulation: true,
|
||||
identity: None,
|
||||
};
|
||||
let approver = Principal {
|
||||
name: approver_name,
|
||||
..planner.clone()
|
||||
};
|
||||
|
||||
for stage in [
|
||||
"revoked_before_approval",
|
||||
"revoked_before_start",
|
||||
"scope_removed",
|
||||
"allowed",
|
||||
] {
|
||||
let token_id = Uuid::new_v4();
|
||||
let raw = format!("rmm_mcp_{}AAAAAAAAAAA", token_id.simple());
|
||||
let mut tx = rmm_persistence::tenant_tx(&pool, tenant).await.unwrap();
|
||||
sqlx::query("SELECT issue_customer_token($1,$2,'submit fixture',$3,$4,now()+interval '1 hour',false,$5)")
|
||||
.bind(&approver.name).bind(token_id).bind(hash(raw.as_bytes())).bind(scopes.as_slice())
|
||||
.bind(vec![tenant]).execute(&mut *tx).await.unwrap();
|
||||
tx.commit().await.unwrap();
|
||||
let submitter = crate::mcp_tokens::authenticate(&state, &raw, Some(tenant))
|
||||
.await
|
||||
.unwrap();
|
||||
let now = Utc::now();
|
||||
let input = PlanInput {
|
||||
targets: Targets {
|
||||
asset_ids: vec![agent],
|
||||
},
|
||||
action: Action::RunScript {
|
||||
interpreter: "posix_sh".into(),
|
||||
script_utf8: ":\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
privileged_script_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
max_runtime_seconds: 30,
|
||||
max_output_bytes: 1024,
|
||||
script_variants: vec![],
|
||||
artifact_ids: vec![],
|
||||
schedule: Schedule {
|
||||
not_before: now,
|
||||
start_before: now + chrono::Duration::hours(1),
|
||||
},
|
||||
rollout: Rollout {
|
||||
max_parallel: 1,
|
||||
halt_after_failures: 1,
|
||||
},
|
||||
reason: stage.into(),
|
||||
};
|
||||
let saved = crate::jobs::plan(&state, &planner, tenant, input)
|
||||
.await
|
||||
.unwrap();
|
||||
let plan: PlanPayload = serde_json::from_value(saved["payload"].clone()).unwrap();
|
||||
let order = crate::jobs::submit(
|
||||
&state,
|
||||
&submitter,
|
||||
tenant,
|
||||
plan.plan_id,
|
||||
Submit {
|
||||
idempotency_key: stage.into(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let op: Uuid = serde_json::from_value(order["operation_id"].clone()).unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&pool, tenant).await.unwrap();
|
||||
let stored_submitter: String =
|
||||
sqlx::query_scalar("SELECT principal FROM approval_requests WHERE operation_id=$1")
|
||||
.bind(op)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(stored_submitter, submitter.name);
|
||||
|
||||
if stage == "revoked_before_approval" {
|
||||
assert!(revoke(&mut tx, &approver, token_id).await);
|
||||
assert_eq!(
|
||||
crate::jobs::recheck_approval(&state, &mut tx, &plan, &stored_submitter, &approver)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.1,
|
||||
"AUTHORIZATION_REVOKED"
|
||||
);
|
||||
let (status, jobs, permits): (String, i64, i64) = sqlx::query_as(
|
||||
"SELECT approval_state,(SELECT count(*) FROM jobs WHERE operation_id=$1),(SELECT count(*) FROM execution_permits WHERE job_id=$2) FROM approval_requests WHERE operation_id=$1"
|
||||
).bind(op).bind(plan.jobs[0].payload.job_id).fetch_one(&mut *tx).await.unwrap();
|
||||
assert_eq!((status.as_str(), jobs, permits), ("pending_approval", 0, 0));
|
||||
tx.commit().await.unwrap();
|
||||
continue;
|
||||
}
|
||||
crate::jobs::recheck_approval(&state, &mut tx, &plan, &stored_submitter, &approver)
|
||||
.await
|
||||
.unwrap();
|
||||
tx.commit().await.unwrap();
|
||||
|
||||
// Isolated ledger fixture for the normal gateway entry point. No client is connected.
|
||||
let job = &plan.jobs[0];
|
||||
let id = Uuid::new_v4();
|
||||
sqlx::query("UPDATE approval_requests SET approval_state='approved' WHERE operation_id=$1")
|
||||
.bind(op)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO authorizations(tenant_id,authorization_id,operation_id,plan_id,plan_hash,principal,session_hash,approval_origin,testsimulation,policy_version) VALUES($1,$2,$3,$4,$5,$6,'fixture','dev_test_browser_simulation',true,1)")
|
||||
.bind(tenant).bind(id).bind(op).bind(plan.plan_id).bind(saved["plan_hash"].as_str().unwrap()).bind(&approver.name)
|
||||
.execute(&admin).await.unwrap();
|
||||
sqlx::query("INSERT INTO operations VALUES($1,$2,$3)")
|
||||
.bind(tenant)
|
||||
.bind(op)
|
||||
.bind(id)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO jobs(tenant_id,job_id,attempt_id,operation_id,agent_id,asset_id,payload,payload_hash,state,resource,journal_proof) VALUES($1,$2,$3,$4,$5,$5,$6,$7,'queued','device_execution','fixture')")
|
||||
.bind(tenant).bind(job.payload.job_id).bind(job.payload.attempt_id).bind(op).bind(agent)
|
||||
.bind(encode(&job.payload).unwrap()).bind(&job.job_payload_hash).execute(&admin).await.unwrap();
|
||||
|
||||
sqlx::query("INSERT INTO outbox(tenant_id,job_id,attempt_id) VALUES($1,$2,$3)")
|
||||
.bind(tenant)
|
||||
.bind(job.payload.job_id)
|
||||
.bind(job.payload.attempt_id)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
if stage == "revoked_before_start" {
|
||||
let mut tx = rmm_persistence::tenant_tx(&pool, tenant).await.unwrap();
|
||||
assert!(revoke(&mut tx, &approver, token_id).await);
|
||||
tx.commit().await.unwrap();
|
||||
} else if stage == "scope_removed" {
|
||||
sqlx::query("UPDATE memberships SET permissions=array_remove(permissions,'scripts:execute') WHERE tenant_id=$1 AND principal=$2")
|
||||
.bind(tenant).bind(&submitter.name).execute(&admin).await.unwrap();
|
||||
}
|
||||
let offer = crate::job_gateway::next(&state, tenant, agent, 1)
|
||||
.await
|
||||
.unwrap();
|
||||
if stage == "allowed" {
|
||||
assert!(
|
||||
matches!(offer, Some(Payload::JobOffer(o)) if o.job_id == job.payload.job_id.to_string())
|
||||
);
|
||||
} else {
|
||||
assert!(offer.is_none());
|
||||
let leased: bool =
|
||||
sqlx::query_scalar("SELECT lease_until IS NOT NULL FROM outbox WHERE job_id=$1")
|
||||
.bind(job.payload.job_id)
|
||||
.fetch_one(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!leased);
|
||||
}
|
||||
// Also model acceptance before the same revocation, so the start gate is exercised independently.
|
||||
sqlx::query("UPDATE jobs SET state='accepted' WHERE job_id=$1")
|
||||
.bind(job.payload.job_id)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let envelope = Envelope {
|
||||
connection_generation: 1,
|
||||
..Default::default()
|
||||
};
|
||||
let request = ExecutionPermitRequest {
|
||||
job_id: job.payload.job_id.to_string(),
|
||||
attempt_id: job.payload.attempt_id.to_string(),
|
||||
job_payload_hash: job.job_payload_hash.clone(),
|
||||
assignment_version: job.payload.assignment_version,
|
||||
};
|
||||
let permit = crate::job_gateway::permit(&state, tenant, agent, &envelope, &request)
|
||||
.await
|
||||
.unwrap();
|
||||
let (reserved, count): (bool, i64) = sqlx::query_as("SELECT start_reserved,(SELECT count(*) FROM execution_permits WHERE job_id=$1) FROM jobs WHERE job_id=$1")
|
||||
.bind(job.payload.job_id).fetch_one(&admin).await.unwrap();
|
||||
if stage == "allowed" {
|
||||
assert_eq!(permit.denial_code, "");
|
||||
assert!(!permit.signature.is_empty());
|
||||
assert_eq!((reserved, count), (true, 1));
|
||||
} else {
|
||||
assert_eq!(permit.denial_code, "AUTHORIZATION_REVOKED");
|
||||
assert!(permit.payload_bytes.is_empty() && permit.signature.is_empty());
|
||||
assert_eq!((reserved, count), (false, 0));
|
||||
// A still-queued denied fixture must not prevent delivery of the next allowed job.
|
||||
sqlx::query("UPDATE jobs SET state='queued' WHERE job_id=$1")
|
||||
.bind(job.payload.job_id)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(key_dir).unwrap();
|
||||
}
|
||||
|
||||
async fn revoke(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
approver: &Principal,
|
||||
id: Uuid,
|
||||
) -> bool {
|
||||
sqlx::query_scalar("SELECT revoke_mcp_token($1,$2,$3,$4)")
|
||||
.bind(&approver.name)
|
||||
.bind(id)
|
||||
.bind(Uuid::new_v4())
|
||||
.bind(&approver.tenants)
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
@@ -17,9 +17,10 @@ use std::collections::BTreeSet;
|
||||
use uuid::Uuid;
|
||||
|
||||
const PREFIX: &str = "rmm_mcp_";
|
||||
const SCOPES: [&str; 11] = [
|
||||
const SCOPES: [&str; 12] = [
|
||||
"inventory:read",
|
||||
"logs:read",
|
||||
"logs:read_sensitive",
|
||||
"operations:read",
|
||||
"operations:plan",
|
||||
"operations:submit",
|
||||
@@ -371,7 +372,7 @@ async fn authenticate_pool(
|
||||
name: principal,
|
||||
operator: effective
|
||||
.iter()
|
||||
.any(|scope| !READ_SCOPES.contains(&scope.as_str())),
|
||||
.any(|scope| !READ_SCOPES.contains(&scope.as_str()) && scope != "logs:read_sensitive"),
|
||||
session_hash: None,
|
||||
csrf: None,
|
||||
scopes: Some(effective),
|
||||
@@ -427,6 +428,7 @@ async fn enabled(pool: &PgPool, principal: &str, tenant: Uuid) -> bool {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
mod stored_logs;
|
||||
|
||||
#[test]
|
||||
fn mcp_token_selection_is_explicit_and_bounded() {
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
use super::*;
|
||||
use crate::monitoring::{LogQuery, query};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
|
||||
async fn stored_results_require_current_log_rights_on_both_read_paths() {
|
||||
let admin = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let pool = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let tenant = Uuid::parse_str(rmm_domain::TENANT_A).unwrap();
|
||||
let foreign = Uuid::parse_str(rmm_domain::TENANT_B).unwrap();
|
||||
let asset = Uuid::new_v4();
|
||||
let actor = format!("local:{}", Uuid::new_v4());
|
||||
let temp = std::env::temp_dir().join(format!("stored-logs-{asset}"));
|
||||
let state = crate::State {
|
||||
pool,
|
||||
signer: None,
|
||||
viewer_a: [0; 32],
|
||||
viewer_b: [1; 32],
|
||||
auth: Arc::new(crate::auth::Auth::from_env("development").await.unwrap()),
|
||||
job_signer: Arc::new(
|
||||
crate::job_signer::JobSigner::load_or_create(&temp.join("key.pem")).unwrap(),
|
||||
),
|
||||
};
|
||||
sqlx::query("INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES($1,$2,'human',ARRAY['tokens:manage','operations:read','logs:read','logs:read_sensitive'])")
|
||||
.bind(tenant).bind(&actor).execute(&admin).await.unwrap();
|
||||
let mut readers = Vec::new();
|
||||
for scopes in [
|
||||
vec!["operations:read"],
|
||||
vec!["operations:read", "logs:read"],
|
||||
vec!["operations:read", "logs:read", "logs:read_sensitive"],
|
||||
] {
|
||||
let (_, token) = mint(&state.pool, tenant, &actor, &scopes).await;
|
||||
let p = authenticate_pool(&state.pool, &token, Some(tenant))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!p.operator);
|
||||
readers.push(p);
|
||||
}
|
||||
|
||||
// Terminal history with inert synthetic bytes, no gateway, outbox or permits.
|
||||
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
|
||||
.bind(tenant)
|
||||
.bind(asset)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256) VALUES($1,$2,$2,$3)").bind(tenant).bind(asset).bind(hash(asset.as_bytes())).execute(&admin).await.unwrap();
|
||||
let operation = Uuid::new_v4();
|
||||
sqlx::query("INSERT INTO operation_plans(tenant_id,plan_id,principal,payload,plan_hash,expires_at) VALUES($1,$2,$3,'{}','fixture',now())").bind(tenant).bind(operation).bind(&actor).execute(&admin).await.unwrap();
|
||||
sqlx::query("INSERT INTO approval_requests(tenant_id,operation_id,plan_id,principal,idempotency_key,request_hash,approval_state) VALUES($1,$2,$2,$3,'fixture','fixture','approved')").bind(tenant).bind(operation).bind(&actor).execute(&admin).await.unwrap();
|
||||
sqlx::query("INSERT INTO authorizations(tenant_id,authorization_id,operation_id,plan_id,plan_hash,principal,session_hash,approval_origin,testsimulation,policy_version) VALUES($1,$2,$2,$2,'fixture',$3,'fixture','dev_test_browser_simulation',true,1)").bind(tenant).bind(operation).bind(&actor).execute(&admin).await.unwrap();
|
||||
sqlx::query("INSERT INTO operations VALUES($1,$2,$2)")
|
||||
.bind(tenant)
|
||||
.bind(operation)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let until = Utc::now();
|
||||
let since = until - Duration::minutes(5);
|
||||
let query_for = |unit: &str| LogQuery {
|
||||
tenant_id: tenant,
|
||||
asset_id: asset,
|
||||
since: since - Duration::seconds(1),
|
||||
until: until + Duration::seconds(1),
|
||||
unit: unit.into(),
|
||||
max_lines: 10,
|
||||
live: false,
|
||||
idempotency_key: None,
|
||||
};
|
||||
let stored = json!({"exit_code":0,"stdout":[65],"stderr":[66],"evidence":{"fixture":true},"error_code":"fixture"});
|
||||
let restricted = json!({"exit_code":0,"output_restricted":true});
|
||||
let mut secure_job = Uuid::nil();
|
||||
for (unit, classification) in [
|
||||
("ordinary.service", Some(false)),
|
||||
("custom-audit.service", Some(true)),
|
||||
("legacy.service", None),
|
||||
] {
|
||||
let job = Uuid::new_v4();
|
||||
let bytes = serde_json::to_vec(&json!({"action":{"action":"query_logs","unit":unit,"since":since,"until":until,"max_lines":10}})).unwrap();
|
||||
sqlx::query("INSERT INTO jobs(tenant_id,job_id,attempt_id,operation_id,agent_id,asset_id,payload,payload_hash,state,resource,result,log_sensitive) VALUES($1,$2,$2,$3,$4,$4,$5,'fixture','succeeded','device_execution',$6,$7)")
|
||||
.bind(tenant).bind(job).bind(operation).bind(asset).bind(bytes).bind(&stored).bind(classification).execute(&admin).await.unwrap();
|
||||
for (index, p) in readers.iter().enumerate() {
|
||||
let permitted = index == 2 || (index == 1 && classification == Some(false));
|
||||
let detail = crate::jobs::job(&state, p, tenant, job).await.unwrap();
|
||||
assert_eq!(detail["state"], "succeeded");
|
||||
assert_eq!(
|
||||
&detail["result"],
|
||||
if permitted { &stored } else { &restricted }
|
||||
);
|
||||
let logs = query(&state, p, query_for(unit)).await;
|
||||
if permitted {
|
||||
assert_eq!(logs.unwrap()["items"][0]["result"], stored);
|
||||
} else {
|
||||
assert_eq!(logs.unwrap_err().0, StatusCode::FORBIDDEN);
|
||||
}
|
||||
}
|
||||
if classification == Some(true) {
|
||||
secure_job = job;
|
||||
}
|
||||
}
|
||||
// Keep the previously authenticated reader and remove just the issuer's
|
||||
// extra permission. The next read must consult current tenant membership.
|
||||
sqlx::query("UPDATE memberships SET permissions=array_remove(permissions,'logs:read_sensitive') WHERE tenant_id=$1 AND principal=$2")
|
||||
.bind(tenant).bind(&actor).execute(&admin).await.unwrap();
|
||||
let reader = &readers[2];
|
||||
assert_eq!(
|
||||
crate::jobs::job(&state, reader, tenant, secure_job)
|
||||
.await
|
||||
.unwrap()["result"],
|
||||
restricted
|
||||
);
|
||||
assert_eq!(
|
||||
query(&state, reader, query_for("custom-audit.service"))
|
||||
.await
|
||||
.unwrap_err()
|
||||
.0,
|
||||
StatusCode::FORBIDDEN
|
||||
);
|
||||
assert_eq!(
|
||||
crate::jobs::job(&state, reader, foreign, secure_job)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.0,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
let mut other = query_for("custom-audit.service");
|
||||
other.tenant_id = foreign;
|
||||
assert_eq!(
|
||||
query(&state, reader, other).await.unwrap_err().0,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
std::fs::remove_dir_all(temp).unwrap();
|
||||
}
|
||||
@@ -37,12 +37,39 @@ pub struct LogQuery {
|
||||
pub live: bool,
|
||||
pub idempotency_key: Option<String>,
|
||||
}
|
||||
/// Both result endpoints use the reader's current token scope and tenant membership.
|
||||
pub(crate) struct LogReadAccess {
|
||||
ordinary: bool,
|
||||
sensitive: bool,
|
||||
}
|
||||
|
||||
impl LogReadAccess {
|
||||
pub(crate) async fn for_principal(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
p: &crate::auth::Principal,
|
||||
) -> Result<Self, crate::jobs::Error> {
|
||||
let ordinary = p.permits_scope("logs:read")
|
||||
&& crate::permissions::allowed(tx, &p.name, "logs:read").await?;
|
||||
let sensitive = ordinary
|
||||
&& p.permits_scope("logs:read_sensitive")
|
||||
&& crate::permissions::allowed(tx, &p.name, "logs:read_sensitive").await?;
|
||||
Ok(Self {
|
||||
ordinary,
|
||||
sensitive,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn permits(&self, stored_sensitivity: Option<bool>) -> bool {
|
||||
self.ordinary && (stored_sensitivity == Some(false) || self.sensitive)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query(
|
||||
s: &crate::State,
|
||||
p: &crate::auth::Principal,
|
||||
i: LogQuery,
|
||||
) -> Result<Value, crate::jobs::Error> {
|
||||
crate::jobs::scope(p, i.tenant_id, true)?;
|
||||
crate::jobs::scope(p, i.tenant_id, i.live)?;
|
||||
let action = rmm_domain::jobs::Action::QueryLogs {
|
||||
unit: i.unit.clone(),
|
||||
since: i.since,
|
||||
@@ -141,7 +168,10 @@ pub async fn query(
|
||||
.await;
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, i.tenant_id).await?;
|
||||
crate::permissions::require_principal(&mut tx, p, "logs:read").await?;
|
||||
let access = LogReadAccess::for_principal(&mut tx, p).await?;
|
||||
if !access.ordinary {
|
||||
return Err(crate::jobs::Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
|
||||
}
|
||||
let exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM assets WHERE asset_id=$1)")
|
||||
.bind(i.asset_id)
|
||||
.fetch_one(&mut *tx)
|
||||
@@ -149,38 +179,37 @@ pub async fn query(
|
||||
if !exists {
|
||||
return Err(crate::jobs::Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
|
||||
}
|
||||
let rows=sqlx::query("SELECT j.job_id,j.payload,j.result FROM jobs j WHERE j.asset_id=$1 AND j.state='succeeded' AND j.result IS NOT NULL ORDER BY job_id LIMIT 100").bind(i.asset_id).fetch_all(&mut *tx).await?;
|
||||
let rows = sqlx::query(
|
||||
"SELECT job_id, result, log_sensitive, action->>'since' AS observed_from, action->>'until' AS observed_until
|
||||
FROM jobs CROSS JOIN LATERAL (SELECT convert_from(payload, 'UTF8')::jsonb->'action' AS action) AS log
|
||||
WHERE asset_id=$1 AND state='succeeded' AND result IS NOT NULL AND action->>'action'='query_logs'
|
||||
AND action->>'unit'=$2 AND (action->>'since')::timestamptz >= $3 AND (action->>'until')::timestamptz <= $4
|
||||
ORDER BY job_id LIMIT 101",
|
||||
).bind(i.asset_id).bind(&i.unit).bind(i.since).bind(i.until).fetch_all(&mut *tx).await?;
|
||||
let mut items = Vec::new();
|
||||
let mut size = 0;
|
||||
let mut lines = 0usize;
|
||||
let mut truncated = false;
|
||||
for r in rows {
|
||||
let payload: rmm_domain::jobs::JobPayload =
|
||||
serde_json::from_slice(&r.get::<Vec<u8>, _>("payload"))?;
|
||||
if let rmm_domain::jobs::Action::QueryLogs {
|
||||
unit, since, until, ..
|
||||
} = payload.action
|
||||
&& unit == i.unit
|
||||
&& since >= i.since
|
||||
&& until <= i.until
|
||||
{
|
||||
let result: Value = r.get("result");
|
||||
let len = result.to_string().len();
|
||||
let stdout = result.get("stdout").and_then(Value::as_array);
|
||||
let count = stdout
|
||||
.map(|bytes| {
|
||||
bytes.iter().filter(|v| v.as_u64() == Some(10)).count()
|
||||
+ usize::from(bytes.last().is_some_and(|v| v.as_u64() != Some(10)))
|
||||
})
|
||||
.unwrap_or(0);
|
||||
if size + len > 262144 || lines + count > i.max_lines as usize {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
size += len;
|
||||
lines += count;
|
||||
items.push(json!({"job_id":r.get::<Uuid,_>("job_id"),"source_id":unit,"observed_from":since,"observed_until":until,"result":result}));
|
||||
let mut truncated = rows.len() > 100;
|
||||
for r in rows.into_iter().take(100) {
|
||||
if !access.permits(r.get("log_sensitive")) {
|
||||
return Err(crate::jobs::Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
|
||||
}
|
||||
let result: Value = r.get("result");
|
||||
let len = result.to_string().len();
|
||||
let stdout = result.get("stdout").and_then(Value::as_array);
|
||||
let count = stdout
|
||||
.map(|bytes| {
|
||||
bytes.iter().filter(|v| v.as_u64() == Some(10)).count()
|
||||
+ usize::from(bytes.last().is_some_and(|v| v.as_u64() != Some(10)))
|
||||
})
|
||||
.unwrap_or(0);
|
||||
if size + len > 262144 || lines + count > i.max_lines as usize {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
size += len;
|
||||
lines += count;
|
||||
items.push(json!({"job_id":r.get::<Uuid,_>("job_id"),"source_id":i.unit,"observed_from":r.get::<String,_>("observed_from"),"observed_until":r.get::<String,_>("observed_until"),"result":result}));
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(
|
||||
|
||||
@@ -85,6 +85,15 @@ fn parse_log_units(raw: Option<&str>) -> Result<Option<Vec<String>>, Error> {
|
||||
}
|
||||
Ok(Some(units))
|
||||
}
|
||||
fn configured_sensitive_units() -> Result<Option<Vec<String>>, Error> {
|
||||
match std::env::var("RMM_ROOT_SENSITIVE_LOG_UNITS") {
|
||||
Ok(raw) => parse_log_units(Some(&raw)),
|
||||
Err(std::env::VarError::NotPresent) => Ok(None),
|
||||
Err(std::env::VarError::NotUnicode(_)) => {
|
||||
Err(Error(StatusCode::CONFLICT, "ROOT_LOG_ALLOWLIST_INVALID"))
|
||||
}
|
||||
}
|
||||
}
|
||||
impl RootLogPolicy {
|
||||
fn valid(&self) -> bool {
|
||||
self.schema_version == 1
|
||||
@@ -92,17 +101,45 @@ impl RootLogPolicy {
|
||||
&& valid_log_units(&self.sensitive_units)
|
||||
}
|
||||
}
|
||||
impl RootPolicy {
|
||||
fn sensitive_log_unit(&self, job: &JobPayload, unit: &str, extra: Option<&[String]>) -> bool {
|
||||
matches!(unit, "ssh.service" | "sshd.service" | "auditd.service" | "systemd-logind.service")
|
||||
|| (unit.starts_with("sshd@") && unit.ends_with(".service"))
|
||||
|| extra.is_some_and(|units| units.iter().any(|u| u == unit))
|
||||
// Classification is shared across matching target scopes, not just
|
||||
// the first scope/actor that grants a unit. Another scope cannot
|
||||
// silently declassify a sensitive source.
|
||||
|| self.scopes.iter().any(|scope| scope.matches_target(job)
|
||||
&& scope.root_logs.as_ref().is_some_and(|logs| logs.sensitive_units.iter().any(|u| u == unit)))
|
||||
}
|
||||
fn sensitive_log_unit(
|
||||
policy: Option<&RootPolicy>,
|
||||
job: &JobPayload,
|
||||
unit: &str,
|
||||
extra: Option<&[String]>,
|
||||
) -> bool {
|
||||
matches!(unit, "ssh.service" | "sshd.service" | "auditd.service" | "systemd-logind.service")
|
||||
|| (unit.starts_with("sshd@") && unit.ends_with(".service"))
|
||||
|| extra.is_some_and(|units| units.iter().any(|u| u == unit))
|
||||
// Any matching scope can classify the source, regardless of principal.
|
||||
|| policy.is_some_and(|p| p.scopes.iter().any(|scope| scope.matches_target(job)
|
||||
&& scope.root_logs.as_ref().is_some_and(|logs| logs.sensitive_units.iter().any(|u| u == unit))))
|
||||
}
|
||||
|
||||
/// Record the source classification alongside the grant. Readers in a separate
|
||||
/// API profile cannot reconstruct an expired or replaced gateway policy.
|
||||
pub(crate) fn stored_log_sensitivity(job: &JobPayload) -> Option<bool> {
|
||||
let Action::QueryLogs { unit, .. } = &job.action else {
|
||||
return None;
|
||||
};
|
||||
let Ok(extra) = configured_sensitive_units() else {
|
||||
return Some(true);
|
||||
};
|
||||
let policy = if std::env::var_os("RMM_DEV_ROOT_POLICY_FILE").is_some()
|
||||
|| std::env::var("RMM_DEV_ROOT_ENABLED").as_deref() == Ok("true")
|
||||
{
|
||||
let Ok(policy) = load() else {
|
||||
return Some(true);
|
||||
};
|
||||
Some(policy)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Some(sensitive_log_unit(
|
||||
policy.as_ref(),
|
||||
job,
|
||||
unit,
|
||||
extra.as_deref(),
|
||||
))
|
||||
}
|
||||
fn required_permissions(job: &JobPayload, sensitive_log: bool) -> Vec<&'static str> {
|
||||
let mut permissions = vec!["root:execute"];
|
||||
@@ -350,12 +387,8 @@ pub async fn authorize(
|
||||
None
|
||||
};
|
||||
if let Action::QueryLogs { unit, .. } = &job.action {
|
||||
let sensitive_units = parse_log_units(
|
||||
std::env::var("RMM_ROOT_SENSITIVE_LOG_UNITS")
|
||||
.ok()
|
||||
.as_deref(),
|
||||
)?;
|
||||
if policy.sensitive_log_unit(job, unit, sensitive_units.as_deref()) {
|
||||
let sensitive_units = configured_sensitive_units()?;
|
||||
if sensitive_log_unit(Some(&policy), job, unit, sensitive_units.as_deref()) {
|
||||
// Re-read current membership on every planning/approval/start call.
|
||||
// No policy flag, viewer role, capability or test profile grants it.
|
||||
crate::permissions::require(tx, principal, "logs:read_sensitive").await?;
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
-- The immutable job payload binds the exact log source and target. NULL on a
|
||||
-- QueryLogs job means no grant-time classification exists (including history).
|
||||
ALTER TABLE jobs ADD COLUMN log_sensitive boolean;
|
||||
GRANT UPDATE(log_sensitive) ON jobs TO rmm_app;
|
||||
|
||||
ALTER TABLE mcp_tokens DROP CONSTRAINT mcp_tokens_scopes_check;
|
||||
ALTER TABLE mcp_tokens ADD CONSTRAINT mcp_tokens_scopes_check CHECK (
|
||||
cardinality(scopes) BETWEEN 1 AND 12 AND scopes <@ ARRAY[
|
||||
'inventory:read','logs:read','logs:read_sensitive','operations:read','operations:plan',
|
||||
'operations:submit','jobs:cancel','scripts:execute','system:execute','root:execute',
|
||||
'updates:apply','catalog:write']::text[]
|
||||
);
|
||||
@@ -53,8 +53,17 @@ Sensitive classifications are unioned across all scopes for the same target, so
|
||||
choosing another principal/scope cannot declassify a source. ssh.service,
|
||||
sshd.service, sshd@*.service instances, auditd.service and systemd-logind.service
|
||||
are always sensitive, even if a configured sensitive list is empty. No membership
|
||||
is seeded or changed by this patch. Stored result-reader APIs are unchanged;
|
||||
this profile governs root execution authorization, not a new general data grant.
|
||||
receives sensitive-log access by default.
|
||||
|
||||
A new grant for `query_logs` records the source classification on its job. The
|
||||
immutable payload identifies the exact source and target. Stored log queries
|
||||
and individual job reads enforce the reader’s current tenant permissions and
|
||||
credential scopes. All log output requires `logs:read`. Sensitive sources and
|
||||
historical jobs without a recorded classification also require
|
||||
`logs:read_sensitive`. An operations reader can still see the job state and
|
||||
numeric exit code. The result then carries `output_restricted: true` and omits
|
||||
the protected output, evidence and free-text fields. Only explicitly selected
|
||||
token scopes can convey the additional permission.
|
||||
|
||||
Root log jobs bind one exact unit and UTC interval, with nonnegative timestamps,
|
||||
positive interval **at most exactly 24h** (no rounded-hour widening), 1–1000 lines,
|
||||
|
||||
@@ -184,7 +184,12 @@ fn classification_cannot_be_bypassed_by_another_scope_or_empty_env() {
|
||||
other.agent_id = job.agent_id;
|
||||
other.principals = vec!["another-actor".into()];
|
||||
policy.scopes.push(other);
|
||||
assert!(policy.sensitive_log_unit(&job, "rmm-acceptance.service", Some(&[])));
|
||||
assert!(sensitive_log_unit(
|
||||
Some(&policy),
|
||||
&job,
|
||||
"rmm-acceptance.service",
|
||||
Some(&[])
|
||||
));
|
||||
for unit in [
|
||||
"ssh.service",
|
||||
"sshd.service",
|
||||
@@ -192,10 +197,20 @@ fn classification_cannot_be_bypassed_by_another_scope_or_empty_env() {
|
||||
"auditd.service",
|
||||
"systemd-logind.service",
|
||||
] {
|
||||
assert!(policy.sensitive_log_unit(&job, unit, Some(&[])));
|
||||
assert!(sensitive_log_unit(Some(&policy), &job, unit, Some(&[])));
|
||||
}
|
||||
assert!(policy.sensitive_log_unit(&job, "custom.service", Some(&["custom.service".into()])));
|
||||
assert!(!policy.sensitive_log_unit(&job, "ordinary.service", None));
|
||||
assert!(sensitive_log_unit(
|
||||
Some(&policy),
|
||||
&job,
|
||||
"custom.service",
|
||||
Some(&["custom.service".into()])
|
||||
));
|
||||
assert!(!sensitive_log_unit(
|
||||
Some(&policy),
|
||||
&job,
|
||||
"ordinary.service",
|
||||
None
|
||||
));
|
||||
}
|
||||
#[test]
|
||||
fn permissions_are_separate_root_read_and_sensitive_requirements() {
|
||||
|
||||
@@ -66,3 +66,11 @@ it('selects the native PowerShell text view only from matching result evidence',
|
||||
const other = renderToStaticMarkup(<ConsoleOutput job={{result:{...result,evidence:{interpreter:'posix_sh',output_encoding:'raw_native_bytes'}}}}/>);
|
||||
expect(other).not.toContain('bösartig');
|
||||
});
|
||||
|
||||
it('shows the stored exit code and permission message for a restricted log result', () => {
|
||||
const html = renderToStaticMarkup(<ConsoleOutput job={{state:'succeeded', result:{output_restricted:true, exit_code:0}}}/>);
|
||||
expect(html).toContain('Exitcode 0');
|
||||
expect(html).toContain('Leseberechtigung');
|
||||
expect(html).not.toContain('herunterladen');
|
||||
expect(html).not.toContain('Noch kein gespeichertes Ergebnis');
|
||||
});
|
||||
|
||||
@@ -77,6 +77,10 @@ function Result({ value }: { value: unknown }) {
|
||||
const windowsUpdate = evidence.script_sha256 === windowsUpdateScriptHash;
|
||||
const reboot = windowsUpdate && Object.hasOwn(evidence, 'windows_update_reboot_required') ? evidence.windows_update_reboot_required : result.reboot_required;
|
||||
const exit = typeof result.exit_code === 'number' && Number.isInteger(result.exit_code) ? String(result.exit_code) : 'Nicht gemeldet';
|
||||
if (result.output_restricted === true) return <>
|
||||
<p><strong>Exitcode {exit}</strong></p>
|
||||
<p>Für diese Protokollausgabe fehlt dir die Leseberechtigung.</p>
|
||||
</>;
|
||||
return <>
|
||||
<p><strong>Exitcode {exit}</strong>{typeof result.error_code === 'string' && result.error_code && ' · Fehlercode '+result.error_code}</p>
|
||||
{reboot === true && <p className="warning">Ein Neustart ist erforderlich.</p>}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ApiError, record, request, tenant, tenantPath, type Tenant, type Sessio
|
||||
const scopeLabels = {
|
||||
'inventory:read': 'Inventar lesen',
|
||||
'logs:read': 'Gespeicherte Protokolle lesen',
|
||||
'logs:read_sensitive': 'Sensible Protokolle lesen',
|
||||
'operations:read': 'Aufträge und Ergebnisse lesen',
|
||||
'operations:plan': 'Aufträge planen',
|
||||
'operations:submit': 'Aufträge zur Genehmigung einreichen',
|
||||
|
||||
Reference in New Issue
Block a user