1 Commits

Author SHA1 Message Date
4a9dec7e34 Fixed version string
Some checks failed
Build and deploy / Build container and manifests (push) Failing after 24s
2025-04-18 12:01:47 +02:00
20 changed files with 138 additions and 359 deletions

View File

@@ -1,2 +0,0 @@
[env]
RUSTC_BOOTSTRAP = "1"

View File

@@ -1,4 +1,4 @@
*
!queries
!src
!Cargo.*
!.cargo/config.toml

View File

@@ -17,13 +17,14 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
fetch-tags: true
- name: Set timestamp and release version
- name: Set git based environment variables
run: |
echo "TIMESTAMP=$(git log -1 --pretty=%ct)" >> $GITHUB_ENV
git fetch --prune --unshallow --tags --force
echo "RELEASE_VERSION=$(git describe --always --dirty='--modified')" >> $GITHUB_ENV
cat $GITHUB_ENV
echo "RELEASE_VERSION=$(git describe --always --dirty='--modified)" >> $GITHUB_ENV
- name: Login to registry
uses: docker/login-action@v3
@@ -79,11 +80,11 @@ jobs:
- name: Push manifests
run: |
flux push artifact oci://${{ env.OCI_REPO }}/manifests:${{ gitea.head_ref || gitea.ref_name }} \
flux push artifact oci://$OCI_REPO/manifests:${{ gitea.head_ref || gitea.ref_name }} \
--path="./manifests.yaml" \
--source="$(git config --get remote.origin.url)" \
--revision="$(git rev-parse HEAD)" \
$(echo "${{ steps.meta.outputs.labels }}" | sed -e 's/^/-a /')
flux tag artifact oci://${{ env.OCI_REPO }}/manifests:${{ gitea.head_ref || gitea.ref_name }} \
flux tag artifact oci://$OCI_REPO/manifests:${{ gitea.head_ref || gitea.ref_name }} \
$(echo "${{ steps.meta.outputs.tags }}" | sed -e 's/^.*:/--tag /')

139
Cargo.lock generated
View File

