52 Commits

Author SHA1 Message Date
3bedadf394 Fix ci 2025-03-14 02:44:17 +02:00
a0f83db19a Fix ci 2025-03-14 02:30:34 +02:00
c01eb48451 Added macos build 2025-03-14 02:27:40 +02:00
c3575b013f Added basic auth support 2025-03-14 02:14:15 +02:00
b4c2fae778 Fix readme 2024-11-11 12:48:00 +02:00
61552a3d70 Fix help a bit. 2024-11-11 12:46:55 +02:00
AB
3ca8e27ded Bump version in Cargo.toml 2024-09-25 15:40:40 +03:00
AB
2b7b3b9a22 Fix help text. Added nix-shell to build locally 2024-09-25 15:24:21 +03:00
AB
bc473ed532 test 2024-07-14 04:07:11 +03:00
68ffe9b62d Update main.rs 2024-07-09 10:03:33 +03:00
AB
86f30b90e8 Bump version. linting. improved logging. 2024-07-09 02:48:50 +03:00
AB
8991a0579b Improve logging and error handling 2024-07-09 02:28:44 +03:00
cd1ba739ab fix ci 2024-07-08 23:29:45 +03:00
1ab0167336 fix ci 2024-07-08 23:27:58 +03:00
a39e4835e5 fix ci 2024-07-08 23:18:18 +03:00
30bf476037 fix ci 2024-07-08 23:15:10 +03:00
b2c32ec2b9 fix ci 2024-07-08 23:08:52 +03:00
f7226e918e fix ci 2024-07-08 22:46:20 +03:00
770633d0c6 fix ci 2024-07-08 22:36:56 +03:00
1c2c234930 fix 2024-07-08 22:29:24 +03:00
655c32a915 Update Dockerfile 2024-07-08 22:03:23 +03:00
21fe8036d3 Update main.yml 2024-07-08 21:47:43 +03:00
eac6f22756 Test docker build 2024-07-08 21:33:30 +03:00
444251ad00 Update main.yml 2024-07-08 21:24:20 +03:00
418de46955 Update main.yml 2024-07-08 21:22:15 +03:00
e500f9ff10 Update main.yml 2024-07-08 21:20:04 +03:00
c01714d8ce Update main.yml 2024-07-08 21:03:34 +03:00
72419aaabd Update main.yml 2024-07-08 20:27:12 +03:00
faacf4c034 Update main.yml 2024-07-08 20:13:47 +03:00
ca7ca3dc38 Update main.yml 2024-07-08 20:05:14 +03:00
9b8efacabc Update main.yml 2024-07-08 19:56:45 +03:00
5b88e4ab50 Update main.yml 2024-07-08 19:45:51 +03:00
98f3957076 Update main.yml 2024-07-08 19:43:47 +03:00
9485cf435a Update main.yml 2024-07-08 19:25:31 +03:00
a9748bf7f8 Update main.yml 2024-07-08 19:24:11 +03:00
ab8e3454e7 Update main.yml 2024-07-08 19:20:24 +03:00
a6f2eaec19 Update main.yml 2024-07-08 19:14:56 +03:00
2f416821f0 Update main.yml 2024-07-08 19:02:20 +03:00
643ea91f27 Update main.yml 2024-07-08 19:01:16 +03:00
41cc5a7bb1 Update main.yml 2024-07-08 18:52:22 +03:00
40a142e9c5 Update main.yml 2024-07-08 18:45:13 +03:00
fcc008e949 Update main.yml 2024-07-08 18:41:10 +03:00
b5560943ee Update main.yml 2024-07-08 18:24:05 +03:00
f51b17ff24 Update main.yml 2024-07-08 17:57:42 +03:00
d47e191b18 Update main.yml 2024-07-08 17:51:05 +03:00
653ad49319 Update main.yml 2024-07-08 16:03:07 +03:00
ce9141e2a0 Update main.yml 2024-07-08 16:00:05 +03:00
7e9d21e49c Update main.yml 2024-07-08 15:46:54 +03:00
efd8659836 Update main.yml 2024-07-08 15:38:17 +03:00
f32014306b Update main.yml 2024-07-08 14:56:54 +03:00
bd3054d2f1 Update main.yml 2024-07-08 14:27:46 +03:00
8b66d7395e Update main.yml 2024-07-08 14:13:30 +03:00
9 changed files with 346 additions and 130 deletions

