Files
rust-discovery/crates/server/src/gateway.rs
T
2026-11-13 19:11:45 +01:00

238 lines
8.4 KiB
Rust

use anyhow::{Context, Result, ensure};
use axum::{
Extension, Json,
extract::{
State,
ws::{Message, WebSocket, WebSocketUpgrade},
},
http::StatusCode,
response::Response,
};
use chrono::Utc;
use prost::Message as ProstMessage;
use rmm_domain::MAX_MESSAGE;
use rmm_protocol::*;
use sha2::{Digest, Sha256};
use std::{
collections::VecDeque,
time::{Duration, Instant},
};
use uuid::Uuid;
pub async fn enroll(
State(state): State<crate::State>,
Json(request): Json<EnrollmentRequest>,
) -> Result<Json<EnrollmentResponse>, StatusCode> {
if request.token.len() != 64 || request.csr_pem.len() > 8192 {
return Err(StatusCode::BAD_REQUEST);
}
let mut tx = state
.pool
.begin()
.await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
let hash = hex::encode(Sha256::digest(request.token.as_bytes()));
let tenant: Option<Uuid> = sqlx::query_scalar("SELECT consume_enrollment($1)")
.bind(hash)
.fetch_one(&mut *tx)
.await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
let tenant = tenant.ok_or(StatusCode::UNAUTHORIZED)?;
sqlx::query("SELECT set_config('app.tenant_id',$1,true)")
.bind(tenant.to_string())
.execute(&mut *tx)
.await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
let agent = Uuid::new_v4();
let asset = Uuid::new_v4();
let certificate =
crate::tls::issue(&state, &request.csr_pem, agent).map_err(|_| StatusCode::BAD_REQUEST)?;
let fingerprint = hex::encode(Sha256::digest(
certificate
.to_der()
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
));
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
.bind(tenant)
.bind(asset)
.execute(&mut *tx)
.await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256) VALUES($1,$2,$3,$4)").bind(tenant).bind(agent).bind(asset).bind(fingerprint).execute(&mut *tx).await.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
let certificate_pem = String::from_utf8(
certificate
.to_pem()
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
tx.commit()
.await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
Ok(Json(EnrollmentResponse {
agent_id: agent.to_string(),
asset_id: asset.to_string(),
certificate_pem,
}))
}
pub async fn connect(
State(state): State<crate::State>,
Extension(peer): Extension<crate::Peer>,
ws: WebSocketUpgrade,
) -> Result<Response, StatusCode> {
let expires = peer
.1
.filter(|expires| *expires > Utc::now())
.ok_or(StatusCode::UNAUTHORIZED)?;
let fingerprint = peer.0.ok_or(StatusCode::UNAUTHORIZED)?;
let binding: Option<(Uuid, Uuid)> =
sqlx::query_as("SELECT tenant_id,agent_id FROM device_binding($1)")
.bind(&fingerprint)
.fetch_optional(&state.pool)
.await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
let (tenant, agent) = binding.ok_or(StatusCode::UNAUTHORIZED)?;
if dev_transport_faults::reject_wss(&state.pool, tenant, agent, &fingerprint)
.await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?
{
return Err(StatusCode::SERVICE_UNAVAILABLE);
}
Ok(ws
.max_message_size(MAX_MESSAGE)
.max_frame_size(MAX_MESSAGE)
.on_upgrade(move |mut socket| async move {
if channel(&state, &mut socket, tenant, agent, expires)
.await
.is_err()
{
let _ = socket.send(Message::Close(None)).await;
}
}))
}
async fn receive(socket: &mut WebSocket) -> Result<Envelope> {
let message = tokio::time::timeout(Duration::from_secs(65), socket.recv())
.await?
.context("closed")??;
let Message::Binary(bytes) = message else {
anyhow::bail!("binary envelope required")
};
ensure!(bytes.len() <= MAX_MESSAGE, "message limit");
Ok(Envelope::decode(bytes)?)
}
async fn send(
state: &crate::State,
socket: &mut WebSocket,
tenant: Uuid,
agent: Uuid,
e: &Envelope,
payload: Payload,
generation: u64,
) -> Result<()> {
let reply = 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(),
observed_at: Utc::now().timestamp_millis(),
sequence: e.sequence,
payload: Some(payload),
};
let claim =
dev_delivery_faults::duplicate_offer(&state.pool, tenant, agent, &reply, "wss").await?;
let bytes = reply.encode_to_vec();
tokio::time::timeout(
Duration::from_secs(10),
socket.send(Message::Binary(bytes.clone().into())),
)
.await??;
if let Some(claim) = claim {
tokio::time::timeout(
Duration::from_secs(10),
socket.send(Message::Binary(bytes.into())),
)
.await??;
dev_delivery_faults::duplicate_emitted(&state.pool, claim).await?;
}
Ok(())
}
async fn channel(
state: &crate::State,
socket: &mut WebSocket,
tenant: Uuid,
agent: Uuid,
certificate_expires: chrono::DateTime<Utc>,
) -> Result<()> {
let hello = tokio::time::timeout(Duration::from_secs(10), receive(socket)).await??;
ensure!(
valid_envelope(&hello, &agent.to_string(), 0),
"invalid hello"
);
ensure!(
matches!(hello.payload, Some(Payload::ClientHello(_))),
"hello required"
);
let response = crate::agent_service::open(state, tenant, agent, &hello, "wss").await?;
let generation = response.connection_generation;
socket
.send(Message::Binary(response.encode_to_vec().into()))
.await?;
if let Some(payload) = crate::job_gateway::next(state, tenant, agent, generation).await? {
send(state, socket, tenant, agent, &hello, payload, generation).await?;
}
let mut recent_messages = VecDeque::new();
let mut timer = tokio::time::interval(Duration::from_secs(1));
let mut last_input = Instant::now();
let connected = Instant::now();
loop {
let e = tokio::select! {
message=receive(socket)=>{last_input=Instant::now();message?},
_=timer.tick()=>{
ensure!(Utc::now()<certificate_expires && connected.elapsed()<Duration::from_secs(3600),"TLS device session requires reauthentication");
ensure!(last_input.elapsed()<Duration::from_secs(65),"inactive channel");
let mut tx=rmm_persistence::tenant_tx(&state.pool,tenant).await?;
let revoked:bool=sqlx::query_scalar("SELECT revoked_at IS NOT NULL FROM agent_installations WHERE agent_id=$1").bind(agent).fetch_one(&mut *tx).await?;
tx.commit().await?;ensure!(!revoked,"device revoked");
if let Some(payload)=crate::job_gateway::next(state,tenant,agent,generation).await?{send(state,socket,tenant,agent,&hello,payload,generation).await?;}
continue;
}
};
ensure!(
Utc::now() < certificate_expires,
"TLS device certificate expired"
);
while recent_messages
.front()
.is_some_and(|t: &Instant| t.elapsed() >= Duration::from_secs(1))
{
recent_messages.pop_front();
}
ensure!(recent_messages.len() < 20, "device rate limit");
recent_messages.push_back(Instant::now());
ensure!(
e.connection_generation == generation,
"channel generation mismatch"
);
let response = crate::agent_service::ingest(state, tenant, agent, &e, "wss").await?;
if !dev_delivery_faults::after_ingest(&state.pool, tenant, agent, &e, &response, "wss")
.await?
{
socket
.send(Message::Binary(response.encode_to_vec().into()))
.await?;
}
if let Some(payload) = crate::job_gateway::next(state, tenant, agent, generation).await? {
send(state, socket, tenant, agent, &e, payload, generation).await?;
}
}
}
#[path = "dev_delivery_faults.rs"]
pub(crate) mod dev_delivery_faults;
#[path = "dev_transport_faults.rs"]
pub(crate) mod dev_transport_faults;