mirror of
https://github.com/house-of-vanity/khm.git
synced 2025-07-07 15:24:07 +00:00
Compare commits
46 Commits
Author | SHA1 | Date | |
---|---|---|---|
3ca8e27ded | |||
2b7b3b9a22 | |||
bc473ed532 | |||
68ffe9b62d | |||
86f30b90e8 | |||
8991a0579b | |||
cd1ba739ab | |||
1ab0167336 | |||
a39e4835e5 | |||
30bf476037 | |||
b2c32ec2b9 | |||
f7226e918e | |||
770633d0c6 | |||
1c2c234930 | |||
655c32a915 | |||
21fe8036d3 | |||
eac6f22756 | |||
444251ad00 | |||
418de46955 | |||
e500f9ff10 | |||
c01714d8ce | |||
72419aaabd | |||
faacf4c034 | |||
ca7ca3dc38 | |||
9b8efacabc | |||
5b88e4ab50 | |||
98f3957076 | |||
9485cf435a | |||
a9748bf7f8 | |||
ab8e3454e7 | |||
a6f2eaec19 | |||
2f416821f0 | |||
643ea91f27 | |||
41cc5a7bb1 | |||
40a142e9c5 | |||
fcc008e949 | |||
b5560943ee | |||
f51b17ff24 | |||
d47e191b18 | |||
653ad49319 | |||
ce9141e2a0 | |||
7e9d21e49c | |||
efd8659836 | |||
f32014306b | |||
bd3054d2f1 | |||
8b66d7395e |
215
.github/workflows/main.yml
vendored
215
.github/workflows/main.yml
vendored
@ -1,84 +1,177 @@
|
||||
name: Rust CI
|
||||
name: Rust static build and publish
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*.*.*' # Запуск при создании новой тэгированной версии
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- 'v*.*.*'
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
BINARY_NAME: khm
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build static binary
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
os: [ubuntu-latest, windows-latest]
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
target: x86_64-unknown-linux-gnu
|
||||
build_target: x86_64-unknown-linux-musl
|
||||
platform_name: linux-amd64
|
||||
- os: windows-latest
|
||||
target: x86_64-pc-windows-msvc
|
||||
- os: macos-latest
|
||||
target: x86_64-apple-darwin
|
||||
|
||||
build_target: x86_64-pc-windows-msvc
|
||||
platform_name: windows-amd64
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Cache Cargo registry
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cargo/registry
|
||||
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-cargo-registry-
|
||||
|
||||
- name: Cache Cargo index
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cargo/git
|
||||
key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-cargo-index-
|
||||
|
||||
- name: Cache Cargo build
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: target
|
||||
key: ${{ runner.os }}-cargo-build-${{ hashFiles('**/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-cargo-build-
|
||||
|
||||
- name: Set up Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
profile: minimal
|
||||
override: true
|
||||
|
||||
- name: Install target
|
||||
run: rustup target add ${{ matrix.target }}
|
||||
|
||||
- name: Build project
|
||||
run: cargo build --release --target ${{ matrix.target }}
|
||||
|
||||
- name: Run tests
|
||||
run: cargo test --target ${{ matrix.target }}
|
||||
|
||||
- name: Upload release assets
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: khm-${{ matrix.os }}
|
||||
path: target/${{ matrix.target }}/release/
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- uses: mbrobbel/rustfmt-check@master
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Install rust targets
|
||||
run: rustup target add ${{ matrix.build_target }}
|
||||
|
||||
- name: Build Linux MUSL
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
uses: gmiam/rust-musl-action@master
|
||||
with:
|
||||
args: cargo build --target ${{ matrix.build_target }} --release
|
||||
|
||||
- name: Build Windows
|
||||
if: matrix.os != 'ubuntu-latest'
|
||||
run: cargo build --target ${{ matrix.build_target }} --release
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
|
||||
path: target/${{ matrix.build_target }}/release/${{ env.BINARY_NAME }}*
|
||||
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
name: Create Release Page
|
||||
needs: build
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: Create Release
|
||||
id: create_release
|
||||
uses: actions/create-release@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: ${{ github.ref }}
|
||||
release_name: Release ${{ github.ref }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
|
||||
- name: Download Linux build artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: khm-ubuntu-latest
|
||||
path: target/x86_64-unknown-linux-gnu/release/
|
||||
upload:
|
||||
name: Upload Release Assets
|
||||
needs: release
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest]
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
platform_name: linux-amd64
|
||||
- os: windows-latest
|
||||
platform_name: windows-amd64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/download-artifact@v4
|
||||
name: Download ${{ matrix.platform_name }} artifact
|
||||
with:
|
||||
name: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
|
||||
path: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
|
||||
|
||||
- name: Upload Release Asset
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ needs.release.outputs.upload_url }}
|
||||
asset_path: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}/${{ env.BINARY_NAME }}${{ matrix.platform_name == 'windows-amd64' && '.exe' || '' }}
|
||||
asset_name: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}${{ matrix.platform_name == 'windows-amd64' && '.exe' || '' }}
|
||||
asset_content_type: application/octet-stream
|
||||
|
||||
- name: Download Windows build artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: khm-windows-latest
|
||||
path: target/x86_64-pc-windows-msvc/release/
|
||||
build_docker:
|
||||
name: Build and Publish Docker Image
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/download-artifact@v4
|
||||
name: Download Linux artifact
|
||||
with:
|
||||
name: ${{ env.BINARY_NAME }}_linux-amd64
|
||||
path: .
|
||||
|
||||
- name: ls
|
||||
run: |
|
||||
ls -lah
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Download macOS build artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: khm-macos-latest
|
||||
path: target/x86_64-apple-darwin/release/
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ultradesu
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Set exec flag
|
||||
run: |
|
||||
chmod +x ${{ env.BINARY_NAME }}
|
||||
|
||||
- name: Set outputs
|
||||
id: get_tag
|
||||
run: |
|
||||
echo "tag=$(echo ${GITHUB_REF} | cut -d'/' -f3)" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ultradesu/${{ env.BINARY_NAME }}:latest,ultradesu/${{ env.BINARY_NAME }}:${{ steps.get_tag.outputs.tag }}
|
||||
|
||||
- name: Create Release
|
||||
id: create_release
|
||||
uses: ncipollo/release-action@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
artifacts: "target/x86_64-apple-darwin/release/khm,target/x86_64-pc-windows-msvc/release/khm.exe,target/x86_64-unknown-linux-gnu/release/khm"
|
||||
#bodyFile: "body.md"
|
||||
|
2
Cargo.lock
generated
2
Cargo.lock
generated
@ -1053,7 +1053,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "khm"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"actix-web",
|
||||
"chrono",
|
||||
|
@ -1,8 +1,8 @@
|
||||
[package]
|
||||
name = "khm"
|
||||
version = "0.1.0"
|
||||
version = "0.2.1"
|
||||
edition = "2021"
|
||||
authors = ["AB <ab@hexor.cy>"]
|
||||
authors = ["AB <ab@hexor.cy>", "ChatGPT-4o"]
|
||||
|
||||
[dependencies]
|
||||
actix-web = "4"
|
||||
@ -15,4 +15,4 @@ tokio = { version = "1", features = ["full"] }
|
||||
tokio-postgres = { version = "0.7", features = ["with-chrono-0_4"] }
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
chrono = "0.4.38"
|
||||
reqwest = { version = "0.12", features = ["json"] }
|
||||
reqwest = { version = "0.12", features = ["json"] }
|
||||
|
5
Dockerfile
Normal file
5
Dockerfile
Normal file
@ -0,0 +1,5 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
FROM alpine:latest
|
||||
COPY khm /usr/local/bin/khm
|
||||
ENTRYPOINT ["/usr/local/bin/khm"]
|
11
shell.nix
Normal file
11
shell.nix
Normal file
@ -0,0 +1,11 @@
|
||||
{ pkgs ? import <nixpkgs> {} }:
|
||||
|
||||
pkgs.mkShell {
|
||||
buildInputs = [
|
||||
pkgs.openssl
|
||||
pkgs.pkg-config
|
||||
];
|
||||
shellHook = ''
|
||||
unset OPENSSL_DIR
|
||||
'';
|
||||
}
|
@ -1,3 +1,4 @@
|
||||
use log::{error, info};
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs::File;
|
||||
@ -17,15 +18,21 @@ fn read_known_hosts(file_path: &str) -> io::Result<Vec<SshKey>> {
|
||||
|
||||
let mut keys = Vec::new();
|
||||
for line in reader.lines() {
|
||||
if let Ok(line) = line {
|
||||
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||
if parts.len() >= 2 {
|
||||
let server = parts[0].to_string();
|
||||
let public_key = parts[1..].join(" ");
|
||||
keys.push(SshKey { server, public_key });
|
||||
match line {
|
||||
Ok(line) => {
|
||||
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||
if parts.len() >= 2 {
|
||||
let server = parts[0].to_string();
|
||||
let public_key = parts[1..].join(" ");
|
||||
keys.push(SshKey { server, public_key });
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Error reading line from known_hosts file: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
info!("Read {} keys from known_hosts file", keys.len());
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
@ -36,6 +43,7 @@ fn write_known_hosts(file_path: &str, keys: &[SshKey]) -> io::Result<()> {
|
||||
for key in keys {
|
||||
writeln!(file, "{} {}", key.server, key.public_key)?;
|
||||
}
|
||||
info!("Wrote {} keys to known_hosts file", keys.len());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@ -46,9 +54,9 @@ async fn send_keys_to_server(host: &str, keys: Vec<SshKey>) -> Result<(), reqwes
|
||||
let response = client.post(&url).json(&keys).send().await?;
|
||||
|
||||
if response.status().is_success() {
|
||||
println!("Keys successfully sent to server.");
|
||||
info!("Keys successfully sent to server.");
|
||||
} else {
|
||||
eprintln!(
|
||||
error!(
|
||||
"Failed to send keys to server. Status: {}",
|
||||
response.status()
|
||||
);
|
||||
@ -64,9 +72,10 @@ async fn get_keys_from_server(host: &str) -> Result<Vec<SshKey>, reqwest::Error>
|
||||
|
||||
if response.status().is_success() {
|
||||
let keys: Vec<SshKey> = response.json().await?;
|
||||
info!("Received {} keys from server", keys.len());
|
||||
Ok(keys)
|
||||
} else {
|
||||
eprintln!(
|
||||
error!(
|
||||
"Failed to get keys from server. Status: {}",
|
||||
response.status()
|
||||
);
|
||||
@ -75,21 +84,26 @@ async fn get_keys_from_server(host: &str) -> Result<Vec<SshKey>, reqwest::Error>
|
||||
}
|
||||
|
||||
pub async fn run_client(args: crate::Args) -> std::io::Result<()> {
|
||||
info!("Client mode: Reading known_hosts file");
|
||||
let keys = read_known_hosts(&args.known_hosts).expect("Failed to read known hosts file");
|
||||
|
||||
let host = args.host.expect("host is required in client mode");
|
||||
info!("Client mode: Sending keys to server at {}", host);
|
||||
send_keys_to_server(&host, keys)
|
||||
.await
|
||||
.expect("Failed to send keys to server");
|
||||
|
||||
if args.in_place {
|
||||
info!("Client mode: In-place update is enabled. Fetching keys from server.");
|
||||
let server_keys = get_keys_from_server(&host)
|
||||
.await
|
||||
.expect("Failed to get keys from server");
|
||||
|
||||
info!("Client mode: Writing updated known_hosts file");
|
||||
write_known_hosts(&args.known_hosts, &server_keys)
|
||||
.expect("Failed to write known hosts file");
|
||||
}
|
||||
|
||||
info!("Client mode: Finished operations");
|
||||
Ok(())
|
||||
}
|
||||
|
51
src/main.rs
51
src/main.rs
@ -3,6 +3,7 @@ mod server;
|
||||
|
||||
use clap::Parser;
|
||||
use env_logger;
|
||||
use log::{error, info};
|
||||
|
||||
/// This application manages SSH keys and flows, either as a server or client.
|
||||
/// In server mode, it stores keys and flows in a PostgreSQL database.
|
||||
@ -11,7 +12,7 @@ use env_logger;
|
||||
#[command(
|
||||
author = env!("CARGO_PKG_AUTHORS"),
|
||||
version = env!("CARGO_PKG_VERSION"),
|
||||
about = "SSH Key Manager",
|
||||
about = "SSH Host Key Manager",
|
||||
long_about = None,
|
||||
after_help = "Examples:\n\
|
||||
\n\
|
||||
@ -19,11 +20,26 @@ use env_logger;
|
||||
khm --server --ip 0.0.0.0 --port 1337 --db-host psql.psql.svc --db-name khm --db-user admin --db-password <SECRET> --flows work,home\n\
|
||||
\n\
|
||||
Running in client mode to send diff and sync ~/.ssh/known_hosts with remote flow in place:\n\
|
||||
khm --host http://kh.example.com:8080 --known_hosts ~/.ssh/known_hosts --in-place\n\
|
||||
khm --host https://khm.example.com/default/keys --known-hosts ~/.ssh/known_hosts --in-place\n\
|
||||
\n\
|
||||
"
|
||||
)]
|
||||
struct Args {
|
||||
/// Run in server mode (default: false)
|
||||
#[arg(long, help = "Run in server mode")]
|
||||
server: bool,
|
||||
|
||||
/// Update the known_hosts file with keys from the server after sending keys (default: false)
|
||||
#[arg(
|
||||
long,
|
||||
help = "Server mode: Sync the known_hosts file with keys from the server"
|
||||
)]
|
||||
in_place: bool,
|
||||
|
||||
/// Comma-separated list of flows to manage (default: default)
|
||||
#[arg(long, default_value = "default", value_parser, num_args = 1.., value_delimiter = ',', help = "Server mode: Comma-separated list of flows to manage")]
|
||||
flows: Vec<String>,
|
||||
|
||||
/// IP address to bind the server or client to (default: 127.0.0.1)
|
||||
#[arg(
|
||||
short,
|
||||
@ -78,14 +94,10 @@ struct Args {
|
||||
#[arg(
|
||||
long,
|
||||
required_if_eq("server", "false"),
|
||||
help = "Client mode: Host address of the server to connect to"
|
||||
help = "Client mode: Full host address of the server to connect to. Like https://khm.example.com/flow_name/keys"
|
||||
)]
|
||||
host: Option<String>,
|
||||
|
||||
/// Run in server mode (default: false)
|
||||
#[arg(long, help = "Run in server mode")]
|
||||
server: bool,
|
||||
|
||||
/// Path to the known_hosts file (default: ~/.ssh/known_hosts)
|
||||
#[arg(
|
||||
long,
|
||||
@ -93,28 +105,27 @@ struct Args {
|
||||
help = "Client mode: Path to the known_hosts file"
|
||||
)]
|
||||
known_hosts: String,
|
||||
|
||||
/// Update the known_hosts file with keys from the server after sending keys (default: false)
|
||||
#[arg(
|
||||
long,
|
||||
help = "Server mode: Sync the known_hosts file with keys from the server"
|
||||
)]
|
||||
in_place: bool,
|
||||
|
||||
/// Comma-separated list of flows to manage (default: default)
|
||||
#[arg(long, default_value = "default", value_parser, num_args = 1.., value_delimiter = ',', help = "Comma-separated list of flows to manage")]
|
||||
flows: Vec<String>,
|
||||
}
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
env_logger::init();
|
||||
info!("Starting SSH Key Manager");
|
||||
|
||||
let args = Args::parse();
|
||||
|
||||
if args.server {
|
||||
server::run_server(args).await
|
||||
info!("Running in server mode");
|
||||
if let Err(e) = server::run_server(args).await {
|
||||
error!("Failed to run server: {}", e);
|
||||
}
|
||||
} else {
|
||||
client::run_client(args).await
|
||||
info!("Running in client mode");
|
||||
if let Err(e) = client::run_client(args).await {
|
||||
error!("Failed to run client: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
info!("Application has exited");
|
||||
Ok(())
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
|
||||
use log;
|
||||
use log::{error, info};
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
@ -51,12 +51,14 @@ pub async fn insert_key_if_not_exists(
|
||||
&[&row.get::<_, i32>(0)],
|
||||
)
|
||||
.await?;
|
||||
info!("Updated existing key for server: {}", key.server);
|
||||
Ok(row.get(0))
|
||||
} else {
|
||||
let row = client.query_one(
|
||||
"INSERT INTO public.keys (host, key, updated) VALUES ($1, $2, NOW()) RETURNING key_id",
|
||||
&[&key.server, &key.public_key]
|
||||
).await?;
|
||||
info!("Inserted new key for server: {}", key.server);
|
||||
Ok(row.get(0))
|
||||
}
|
||||
}
|
||||
@ -72,6 +74,7 @@ pub async fn insert_flow_key(
|
||||
&[&flow_name, &key_id],
|
||||
)
|
||||
.await?;
|
||||
info!("Inserted key_id {} into flow: {}", key_id, flow_name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@ -106,6 +109,7 @@ pub async fn get_keys_from_db(client: &Client) -> Result<Vec<Flow>, tokio_postgr
|
||||
}
|
||||
}
|
||||
|
||||
info!("Retrieved {} flows from database", flows_map.len());
|
||||
Ok(flows_map.into_values().collect())
|
||||
}
|
||||
|
||||
@ -116,14 +120,17 @@ pub async fn get_keys(
|
||||
) -> impl Responder {
|
||||
let flow_id_str = flow_id.into_inner();
|
||||
if !allowed_flows.contains(&flow_id_str) {
|
||||
error!("Flow ID not allowed: {}", flow_id_str);
|
||||
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: {}", servers.len(), flow_id_str);
|
||||
HttpResponse::Ok().json(servers)
|
||||
} else {
|
||||
error!("Flow ID not found: {}", flow_id_str);
|
||||
HttpResponse::NotFound().body("Flow ID not found")
|
||||
}
|
||||
}
|
||||
@ -137,11 +144,13 @@ pub async fn add_keys(
|
||||
) -> impl Responder {
|
||||
let flow_id_str = flow_id.into_inner();
|
||||
if !allowed_flows.contains(&flow_id_str) {
|
||||
error!("Flow ID not allowed: {}", flow_id_str);
|
||||
return HttpResponse::Forbidden().body("Flow ID not allowed");
|
||||
}
|
||||
|
||||
for new_key in new_keys.iter() {
|
||||
if !is_valid_ssh_key(&new_key.public_key) {
|
||||
error!("Invalid SSH key format for server: {}", new_key.server);
|
||||
return HttpResponse::BadRequest().body(format!(
|
||||
"Invalid SSH key format for server: {}",
|
||||
new_key.server
|
||||
@ -151,31 +160,38 @@ pub async fn add_keys(
|
||||
match insert_key_if_not_exists(&db_client, new_key).await {
|
||||
Ok(key_id) => {
|
||||
if let Err(e) = insert_flow_key(&db_client, &flow_id_str, key_id).await {
|
||||
log::error!("Failed to insert flow key into database: {}", e);
|
||||
error!("Failed to insert flow key into database: {}", e);
|
||||
return HttpResponse::InternalServerError()
|
||||
.body("Failed to insert flow key into database");
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("Failed to insert key into database: {}", e);
|
||||
error!("Failed to insert key into database: {}", e);
|
||||
return HttpResponse::InternalServerError()
|
||||
.body("Failed to insert key into database");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh the flows data from the database
|
||||
let updated_flows = get_keys_from_db(&db_client)
|
||||
.await
|
||||
.unwrap_or_else(|_| Vec::new());
|
||||
let updated_flows = match get_keys_from_db(&db_client).await {
|
||||
Ok(flows) => flows,
|
||||
Err(e) => {
|
||||
error!("Failed to get updated flows from database: {}", e);
|
||||
return HttpResponse::InternalServerError()
|
||||
.body("Failed to refresh flows from database");
|
||||
}
|
||||
};
|
||||
|
||||
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();
|
||||
info!("Updated flow: {} with {} keys", flow_id_str, servers.len());
|
||||
HttpResponse::Ok().json(servers)
|
||||
} else {
|
||||
error!("Flow ID not found after update: {}", flow_id_str);
|
||||
HttpResponse::NotFound().body("Flow ID not found")
|
||||
}
|
||||
}
|
||||
@ -197,13 +213,17 @@ pub async fn run_server(args: crate::Args) -> std::io::Result<()> {
|
||||
// Spawn a new thread to run the database connection
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = connection.await {
|
||||
eprintln!("Connection error: {}", e);
|
||||
error!("Connection error: {}", e);
|
||||
}
|
||||
});
|
||||
|
||||
let mut initial_flows = get_keys_from_db(&db_client)
|
||||
.await
|
||||
.unwrap_or_else(|_| Vec::new());
|
||||
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()
|
||||
}
|
||||
};
|
||||
|
||||
// Ensure all allowed flows are initialized
|
||||
for allowed_flow in &args.flows {
|
||||
@ -218,6 +238,7 @@ pub async fn run_server(args: crate::Args) -> std::io::Result<()> {
|
||||
let flows: Flows = Arc::new(Mutex::new(initial_flows));
|
||||
let allowed_flows = web::Data::new(args.flows);
|
||||
|
||||
info!("Starting HTTP server on {}:{}", args.ip, args.port);
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.app_data(web::Data::new(flows.clone()))
|
||||
|
Reference in New Issue
Block a user