Separate SYSTEM policy and verify thirteen policy guards on cloud Linux
Rust development slice / linux (push) Failing after 7s
Rust development slice / linux (push) Failing after 7s
This commit is contained in:
@@ -317,9 +317,9 @@ pub async fn permit(
|
||||
if !payload.action.validate() {
|
||||
return Ok(denied("APT_MANIFEST_REQUIRED"));
|
||||
}
|
||||
if payload.execution_identity == "root" {
|
||||
if crate::root_policy::needs_helper(&payload.execution_identity) {
|
||||
let helper_ready: bool = sqlx::query_scalar(
|
||||
"SELECT helper_sync_ready FROM agent_installations WHERE agent_id=$1",
|
||||
"SELECT i.helper_sync_ready AND EXISTS(SELECT 1 FROM agent_sync_state s WHERE s.tenant_id=i.tenant_id AND s.agent_id=i.agent_id AND s.helper_journal_id IS NOT NULL) FROM agent_installations i WHERE i.agent_id=$1",
|
||||
)
|
||||
.bind(agent)
|
||||
.fetch_one(&mut *tx)
|
||||
@@ -332,7 +332,11 @@ pub async fn permit(
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return Ok(denied("ROOT_SCOPE_OR_HELPER_SYNC_REQUIRED"));
|
||||
return Ok(denied(if payload.execution_identity == "system" {
|
||||
"SYSTEM_SCOPE_OR_HELPER_SYNC_REQUIRED"
|
||||
} else {
|
||||
"ROOT_SCOPE_OR_HELPER_SYNC_REQUIRED"
|
||||
}));
|
||||
}
|
||||
}
|
||||
let sync: (bool, bool) = sqlx::query_as(
|
||||
@@ -497,7 +501,7 @@ 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,p.plan_hash,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 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);
|
||||
@@ -511,6 +515,19 @@ pub async fn next(
|
||||
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()
|
||||
{
|
||||
tx.commit().await?;
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
sqlx::query("UPDATE outbox SET lease_until=now()+interval '30 seconds' WHERE job_id=$1")
|
||||
.bind(row.get::<Uuid, _>("job_id"))
|
||||
.execute(&mut *tx)
|
||||
|
||||
@@ -384,7 +384,10 @@ pub async fn plan(
|
||||
if input.targets.asset_ids.is_empty()
|
||||
|| input.targets.asset_ids.len() > 100
|
||||
|| !input.action.validate_plan_shape()
|
||||
|| !matches!(input.execution_identity.as_str(), "agent_service" | "root")
|
||||
|| !matches!(
|
||||
input.execution_identity.as_str(),
|
||||
"agent_service" | "root" | "system"
|
||||
)
|
||||
|| !(1..=3600).contains(&input.max_runtime_seconds)
|
||||
|| input.max_output_bytes == 0
|
||||
|| input.max_output_bytes > 262144
|
||||
@@ -423,8 +426,8 @@ pub async fn plan(
|
||||
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 input.execution_identity == "root" && !p.permits_scope("root:execute") {
|
||||
return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
|
||||
if let Some(permission) = crate::root_policy::execution_permission(&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?;
|
||||
@@ -661,8 +664,11 @@ pub async fn submit(
|
||||
if matches!(job.payload.action, Action::QueryLogs { .. }) {
|
||||
crate::permissions::require_principal(&mut tx, p, "logs:read").await?;
|
||||
}
|
||||
if job.payload.execution_identity == "root" {
|
||||
crate::permissions::require_principal(&mut tx, p, "root:execute").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?;
|
||||
}
|
||||
if matches!(job.payload.action, Action::AptNativeAcceptance { .. }) {
|
||||
crate::permissions::require_principal(&mut tx, p, "apt:native_acceptance").await?;
|
||||
@@ -763,6 +769,11 @@ async fn authorize_http(
|
||||
return Err(fail("AUTHORIZATION_REVOKED"));
|
||||
}
|
||||
for job in &plan.jobs {
|
||||
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?;
|
||||
}
|
||||
let authorization = Uuid::new_v4();
|
||||
|
||||
@@ -21,6 +21,7 @@ mod root_policy;
|
||||
mod scheduler;
|
||||
mod synchronization;
|
||||
mod tls;
|
||||
mod windows_policy;
|
||||
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use axum::{
|
||||
|
||||
@@ -152,7 +152,7 @@ impl RootScope {
|
||||
capabilities: &[String],
|
||||
global_log_units: Option<&[String]>,
|
||||
) -> bool {
|
||||
if job.execution_identity != "root" {
|
||||
if job.execution_identity != "root" || capabilities.iter().any(|c| c == "windows.base/1") {
|
||||
return false;
|
||||
}
|
||||
if !self.matches_target(job)
|
||||
@@ -279,13 +279,26 @@ fn load() -> Result<RootPolicy, Error> {
|
||||
}
|
||||
Ok(policy)
|
||||
}
|
||||
pub fn execution_permission(identity: &str) -> Option<&'static str> {
|
||||
match identity {
|
||||
"root" => Some("root:execute"),
|
||||
"system" => Some("system:execute"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn needs_helper(identity: &str) -> bool {
|
||||
execution_permission(identity).is_some()
|
||||
}
|
||||
pub async fn authorize(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
principal: &str,
|
||||
job: &JobPayload,
|
||||
) -> Result<(), Error> {
|
||||
if job.execution_identity != "root" {
|
||||
return Ok(());
|
||||
match job.execution_identity.as_str() {
|
||||
"system" => return crate::windows_policy::authorize(tx, principal, job).await,
|
||||
"agent_service" => return Ok(()),
|
||||
"root" => {}
|
||||
_ => return Err(Error(StatusCode::FORBIDDEN, "EXECUTION_IDENTITY_DENIED")),
|
||||
}
|
||||
for permission in required_permissions(job, false) {
|
||||
crate::permissions::require(tx, principal, permission).await?;
|
||||
@@ -375,6 +388,9 @@ mod tests {
|
||||
assert!(scope.permits("selected", &job, &caps, None));
|
||||
assert!(!scope.permits("automation", &job, &caps, None));
|
||||
assert!(!scope.permits("selected", &job, &caps[..4], None));
|
||||
let mut windows = caps;
|
||||
windows.push("windows.base/1".into());
|
||||
assert!(!scope.permits("selected", &job, &windows, None));
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -504,6 +504,11 @@ pub async fn reconcile(
|
||||
decisions.push(decision);
|
||||
continue;
|
||||
}
|
||||
let missing_helper =
|
||||
crate::root_policy::needs_helper(&payload.execution_identity) && !helper_ready;
|
||||
if missing_helper {
|
||||
ready = false;
|
||||
}
|
||||
let grant = sqlx::query(
|
||||
"SELECT grant_id,payload,created_at FROM execution_permits WHERE job_id=$1 AND attempt_id=$2",
|
||||
)
|
||||
@@ -720,8 +725,7 @@ pub async fn reconcile(
|
||||
}
|
||||
.into();
|
||||
}
|
||||
if payload.execution_identity == "root" && !helper_ready {
|
||||
ready = false;
|
||||
if missing_helper {
|
||||
decision.unlock = false;
|
||||
decision.reason = "HELPER_JOURNAL_REQUIRED".into();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,453 @@
|
||||
//! Independent development-only Windows SYSTEM ceiling. Policy never approves a
|
||||
//! plan, publishes a capability, provisions a helper or substitutes for Sync.
|
||||
use crate::jobs::Error;
|
||||
use axum::http::StatusCode;
|
||||
use chrono::{DateTime, Utc};
|
||||
use rmm_domain::jobs::{Action, JobPayload};
|
||||
use serde::Deserialize;
|
||||
use sqlx::{Postgres, Transaction};
|
||||
use std::{
|
||||
fs::{self, File},
|
||||
io::Read,
|
||||
os::unix::fs::{MetadataExt, PermissionsExt},
|
||||
path::Path,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
const POLICY_LIMIT: u64 = 65536;
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SystemPolicy {
|
||||
schema_version: u32,
|
||||
profile: String,
|
||||
expires_at: DateTime<Utc>,
|
||||
scopes: Vec<SystemScope>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SystemScope {
|
||||
tenant_id: Uuid,
|
||||
asset_id: Uuid,
|
||||
agent_id: Uuid,
|
||||
enrollment_generation: u64,
|
||||
assignment_version: u64,
|
||||
principals: Vec<String>,
|
||||
helper_policy_sha256: String,
|
||||
helper_binary_sha256: String,
|
||||
// Administrative evidence pin, never an approval or authorization ID.
|
||||
acceptance_evidence_id: Uuid,
|
||||
allowed_services: Vec<String>,
|
||||
max_runtime_seconds: u32,
|
||||
}
|
||||
fn digest(value: &str) -> bool {
|
||||
value.len() == 64
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_digit() || b"abcdef".contains(&c))
|
||||
}
|
||||
fn fixture_service(name: &str) -> bool {
|
||||
name.starts_with("RmmDiscoveryFixture")
|
||||
&& name.len() > "RmmDiscoveryFixture".len()
|
||||
&& name.len() <= 80
|
||||
&& name
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
|
||||
}
|
||||
impl SystemScope {
|
||||
fn valid(&self) -> bool {
|
||||
!self.tenant_id.is_nil()
|
||||
&& !self.asset_id.is_nil()
|
||||
&& !self.agent_id.is_nil()
|
||||
&& self.enrollment_generation > 0
|
||||
&& self.assignment_version > 0
|
||||
&& !self.acceptance_evidence_id.is_nil()
|
||||
&& digest(&self.helper_policy_sha256)
|
||||
&& digest(&self.helper_binary_sha256)
|
||||
&& !self.principals.is_empty()
|
||||
&& self.principals.len() <= 64
|
||||
&& self
|
||||
.principals
|
||||
.iter()
|
||||
.all(|p| !p.trim().is_empty() && p.len() <= 256)
|
||||
&& self
|
||||
.principals
|
||||
.iter()
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.len()
|
||||
== self.principals.len()
|
||||
&& self.allowed_services.len() <= 16
|
||||
&& self
|
||||
.allowed_services
|
||||
.iter()
|
||||
.all(|name| fixture_service(name))
|
||||
&& self
|
||||
.allowed_services
|
||||
.iter()
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.len()
|
||||
== self.allowed_services.len()
|
||||
&& (1..=120).contains(&self.max_runtime_seconds)
|
||||
}
|
||||
fn permits(&self, principal: &str, job: &JobPayload, capabilities: &[String]) -> bool {
|
||||
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
|
||||
self.valid()
|
||||
&& job.execution_identity == "system"
|
||||
&& self.tenant_id == job.tenant_id
|
||||
&& self.asset_id == job.asset_id
|
||||
&& self.agent_id == job.agent_id
|
||||
&& self.enrollment_generation == job.enrollment_generation
|
||||
&& self.assignment_version == job.assignment_version
|
||||
&& self.principals.iter().any(|p| p == principal)
|
||||
&& has("windows.base/1")
|
||||
&& !has("linux.base/1")
|
||||
&& has("rmm.sync.v1")
|
||||
&& has("helper.system.v1")
|
||||
&& has(&format!(
|
||||
"helper.policy.sha256:{}",
|
||||
self.helper_policy_sha256
|
||||
))
|
||||
&& has(&format!(
|
||||
"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"))
|
||||
}
|
||||
}
|
||||
impl SystemPolicy {
|
||||
fn valid(&self, now: DateTime<Utc>) -> bool {
|
||||
self.schema_version == 1
|
||||
&& self.profile == "development"
|
||||
&& self.expires_at > now
|
||||
&& !self.scopes.is_empty()
|
||||
&& self.scopes.len() <= 64
|
||||
&& self.scopes.iter().all(SystemScope::valid)
|
||||
}
|
||||
fn permits(
|
||||
&self,
|
||||
principal: &str,
|
||||
job: &JobPayload,
|
||||
capabilities: &[String],
|
||||
now: DateTime<Utc>,
|
||||
) -> bool {
|
||||
self.valid(now)
|
||||
&& self
|
||||
.scopes
|
||||
.iter()
|
||||
.any(|scope| scope.permits(principal, job, capabilities))
|
||||
}
|
||||
}
|
||||
fn disabled() -> Error {
|
||||
Error(StatusCode::CONFLICT, "UNSUPPORTED_CAPABILITY")
|
||||
}
|
||||
fn no_symlink_components(path: &Path) -> Result<(), Error> {
|
||||
let absolute = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
std::env::current_dir().map_err(|_| disabled())?.join(path)
|
||||
};
|
||||
for component in absolute.ancestors() {
|
||||
if fs::symlink_metadata(component)
|
||||
.map_err(|_| disabled())?
|
||||
.file_type()
|
||||
.is_symlink()
|
||||
{
|
||||
return Err(disabled());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn protected_parent_chain(path: &Path, owner: u32) -> Result<(), Error> {
|
||||
// A private immediate parent can itself be renamed through an unsafe
|
||||
// ancestor. Trust every directory owner, and reject writable ancestors
|
||||
// unless their sticky bit protects the trusted-owned next component.
|
||||
// This deliberately preserves /tmp's root-owned sticky-directory contract.
|
||||
let absolute = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
std::env::current_dir().map_err(|_| disabled())?.join(path)
|
||||
};
|
||||
for ancestor in absolute.ancestors().skip(1) {
|
||||
let directory = fs::symlink_metadata(ancestor).map_err(|_| disabled())?;
|
||||
let mode = directory.permissions().mode();
|
||||
if !directory.is_dir()
|
||||
|| ![0, owner].contains(&directory.uid())
|
||||
|| (mode & 0o022 != 0 && mode & 0o1000 == 0)
|
||||
{
|
||||
return Err(disabled());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn protected_bytes(path: &Path, owner: u32) -> Result<Vec<u8>, Error> {
|
||||
no_symlink_components(path)?;
|
||||
protected_parent_chain(path, owner)?;
|
||||
let before = fs::symlink_metadata(path).map_err(|_| disabled())?;
|
||||
let parent = path.parent().ok_or_else(disabled)?;
|
||||
let directory = fs::symlink_metadata(parent).map_err(|_| disabled())?;
|
||||
if !before.is_file()
|
||||
|| before.uid() != owner
|
||||
|| before.permissions().mode() & 0o777 != 0o600
|
||||
|| before.len() > POLICY_LIMIT
|
||||
|| !directory.is_dir()
|
||||
|| ![0, owner].contains(&directory.uid())
|
||||
|| directory.permissions().mode() & 0o022 != 0
|
||||
{
|
||||
return Err(disabled());
|
||||
}
|
||||
// The protected immediate parent excludes unprivileged swaps. Additionally
|
||||
// bind the opened descriptor to the lstat identity and bound the actual read.
|
||||
let mut file = File::open(path).map_err(|_| disabled())?;
|
||||
let opened = file.metadata().map_err(|_| disabled())?;
|
||||
if opened.dev() != before.dev() || opened.ino() != before.ino() {
|
||||
return Err(disabled());
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
file.by_ref()
|
||||
.take(POLICY_LIMIT + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|_| disabled())?;
|
||||
no_symlink_components(path)?;
|
||||
protected_parent_chain(path, owner)?;
|
||||
let after = fs::symlink_metadata(path).map_err(|_| disabled())?;
|
||||
if bytes.len() as u64 > POLICY_LIMIT
|
||||
|| !after.is_file()
|
||||
|| after.dev() != before.dev()
|
||||
|| after.ino() != before.ino()
|
||||
|| after.uid() != owner
|
||||
|| after.permissions().mode() & 0o777 != 0o600
|
||||
|| after.len() != before.len()
|
||||
|| after.mtime() != before.mtime()
|
||||
|| after.mtime_nsec() != before.mtime_nsec()
|
||||
{
|
||||
return Err(disabled());
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
fn load() -> Result<SystemPolicy, Error> {
|
||||
if std::env::var("RMM_PROFILE").as_deref() != Ok("development")
|
||||
|| std::env::var("RMM_DEV_SYSTEM_ENABLED").as_deref() != Ok("true")
|
||||
{
|
||||
return Err(disabled());
|
||||
}
|
||||
let path = std::env::var("RMM_DEV_SYSTEM_POLICY_FILE").map_err(|_| disabled())?;
|
||||
let key =
|
||||
std::env::var("RMM_JOB_KEY_FILE").unwrap_or_else(|_| "devstate/jobs/ed25519.pem".into());
|
||||
// Inspect only signing-key metadata, never read/log/export the private key.
|
||||
no_symlink_components(Path::new(&key))?;
|
||||
let key = fs::symlink_metadata(key).map_err(|_| disabled())?;
|
||||
if !key.is_file() {
|
||||
return Err(disabled());
|
||||
}
|
||||
let policy: SystemPolicy =
|
||||
serde_json::from_slice(&protected_bytes(Path::new(&path), key.uid())?)
|
||||
.map_err(|_| disabled())?;
|
||||
if !policy.valid(Utc::now()) {
|
||||
return Err(disabled());
|
||||
}
|
||||
Ok(policy)
|
||||
}
|
||||
pub async fn authorize(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
principal: &str,
|
||||
job: &JobPayload,
|
||||
) -> Result<(), Error> {
|
||||
if job.execution_identity != "system" {
|
||||
return Err(Error(StatusCode::FORBIDDEN, "SYSTEM_IDENTITY_REQUIRED"));
|
||||
}
|
||||
// Independent DB permission; root:execute never implies this scope.
|
||||
crate::permissions::require(tx, principal, "system:execute").await?;
|
||||
let policy = load()?;
|
||||
let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND asset_id=$3 AND revoked_at IS NULL AND enrollment_generation=$4 AND assignment_version=$5").bind(job.tenant_id).bind(job.agent_id).bind(job.asset_id).bind(i64::try_from(job.enrollment_generation).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).bind(i64::try_from(job.assignment_version).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).fetch_optional(&mut **tx).await?.ok_or(Error(StatusCode::CONFLICT,"AUTHORIZATION_REVOKED"))?;
|
||||
let capabilities: Vec<String> = serde_json::from_value(caps)?;
|
||||
if !policy.permits(principal, job, &capabilities, Utc::now()) {
|
||||
return Err(Error(
|
||||
StatusCode::FORBIDDEN,
|
||||
"SYSTEM_SCOPE_OR_HELPER_POLICY_DENIED",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
fn fixture() -> (SystemPolicy, JobPayload, Vec<String>) {
|
||||
let id = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
let policy:SystemPolicy=serde_json::from_value(json!({"schema_version":1,"profile":"development","expires_at":now+chrono::Duration::minutes(10),"scopes":[{"tenant_id":id,"asset_id":id,"agent_id":id,"enrollment_generation":1,"assignment_version":1,"principals":["selected"],"helper_policy_sha256":"ab".repeat(32),"helper_binary_sha256":"cd".repeat(32),"acceptance_evidence_id":Uuid::new_v4(),"allowed_services":["RmmDiscoveryFixtureService"],"max_runtime_seconds":30}]})).unwrap();
|
||||
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: Action::SetServiceState {
|
||||
unit: "RmmDiscoveryFixtureService".into(),
|
||||
state: "running".into(),
|
||||
},
|
||||
execution_identity: "system".into(),
|
||||
not_before: now,
|
||||
start_before: now + chrono::Duration::minutes(5),
|
||||
max_runtime_seconds: 30,
|
||||
max_output_bytes: 4096,
|
||||
};
|
||||
let caps = vec![
|
||||
"windows.base/1".into(),
|
||||
"rmm.sync.v1".into(),
|
||||
"helper.system.v1".into(),
|
||||
format!("helper.policy.sha256:{}", "ab".repeat(32)),
|
||||
format!("helper.binary.sha256:{}", "cd".repeat(32)),
|
||||
"system:set_service_state".into(),
|
||||
"set_service_state".into(),
|
||||
];
|
||||
(policy, job, caps)
|
||||
}
|
||||
#[test]
|
||||
fn system_permission_and_helper_requirement_are_distinct_from_root() {
|
||||
let id = Uuid::new_v4();
|
||||
let principal = crate::auth::Principal {
|
||||
tenant: id,
|
||||
name: "root-only".into(),
|
||||
operator: true,
|
||||
session_hash: None,
|
||||
csrf: None,
|
||||
scopes: Some(std::collections::BTreeSet::from(["root:execute".into()])),
|
||||
testsimulation: false,
|
||||
identity: None,
|
||||
tenants: vec![id],
|
||||
};
|
||||
assert!(principal.permits_scope(crate::root_policy::execution_permission("root").unwrap()));
|
||||
assert!(
|
||||
!principal.permits_scope(crate::root_policy::execution_permission("system").unwrap())
|
||||
);
|
||||
assert!(crate::root_policy::needs_helper("system"));
|
||||
assert!(crate::root_policy::needs_helper("root"));
|
||||
assert!(!crate::root_policy::needs_helper("agent_service"));
|
||||
let (policy, job, caps) = fixture();
|
||||
let mut empty = policy;
|
||||
empty.scopes.clear();
|
||||
assert!(!empty.permits("selected", &job, &caps, Utc::now()));
|
||||
}
|
||||
#[test]
|
||||
fn exact_system_scope_never_inherits_root_or_other_device_authority() {
|
||||
let (policy, job, caps) = fixture();
|
||||
let now = Utc::now();
|
||||
assert!(policy.permits("selected", &job, &caps, now));
|
||||
assert!(!policy.permits("root-operator", &job, &caps, now));
|
||||
for identity in ["root", "agent_service", "SYSTEM"] {
|
||||
let mut other = job.clone();
|
||||
other.execution_identity = identity.into();
|
||||
assert!(!policy.permits("selected", &other, &caps, now));
|
||||
}
|
||||
for field in ["tenant", "asset", "agent", "enrollment", "assignment"] {
|
||||
let mut other = job.clone();
|
||||
match field {
|
||||
"tenant" => other.tenant_id = Uuid::new_v4(),
|
||||
"asset" => other.asset_id = Uuid::new_v4(),
|
||||
"agent" => other.agent_id = Uuid::new_v4(),
|
||||
"enrollment" => other.enrollment_generation += 1,
|
||||
_ => other.assignment_version += 1,
|
||||
}
|
||||
assert!(!policy.permits("selected", &other, &caps, now));
|
||||
}
|
||||
for i in 0..caps.len() {
|
||||
let mut missing = caps.clone();
|
||||
missing.remove(i);
|
||||
assert!(!policy.permits("selected", &job, &missing, now));
|
||||
}
|
||||
let mut mixed = caps.clone();
|
||||
mixed.push("linux.base/1".into());
|
||||
assert!(!policy.permits("selected", &job, &mixed, now));
|
||||
let mut wrong = caps.clone();
|
||||
wrong[4] = format!("helper.binary.sha256:{}", "ef".repeat(32));
|
||||
assert!(!policy.permits("selected", &job, &wrong, now));
|
||||
assert!(!policy.permits("selected", &job, &caps, policy.expires_at));
|
||||
}
|
||||
#[test]
|
||||
fn narrow_scm_ceiling_denies_unreviewed_effects_and_provider_inputs() {
|
||||
let (mut policy, mut job, caps) = fixture();
|
||||
let now = Utc::now();
|
||||
for (unit, state) in [
|
||||
("RmmDiscoveryWindows", "stopped"),
|
||||
("RmmDiscoverySystemHelper", "stopped"),
|
||||
("Spooler", "running"),
|
||||
("RmmDiscoveryFixtureService", "restarted"),
|
||||
] {
|
||||
job.action = Action::SetServiceState {
|
||||
unit: unit.into(),
|
||||
state: state.into(),
|
||||
};
|
||||
assert!(!policy.permits("selected", &job, &caps, now));
|
||||
}
|
||||
job.action = Action::RunScript {
|
||||
interpreter: "powershell".into(),
|
||||
script_utf8: "Write-Output 'hello'".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
};
|
||||
assert!(!policy.permits("selected", &job, &caps, now));
|
||||
job.action = Action::SetServiceState {
|
||||
unit: "RmmDiscoveryFixtureService".into(),
|
||||
state: "stopped".into(),
|
||||
};
|
||||
assert!(policy.permits("selected", &job, &caps, now));
|
||||
job.max_runtime_seconds = 31;
|
||||
assert!(!policy.permits("selected", &job, &caps, now));
|
||||
job.max_runtime_seconds = 30;
|
||||
policy.scopes[0].acceptance_evidence_id = Uuid::nil();
|
||||
assert!(!policy.permits("selected", &job, &caps, now));
|
||||
let invalid = json!({"schema_version":1,"profile":"development","expires_at":now,"scopes":[],"allow_system_scripts":true});
|
||||
assert!(serde_json::from_value::<SystemPolicy>(invalid).is_err());
|
||||
}
|
||||
#[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()));
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let path = directory.join("policy.json");
|
||||
fs::write(&path, b"{}").unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
let owner = fs::metadata(&path).unwrap().uid();
|
||||
assert_eq!(protected_bytes(&path, owner).unwrap(), b"{}");
|
||||
assert!(protected_bytes(&path, owner.wrapping_add(1)).is_err());
|
||||
let link = directory.join("link.json");
|
||||
symlink(&path, &link).unwrap();
|
||||
assert!(protected_bytes(&link, owner).is_err());
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).unwrap();
|
||||
assert!(protected_bytes(&path, owner).is_err());
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o770)).unwrap();
|
||||
assert!(protected_bytes(&path, owner).is_err());
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
fs::write(&path, vec![b' '; POLICY_LIMIT as usize + 1]).unwrap();
|
||||
assert!(protected_bytes(&path, owner).is_err());
|
||||
let real = directory.join("real");
|
||||
let nested = real.join("nested");
|
||||
fs::create_dir_all(&nested).unwrap();
|
||||
fs::set_permissions(&nested, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let data = nested.join("policy.json");
|
||||
fs::write(&data, b"{}").unwrap();
|
||||
fs::set_permissions(&data, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
// The immediate parent remains protected throughout. A writable
|
||||
// ancestor still permits substitution of that entire directory.
|
||||
fs::set_permissions(&real, fs::Permissions::from_mode(0o777)).unwrap();
|
||||
assert!(protected_bytes(&data, owner).is_err());
|
||||
fs::set_permissions(&real, fs::Permissions::from_mode(0o1777)).unwrap();
|
||||
assert_eq!(protected_bytes(&data, owner).unwrap(), b"{}");
|
||||
fs::set_permissions(&real, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let alias = directory.join("alias");
|
||||
symlink(&real, &alias).unwrap();
|
||||
assert!(protected_bytes(&alias.join("nested/policy.json"), owner).is_err());
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user