@@ -304,9 +304,9 @@ dependencies = [
[[package]]
name = "cc"
version = "1.2.19"
version = "1.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e3a13707ac958681c13b39b458c073d0d9bc8a22cb1b2f4c8e55eb72c13f362"
checksum = "1fcb57c740ae1daf453ae85f16e37396f672b039e00d9d866e07ddb24e328e3a"
dependencies = [
"shlex",
]
@@ -360,9 +360,9 @@ dependencies = [
[[package]]
name = "clap"
version = "4.5.36"
version = "4.5.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2df961d8c8a0d08aa9945718ccf584145eee3f3aa06cddbeac12933781102e04"
checksum = "d8aa86934b44c19c50f87cc2790e19f54f7a67aedb64101c2e1a2e5ecfb73944"
dependencies = [
"clap_builder",
"clap_derive",
@@ -370,9 +370,9 @@ dependencies = [
[[package]]
name = "clap_builder"
version = "4.5.36"
version = "4.5.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "132dbda40fb6753878316a489d5a1242a8ef2f0d9e47ba01c951ea8aa7d013a5"
checksum = "2414dbb2dd0695280da6ea9261e327479e9d37b0630f6b53ba2a11c60c679fd9"
dependencies = [
"anstream",
"anstyle",
@@ -648,9 +648,9 @@ dependencies = [
[[package]]
name = "data-encoding"
version = "2.9.0"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a2330da5de22e8a3cb63252ce2abb30116bf5265e89c0e01bc17015ce30a476"
checksum = "575f75dfd25738df5b91b8e43e14d44bda14637a58fae779fd2b064f8bf3e010"
[[package]]
name = "delegate"
@@ -870,12 +870,12 @@ checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]]
name = "flate2"
version = "1.1.1"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ced92e76e966ca2fd84c8f7aa01a4aea65b0eb6648d72f7c8f3e2764a67fece"
checksum = "11faaf5a5236997af9848be0bef4db95824b1d534ebc64d0f0c6cf3e67bd38dc"
dependencies = [
"crc32fast",
"miniz_oxide 0.8.8",
"miniz_oxide 0.8.5",
]
[[package]]
@@ -1090,9 +1090,9 @@ dependencies = [
[[package]]
name = "h2"
version = "0.4.9"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75249d144030531f8dee69fe9cea04d3edf809a017ae445e2abdff6629e86633"
checksum = "5017294ff4bb30944501348f6f8e42e6ad28f42c8bbef7a74029aff064a4e3c2"
dependencies = [
"atomic-waker",
"bytes",
@@ -1107,12 +1107,6 @@ dependencies = [
"tracing",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]]
name = "hashbrown"
version = "0.15.2"
@@ -1299,9 +1293,9 @@ dependencies = [
[[package]]
name = "iana-time-zone"
version = "0.1.63"
version = "0.1.62"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0c919e5debc312ad217002b8048a17b7d83f80703865bbfcfebb0458b0b27d8"
checksum = "b2fd658b06e56721792c5df4475705b6cda790e9298d19d2f8af083457bcd127"
dependencies = [
"android_system_properties",
"core-foundation-sys",
@@ -1309,7 +1303,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
"windows-core 0.61.0",
"windows-core 0.52.0",
]
[[package]]
@@ -1479,7 +1473,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cea70ddb795996207ad57735b50c5982d8844f38ba9ee5f1aedcfb708a2aa11e"
dependencies = [
"equivalent",
"hashbrown 0.15.2",
"hashbrown",
]
[[package]]
@@ -1632,9 +1626,9 @@ dependencies = [
[[package]]
name = "libc"
version = "0.2.172"
version = "0.2.171"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa"
checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6"
[[package]]
name = "libm"
@@ -1650,9 +1644,9 @@ checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
[[package]]
name = "linux-raw-sys"
version = "0.9.4"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12"
checksum = "fe7db12097d22ec582439daf8618b8fdd1a7bef6270e9af3b1ebcd30893cf413"
[[package]]
name = "litemap"
@@ -1688,7 +1682,7 @@ version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38"
dependencies = [
"hashbrown 0.15.2",
"hashbrown",
]
[[package]]
@@ -1735,9 +1729,9 @@ dependencies = [
[[package]]
name = "miniz_oxide"
version = "0.8.8"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3be647b768db090acb35d5ec5db2b0e1f1de11133ca123b9eacf5137868f892a"
checksum = "8e3e04debbb59698c15bacbb6d93584a8c0ca9cc3213cb423d31f760d8843ce5"
dependencies = [
"adler2",
]
@@ -2156,9 +2150,9 @@ dependencies = [
[[package]]
name = "proc-macro2"
version = "1.0.95"
version = "1.0.94"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84"
dependencies = [
"unicode-ident",
]
@@ -2191,7 +2185,7 @@ checksum = "b820744eb4dc9b57a3398183639c511b5a26d2ed702cedd3febaa1393caa22cc"
dependencies = [
"bytes",
"getrandom 0.3.2",
"rand 0.9.1",
"rand 0.9.0",
"ring",
"rustc-hash",
"rustls",
@@ -2205,9 +2199,9 @@ dependencies = [
[[package]]
name = "quinn-udp"
version = "0.5.11"
version = "0.5.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "541d0f57c6ec747a90738a52741d3221f7960e8ac2f0ff4b1a63680e033b4ab5"
checksum = "e46f3055866785f6b92bc6164b76be02ca8f2eb4b002c0354b28cf4c119e5944"
dependencies = [
"cfg_aliases",
"libc",
@@ -2245,12 +2239,13 @@ dependencies = [
[[package]]
name = "rand"
version = "0.9.1"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97"
checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94"
dependencies = [
"rand_chacha 0.9.0",
"rand_core 0.9.3",
"zerocopy",
]
[[package]]
@@ -2314,9 +2309,9 @@ dependencies = [
[[package]]
name = "redox_syscall"
version = "0.5.11"
version = "0.5.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f103c6d277498fbceb16e84d317e2a400f160f46904d5f5410848c829511a3"
checksum = "0b8c0c260b63a8219631167be35e6a988e9554dbd323f8bd08439c8ed1302bd1"
dependencies = [
"bitflags",
]
@@ -2591,15 +2586,15 @@ dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys 0.9.4",
"linux-raw-sys 0.9.3",
"windows-sys 0.59.0",
]
[[package]]
name = "rustls"
version = "0.23.26"
version = "0.23.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df51b5869f3a441595eac5e8ff14d486ff285f7b8c0df8770e49c3b56351f0f0"
checksum = "822ee9188ac4ec04a2f0531e55d035fb2de73f18b41a63c70c2712503b6fb13c"
dependencies = [
"once_cell",
"ring",
@@ -2881,7 +2876,6 @@ dependencies = [
"russh",
"thiserror 2.0.12",
"tokio",
"tokio-util",
"tracing",
"tracing-subscriber",
"unicode-width 0.2.0",
@@ -2898,9 +2892,9 @@ dependencies = [
[[package]]
name = "smallvec"
version = "1.15.0"
version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8917285742e9f3e1683f0a9c4e6b57960b7314d0b08d30d1ecd426713ee2eee9"
checksum = "7fcf8323ef1faaee30a44a340193b1ac6814fd9b7b4e88e9d4519a3e4abe1cfd"
[[package]]
name = "socket2"
@@ -3212,8 +3206,6 @@ dependencies = [
"bytes",
"futures-core",
"futures-sink",
"futures-util",
"hashbrown 0.14.5",
"pin-project-lite",
"tokio",
]
@@ -3616,28 +3608,24 @@ dependencies = [
[[package]]
name = "windows-core"
version = "0.58.0"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"
checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
dependencies = [
"windows-implement 0.58.0",
"windows-interface 0.58.0",
"windows-result 0.2.0",
"windows-strings 0.1.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-core"
version = "0.61.0"
version = "0.58.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4763c1de310c86d75a878046489e2e5ba02c649d185f21c67d4cf8a56d098980"
checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"
dependencies = [
"windows-implement 0.60.0",
"windows-interface 0.59.1",
"windows-link",
"windows-result 0.3.2",
"windows-strings 0.4.0",
"windows-implement",
"windows-interface",
"windows-result 0.2.0",
"windows-strings 0.1.0",
"windows-targets 0.52.6",
]
[[package]]
@@ -3651,17 +3639,6 @@ dependencies = [
"syn",
]
[[package]]
name = "windows-implement"
version = "0.60.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "windows-interface"
version = "0.58.0"
@@ -3673,17 +3650,6 @@ dependencies = [
"syn",
]
[[package]]
name = "windows-interface"
version = "0.59.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "windows-link"
version = "0.1.1"
@@ -3738,15 +3704,6 @@ dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a2ba9642430ee452d5a7aa78d72907ebe8cfda358e8cb7918a2050581322f97"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-sys"
version = "0.42.0"

View File

@@ -24,7 +24,6 @@ reqwest = { version = "0.12.15", features = ["rustls-tls"] }
russh = "0.51.1"
thiserror = "2.0.12"
tokio = { version = "1.44.2", features = ["full"] }
tokio-util = { version = "0.7.14", features = ["rt"] }
tracing = "0.1.41"
tracing-subscriber = { version = "0.3.19", features = ["json", "env-filter"] }
unicode-width = "0.2.0"

View File

@@ -1,4 +1,4 @@
FROM rust:1.86 AS base
FROM rust:1.85 AS base
ENV CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse
RUN cargo install cargo-chef --locked --version 0.1.71 && \
cargo install cargo-auditable --locked --version 0.6.6
@@ -15,7 +15,9 @@ RUN cargo chef cook --release --recipe-path recipe.json
COPY . .
ARG RELEASE_VERSION
ENV RELEASE_VERSION=${RELEASE_VERSION}
ENV RELEASE_VERSION ${RELEASE_VERSION}
# HACK: Enable the use of features on stable
ENV RUSTC_BOOTSTRAP=1
RUN cargo auditable build --release
FROM gcr.io/distroless/cc-debian12:nonroot AS runtime

View File

@@ -29,7 +29,7 @@ This deployment runs in a cluster with [Authelia](https://github.com/authelia/au
A tunnel can be opened using the following command:
```
ssh <username>@<host> [-p <ssh port>] -tq -R <local port>:localhost:<local port>
ssh <username>@<host> [-p <ssh port>] -t -R <local port>:localhost:<local port>
```
This will open a new tunnel with a randomly generated name, you can specify a name for the tunnel by instead using `-R <name>:<local port>:localhost:<local port>`.
@@ -44,11 +44,10 @@ To make connecting slightly easier I recommend adding the following to `~/.ssh/c
```
Host tunnel
HostName <host>
HostName <host>
Port <ssh port>
User <username>
RequestTTY yes
LogLevel QUIET
User <username>
RequestTTY yes
```
You can now connect with `ssh tunnel -R <local port>:localhost:<local port>`.

View File

@@ -1,7 +1,10 @@
apiVersion: authelia.huizinga.dev/v1
kind: AccessControlRule
apiVersion: v1
kind: ConfigMap
metadata:
name: tunnel-dev
spec:
domain: "*.tunnel.huizinga.dev"
policy: one_factor
name: authelia-acl
annotations:
config.huizinga.dev/fragment: authelia-acl
data:
rules: |
- domain: "*.tunnel.huizinga.dev"
policy: one_factor

View File

@@ -1,4 +0,0 @@
[toolchain]
channel = "1.86"
profile = "default"
components = ["rust-analyzer"]

View File

@@ -1,6 +1,6 @@
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::task::{Context, Poll};
use pin_project_lite::pin_project;
@@ -14,7 +14,6 @@ pub struct Stats {
connections: AtomicUsize,
rx: AtomicUsize,
tx: AtomicUsize,
failed: AtomicBool,
}
impl Stats {
@@ -34,14 +33,6 @@ impl Stats {
self.connections.load(Ordering::Relaxed)
}
pub fn failed(&self) -> bool {
self.failed.load(Ordering::Relaxed)
}
pub fn set_failed(&self, failed: bool) {
self.failed.store(failed, Ordering::Relaxed);
}
pub fn rx(&self) -> Unit {
Unit::new(self.rx.load(Ordering::Relaxed), "B")
}

View File

@@ -1,9 +1,5 @@
use ldap3::{LdapConnAsync, SearchEntry};
use russh::keys::PublicKey;
use tokio::select;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error};
#[derive(Debug, Clone)]
pub struct Ldap {
@@ -24,9 +20,7 @@ pub enum LdapError {
}
impl Ldap {
pub async fn start_from_env(
token: CancellationToken,
) -> Result<(Ldap, JoinHandle<()>), LdapError> {
pub async fn start_from_env() -> Result<Ldap, LdapError> {
let address = std::env::var("LDAP_ADDRESS")
.map_err(|_| LdapError::MissingEnvironmentVariable("LDAP_ADDRESS"))?;
let base = std::env::var("LDAP_BASE")
@@ -47,25 +41,11 @@ impl Ldap {
)?;
let (conn, mut ldap) = LdapConnAsync::new(&address).await?;
let handle = tokio::spawn(async move {
select! {
res = conn.drive() => {
if let Err(err) = res {
error!("LDAP connection error: {}", err);
} else {
error!("LDAP connection lost");
token.cancel();
}
}
_ = token.cancelled() => {
debug!("Graceful shutdown");
}
}
});
ldap3::drive!(conn);
ldap.simple_bind(&bind_dn, &password).await?.success()?;
Ok((Self { base, ldap }, handle))
Ok(Self { base, ldap })
}
pub async fn get_ssh_keys(

View File

@@ -1,12 +1,14 @@
#![feature(let_chains)]
#![feature(iter_intersperse)]
#![feature(future_join)]
mod helper;
mod io;
pub mod ldap;
pub mod ssh;
pub mod tunnel;
mod version;
pub mod web;
pub use version::VERSION;
pub fn get_version() -> &'static str {
std::option_env!("RELEASE_VERSION")
.filter(|version| !version.is_empty())
.unwrap_or(git_version::git_version!())
}

View File

@@ -1,59 +1,22 @@
#![feature(future_join)]
use std::future::join;
use std::net::SocketAddr;
use std::path::Path;
use std::time::Duration;
use color_eyre::eyre::Context;
use dotenvy::dotenv;
use hyper::server::conn::http1::{self};
use hyper_util::rt::TokioIo;
use rand::rngs::OsRng;
use siranga::VERSION;
use siranga::get_version;
use siranga::ldap::Ldap;
use siranga::ssh::Server;
use siranga::tunnel::Registry;
use siranga::web::{ForwardAuth, Service};
use tokio::net::TcpListener;
use tokio::select;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};
use tracing::{error, info, warn};
use tracing_subscriber::EnvFilter;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
#[cfg(unix)]
async fn sigterm() {
use tokio::signal::unix::SignalKind;
let mut sigterm =
tokio::signal::unix::signal(SignalKind::terminate()).expect("should be able to initialize");
sigterm.recv().await;
}
#[cfg(not(unix))]
async fn sigterm() {
std::future::pending::<()>().await;
}
async fn shutdown_task(token: CancellationToken) {
select! {
_ = tokio::signal::ctrl_c() => {
debug!("Received SIGINT");
}
_ = sigterm() => {
debug!("Received SIGTERM");
}
_ = token.cancelled() => {
debug!("Application called for graceful shutdown");
}
}
info!("Starting graceful shutdown");
token.cancel();
select! {
_ = tokio::time::sleep(Duration::from_secs(5)) => {}
_ = tokio::signal::ctrl_c() => {}
}
}
#[tokio::main]
async fn main() -> color_eyre::Result<()> {
color_eyre::install()?;
@@ -75,7 +38,7 @@ async fn main() -> color_eyre::Result<()> {
.init();
}
info!(version = VERSION, "Starting",);
info!(version = get_version(), "Starting",);
let key = if let Ok(path) = std::env::var("PRIVATE_KEY_FILE") {
russh::keys::PrivateKey::read_openssh_file(Path::new(&path))
@@ -96,32 +59,35 @@ async fn main() -> color_eyre::Result<()> {
std::env::var("TUNNEL_DOMAIN").unwrap_or_else(|_| format!("localhost:{http_port}"));
let authz_address = std::env::var("AUTHZ_ENDPOINT").wrap_err("AUTHZ_ENDPOINT is not set")?;
let ldap = Ldap::start_from_env().await?;
let registry = Registry::new(domain);
let token = CancellationToken::new();
let (ldap, ldap_handle) = Ldap::start_from_env(token.clone()).await?;
let ssh = Server::new(ldap, registry.clone(), token.clone());
let ssh_addr = SocketAddr::from(([0, 0, 0, 0], ssh_port));
let ssh_task = ssh.run(key, ssh_addr);
info!("SSH is available on {ssh_addr}");
let mut ssh = Server::new(ldap, registry.clone());
let addr = SocketAddr::from(([0, 0, 0, 0], ssh_port));
tokio::spawn(async move { ssh.run(key, addr).await });
info!("SSH is available on {addr}");
let auth = ForwardAuth::new(authz_address);
let service = Service::new(registry, auth);
let http_addr = SocketAddr::from(([0, 0, 0, 0], http_port));
let http_listener = TcpListener::bind(http_addr).await?;
let http_task = service.serve(http_listener, token.clone());
info!("HTTP is available on {http_addr}");
let addr = SocketAddr::from(([0, 0, 0, 0], http_port));
let listener = TcpListener::bind(addr).await?;
info!("HTTP is available on {addr}");
select! {
_ = join!(ldap_handle, ssh_task, http_task) => {
info!("Shutdown gracefully");
}
_ = shutdown_task(token.clone()) => {
error!("Failed to shut down gracefully");
}
};
// TODO: Graceful shutdown
loop {
let (stream, _) = listener.accept().await?;
let io = TokioIo::new(stream);
Ok(())
let service = service.clone();
tokio::spawn(async move {
if let Err(err) = http1::Builder::new()
.preserve_header_case(true)
.title_case_headers(true)
.serve_connection(io, service)
.with_upgrades()
.await
{
error!("Failed to serve connection: {err:?}");
}
});
}
}

View File

@@ -2,24 +2,22 @@ use std::cmp::min;
use std::iter::once;
use clap::Parser;
use git_version::git_version;
use ratatui::layout::Rect;
use ratatui::prelude::CrosstermBackend;
use ratatui::{Terminal, TerminalOptions, Viewport};
use russh::ChannelId;
use russh::keys::ssh_key::PublicKey;
use russh::server::{Auth, Msg, Session};
use tokio_util::sync::CancellationToken;
use tracing::{debug, trace, warn};
use super::renderer::Renderer;
use crate::VERSION;
use crate::io::{Input, TerminalHandle};
use crate::ldap::{Ldap, LdapError};
use crate::tunnel::{Registry, Tunnel, TunnelAccess};
/// Quickly create http tunnels for development
#[derive(Parser, Debug)]
#[command(version = VERSION, about, long_about = None)]
#[command(version = git_version!(), about, long_about = None)]
pub struct Args {
/// Make all tunnels public by default instead of private
#[arg(long, group = "access")]
@@ -64,7 +62,7 @@ pub struct Handler {
}
impl Handler {
pub fn new(ldap: Ldap, registry: Registry, token: CancellationToken) -> Self {
pub fn new(ldap: Ldap, registry: Registry) -> Self {
Self {
ldap,
registry,
@@ -72,7 +70,7 @@ impl Handler {
user: None,
pty_channel: None,
renderer: Renderer::new(token),
renderer: Default::default(),
selected: None,
rename_input: None,
}

View File

@@ -11,9 +11,7 @@ use russh::MethodKind;
use russh::keys::PrivateKey;
use russh::server::Server as _;
use tokio::net::ToSocketAddrs;
use tokio::select;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, warn};
use tracing::{debug, warn};
use crate::ldap::Ldap;
use crate::tunnel::Registry;
@@ -21,30 +19,18 @@ use crate::tunnel::Registry;
pub struct Server {
ldap: Ldap,
registry: Registry,
token: CancellationToken,
}
async fn graceful_shutdown(token: CancellationToken) {
token.cancelled().await;
let duration = 1;
// All pty sessions will close once the token is cancelled, but to properly allow the sessions
// to close the ssh server still needs to be driven, so we let it run a little bit longer.
// TODO: Figure out a way to wait for all connections to be closed, would require also closing
// non-pty sessions somehow
debug!("Waiting for {duration}s before stopping");
tokio::time::sleep(Duration::from_secs(duration)).await;
}
impl Server {
pub fn new(ldap: Ldap, registry: Registry, token: CancellationToken) -> Self {
Server {
ldap,
registry,
token,
}
pub fn new(ldap: Ldap, registry: Registry) -> Self {
Server { ldap, registry }
}
pub async fn run(mut self, key: PrivateKey, addr: impl ToSocketAddrs + Send + std::fmt::Debug) {
pub fn run(
&mut self,
key: PrivateKey,
addr: impl ToSocketAddrs + Send + std::fmt::Debug,
) -> impl Future<Output = Result<(), std::io::Error>> + Send {
let config = russh::server::Config {
inactivity_timeout: Some(Duration::from_secs(3600)),
auth_rejection_time: Duration::from_secs(1),
@@ -61,17 +47,7 @@ impl Server {
debug!(?addr, "Running ssh");
let token = self.token.clone();
select! {
res = self.run_on_address(config, addr) => {
if let Err(err) = res {
error!("SSH Server error: {err}");
}
}
_ = graceful_shutdown(token) => {
debug!("Graceful shutdown");
}
}
async move { self.run_on_address(config, addr).await }
}
}
@@ -79,7 +55,7 @@ impl russh::server::Server for Server {
type Handler = Handler;
fn new_client(&mut self, _peer_addr: Option<SocketAddr>) -> Self::Handler {
Handler::new(self.ldap.clone(), self.registry.clone(), self.token.clone())
Handler::new(self.ldap.clone(), self.registry.clone())
}
fn handle_session_error(&mut self, error: <Self::Handler as russh::server::Handler>::Error) {

View File

@@ -14,11 +14,10 @@ use ratatui::widgets::{
use ratatui::{Frame, Terminal};
use tokio::select;
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
use tokio_util::sync::CancellationToken;
use tracing::{debug, error};
use tracing::error;
use unicode_width::UnicodeWidthStr;
use crate::VERSION;
use crate::get_version;
use crate::io::TerminalHandle;
use crate::tunnel::{Tunnel, TunnelRow};
@@ -37,8 +36,6 @@ struct RendererInner {
rows: Vec<TunnelRow>,
input: Option<String>,
rx: UnboundedReceiver<Message>,
token: CancellationToken,
}
fn compute_widths(rows: &Vec<Vec<Span<'static>>>) -> Vec<u16> {
@@ -78,13 +75,12 @@ fn compute_column_skip(
}
impl RendererInner {
fn new(rx: UnboundedReceiver<Message>, token: CancellationToken) -> Self {
fn new(rx: UnboundedReceiver<Message>) -> Self {
Self {
state: Default::default(),
rows: Default::default(),
input: None,
rx,
token,
}
}
@@ -169,7 +165,7 @@ impl RendererInner {
}
fn render_title(&self, frame: &mut Frame, rect: Rect) {
let title = format!("{} ({})", std::env!("CARGO_PKG_NAME"), VERSION).bold();
let title = format!("{} ({})", std::env!("CARGO_PKG_NAME"), get_version()).bold();
let title = Line::from(title).centered();
frame.render_widget(title, rect);
}
@@ -307,10 +303,6 @@ impl RendererInner {
self.render(frame);
})?;
}
_ = self.token.cancelled() => {
debug!("Graceful shutdown");
break;
}
}
}
@@ -318,24 +310,16 @@ impl RendererInner {
}
}
#[derive(Debug, Clone)]
#[derive(Debug, Default, Clone)]
pub struct Renderer {
tx: Option<UnboundedSender<Message>>,
token: CancellationToken,
}
impl Renderer {
pub fn new(token: CancellationToken) -> Self {
Self {
tx: Default::default(),
token,
}
}
pub fn start(&mut self, terminal: Terminal<CrosstermBackend<TerminalHandle>>) {
let (tx, rx) = unbounded_channel();
let mut inner = RendererInner::new(rx, self.token.clone());
let mut inner = RendererInner::new(rx);
tokio::spawn(async move {
if let Err(err) = inner.start(terminal).await {

View File

@@ -40,12 +40,7 @@ impl TunnelInner {
&self.internal_address,
self.port,
)
.await
.inspect_err(|_| {
self.stats.set_failed(true);
})?;
self.stats.set_failed(false);
.await?;
Ok(TrackStats::new(channel.into_stream(), self.stats.clone()))
}

View File

@@ -17,15 +17,9 @@ pub struct TunnelRow {
impl From<&TunnelRow> for Vec<Span<'static>> {
fn from(row: &TunnelRow) -> Self {
let port = if row.stats.failed() {
row.port.clone().red()
} else {
row.port.clone()
};
vec![
row.name.clone(),
port,
row.port.clone(),
row.access.clone(),
row.address.clone(),
row.stats.connections().to_string().into(),

View File

@@ -1,11 +0,0 @@
pub const VERSION: &str = get_version();
const fn get_version() -> &'static str {
if let Some(version) = std::option_env!("RELEASE_VERSION")
&& !version.is_empty()
{
version
} else {
git_version::git_version!(fallback = "unknown")
}
}

View File

@@ -1,7 +1,6 @@
mod auth;
mod response;
use std::future::join;
use std::ops::Deref;
use std::pin::Pin;
@@ -13,14 +12,8 @@ use http_body_util::{BodyExt as _, Empty};
use hyper::body::Incoming;
use hyper::client::conn::http1::Builder;
use hyper::header::{self, HOST};
use hyper::server::conn::http1;
use hyper::{Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use hyper_util::server::graceful::GracefulShutdown;
use response::response;
use tokio::net::TcpListener;
use tokio::select;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, trace, warn};
use crate::tunnel::{Registry, TunnelAccess};
@@ -35,49 +28,6 @@ impl Service {
pub fn new(registry: Registry, auth: ForwardAuth) -> Self {
Self { registry, auth }
}
pub async fn handle_connection(
&self,
listener: &TcpListener,
graceful_shutdown: &GracefulShutdown,
) -> std::io::Result<()> {
let (stream, _) = listener.accept().await?;
let io = TokioIo::new(stream);
let connection = http1::Builder::new()
.preserve_header_case(true)
.title_case_headers(true)
.serve_connection(io, self.clone());
let connection = graceful_shutdown.watch(connection);
tokio::spawn(async move {
if let Err(err) = connection.await {
error!("Failed to serve connection: {err:?}");
}
});
Ok(())
}
pub async fn serve(self, listener: TcpListener, token: CancellationToken) {
let graceful_shutdown = GracefulShutdown::new();
loop {
select! {
res = self.handle_connection(&listener, &graceful_shutdown) => {
if let Err(err) = res {
error!("Failed to accept connection: {err}")
}
}
_ = token.cancelled() => {
debug!("Graceful shutdown");
break;
}
}
}
graceful_shutdown.shutdown().await;
}
}
impl hyper::service::Service<Request<Incoming>> for Service {
@@ -185,15 +135,14 @@ impl hyper::service::Service<Request<Incoming>> for Service {
.handshake(io)
.await?;
let conn = async {
tokio::spawn(async move {
if let Err(err) = conn.await {
warn!(runnel = authority, "Connection failed: {err}");
}
};
});
let (resp, _) = join!(sender.send_request(req), conn).await;
Ok(resp?.map(|b| b.boxed()))
let resp = sender.send_request(req).await?;
Ok(resp.map(|b| b.boxed()))
})
}
}