Files
rust-discovery/crates/agent-core/src/auth.rs
T
2026-11-14 21:48:21 +01:00

202 lines
6.9 KiB
Rust

//! Exact historical helper request/binding codecs and signed permit rules.
use crate::crypto::{DefaultVerifier, Ed25519Verifier};
use anyhow::{Result, ensure};
use chrono::{DateTime, Utc};
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload, hash};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Binding {
pub tenant_id: Uuid,
pub asset_id: Uuid,
pub agent_id: Uuid,
pub enrollment_generation: u64,
pub assignment_version: u64,
pub public_key_hex: String,
}
pub type AuthBinding = Binding;
impl Binding {
pub fn job(&self, bytes: &[u8]) -> Result<JobPayload> {
ensure!(bytes.len() <= 65536, "JOB_SIZE");
let j: JobPayload = serde_json::from_slice(bytes)?;
ensure!(
j.schema_version == 1
&& j.tenant_id == self.tenant_id
&& j.asset_id == self.asset_id
&& j.agent_id == self.agent_id
&& j.enrollment_generation == self.enrollment_generation
&& j.assignment_version == self.assignment_version,
"IDENTITY_BINDING"
);
ensure!(
j.action.validate()
&& j.action.valid_execution_identity(&j.execution_identity)
&& j.action
.valid_job_limits(j.max_runtime_seconds, j.max_output_bytes)
&& j.not_before < j.start_before,
"INVALID_JOB"
);
Ok(j)
}
pub fn verify(
&self,
request: &Request,
now: DateTime<Utc>,
) -> Result<(JobPayload, ExecutionPermitPayload)> {
self.verify_with(request, now, &DefaultVerifier::default())
}
pub fn verify_with(
&self,
request: &Request,
now: DateTime<Utc>,
verifier: &impl Ed25519Verifier,
) -> Result<(JobPayload, ExecutionPermitPayload)> {
let (job, p) = self.verify_signed_request(request, verifier)?;
ensure!(
permit_window(&job, &p) && now >= p.not_before && now < p.start_before,
"PERMIT_TIME"
);
Ok((job, p))
}
/// Evidence-only verification. This never supplies a current start window
/// and cannot be substituted for verify_with at an execution boundary.
pub fn verify_historical_for_denial_with(
&self,
request: &Request,
identity: HelperIdentity,
verifier: &impl Ed25519Verifier,
) -> Result<VerifiedHistoricalDenial> {
let (job, permit) = self.verify_signed_request(request, verifier)?;
ensure!(permit_window(&job, &permit), "PERMIT_TIME");
ensure!(
job.execution_identity == identity.as_str()
&& job.action.valid_helper_denial_shape(identity.as_str()),
"DENIAL_HELPER_SCOPE"
);
Ok(VerifiedHistoricalDenial {
request: request.clone(),
permit,
request_sha256: hash(&serde_json::to_vec(request)?),
})
}
fn verify_signed_request(
&self,
request: &Request,
verifier: &impl Ed25519Verifier,
) -> Result<(JobPayload, ExecutionPermitPayload)> {
let job = self.job(&request.job_bytes)?;
ensure!(
request.permit_bytes.len() <= 8192 && request.signature.len() == 64,
"PERMIT_SIZE"
);
let raw = hex::decode(&self.public_key_hex)?;
ensure!(raw.len() == 32, "TRUST_KEY_SIZE");
ensure!(
verifier.verify(&raw, &request.permit_bytes, &request.signature)?,
"INVALID_SIGNATURE"
);
let p: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
ensure!(
p.domain == "rmm.execution-permit"
&& p.schema_version == 1
&& p.key_id == hash(&raw)
&& !p.grant_id.is_nil()
&& !p.authorization_id.is_nil(),
"PERMIT_DOMAIN"
);
ensure!(
p.authorization_id == request.authorization_id
&& p.plan_hash == request.plan_hash
&& p.plan_hash.len() == 64
&& hex::decode(&p.plan_hash)?.len() == 32
&& p.job_payload_hash == hash(&request.job_bytes)
&& p.tenant_id == job.tenant_id
&& p.asset_id == job.asset_id
&& p.agent_id == job.agent_id
&& p.enrollment_generation == job.enrollment_generation
&& p.assignment_version == job.assignment_version
&& p.job_id == job.job_id
&& p.attempt_id == job.attempt_id
&& p.action == job.action.name()
&& if matches!(job.action, rmm_domain::jobs::Action::UpdateAgent { .. }) {
p.agent_update_plan_id.is_some_and(|id| !id.is_nil())
} else {
p.agent_update_plan_id.is_none()
}
&& p.execution_identity == job.execution_identity
&& p.max_runtime_seconds == job.max_runtime_seconds,
"PERMIT_BINDING"
);
Ok((job, p))
}
}
fn permit_window(job: &JobPayload, p: &ExecutionPermitPayload) -> bool {
p.not_before >= job.not_before
&& p.start_before <= job.start_before
&& p.not_before < p.start_before
&& (p.start_before - p.not_before).num_seconds() <= 60
}
/// Not serializable or constructible by an IPC caller. Only the deny-only
/// helper path consumes this evidence; it is never an execution authorization.
pub struct VerifiedHistoricalDenial {
pub(crate) request: Request,
pub(crate) permit: ExecutionPermitPayload,
pub(crate) request_sha256: String,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Request {
pub job_bytes: Vec<u8>,
pub permit_bytes: Vec<u8>,
pub signature: Vec<u8>,
pub plan_hash: String,
pub authorization_id: Uuid,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Outcome {
pub state: String,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub exit_code: Option<i32>,
pub output_truncated: bool,
pub reboot_required: bool,
pub evidence: serde_json::Value,
pub error_code: String,
}
impl Outcome {
pub fn unknown(code: &str) -> Self {
Self {
state: "unknown".into(),
stdout: vec![],
stderr: vec![],
exit_code: None,
output_truncated: false,
reboot_required: false,
evidence: serde_json::json!({"postconditions_passed":false}),
error_code: code.into(),
}
}
}
/// Explicit configured privileged identity; never infer SYSTEM from Linux root.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HelperIdentity {
#[default]
Root,
System,
}
impl HelperIdentity {
pub fn as_str(self) -> &'static str {
match self {
Self::Root => "root",
Self::System => "system",
}
}
}