2025-04-29 22:44:17 +00:00
|
|
|
use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer, Responder};
|
2024-07-09 02:48:50 +03:00
|
|
|
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,
|
2025-07-18 18:35:04 +03:00
|
|
|
#[serde(default)]
|
|
|
|
pub deprecated: bool,
|
2024-07-07 21:02:39 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
#[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();
|
2024-07-09 02:48:50 +03:00
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn get_keys_from_db(client: &Client) -> Result<Vec<Flow>, tokio_postgres::Error> {
|
|
|
|
let rows = client.query(
|
2025-07-18 18:35:04 +03:00
|
|
|
"SELECT k.host, k.key, k.deprecated, f.name FROM public.keys k INNER JOIN public.flows f ON k.key_id = f.key_id",
|
2024-07-07 21:02:39 +03:00
|
|
|
&[]
|
|
|
|
).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);
|
2025-07-18 18:35:04 +03:00
|
|
|
let deprecated: bool = row.get(2);
|
|
|
|
let flow: String = row.get(3);
|
2024-07-07 21:02:39 +03:00
|
|
|
|
2024-07-07 21:13:19 +03:00
|
|
|
let ssh_key = SshKey {
|
|
|
|
server: host,
|
|
|
|
public_key: key,
|
2025-07-18 18:35:04 +03:00
|
|
|
deprecated,
|
2024-07-07 21:13:19 +03:00
|
|
|
};
|
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())
|
|
|
|
}
|
|
|
|
|
2025-04-29 22:44:17 +00:00
|
|
|
// 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>>,
|
2025-04-29 22:44:17 +00:00
|
|
|
req: HttpRequest,
|
2024-07-07 21:02:39 +03:00
|
|
|
) -> impl Responder {
|
2025-04-29 22:44:17 +00:00
|
|
|
let client_hostname = get_client_hostname(&req);
|
2024-07-07 21:02:39 +03:00
|
|
|
let flow_id_str = flow_id.into_inner();
|
2025-04-29 22:44:17 +00:00
|
|
|
|
|
|
|
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) {
|
2025-04-29 22:44:17 +00:00
|
|
|
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();
|
2025-04-29 22:44:17 +00:00
|
|
|
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 {
|
2025-04-29 22:44:17 +00:00
|
|
|
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>>,
|
2025-04-29 22:44:17 +00:00
|
|
|
req: HttpRequest,
|
2024-07-07 21:02:39 +03:00
|
|
|
) -> impl Responder {
|
2025-04-29 22:44:17 +00:00
|
|
|
let client_hostname = get_client_hostname(&req);
|
2024-07-07 21:02:39 +03:00
|
|
|
let flow_id_str = flow_id.into_inner();
|
2025-04-29 22:44:17 +00:00
|
|
|
|
|
|
|
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) {
|
2025-04-29 22:44:17 +00:00
|
|
|
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");
|
|
|
|
}
|
|
|
|
|
2025-04-29 22:44:17 +00:00
|
|
|
// 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) {
|
2025-04-29 22:44:17 +00:00
|
|
|
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!(
|
2025-04-29 22:44:17 +00:00
|
|
|
"Processing batch of {} keys from client '{}' for flow: {}",
|
2025-04-29 21:17:40 +00:00
|
|
|
valid_keys.len(),
|
2025-04-29 22:44:17 +00:00
|
|
|
client_hostname,
|
2025-04-29 21:17:40 +00:00
|
|
|
flow_id_str
|
|
|
|
);
|
|
|
|
|
2025-04-29 22:44:17 +00:00
|
|
|
// 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) => {
|
2025-04-29 22:44:17 +00:00
|
|
|
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
|
|
|
|
2025-05-11 23:44:18 +00:00
|
|
|
// Always try to associate all keys with the flow, regardless of whether they're new or existing
|
|
|
|
if !key_stats.key_id_map.is_empty() {
|
|
|
|
// Extract all key IDs from statistics, both new and existing
|
2025-04-29 21:17:40 +00:00
|
|
|
let key_ids: Vec<i32> = key_stats.key_id_map.iter().map(|(_, id)| *id).collect();
|
|
|
|
|
2025-04-29 22:44:17 +00:00
|
|
|
// 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
|
|
|
|
{
|
2025-04-29 22:44:17 +00:00
|
|
|
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!(
|
2025-04-29 22:44:17 +00:00
|
|
|
"Added flow associations for {} keys from client '{}' in flow '{}'",
|
2025-04-29 21:17:40 +00:00
|
|
|
key_ids.len(),
|
2025-04-29 22:44:17 +00:00
|
|
|
client_hostname,
|
2025-04-29 21:17:40 +00:00
|
|
|
flow_id_str
|
|
|
|
);
|
2025-04-29 21:12:27 +00:00
|
|
|
} else {
|
2025-04-29 22:44:17 +00:00
|
|
|
info!(
|
2025-05-11 23:44:18 +00:00
|
|
|
"No keys to associate from client '{}' with flow '{}'",
|
2025-04-29 22:44:17 +00:00
|
|
|
client_hostname, flow_id_str
|
|
|
|
);
|
2024-07-07 21:02:39 +03:00
|
|
|
}
|
|
|
|
|
2025-04-29 22:44:17 +00: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) => {
|
2025-04-29 22:44:17 +00:00
|
|
|
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!(
|
2025-04-29 22:44:17 +00:00
|
|
|
"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()
|
|
|
|
);
|
|
|
|
|
2025-04-29 22:44:17 +00:00
|
|
|
// 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 {
|
2025-04-29 22:44:17 +00:00
|
|
|
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())
|
2025-07-18 17:52:58 +03:00
|
|
|
// API routes
|
|
|
|
.route("/api/flows", web::get().to(crate::web::get_flows_api))
|
|
|
|
.route("/{flow_id}/keys/{server}", web::delete().to(crate::web::delete_key_by_server))
|
2025-07-18 18:35:04 +03:00
|
|
|
.route("/{flow_id}/keys/{server}/restore", web::post().to(crate::web::restore_key_by_server))
|
|
|
|
.route("/{flow_id}/keys/{server}/delete", web::delete().to(crate::web::permanently_delete_key_by_server))
|
2025-07-18 17:52:58 +03:00
|
|
|
// Original API routes
|
2024-07-07 21:02:39 +03:00
|
|
|
.route("/{flow_id}/keys", web::get().to(get_keys))
|
|
|
|
.route("/{flow_id}/keys", web::post().to(add_keys))
|
2025-07-18 17:52:58 +03:00
|
|
|
// Web interface routes
|
|
|
|
.route("/", web::get().to(crate::web::serve_web_interface))
|
|
|
|
.route("/static/{filename:.*}", web::get().to(crate::web::serve_static_file))
|
2024-07-07 21:02:39 +03:00
|
|
|
})
|
2024-07-09 02:48:50 +03:00
|
|
|
.bind((args.ip.as_str(), args.port))?
|
|
|
|
.run()
|
|
|
|
.await
|
2024-07-07 21:02:39 +03:00
|
|
|
}
|