Files
khm/src/server.rs

336 lines
11 KiB
Rust
Raw Normal View History

use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer, Responder};
use log::{error, info};
2024-07-07 21:13:19 +03:00
use regex::Regex;
use serde::{Deserialize, Serialize};
2024-07-07 21:02:39 +03:00
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
2024-07-07 21:13:19 +03:00
use tokio_postgres::{Client, NoTls};
2024-07-07 21:02:39 +03:00
2025-04-29 21:12:27 +00:00
use crate::db;
2024-07-07 21:02:39 +03:00
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SshKey {
pub server: String,
pub public_key: String,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Flow {
pub name: String,
pub servers: Vec<SshKey>,
}
pub type Flows = Arc<Mutex<Vec<Flow>>>;
pub fn is_valid_ssh_key(key: &str) -> bool {
let rsa_re = Regex::new(r"^ssh-rsa AAAA[0-9A-Za-z+/]+[=]{0,3}( .+)?$").unwrap();
let dsa_re = Regex::new(r"^ssh-dss AAAA[0-9A-Za-z+/]+[=]{0,3}( .+)?$").unwrap();
let ecdsa_re =
Regex::new(r"^ecdsa-sha2-nistp(256|384|521) AAAA[0-9A-Za-z+/]+[=]{0,3}( .+)?$").unwrap();
2024-07-07 21:02:39 +03:00
let ed25519_re = Regex::new(r"^ssh-ed25519 AAAA[0-9A-Za-z+/]+[=]{0,3}( .+)?$").unwrap();
2024-07-07 21:13:19 +03:00
rsa_re.is_match(key)
|| dsa_re.is_match(key)
|| ecdsa_re.is_match(key)
|| ed25519_re.is_match(key)
2024-07-07 21:02:39 +03:00
}
// Note: Removed unused functions insert_key_if_not_exists and insert_flow_key
2024-07-07 21:02:39 +03:00
pub async fn get_keys_from_db(client: &Client) -> Result<Vec<Flow>, tokio_postgres::Error> {
let rows = client.query(
"SELECT k.host, k.key, f.name FROM public.keys k INNER JOIN public.flows f ON k.key_id = f.key_id",
&[]
).await?;
let mut flows_map: HashMap<String, Flow> = HashMap::new();
for row in rows {
let host: String = row.get(0);
let key: String = row.get(1);
let flow: String = row.get(2);
2024-07-07 21:13:19 +03:00
let ssh_key = SshKey {
server: host,
public_key: key,
};
2024-07-07 21:02:39 +03:00
if let Some(flow_entry) = flows_map.get_mut(&flow) {
flow_entry.servers.push(ssh_key);
} else {
2024-07-07 21:13:19 +03:00
flows_map.insert(
flow.clone(),
Flow {
name: flow,
servers: vec![ssh_key],
},
);
2024-07-07 21:02:39 +03:00
}
}
2024-07-09 02:28:44 +03:00
info!("Retrieved {} flows from database", flows_map.len());
2024-07-07 21:02:39 +03:00
Ok(flows_map.into_values().collect())
}
// Extract client hostname from request headers
fn get_client_hostname(req: &HttpRequest) -> String {
if let Some(hostname) = req.headers().get("X-Client-Hostname") {
if let Ok(hostname_str) = hostname.to_str() {
return hostname_str.to_string();
}
}
"unknown-client".to_string()
}
2024-07-07 21:02:39 +03:00
pub async fn get_keys(
flows: web::Data<Flows>,
flow_id: web::Path<String>,
2024-07-07 21:13:19 +03:00
allowed_flows: web::Data<Vec<String>>,
req: HttpRequest,
2024-07-07 21:02:39 +03:00
) -> impl Responder {
let client_hostname = get_client_hostname(&req);
2024-07-07 21:02:39 +03:00
let flow_id_str = flow_id.into_inner();
info!(
"Received keys request from client '{}' for flow '{}'",
client_hostname, flow_id_str
);
2024-07-07 21:02:39 +03:00
if !allowed_flows.contains(&flow_id_str) {
error!(
"Flow ID not allowed for client '{}': {}",
client_hostname, flow_id_str
);
2024-07-07 21:02:39 +03:00
return HttpResponse::Forbidden().body("Flow ID not allowed");
}
let flows = flows.lock().unwrap();
if let Some(flow) = flows.iter().find(|flow| flow.name == flow_id_str) {
let servers: Vec<&SshKey> = flow.servers.iter().collect();
info!(
"Returning {} keys for flow '{}' to client '{}'",
servers.len(),
flow_id_str,
client_hostname
);
2024-07-07 21:02:39 +03:00
HttpResponse::Ok().json(servers)
} else {
error!(
"Flow ID not found for client '{}': {}",
client_hostname, flow_id_str
);
2024-07-07 21:02:39 +03:00
HttpResponse::NotFound().body("Flow ID not found")
}
}
pub async fn add_keys(
flows: web::Data<Flows>,
flow_id: web::Path<String>,
new_keys: web::Json<Vec<SshKey>>,
db_client: web::Data<Arc<Client>>,
2024-07-07 21:13:19 +03:00
allowed_flows: web::Data<Vec<String>>,
req: HttpRequest,
2024-07-07 21:02:39 +03:00
) -> impl Responder {
let client_hostname = get_client_hostname(&req);
2024-07-07 21:02:39 +03:00
let flow_id_str = flow_id.into_inner();
info!(
"Received {} keys from client '{}' for flow '{}'",
new_keys.len(),
client_hostname,
flow_id_str
);
2024-07-07 21:02:39 +03:00
if !allowed_flows.contains(&flow_id_str) {
error!(
"Flow ID not allowed for client '{}': {}",
client_hostname, flow_id_str
);
2024-07-07 21:02:39 +03:00
return HttpResponse::Forbidden().body("Flow ID not allowed");
}
// Check SSH key format
2025-04-29 21:12:27 +00:00
let mut valid_keys = Vec::new();
2024-07-07 21:02:39 +03:00
for new_key in new_keys.iter() {
if !is_valid_ssh_key(&new_key.public_key) {
error!(
"Invalid SSH key format from client '{}' for server: {}",
client_hostname, new_key.server
);
2024-07-07 21:13:19 +03:00
return HttpResponse::BadRequest().body(format!(
"Invalid SSH key format for server: {}",
new_key.server
));
2024-07-07 21:02:39 +03:00
}
2025-04-29 21:12:27 +00:00
valid_keys.push(new_key.clone());
}
2025-04-29 21:17:40 +00:00
info!(
"Processing batch of {} keys from client '{}' for flow: {}",
2025-04-29 21:17:40 +00:00
valid_keys.len(),
client_hostname,
2025-04-29 21:17:40 +00:00
flow_id_str
);
// Batch insert keys with statistics
2025-04-29 21:12:27 +00:00
let key_stats = match crate::db::batch_insert_keys(&db_client, &valid_keys).await {
Ok(stats) => stats,
Err(e) => {
error!(
"Failed to batch insert keys from client '{}' into database: {}",
client_hostname, e
);
2025-04-29 21:12:27 +00:00
return HttpResponse::InternalServerError()
.body("Failed to batch insert keys into database");
}
};
2024-07-07 21:02:39 +03:00
// If there are no new keys, no need to update flow associations
2025-04-29 21:12:27 +00:00
if key_stats.inserted > 0 {
// Extract only key IDs from statistics
2025-04-29 21:17:40 +00:00
let key_ids: Vec<i32> = key_stats.key_id_map.iter().map(|(_, id)| *id).collect();
// Batch insert key-flow associations
2025-04-29 21:17:40 +00:00
if let Err(e) = crate::db::batch_insert_flow_keys(&db_client, &flow_id_str, &key_ids).await
{
error!(
"Failed to batch insert flow keys from client '{}' into database: {}",
client_hostname, e
);
2025-04-29 21:12:27 +00:00
return HttpResponse::InternalServerError()
.body("Failed to batch insert flow keys into database");
2024-07-07 21:02:39 +03:00
}
2025-04-29 21:17:40 +00:00
info!(
"Added flow associations for {} keys from client '{}' in flow '{}'",
2025-04-29 21:17:40 +00:00
key_ids.len(),
client_hostname,
2025-04-29 21:17:40 +00:00
flow_id_str
);
2025-04-29 21:12:27 +00:00
} else {
info!(
"No new keys to associate from client '{}' with flow '{}'",
client_hostname, flow_id_str
);
2024-07-07 21:02:39 +03:00
}
// Get updated data
2024-07-09 02:28:44 +03:00
let updated_flows = match get_keys_from_db(&db_client).await {
Ok(flows) => flows,
Err(e) => {
error!(
"Failed to get updated flows from database after client '{}' request: {}",
client_hostname, e
);
2024-07-09 02:28:44 +03:00
return HttpResponse::InternalServerError()
.body("Failed to refresh flows from database");
}
};
2024-07-07 21:02:39 +03:00
let mut flows_guard = flows.lock().unwrap();
*flows_guard = updated_flows;
let updated_flow = flows_guard.iter().find(|flow| flow.name == flow_id_str);
if let Some(flow) = updated_flow {
let servers: Vec<&SshKey> = flow.servers.iter().collect();
2025-04-29 21:17:40 +00:00
info!(
"Keys summary for client '{}', flow '{}': total received={}, new={}, unchanged={}, total in flow={}",
client_hostname,
2025-04-29 21:17:40 +00:00
flow_id_str,
key_stats.total,
key_stats.inserted,
key_stats.unchanged,
servers.len()
);
// Add statistics to HTTP response headers
2025-04-29 21:12:27 +00:00
let mut response = HttpResponse::Ok();
response.append_header(("X-Keys-Total", key_stats.total.to_string()));
response.append_header(("X-Keys-New", key_stats.inserted.to_string()));
response.append_header(("X-Keys-Unchanged", key_stats.unchanged.to_string()));
2025-04-29 21:17:40 +00:00
2025-04-29 21:12:27 +00:00
response.json(servers)
2024-07-07 21:02:39 +03:00
} else {
error!(
"Flow ID not found after update from client '{}': {}",
client_hostname, flow_id_str
);
2024-07-07 21:02:39 +03:00
HttpResponse::NotFound().body("Flow ID not found")
}
}
pub async fn run_server(args: crate::Args) -> std::io::Result<()> {
let db_user = args.db_user.expect("db_user is required in server mode");
2024-07-07 21:13:19 +03:00
let db_password = args
.db_password
.expect("db_password is required in server mode");
2024-07-07 21:02:39 +03:00
let db_conn_str = format!(
"host={} user={} password={} dbname={}",
args.db_host, db_user, db_password, args.db_name
);
2025-04-29 21:12:27 +00:00
info!("Connecting to database at {}", args.db_host);
let (db_client, connection) = match tokio_postgres::connect(&db_conn_str, NoTls).await {
Ok((client, conn)) => (client, conn),
Err(e) => {
error!("Failed to connect to the database: {}", e);
return Err(std::io::Error::new(
std::io::ErrorKind::ConnectionRefused,
format!("Database connection error: {}", e),
));
}
};
2024-07-07 21:02:39 +03:00
let db_client = Arc::new(db_client);
// Spawn a new thread to run the database connection
tokio::spawn(async move {
if let Err(e) = connection.await {
2024-07-09 02:28:44 +03:00
error!("Connection error: {}", e);
2024-07-07 21:02:39 +03:00
}
});
2025-04-29 21:12:27 +00:00
// Initialize database schema if needed
if let Err(e) = db::initialize_db_schema(&db_client).await {
error!("Failed to initialize database schema: {}", e);
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("Database schema initialization error: {}", e),
));
}
2024-07-09 02:28:44 +03:00
let mut initial_flows = match get_keys_from_db(&db_client).await {
Ok(flows) => flows,
Err(e) => {
error!("Failed to get initial flows from database: {}", e);
Vec::new()
}
};
2024-07-07 21:02:39 +03:00
// Ensure all allowed flows are initialized
for allowed_flow in &args.flows {
if !initial_flows.iter().any(|flow| &flow.name == allowed_flow) {
initial_flows.push(Flow {
name: allowed_flow.clone(),
servers: vec![],
});
}
}
let flows: Flows = Arc::new(Mutex::new(initial_flows));
let allowed_flows = web::Data::new(args.flows);
2024-07-09 02:28:44 +03:00
info!("Starting HTTP server on {}:{}", args.ip, args.port);
2024-07-07 21:02:39 +03:00
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(flows.clone()))
.app_data(web::Data::new(db_client.clone()))
.app_data(allowed_flows.clone())
.route("/{flow_id}/keys", web::get().to(get_keys))
.route("/{flow_id}/keys", web::post().to(add_keys))
})
.bind((args.ip.as_str(), args.port))?
.run()
.await
2024-07-07 21:02:39 +03:00
}