Lines
100 %
Functions
95 %
Branches
use crate::handler::{AuthMethod, SshConnectInfo, SshdState};
use crate::metrics::{SessionGauge, start};
use crate::rate_limit::{Config, InstantClock, RateLimiter};
use russh::server::{Handler as _, Server as _};
use server::telemetry::recorder::{SSH_SESSIONS_ACTIVE, SSH_SESSIONS_TOTAL, build_recorder};
use sqlx::types::Uuid;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::sync::Mutex;
fn sshd_state() -> SshdState {
SshdState {
limiter: Arc::new(Mutex::new(RateLimiter::new(
Config {
max_attempts_per_ip: 6,
max_pubkey_attempts_per_ip: 30,
window: Duration::from_mins(1),
account_lockout_threshold: 3,
account_lockout_duration: Duration::from_mins(15),
},
InstantClock,
))),
connect_info: SshConnectInfo {
hostname: "h".into(),
port: 22,
host_fingerprint: String::new(),
}
fn value(rendered: &str, name: &str) -> f64 {
rendered
.lines()
.find(|line| line.starts_with(name) && line[name.len()..].starts_with(' '))
.and_then(|line| line.rsplit(' ').next())
.and_then(|v| v.parse().ok())
.unwrap_or(0.0)
fn denying_state() -> SshdState {
let mut state = sshd_state();
state.limiter = Arc::new(Mutex::new(RateLimiter::new(
max_attempts_per_ip: 0,
max_pubkey_attempts_per_ip: 0,
account_lockout_threshold: 100,
account_lockout_duration: Duration::from_mins(1),
)));
state
#[test]
fn a_connection_that_never_authenticates_counts_nothing() {
let recorder = build_recorder().expect("recorder");
let handle = recorder.handle();
metrics::with_local_recorder(&recorder, || {
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.expect("runtime");
let mut client = denying_state().new_client(None);
let auth = runtime
.block_on(client.auth_password("anyone", "pw"))
.expect("auth");
assert!(matches!(auth, russh::server::Auth::Reject { .. }));
drop(client);
let rendered = handle.render();
assert_eq!(value(&rendered, SSH_SESSIONS_ACTIVE), 0.0, "{rendered}");
assert_eq!(value(&rendered, SSH_SESSIONS_TOTAL), 0.0, "{rendered}");
});
fn an_accepted_session_counts_once_and_is_released_on_drop() {
let mut client = state.new_client(None);
client.accept(Uuid::nil(), "u", AuthMethod::Publickey);
client.accept(Uuid::nil(), "u", AuthMethod::Password);
assert_eq!(value(&rendered, SSH_SESSIONS_ACTIVE), 1.0, "{rendered}");
assert_eq!(value(&rendered, SSH_SESSIONS_TOTAL), 1.0, "{rendered}");
fn an_authenticated_handler_releases_the_gauge_when_it_panics() {
let unwound = std::panic::catch_unwind(|| {
let mut client = sshd_state().new_client(None);
std::panic::resume_unwind(Box::new("session task died"));
assert!(unwound.is_err());
#[tokio::test]
async fn no_metrics_listener_without_the_flag() {
assert!(
start(None, || panic!("recorder must not be installed"))
.await
.expect("start")
.is_none()
);
async fn metrics_bind_serves_the_session_series() {
let (addr, task) = start(Some("127.0.0.1:0".parse().expect("addr")), || Ok(handle))
.expect("listener");
metrics::with_local_recorder(&recorder, || drop(SessionGauge::open()));
let mut stream = TcpStream::connect(addr).await.expect("connect");
stream
.write_all(b"GET /metrics HTTP/1.1\r\nhost: x\r\n\r\n")
.expect("write");
let mut body = String::new();
stream.read_to_string(&mut body).await.expect("read");
assert!(body.starts_with("HTTP/1.1 200"), "{body}");
assert!(body.contains(SSH_SESSIONS_ACTIVE), "{body}");
task.abort();