View File

@ -1,84 +1,183 @@
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]
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
build_target: x86_64-pc-windows-msvc
platform_name: windows-amd64
- os: macos-latest
target: x86_64-apple-darwin
build_target: aarch64-apple-darwin
platform_name: macos-arm64
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 MacOS
if: matrix.os == 'macos-latest'
run: cargo build --target ${{ matrix.build_target }} --release
- name: Build Windows
if: matrix.os == 'windows-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
- uses: ncipollo/release-action@v1
id: create_release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
allowUpdates: true
#artifacts: "release.tar.gz,foo/*.txt"
- 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, macos-latest]
include:
- os: ubuntu-latest
platform_name: linux-amd64
- os: windows-latest
platform_name: windows-amd64
- os: macos-latest
platform_name: macos-arm64
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"

5
Cargo.lock generated
View File

@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
version = 4
[[package]]
name = "actix-codec"
@ -1053,9 +1053,10 @@ dependencies = [
[[package]]
name = "khm"
version = "0.1.0"
version = "0.2.2"
dependencies = [
"actix-web",
"base64 0.21.7",
"chrono",
"clap",
"env_logger",

View File

@ -1,8 +1,8 @@
[package]
name = "khm"
version = "0.1.0"
version = "0.3.0"
edition = "2021"
authors = ["AB <ab@hexor.cy>"]
authors = ["AB <ab@hexor.cy>", "ChatGPT-4o"]
[dependencies]
actix-web = "4"
@ -11,8 +11,9 @@ serde_json = "1.0"
env_logger = "0.11.3"
log = "0.4"
regex = "1.10.5"
base64 = "0.21"
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
View File

@ -0,0 +1,5 @@
# syntax=docker/dockerfile:1
FROM alpine:latest
COPY khm /usr/local/bin/khm
ENTRYPOINT ["/usr/local/bin/khm"]

View File

@ -24,21 +24,23 @@ khm --server --ip 127.0.0.1 --port 8080 --db-host 127.0.0.1 --db-name khm --db-u
To run the application in client mode, use the following command:
```bash
khm --host http://khm.example.com:8080 --known-hosts ~/.ssh/known_hosts --in-place
khm --host http://khm.example.com:8080/<FLOW_NAME>/ --known-hosts ~/.ssh/known_hosts --in-place
```
### Arguments
- `--server`: Run in server mode (default: false).
- `--ip`: IP address to bind the server or client to (default: 127.0.0.1).
- `--port`: Port to bind the server or client to (default: 8080).
- `--db-host`: Hostname or IP address of the PostgreSQL database (default: 127.0.0.1).
- `--db-name`: Name of the PostgreSQL database (default: khm).
- `--db-user`: Username for the PostgreSQL database (required in server mode).
- `--db-password`: Password for the PostgreSQL database (required in server mode).
- `--host`: Host address of the server to connect to in client mode (required in client mode).
- `--known-hosts`: Path to the `known_hosts` file (default: ~/.ssh/known_hosts).
- `--in-place`: Update the `known_hosts` file with keys from the server after sending keys (default: false).
- `--flows`: Comma-separated list of flows to manage (default: default).
Options:
- `--server` Run in server mode
- `--in-place` Server mode: Sync the known_hosts file with keys from the server
- `--flows <FLOWS>...` Server mode: Comma-separated list of flows to manage [default: default]
- `-i, --ip <IP>` Server mode: IP address to bind the server to [default: 127.0.0.1]
- `-p, --port <PORT>` Server mode: Port to bind the server to [default: 8080]
- `--db-host <DB_HOST>` Server mode: Hostname or IP address of the PostgreSQL database [default: 127.0.0.1]
- `--db-name <DB_NAME>` Server mode: Name of the PostgreSQL database [default: khm]
- `--db-user <DB_USER>` Server mode: Username for the PostgreSQL database
- `--db-password <DB_PASSWORD>` Server mode: Password for the PostgreSQL database
- `--host <HOST>` Client mode: Full host address of the server to connect to. Like `https://khm.example.com/<FLOW_NAME>`
- `--known-hosts <KNOWN_HOSTS>` Client mode: Path to the known_hosts file [default: ~/.ssh/known_hosts]
## Installation

11
shell.nix Normal file
View File

@ -0,0 +1,11 @@
{ pkgs ? import <nixpkgs> {} }:
pkgs.mkShell {
buildInputs = [
pkgs.openssl
pkgs.pkg-config
];
shellHook = ''
unset OPENSSL_DIR
'';
}

View File

@ -1,3 +1,6 @@
use base64::{engine::general_purpose, Engine as _};
use log::{error, info};
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::fs::File;
@ -17,15 +20,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,19 +45,49 @@ 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(())
}
async fn send_keys_to_server(host: &str, keys: Vec<SshKey>) -> Result<(), reqwest::Error> {
async fn send_keys_to_server(
host: &str,
keys: Vec<SshKey>,
auth_string: &str,
) -> Result<(), reqwest::Error> {
let client = Client::new();
let url = format!("{}/keys", host);
let response = client.post(&url).json(&keys).send().await?;
info!("URL: {} ", url);
let mut headers = HeaderMap::new();
if !auth_string.is_empty() {
let parts: Vec<&str> = auth_string.splitn(2, ':').collect();
if parts.len() == 2 {
let username = parts[0];
let password = parts[1];
let auth_header_value = format!("{}:{}", username, password);
let encoded_auth = general_purpose::STANDARD.encode(auth_header_value);
let auth_header = format!("Basic {}", encoded_auth);
headers.insert(AUTHORIZATION, HeaderValue::from_str(&auth_header).unwrap());
} else {
error!("Invalid auth string format. Expected 'username:password'");
}
}
let response = client
.post(&url)
.headers(headers)
.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()
);
@ -57,39 +96,61 @@ async fn send_keys_to_server(host: &str, keys: Vec<SshKey>) -> Result<(), reqwes
Ok(())
}
async fn get_keys_from_server(host: &str) -> Result<Vec<SshKey>, reqwest::Error> {
async fn get_keys_from_server(
host: &str,
auth_string: &str,
) -> Result<Vec<SshKey>, reqwest::Error> {
let client = Client::new();
let url = format!("{}/keys", host);
let response = client.get(&url).send().await?;
if response.status().is_success() {
let keys: Vec<SshKey> = response.json().await?;
Ok(keys)
} else {
eprintln!(
"Failed to get keys from server. Status: {}",
response.status()
);
Ok(vec![])
let mut headers = HeaderMap::new();
if !auth_string.is_empty() {
let parts: Vec<&str> = auth_string.splitn(2, ':').collect();
if parts.len() == 2 {
let username = parts[0];
let password = parts[1];
let auth_header_value = format!("{}:{}", username, password);
let encoded_auth = general_purpose::STANDARD.encode(auth_header_value);
let auth_header = format!("Basic {}", encoded_auth);
headers.insert(AUTHORIZATION, HeaderValue::from_str(&auth_header).unwrap());
} else {
error!("Invalid auth string format. Expected 'username:password'");
}
}
let response = client.get(&url).headers(headers).send().await?;
let response = response.error_for_status()?;
let keys: Vec<SshKey> = response.json().await?;
info!("Received {} keys from server", keys.len());
Ok(keys)
}
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");
send_keys_to_server(&host, keys)
info!("Client mode: Sending keys to server at {}", host);
send_keys_to_server(&host, keys, &args.basic_auth)
.await
.expect("Failed to send keys to server");
if args.in_place {
let server_keys = get_keys_from_server(&host)
info!("Client mode: In-place update is enabled. Fetching keys from server.");
let server_keys = get_keys_from_server(&host, &args.basic_auth)
.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(())
}

View File

@ -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,19 +12,34 @@ 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\
Running in server mode:\n\
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\
Running in client mode to send diff and sync ~/.ssh/known_hosts with remote flow `work` in place:\n\
khm --host https://khm.example.com/work --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>"
)]
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,
@ -94,27 +106,30 @@ struct Args {
)]
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>,
/// Basic auth string for client mode. Format: user:pass
#[arg(long, default_value = "", help = "Client mode: Basic Auth credentials")]
basic_auth: 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(())
}

View File

@ -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()))