Files
rust-discovery/crates/server/src/agent_service.rs
T
2026-11-13 15:55:35 +01:00

193 lines
8.7 KiB
Rust

//! One durable ingestion service for WSS and HTTPS; transport only frames replies.
use anyhow::{Context, Result, ensure};
use chrono::{DateTime, Utc};
use prost::Message;
use rmm_domain::MAX_MESSAGE;
use rmm_protocol::*;
use sha2::{Digest, Sha256};
use sqlx::Row;
use uuid::Uuid;
pub fn reply(e: &Envelope, payload: Payload, generation: u64) -> Envelope {
Envelope {
protocol_major: 1,
protocol_minor: 0,
message_id: Uuid::new_v4().to_string(),
agent_id: e.agent_id.clone(),
enrollment_generation: 1,
connection_generation: generation,
boot_id: e.boot_id.clone(),
sequence: e.sequence,
observed_at: Utc::now().timestamp_millis(),
payload: Some(payload),
}
}
pub async fn binding(state: &crate::State, fingerprint: &str) -> Result<(Uuid, Uuid)> {
sqlx::query_as("SELECT tenant_id,agent_id FROM device_binding($1)")
.bind(fingerprint)
.fetch_optional(&state.pool)
.await?
.context("device not authorized")
}
pub async fn control_lock(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
tenant: Uuid,
agent: Uuid,
) -> Result<()> {
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))")
.bind(format!("agent-control:{tenant}:{agent}"))
.execute(&mut **tx)
.await?;
Ok(())
}
pub async fn open(
state: &crate::State,
tenant: Uuid,
agent: Uuid,
e: &Envelope,
transport: &str,
) -> Result<Envelope> {
ensure!(valid_envelope(e, &agent.to_string(), 0), "invalid hello");
let Some(Payload::ClientHello(client)) = &e.payload else {
anyhow::bail!("hello required")
};
let observed =
DateTime::from_timestamp_millis(e.observed_at).context("invalid hello timestamp")?;
ensure!(
(Utc::now() - observed).num_seconds().unsigned_abs() <= 45,
"hello clock outside window"
);
ensure!(
client.capabilities.len() <= 64 && client.capabilities.iter().all(|c| c.len() <= 128),
"capability bound"
);
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
control_lock(&mut tx, tenant, agent).await?;
let generation:i64=sqlx::query_scalar("UPDATE agent_installations SET connection_generation=connection_generation+1,capabilities=$2,transport=$3,connection_boot_id=$4,restore_blocked=restore_blocked OR $5<=last_sequence,sequence_regressed=sequence_regressed OR $5<=last_sequence,sync_required=$6,sync_ready=NOT $6,helper_sync_ready=false,last_sequence=$5 WHERE agent_id=$1 AND revoked_at IS NULL RETURNING connection_generation").bind(agent).bind(serde_json::to_value(&client.capabilities)?).bind(transport).bind(Uuid::parse_str(&e.boot_id)?).bind(i64::try_from(e.sequence)?).bind(client.capabilities.iter().any(|c|c=="rmm.sync.v1")).fetch_one(&mut *tx).await?;
tx.commit().await?;
Ok(reply(
e,
Payload::ServerHello(ServerHello {
connection_generation: u64::try_from(generation)?,
max_message_bytes: MAX_MESSAGE as u32,
}),
u64::try_from(generation)?,
))
}
pub async fn ingest(
state: &crate::State,
tenant: Uuid,
agent: Uuid,
e: &Envelope,
transport: &str,
) -> Result<Envelope> {
ensure!(
valid_envelope(e, &agent.to_string(), e.connection_generation),
"invalid envelope"
);
let job = matches!(
e.payload,
Some(Payload::JobAccepted(_) | Payload::JobStateChanged(_) | Payload::JobResult(_))
);
let durable = job || matches!(e.payload, Some(Payload::InventorySnapshot(_)));
let observed =
DateTime::from_timestamp_millis(e.observed_at).context("invalid observation time")?;
let age = (Utc::now() - observed).num_seconds();
ensure!(
age >= -45 && (job || age <= if durable { 72 * 3600 } else { 45 }),
"stale/future envelope"
);
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
control_lock(&mut tx, tenant, agent).await?;
let row=sqlx::query("SELECT revoked_at,connection_generation,transport,connection_boot_id,last_sequence,capabilities FROM agent_installations WHERE agent_id=$1 FOR UPDATE").bind(agent).fetch_one(&mut *tx).await?;
let active = row.get::<Option<DateTime<Utc>>, _>("revoked_at").is_none()
&& row.get::<i64, _>("connection_generation") == i64::try_from(e.connection_generation)?
&& row.get::<String, _>("transport") == transport;
ensure!(active || job, "revoked/fenced channel");
let rate:i32=sqlx::query_scalar("UPDATE agent_installations SET ingress_count=CASE WHEN ingress_window<now()-interval '1 second' THEN 1 ELSE ingress_count+1 END,ingress_window=CASE WHEN ingress_window<now()-interval '1 second' THEN now() ELSE ingress_window END WHERE agent_id=$1 RETURNING ingress_count").bind(agent).fetch_one(&mut *tx).await?;
ensure!(rate <= 20, "device ingress rate limit");
if !durable {
ensure!(
active
&& row.get::<Option<Uuid>, _>("connection_boot_id")
== Some(Uuid::parse_str(&e.boot_id)?)
&& i64::try_from(e.sequence)? > row.get::<i64, _>("last_sequence"),
"fresh message replay"
);
}
if active {
sqlx::query("UPDATE agent_installations SET last_sequence=GREATEST(last_sequence,$2) WHERE agent_id=$1").bind(agent).bind(i64::try_from(e.sequence)?).execute(&mut *tx).await?;
}
if let Some(Payload::SyncRequest(request)) = &e.payload {
let response =
crate::synchronization::reconcile(state, &mut tx, tenant, agent, e, request).await?;
tx.commit().await?;
return Ok(reply(
e,
Payload::SyncResponse(response),
e.connection_generation,
));
}
if let Some(Payload::ExecutionPermitRequest(request)) = &e.payload {
tx.commit().await?;
return Ok(reply(
e,
Payload::ExecutionPermit(
crate::job_gateway::permit(state, tenant, agent, e, request).await?,
),
e.connection_generation,
));
}
match &e.payload {
Some(Payload::Heartbeat(h)) => {
Uuid::parse_str(&h.instance_id)?;
sqlx::query("UPDATE agent_installations SET last_contact_at=now() WHERE agent_id=$1 AND revoked_at IS NULL").bind(agent).execute(&mut *tx).await?;
}
Some(Payload::InventorySnapshot(s)) => {
ensure!(
matches!(s.scope.as_str(), "linux.base" | "windows.base")
&& s.schema_version == 1
&& s.chunk_count == 1
&& s.chunk_index == 0
&& s.completeness == "partial"
&& s.data.len() <= 512 * 1024,
"unsupported snapshot"
);
ensure!(
s.sha256 == Sha256::digest(&s.data).as_slice(),
"snapshot hash mismatch"
);
let capabilities: Vec<String> = serde_json::from_value(row.get("capabilities"))?;
ensure!(
capabilities.contains(&format!("{}/1", s.scope)),
"snapshot capability mismatch"
);
let inventory =
rmm_domain::inventory_document::validate_for_scope(&s.data, Utc::now(), &s.scope)
.map_err(anyhow::Error::msg)?;
let mut identity = e.clone();
identity.connection_generation = 0;
let hash = hex::encode(Sha256::digest(identity.encode_to_vec()));
sqlx::query("INSERT INTO observations(tenant_id,agent_id,message_id,boot_id,sequence,observed_at,source_id,quality,completeness,snapshot_id,data,payload_sha256) VALUES($1,$2,$3,$4,$5,$6,$10,'valid','partial',$7,$8,$9) ON CONFLICT(tenant_id,message_id) DO NOTHING").bind(tenant).bind(agent).bind(Uuid::parse_str(&e.message_id)?).bind(Uuid::parse_str(&e.boot_id)?).bind(i64::try_from(e.sequence)?).bind(observed).bind(Uuid::parse_str(&s.snapshot_id)?).bind(serde_json::to_value(inventory)?).bind(&hash).bind(&s.scope).execute(&mut *tx).await?;
let stored: String =
sqlx::query_scalar("SELECT payload_sha256 FROM observations WHERE message_id=$1")
.bind(Uuid::parse_str(&e.message_id)?)
.fetch_one(&mut *tx)
.await?;
ensure!(stored == hash, "message identity conflict");
}
Some(Payload::JobAccepted(_) | Payload::JobStateChanged(_) | Payload::JobResult(_)) => {
crate::job_gateway::event(&mut tx, tenant, agent, e).await?
}
_ => anyhow::bail!("unsupported capability"),
}
tx.commit().await?;
Ok(reply(
e,
Payload::Ack(Ack {
message_id: e.message_id.clone(),
}),
e.connection_generation,
))
}