mirror of
https://github.com/house-of-vanity/khm.git
synced 2025-07-07 23:34:07 +00:00
Compare commits
48 Commits
Author | SHA1 | Date | |
---|---|---|---|
b4c2fae778 | |||
61552a3d70 | |||
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 |
199
.github/workflows/main.yml
vendored
199
.github/workflows/main.yml
vendored
@ -1,84 +1,177 @@
|
|||||||
name: Rust CI
|
name: Rust static build and publish
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
tags:
|
tags:
|
||||||
- 'v*.*.*' # Запуск при создании новой тэгированной версии
|
- 'v*.*.*'
|
||||||
pull_request:
|
|
||||||
branches:
|
env:
|
||||||
- main
|
CARGO_TERM_COLOR: always
|
||||||
|
BINARY_NAME: khm
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
|
name: Build static binary
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
os: [ubuntu-latest, windows-latest]
|
||||||
include:
|
include:
|
||||||
- os: ubuntu-latest
|
- os: ubuntu-latest
|
||||||
target: x86_64-unknown-linux-gnu
|
build_target: x86_64-unknown-linux-musl
|
||||||
|
platform_name: linux-amd64
|
||||||
- os: windows-latest
|
- os: windows-latest
|
||||||
target: x86_64-pc-windows-msvc
|
build_target: x86_64-pc-windows-msvc
|
||||||
- os: macos-latest
|
platform_name: windows-amd64
|
||||||
target: x86_64-apple-darwin
|
permissions:
|
||||||
|
contents: write
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- uses: actions/checkout@v4
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Set up Rust
|
- name: Cache Cargo registry
|
||||||
uses: actions-rs/toolchain@v1
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
toolchain: stable
|
path: ~/.cargo/registry
|
||||||
profile: minimal
|
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
|
||||||
override: true
|
restore-keys: |
|
||||||
|
${{ runner.os }}-cargo-registry-
|
||||||
|
|
||||||
- name: Install target
|
- name: Cache Cargo index
|
||||||
run: rustup target add ${{ matrix.target }}
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ~/.cargo/git
|
||||||
|
key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-cargo-index-
|
||||||
|
|
||||||
- name: Build project
|
- name: Cache Cargo build
|
||||||
run: cargo build --release --target ${{ matrix.target }}
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: target
|
||||||
|
key: ${{ runner.os }}-cargo-build-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-cargo-build-
|
||||||
|
|
||||||
- name: Run tests
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
run: cargo test --target ${{ matrix.target }}
|
|
||||||
|
|
||||||
- name: Upload release assets
|
- 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
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: khm-${{ matrix.os }}
|
name: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
|
||||||
path: target/${{ matrix.target }}/release/
|
path: target/${{ matrix.build_target }}/release/${{ env.BINARY_NAME }}*
|
||||||
|
|
||||||
release:
|
release:
|
||||||
runs-on: ubuntu-latest
|
name: Create Release Page
|
||||||
needs: build
|
needs: build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
outputs:
|
||||||
|
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- uses: actions/checkout@v4
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Download Linux build artifact
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
name: khm-ubuntu-latest
|
|
||||||
path: target/x86_64-unknown-linux-gnu/release/
|
|
||||||
|
|
||||||
- name: Download Windows build artifact
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
name: khm-windows-latest
|
|
||||||
path: target/x86_64-pc-windows-msvc/release/
|
|
||||||
|
|
||||||
- name: Download macOS build artifact
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
name: khm-macos-latest
|
|
||||||
path: target/x86_64-apple-darwin/release/
|
|
||||||
|
|
||||||
- name: Create Release
|
- name: Create Release
|
||||||
id: create_release
|
id: create_release
|
||||||
uses: ncipollo/release-action@v1
|
uses: actions/create-release@v1
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
with:
|
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"
|
tag_name: ${{ github.ref }}
|
||||||
#bodyFile: "body.md"
|
release_name: Release ${{ github.ref }}
|
||||||
|
draft: false
|
||||||
|
prerelease: false
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
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: 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 }}
|
||||||
|
|
||||||
|
2
Cargo.lock
generated
2
Cargo.lock
generated
@ -1053,7 +1053,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "khm"
|
name = "khm"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"actix-web",
|
"actix-web",
|
||||||
"chrono",
|
"chrono",
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "khm"
|
name = "khm"
|
||||||
version = "0.1.0"
|
version = "0.2.2"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
authors = ["AB <ab@hexor.cy>"]
|
authors = ["AB <ab@hexor.cy>", "ChatGPT-4o"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "4"
|
actix-web = "4"
|
||||||
|
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"]
|
26
README.MD
26
README.MD
@ -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:
|
To run the application in client mode, use the following command:
|
||||||
|
|
||||||
```bash
|
```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
|
### Arguments
|
||||||
- `--server`: Run in server mode (default: false).
|
Options:
|
||||||
- `--ip`: IP address to bind the server or client to (default: 127.0.0.1).
|
- `--server` Run in server mode
|
||||||
- `--port`: Port to bind the server or client to (default: 8080).
|
- `--in-place` Server mode: Sync the known_hosts file with keys from the server
|
||||||
- `--db-host`: Hostname or IP address of the PostgreSQL database (default: 127.0.0.1).
|
- `--flows <FLOWS>...` Server mode: Comma-separated list of flows to manage [default: default]
|
||||||
- `--db-name`: Name of the PostgreSQL database (default: khm).
|
- `-i, --ip <IP>` Server mode: IP address to bind the server to [default: 127.0.0.1]
|
||||||
- `--db-user`: Username for the PostgreSQL database (required in server mode).
|
- `-p, --port <PORT>` Server mode: Port to bind the server to [default: 8080]
|
||||||
- `--db-password`: Password for the PostgreSQL database (required in server mode).
|
- `--db-host <DB_HOST>` Server mode: Hostname or IP address of the PostgreSQL database [default: 127.0.0.1]
|
||||||
- `--host`: Host address of the server to connect to in client mode (required in client mode).
|
- `--db-name <DB_NAME>` Server mode: Name of the PostgreSQL database [default: khm]
|
||||||
- `--known-hosts`: Path to the `known_hosts` file (default: ~/.ssh/known_hosts).
|
- `--db-user <DB_USER>` Server mode: Username for the PostgreSQL database
|
||||||
- `--in-place`: Update the `known_hosts` file with keys from the server after sending keys (default: false).
|
- `--db-password <DB_PASSWORD>` Server mode: Password for the PostgreSQL database
|
||||||
- `--flows`: Comma-separated list of flows to manage (default: default).
|
- `--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
|
## Installation
|
||||||
|
|
||||||
|
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 reqwest::Client;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
@ -17,7 +18,8 @@ fn read_known_hosts(file_path: &str) -> io::Result<Vec<SshKey>> {
|
|||||||
|
|
||||||
let mut keys = Vec::new();
|
let mut keys = Vec::new();
|
||||||
for line in reader.lines() {
|
for line in reader.lines() {
|
||||||
if let Ok(line) = line {
|
match line {
|
||||||
|
Ok(line) => {
|
||||||
let parts: Vec<&str> = line.split_whitespace().collect();
|
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||||
if parts.len() >= 2 {
|
if parts.len() >= 2 {
|
||||||
let server = parts[0].to_string();
|
let server = parts[0].to_string();
|
||||||
@ -25,7 +27,12 @@ fn read_known_hosts(file_path: &str) -> io::Result<Vec<SshKey>> {
|
|||||||
keys.push(SshKey { server, public_key });
|
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)
|
Ok(keys)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,6 +43,7 @@ fn write_known_hosts(file_path: &str, keys: &[SshKey]) -> io::Result<()> {
|
|||||||
for key in keys {
|
for key in keys {
|
||||||
writeln!(file, "{} {}", key.server, key.public_key)?;
|
writeln!(file, "{} {}", key.server, key.public_key)?;
|
||||||
}
|
}
|
||||||
|
info!("Wrote {} keys to known_hosts file", keys.len());
|
||||||
|
|
||||||
Ok(())
|
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?;
|
let response = client.post(&url).json(&keys).send().await?;
|
||||||
|
|
||||||
if response.status().is_success() {
|
if response.status().is_success() {
|
||||||
println!("Keys successfully sent to server.");
|
info!("Keys successfully sent to server.");
|
||||||
} else {
|
} else {
|
||||||
eprintln!(
|
error!(
|
||||||
"Failed to send keys to server. Status: {}",
|
"Failed to send keys to server. Status: {}",
|
||||||
response.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() {
|
if response.status().is_success() {
|
||||||
let keys: Vec<SshKey> = response.json().await?;
|
let keys: Vec<SshKey> = response.json().await?;
|
||||||
|
info!("Received {} keys from server", keys.len());
|
||||||
Ok(keys)
|
Ok(keys)
|
||||||
} else {
|
} else {
|
||||||
eprintln!(
|
error!(
|
||||||
"Failed to get keys from server. Status: {}",
|
"Failed to get keys from server. Status: {}",
|
||||||
response.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<()> {
|
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 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");
|
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)
|
send_keys_to_server(&host, keys)
|
||||||
.await
|
.await
|
||||||
.expect("Failed to send keys to server");
|
.expect("Failed to send keys to server");
|
||||||
|
|
||||||
if args.in_place {
|
if args.in_place {
|
||||||
|
info!("Client mode: In-place update is enabled. Fetching keys from server.");
|
||||||
let server_keys = get_keys_from_server(&host)
|
let server_keys = get_keys_from_server(&host)
|
||||||
.await
|
.await
|
||||||
.expect("Failed to get keys from server");
|
.expect("Failed to get keys from server");
|
||||||
|
|
||||||
|
info!("Client mode: Writing updated known_hosts file");
|
||||||
write_known_hosts(&args.known_hosts, &server_keys)
|
write_known_hosts(&args.known_hosts, &server_keys)
|
||||||
.expect("Failed to write known hosts file");
|
.expect("Failed to write known hosts file");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
info!("Client mode: Finished operations");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
53
src/main.rs
53
src/main.rs
@ -3,6 +3,7 @@ mod server;
|
|||||||
|
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use env_logger;
|
use env_logger;
|
||||||
|
use log::{error, info};
|
||||||
|
|
||||||
/// This application manages SSH keys and flows, either as a server or client.
|
/// 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.
|
/// In server mode, it stores keys and flows in a PostgreSQL database.
|
||||||
@ -11,19 +12,34 @@ use env_logger;
|
|||||||
#[command(
|
#[command(
|
||||||
author = env!("CARGO_PKG_AUTHORS"),
|
author = env!("CARGO_PKG_AUTHORS"),
|
||||||
version = env!("CARGO_PKG_VERSION"),
|
version = env!("CARGO_PKG_VERSION"),
|
||||||
about = "SSH Key Manager",
|
about = "SSH Host Key Manager",
|
||||||
long_about = None,
|
long_about = None,
|
||||||
after_help = "Examples:\n\
|
after_help = "Examples:\n\
|
||||||
\n\
|
\n\
|
||||||
Running in server mode:\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\
|
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\
|
\n\
|
||||||
Running in client mode to send diff and sync ~/.ssh/known_hosts with remote flow in place:\n\
|
Running in client mode to send diff and sync ~/.ssh/known_hosts with remote flow `work` in place:\n\
|
||||||
khm --host http://kh.example.com:8080 --known_hosts ~/.ssh/known_hosts --in-place\n\
|
khm --host https://khm.example.com/work --known-hosts ~/.ssh/known_hosts --in-place\n\
|
||||||
\n\
|
\n\
|
||||||
"
|
"
|
||||||
)]
|
)]
|
||||||
struct Args {
|
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)
|
/// IP address to bind the server or client to (default: 127.0.0.1)
|
||||||
#[arg(
|
#[arg(
|
||||||
short,
|
short,
|
||||||
@ -78,14 +94,10 @@ struct Args {
|
|||||||
#[arg(
|
#[arg(
|
||||||
long,
|
long,
|
||||||
required_if_eq("server", "false"),
|
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>,
|
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)
|
/// Path to the known_hosts file (default: ~/.ssh/known_hosts)
|
||||||
#[arg(
|
#[arg(
|
||||||
long,
|
long,
|
||||||
@ -93,28 +105,27 @@ struct Args {
|
|||||||
help = "Client mode: Path to the known_hosts file"
|
help = "Client mode: Path to the known_hosts file"
|
||||||
)]
|
)]
|
||||||
known_hosts: String,
|
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]
|
#[actix_web::main]
|
||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
env_logger::init();
|
env_logger::init();
|
||||||
|
info!("Starting SSH Key Manager");
|
||||||
|
|
||||||
let args = Args::parse();
|
let args = Args::parse();
|
||||||
|
|
||||||
if args.server {
|
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 {
|
} 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 actix_web::{web, App, HttpResponse, HttpServer, Responder};
|
||||||
use log;
|
use log::{error, info};
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@ -51,12 +51,14 @@ pub async fn insert_key_if_not_exists(
|
|||||||
&[&row.get::<_, i32>(0)],
|
&[&row.get::<_, i32>(0)],
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
info!("Updated existing key for server: {}", key.server);
|
||||||
Ok(row.get(0))
|
Ok(row.get(0))
|
||||||
} else {
|
} else {
|
||||||
let row = client.query_one(
|
let row = client.query_one(
|
||||||
"INSERT INTO public.keys (host, key, updated) VALUES ($1, $2, NOW()) RETURNING key_id",
|
"INSERT INTO public.keys (host, key, updated) VALUES ($1, $2, NOW()) RETURNING key_id",
|
||||||
&[&key.server, &key.public_key]
|
&[&key.server, &key.public_key]
|
||||||
).await?;
|
).await?;
|
||||||
|
info!("Inserted new key for server: {}", key.server);
|
||||||
Ok(row.get(0))
|
Ok(row.get(0))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -72,6 +74,7 @@ pub async fn insert_flow_key(
|
|||||||
&[&flow_name, &key_id],
|
&[&flow_name, &key_id],
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
info!("Inserted key_id {} into flow: {}", key_id, flow_name);
|
||||||
Ok(())
|
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())
|
Ok(flows_map.into_values().collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -116,14 +120,17 @@ pub async fn get_keys(
|
|||||||
) -> impl Responder {
|
) -> impl Responder {
|
||||||
let flow_id_str = flow_id.into_inner();
|
let flow_id_str = flow_id.into_inner();
|
||||||
if !allowed_flows.contains(&flow_id_str) {
|
if !allowed_flows.contains(&flow_id_str) {
|
||||||
|
error!("Flow ID not allowed: {}", flow_id_str);
|
||||||
return HttpResponse::Forbidden().body("Flow ID not allowed");
|
return HttpResponse::Forbidden().body("Flow ID not allowed");
|
||||||
}
|
}
|
||||||
|
|
||||||
let flows = flows.lock().unwrap();
|
let flows = flows.lock().unwrap();
|
||||||
if let Some(flow) = flows.iter().find(|flow| flow.name == flow_id_str) {
|
if let Some(flow) = flows.iter().find(|flow| flow.name == flow_id_str) {
|
||||||
let servers: Vec<&SshKey> = flow.servers.iter().collect();
|
let servers: Vec<&SshKey> = flow.servers.iter().collect();
|
||||||
|
info!("Returning {} keys for flow: {}", servers.len(), flow_id_str);
|
||||||
HttpResponse::Ok().json(servers)
|
HttpResponse::Ok().json(servers)
|
||||||
} else {
|
} else {
|
||||||
|
error!("Flow ID not found: {}", flow_id_str);
|
||||||
HttpResponse::NotFound().body("Flow ID not found")
|
HttpResponse::NotFound().body("Flow ID not found")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -137,11 +144,13 @@ pub async fn add_keys(
|
|||||||
) -> impl Responder {
|
) -> impl Responder {
|
||||||
let flow_id_str = flow_id.into_inner();
|
let flow_id_str = flow_id.into_inner();
|
||||||
if !allowed_flows.contains(&flow_id_str) {
|
if !allowed_flows.contains(&flow_id_str) {
|
||||||
|
error!("Flow ID not allowed: {}", flow_id_str);
|
||||||
return HttpResponse::Forbidden().body("Flow ID not allowed");
|
return HttpResponse::Forbidden().body("Flow ID not allowed");
|
||||||
}
|
}
|
||||||
|
|
||||||
for new_key in new_keys.iter() {
|
for new_key in new_keys.iter() {
|
||||||
if !is_valid_ssh_key(&new_key.public_key) {
|
if !is_valid_ssh_key(&new_key.public_key) {
|
||||||
|
error!("Invalid SSH key format for server: {}", new_key.server);
|
||||||
return HttpResponse::BadRequest().body(format!(
|
return HttpResponse::BadRequest().body(format!(
|
||||||
"Invalid SSH key format for server: {}",
|
"Invalid SSH key format for server: {}",
|
||||||
new_key.server
|
new_key.server
|
||||||
@ -151,31 +160,38 @@ pub async fn add_keys(
|
|||||||
match insert_key_if_not_exists(&db_client, new_key).await {
|
match insert_key_if_not_exists(&db_client, new_key).await {
|
||||||
Ok(key_id) => {
|
Ok(key_id) => {
|
||||||
if let Err(e) = insert_flow_key(&db_client, &flow_id_str, key_id).await {
|
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()
|
return HttpResponse::InternalServerError()
|
||||||
.body("Failed to insert flow key into database");
|
.body("Failed to insert flow key into database");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
log::error!("Failed to insert key into database: {}", e);
|
error!("Failed to insert key into database: {}", e);
|
||||||
return HttpResponse::InternalServerError()
|
return HttpResponse::InternalServerError()
|
||||||
.body("Failed to insert key into database");
|
.body("Failed to insert key into database");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Refresh the flows data from the database
|
let updated_flows = match get_keys_from_db(&db_client).await {
|
||||||
let updated_flows = get_keys_from_db(&db_client)
|
Ok(flows) => flows,
|
||||||
.await
|
Err(e) => {
|
||||||
.unwrap_or_else(|_| Vec::new());
|
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();
|
let mut flows_guard = flows.lock().unwrap();
|
||||||
*flows_guard = updated_flows;
|
*flows_guard = updated_flows;
|
||||||
|
|
||||||
let updated_flow = flows_guard.iter().find(|flow| flow.name == flow_id_str);
|
let updated_flow = flows_guard.iter().find(|flow| flow.name == flow_id_str);
|
||||||
if let Some(flow) = updated_flow {
|
if let Some(flow) = updated_flow {
|
||||||
let servers: Vec<&SshKey> = flow.servers.iter().collect();
|
let servers: Vec<&SshKey> = flow.servers.iter().collect();
|
||||||
|
info!("Updated flow: {} with {} keys", flow_id_str, servers.len());
|
||||||
HttpResponse::Ok().json(servers)
|
HttpResponse::Ok().json(servers)
|
||||||
} else {
|
} else {
|
||||||
|
error!("Flow ID not found after update: {}", flow_id_str);
|
||||||
HttpResponse::NotFound().body("Flow ID not found")
|
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
|
// Spawn a new thread to run the database connection
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
if let Err(e) = connection.await {
|
if let Err(e) = connection.await {
|
||||||
eprintln!("Connection error: {}", e);
|
error!("Connection error: {}", e);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut initial_flows = get_keys_from_db(&db_client)
|
let mut initial_flows = match get_keys_from_db(&db_client).await {
|
||||||
.await
|
Ok(flows) => flows,
|
||||||
.unwrap_or_else(|_| Vec::new());
|
Err(e) => {
|
||||||
|
error!("Failed to get initial flows from database: {}", e);
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Ensure all allowed flows are initialized
|
// Ensure all allowed flows are initialized
|
||||||
for allowed_flow in &args.flows {
|
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 flows: Flows = Arc::new(Mutex::new(initial_flows));
|
||||||
let allowed_flows = web::Data::new(args.flows);
|
let allowed_flows = web::Data::new(args.flows);
|
||||||
|
|
||||||
|
info!("Starting HTTP server on {}:{}", args.ip, args.port);
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
App::new()
|
App::new()
|
||||||
.app_data(web::Data::new(flows.clone()))
|
.app_data(web::Data::new(flows.clone()))
|
||||||
|
Reference in New Issue
Block a user