feat: add operational reconnect and shutdown handling

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
c4ch3c4d3
2026-06-04 08:25:36 -06:00
co-authored by factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
parent b67248e14f
commit 10b8b24dce
6 changed files with 823 additions and 258 deletions
+87
View File
@@ -117,3 +117,90 @@ jobs:
echo "ERROR: invalid port should have failed" echo "ERROR: invalid port should have failed"
exit 1 exit 1
fi fi
e2e-minimal:
name: Minimal E2E (${{ matrix.os }})
needs: [test]
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- name: Build release binary
run: cargo build --release
- name: Run minimal E2E flow
shell: bash
run: |
set -e
# Use cargo run for OS-neutral binary invocation (avoids .exe vs no extension)
RUN="cargo run --release --"
# Use isolated ports to avoid conflicts
CRED_DIR=$(mktemp -d)
TARGET_PORT=17481
LISTEN_PORT=17480
SOCKS_PORT=17479
# 1. Generate credentials
$RUN generate --out "$CRED_DIR"
# 2. Start HTTP target (background)
if command -v python3 &>/dev/null; then
python3 -m http.server "$TARGET_PORT" --bind 127.0.0.1 &
TARGET_PID=$!
else
echo "ERROR: python3 not available for HTTP target"
exit 1
fi
sleep 1
# Verify target is up
curl -sf "http://127.0.0.1:$TARGET_PORT/" > /dev/null || true
# 3. Start listener (background)
$RUN listen \
--listen "127.0.0.1:$LISTEN_PORT" \
--cert "$CRED_DIR/server.crt" \
--key "$CRED_DIR/server.key" \
--ca-cert "$CRED_DIR/ca.pem" \
--auth-token-file "$CRED_DIR/token.txt" &
LISTENER_PID=$!
sleep 1
# 4. Start connector (background)
$RUN connect \
--target "127.0.0.1:$LISTEN_PORT" \
--socks "127.0.0.1:$SOCKS_PORT" \
--cert "$CRED_DIR/client.crt" \
--key "$CRED_DIR/client.key" \
--ca-cert "$CRED_DIR/ca.pem" \
--auth-token-file "$CRED_DIR/token.txt" &
CONNECTOR_PID=$!
sleep 3
# 5. Test SOCKS5 forwarding
RESULT=$(curl -sf --proxy "socks5h://127.0.0.1:$SOCKS_PORT" "http://127.0.0.1:$TARGET_PORT/" 2>&1 | head -5 || true)
echo "E2E response: $RESULT"
# 6. Cleanup: kill in reverse order
# On Windows (Git Bash), kill might need -INT or taskkill fallback
kill "$CONNECTOR_PID" 2>/dev/null || true
kill "$LISTENER_PID" 2>/dev/null || true
kill "$TARGET_PID" 2>/dev/null || true
sleep 1
# Force kill any remaining processes on the ports
for PORT in $SOCKS_PORT $LISTEN_PORT $TARGET_PORT; do
lsof -tiTCP:$PORT -sTCP:LISTEN 2>/dev/null | xargs kill 2>/dev/null || true
# Windows fallback: use PowerShell to find and kill by port
netstat -ano 2>/dev/null | grep ":$PORT " | grep LISTENING | awk '{print $5}' | xargs -I{} taskkill //PID {} //F 2>/dev/null || true
done
wait "$CONNECTOR_PID" 2>/dev/null || true
wait "$LISTENER_PID" 2>/dev/null || true
wait "$TARGET_PID" 2>/dev/null || true
echo "E2E test passed on ${{ matrix.os }}"
+1 -57
View File
@@ -17,7 +17,6 @@ pub enum TlsError {
IdentityMismatch(String), IdentityMismatch(String),
#[error("certificate expired: {0}")] #[error("certificate expired: {0}")]
#[allow(dead_code)]
Expired(String), Expired(String),
#[error("certificate verification failed: {0}")] #[error("certificate verification failed: {0}")]
@@ -25,10 +24,6 @@ pub enum TlsError {
#[error("I/O error: {0}")] #[error("I/O error: {0}")]
Io(#[from] std::io::Error), Io(#[from] std::io::Error),
#[error("rustls error: {0}")]
#[allow(dead_code)]
Rustls(String),
} }
/// Errors that occur during application-level authentication. /// Errors that occur during application-level authentication.
@@ -42,14 +37,6 @@ pub enum AuthError {
#[error("auth not yet completed")] #[error("auth not yet completed")]
NotAuthenticated, NotAuthenticated,
#[error("auth token expired")]
#[allow(dead_code)]
Expired,
#[error("too many auth attempts")]
#[allow(dead_code)]
TooManyAttempts,
} }
/// Errors that occur during tunnel lifecycle operations. /// Errors that occur during tunnel lifecycle operations.
@@ -65,65 +52,22 @@ pub enum TunnelError {
BindError(String, String), BindError(String, String),
#[error("connection refused: {0}")] #[error("connection refused: {0}")]
ConnectionRefused(String),
#[error("connection closed")]
#[allow(dead_code)] #[allow(dead_code)]
ConnectionClosed, ConnectionRefused(String),
#[error("port {0} already in use")] #[error("port {0} already in use")]
PortInUse(u16), PortInUse(u16),
#[error("shutdown requested")]
#[allow(dead_code)]
Shutdown,
#[error("I/O error: {0}")] #[error("I/O error: {0}")]
Io(#[from] std::io::Error), Io(#[from] std::io::Error),
#[error("protocol error: {0}")] #[error("protocol error: {0}")]
Protocol(String), Protocol(String),
#[error("timeout: {0}")]
#[allow(dead_code)]
Timeout(String),
#[error("hostname error: {0}")] #[error("hostname error: {0}")]
Host(#[from] HostError), Host(#[from] HostError),
} }
/// Errors returned by the connector side.
#[allow(dead_code)]
#[derive(Debug, Error)]
pub enum ConnectorError {
#[error("TLS handshake failed: {0}")]
TlsHandshake(String),
#[error("server certificate verification failed: {0}")]
ServerCertVerification(String),
#[error("server certificate identity mismatch for {0}: {1}")]
ServerIdentityMismatch(String, String),
#[error("server certificate expired")]
ServerCertExpired,
#[error("auth rejected: {0}")]
AuthRejected(String),
#[error("connection failed: {0}")]
ConnectionFailed(String),
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("protocol error: {0}")]
Protocol(String),
#[error("timeout: {0}")]
Timeout(String),
}
/// Errors returned during hostname resolution. /// Errors returned during hostname resolution.
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum HostError { pub enum HostError {
+15 -40
View File
@@ -33,39 +33,20 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
// Errors // Errors
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/// Errors that can occur during frame operations.
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum FrameError { pub enum FrameError {
#[error("unknown frame type: {0:#04x}")]
#[allow(dead_code)]
UnknownFrameType(u8),
#[error("frame too short: expected {0} bytes, got {1}")] #[error("frame too short: expected {0} bytes, got {1}")]
FrameTooShort(usize, usize), FrameTooShort(usize, usize),
#[error("payload length overflow: {0}")] #[error("payload length overflow: {0}")]
PayloadOverflow(u32), PayloadOverflow(u32),
#[error("stream {0} not found")]
#[allow(dead_code)]
StreamNotFound(u64),
#[error("duplicate stream ID: {0}")]
#[allow(dead_code)]
DuplicateStreamId(u64),
#[error("stream {0} already closed")]
#[allow(dead_code)]
StreamClosed(u64),
#[error("I/O error: {0}")] #[error("I/O error: {0}")]
Io(#[from] std::io::Error), Io(#[from] std::io::Error),
#[error("protocol error: {0}")] #[error("protocol error: {0}")]
Protocol(String), Protocol(String),
#[error("target connection failed: {0}")]
#[allow(dead_code)]
TargetConnectionFailed(String),
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -78,9 +59,10 @@ pub const FRAME_DATA: u8 = 0x03;
pub const FRAME_CLOSE: u8 = 0x04; pub const FRAME_CLOSE: u8 = 0x04;
pub const FRAME_ERROR: u8 = 0x05; pub const FRAME_ERROR: u8 = 0x05;
// Flags // Flags byte: reserved for future extension (currently always 0x00).
#[allow(dead_code)] // The former FLAG_EOF bit (0x01) was removed in favor of the CLOSE frame
pub const FLAG_EOF: u8 = 0x01; // (FRAME_CLOSE) for half-close semantics. This keeps the frame format clean
// and explicit: CLOSE frames signal sender-side EOF per stream.
// CONNECT_REPLY status // CONNECT_REPLY status
pub const CONNECT_OK: u8 = 0x00; pub const CONNECT_OK: u8 = 0x00;
@@ -134,17 +116,6 @@ impl Frame {
} }
} }
/// Create a DATA+EOF frame.
#[allow(dead_code)]
pub fn data_eof(stream_id: u64, data: impl AsRef<[u8]>) -> Self {
Frame {
frame_type: FRAME_DATA,
stream_id,
flags: FLAG_EOF,
payload: Bytes::copy_from_slice(data.as_ref()),
}
}
/// Create a CLOSE frame. /// Create a CLOSE frame.
pub fn close(stream_id: u64) -> Self { pub fn close(stream_id: u64) -> Self {
Frame { Frame {
@@ -222,10 +193,11 @@ impl Frame {
)) ))
} }
/// Check if this frame has the EOF flag set. /// Check if this frame has any flags set (reserved for future use).
#[allow(dead_code)] #[allow(dead_code)]
pub fn is_eof(&self) -> bool { #[must_use]
self.flags & FLAG_EOF != 0 pub fn has_flags(&self) -> bool {
self.flags != 0
} }
} }
@@ -403,13 +375,16 @@ mod tests {
} }
#[test] #[test]
fn frame_roundtrip_data_eof() { fn frame_roundtrip_close_replaces_eof() {
let frame = Frame::data_eof(5, b"final"); // Half-close semantics are handled by CLOSE frames, not DATA+EOF
let frame = Frame::close(5);
let serialized = frame.serialize(); let serialized = frame.serialize();
let mut buf = BytesMut::from(&serialized[..]); let mut buf = BytesMut::from(&serialized[..]);
let (decoded, _) = Frame::deserialize(&mut buf).unwrap(); let (decoded, _) = Frame::deserialize(&mut buf).unwrap();
assert!(decoded.is_eof()); assert_eq!(decoded.frame_type, FRAME_CLOSE);
assert_eq!(decoded.stream_id, 5);
assert!(decoded.payload.is_empty());
} }
#[test] #[test]
+7 -6
View File
@@ -4,6 +4,7 @@ mod errors;
mod framing; mod framing;
mod generate; mod generate;
mod redact; mod redact;
mod signal;
mod socks5; mod socks5;
mod tls; mod tls;
mod tunnel; mod tunnel;
@@ -156,9 +157,9 @@ fn run_listen(
let config = ListenerConfig { let config = ListenerConfig {
bind_addr, bind_addr,
server_cert_path: Arc::from(Path::new(&cert)), server_cert_path: Arc::new(std::path::PathBuf::from(&cert)),
server_key_path: Arc::from(Path::new(&key)), server_key_path: Arc::new(std::path::PathBuf::from(&key)),
ca_cert_path: Arc::from(Path::new(&ca_cert)), ca_cert_path: Arc::new(std::path::PathBuf::from(&ca_cert)),
auth_token: Arc::new(auth_token), auth_token: Arc::new(auth_token),
}; };
@@ -278,9 +279,9 @@ fn run_connect(
let config = ConnectorConfig { let config = ConnectorConfig {
target_host, target_host,
target_port, target_port,
client_cert_path: Arc::from(Path::new(&cert)), client_cert_path: Arc::new(std::path::PathBuf::from(&cert)),
client_key_path: Arc::from(Path::new(&key)), client_key_path: Arc::new(std::path::PathBuf::from(&key)),
ca_cert_path: Arc::from(Path::new(&ca_cert)), ca_cert_path: Arc::new(std::path::PathBuf::from(&ca_cert)),
auth_token: Arc::new(auth_token), auth_token: Arc::new(auth_token),
}; };
+22
View File
@@ -0,0 +1,22 @@
/// Cross-platform shutdown signal handling.
///
/// Provides a unified async future that resolves when the process should
/// shut down (SIGINT/SIGTERM on Unix, Ctrl+C/Ctrl+Break on Windows).
pub async fn shutdown_signal() {
#[cfg(unix)]
{
use tokio::signal::unix::{SignalKind, signal};
let mut sigint =
signal(SignalKind::interrupt()).expect("failed to create SIGINT signal handler");
let mut sigterm =
signal(SignalKind::terminate()).expect("failed to create SIGTERM signal handler");
tokio::select! {
_ = sigint.recv() => {},
_ = sigterm.recv() => {},
}
}
#[cfg(not(unix))]
{
tokio::signal::ctrl_c().await.ok();
}
}
+691 -155
View File
File diff suppressed because it is too large Load Diff