Add comprehensive bridge mode testing tools

- test_bridge_mode.sh: Automated test script for bridge mode functionality
- test_bridge_interactive.sh: Interactive testing tool with manual JSON command input
- BRIDGE_MODE_TESTING.md: Complete testing guide with examples and integration patterns

Features:
- Automated and interactive testing modes
- JSON command examples and validation
- Real-time response monitoring
- Error handling and process management
- Integration examples in Python and Node.js
- Troubleshooting guide and best practices
- Colored output and user-friendly interface

These tools provide comprehensive testing capabilities for the new bridge mode,
allowing developers to easily test and integrate with the JSON stdin/stdout interface.
parent e26cd67f
# WebSocket SSH Tunnel - Bridge Mode Testing Guide
This document provides comprehensive testing tools and examples for the wsssht bridge mode functionality.
## Overview
Bridge mode allows programmatic control of wsssht tunnels through JSON commands sent via stdin/stdout. In bridge mode:
- **Tunnel control channel messages** are communicated through stdin/stdout (JSON protocol)
- **Tunnel data channel messages** remain handled by wsssht (normal forwarding)
- External applications can control tunnel behavior via JSON commands
- Real-time status updates and responses are provided
## Test Scripts
### 1. `test_bridge_mode.sh` - Automated Test Script
A comprehensive automated test script that demonstrates basic bridge mode functionality.
#### Usage:
```bash
# Basic test with default settings
./test_bridge_mode.sh
# Custom client and server
./test_bridge_mode.sh --client-id myclient --host example.com
# With debug output
./test_bridge_mode.sh --debug
# Show help
./test_bridge_mode.sh --help
```
#### Features:
- ✅ Automatic wsssht startup in bridge mode
- ✅ Sends test JSON commands (status, quit)
- ✅ Monitors and displays JSON responses
- ✅ Colored output for easy reading
- ✅ Error handling and process management
- ✅ Configurable via environment variables
#### Environment Variables:
```bash
export CLIENT_ID="myclient" # Client ID
export WSSSHD_HOST="example.com" # wssshd server hostname
export WSSSHD_PORT="9898" # wssshd server port
export DEBUG="1" # Enable debug output
```
### 2. `test_bridge_interactive.sh` - Interactive Test Script
An interactive testing tool that allows manual JSON command input and real-time response monitoring.
#### Usage:
```bash
# Start interactive mode
./test_bridge_interactive.sh start
# Send specific commands
./test_bridge_interactive.sh status
./test_bridge_interactive.sh quit
# Monitor responses only
./test_bridge_interactive.sh monitor
# Show available commands
./test_bridge_interactive.sh commands
```
#### Interactive Mode Features:
- ✅ Manual JSON command input
- ✅ Real-time response monitoring
- ✅ Command history and help
- ✅ JSON validation
- ✅ Process management and cleanup
## JSON Command Examples
### Basic Commands
#### Status Check
```json
{"command":"status","timestamp":1640995200}
```
**Response:**
```json
{"type":"tunnel_status","active":true,"timestamp":1640995200}
```
#### Quit/Exit
```json
{"command":"quit","timestamp":1640995200}
```
**Response:**
```json
{"type":"bridge_ended","timestamp":1640995200}
```
#### Ping
```json
{"command":"ping","timestamp":1640995200}
```
**Response:**
```json
{"type":"pong","timestamp":1640995200}
```
### Advanced Commands
#### Custom Command with Data
```json
{"command":"custom","timestamp":1640995200,"data":"additional_info"}
```
#### Help Request
```json
{"command":"help","timestamp":1640995200}
```
## Bridge Mode Workflow
### 1. Starting Bridge Mode
```bash
./wssshtools/wsssht --bridge --clientid myclient --wssshd-host mbetter.nexlab.net
```
### 2. Initial Responses
Bridge mode sends initial status messages:
```json
{"type":"status","message":"Bridge mode started","client_id":"myclient","host":"mbetter.nexlab.net","port":9898}
{"type":"tunnel_established","listen_sock":5}
{"type":"connection_accepted","socket":6}
{"type":"ready","message":"Bridge mode active"}
```
### 3. Command/Response Cycle
Send JSON commands via stdin, receive responses via stdout:
```bash
# Send command
echo '{"command":"status","timestamp":1640995200}' | ./wssshtools/wsssht --bridge --clientid myclient --wssshd-host mbetter.nexlab.net
# Receive response
{"type":"tunnel_status","active":true,"timestamp":1640995200}
```
### 4. Tunnel Operation
While bridge mode is active:
- **Data Channel**: wsssht handles actual tunnel data forwarding
- **Control Channel**: JSON commands control tunnel behavior
- **Status Updates**: Real-time status information via stdout
## Testing Scenarios
### Scenario 1: Basic Connectivity Test
```bash
# Test basic bridge mode startup and shutdown
./test_bridge_mode.sh --client-id testclient --host mbetter.nexlab.net
```
### Scenario 2: Interactive Control
```bash
# Start interactive session
./test_bridge_interactive.sh start
# In interactive mode, try:
> {"command":"status","timestamp":1640995200}
> {"command":"ping","timestamp":1640995200}
> quit
```
### Scenario 3: Programmatic Integration
```bash
#!/bin/bash
# Example of programmatic integration
# Start wsssht in background
./wssshtools/wsssht --bridge --clientid myclient --wssshd-host mbetter.nexlab.net &
WSSSHT_PID=$!
# Send commands programmatically
echo '{"command":"status","timestamp":'$(date +%s)'}' > /proc/$WSSSHT_PID/fd/0
# Read responses
while read -r response; do
echo "Response: $response"
# Parse JSON and handle accordingly
done < /proc/$WSSSHT_PID/fd/1
# Cleanup
kill $WSSSHT_PID
```
### Scenario 4: Error Handling
```bash
# Test with invalid client ID
./test_bridge_mode.sh --client-id invalid_client
# Test with unreachable host
./test_bridge_mode.sh --host unreachable.example.com
# Test timeout scenarios
timeout 10 ./test_bridge_mode.sh
```
## Troubleshooting
### Common Issues
#### 1. "wsssht binary not found"
```bash
# Build wsssht first
cd wssshtools
make clean && make
# Or update path in test scripts
WSSSHT="/path/to/wsssht"
```
#### 2. "Failed to establish tunnel"
- Check client ID is registered with wssshd
- Verify wssshd server is running and accessible
- Check network connectivity
#### 3. "No response received"
- Bridge mode may not be fully initialized
- Check if wsssht process is still running
- Verify JSON command format
#### 4. "Invalid JSON"
- Ensure JSON is properly formatted
- Check for missing quotes or brackets
- Use `jq` to validate JSON: `echo '{"test":"data"}' | jq .`
### Debug Mode
Enable debug output for detailed information:
```bash
./test_bridge_mode.sh --debug
# or
DEBUG=1 ./test_bridge_interactive.sh start
```
## Integration Examples
### Python Integration
```python
import subprocess
import json
import time
def send_bridge_command(command):
"""Send JSON command to wsssht bridge mode"""
cmd = [
'./wssshtools/wsssht',
'--bridge',
'--clientid', 'myclient',
'--wssshd-host', 'mbetter.nexlab.net'
]
proc = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
# Send command
json_cmd = json.dumps({
'command': command,
'timestamp': int(time.time())
})
proc.stdin.write(json_cmd + '\n')
proc.stdin.flush()
# Read response
response = proc.stdout.readline().strip()
if response:
return json.loads(response)
return None
# Usage
response = send_bridge_command('status')
print(f"Tunnel active: {response.get('active', False)}")
```
### Node.js Integration
```javascript
const { spawn } = require('child_process');
const fs = require('fs');
function startBridgeMode() {
const wsssht = spawn('./wssshtools/wsssht', [
'--bridge',
'--clientid', 'myclient',
'--wssshd-host', 'mbetter.nexlab.net'
]);
// Send command
const command = JSON.stringify({
command: 'status',
timestamp: Math.floor(Date.now() / 1000)
});
wsssht.stdin.write(command + '\n');
// Handle responses
wsssht.stdout.on('data', (data) => {
const response = JSON.parse(data.toString().trim());
console.log('Response:', response);
});
wsssht.stderr.on('data', (data) => {
console.error('Error:', data.toString());
});
return wsssht;
}
// Usage
const proc = startBridgeMode();
// Cleanup on exit
process.on('SIGINT', () => {
proc.kill();
process.exit();
});
```
## Best Practices
### 1. Command Format
- Always include `timestamp` field for tracking
- Use valid JSON format
- Handle responses asynchronously
### 2. Error Handling
- Check process exit codes
- Monitor for timeout scenarios
- Validate JSON responses
### 3. Resource Management
- Properly terminate wsssht processes
- Handle signals gracefully
- Clean up file descriptors
### 4. Security
- Validate input data
- Use secure communication channels
- Implement proper authentication
## Files Created
- `test_bridge_mode.sh` - Automated test script
- `test_bridge_interactive.sh` - Interactive test script
- `BRIDGE_MODE_TESTING.md` - This documentation
## Next Steps
1. **Build wsssht**: Ensure wsssht is compiled and executable
2. **Configure wssshd**: Set up wssshd server with client registration
3. **Run tests**: Use the provided test scripts to verify functionality
4. **Integrate**: Use the examples to integrate bridge mode into your applications
For additional support, refer to the main wsssht documentation or check the project repository.
\ No newline at end of file
#!/bin/bash
# WebSocket SSH Tunnel - Interactive Bridge Mode Test
# This script provides an interactive way to test wsssht bridge mode
# allowing manual JSON command input and response monitoring
set -e
# Configuration
WSSSHT="./wssshtools/wsssht" # Path to wsssht binary
CLIENT_ID="${CLIENT_ID:-testclient}"
WSSSHD_HOST="${WSSSHD_HOST:-mbetter.nexlab.net}"
WSSSHD_PORT="${WSSSHD_PORT:-9898}"
DEBUG="${DEBUG:-0}"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
# Logging functions
log_info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
log_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
log_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
log_command() {
echo -e "${CYAN}[COMMAND]${NC} $1"
}
log_response() {
echo -e "${PURPLE}[RESPONSE]${NC} $1"
}
# Function to show available commands
show_commands() {
cat << EOF
Available JSON Commands for Bridge Mode:
1. Status Check:
{"command":"status","timestamp":\$(date +%s)}
2. Quit/Exit:
{"command":"quit","timestamp":\$(date +%s)}
{"command":"exit","timestamp":\$(date +%s)}
3. Custom Command (replace 'your_command' with actual command):
{"command":"your_command","timestamp":\$(date +%s),"data":"optional_data"}
4. Ping Command:
{"command":"ping","timestamp":\$(date +%s)}
5. Help Command:
{"command":"help","timestamp":\$(date +%s)}
EOF
}
# Function to start bridge mode
start_bridge() {
log_info "Starting wsssht in bridge mode..."
log_info "Client ID: $CLIENT_ID"
log_info "WSSSHD Host: $WSSSHD_HOST"
log_info "WSSSHD Port: $WSSSHD_PORT"
# Build command arguments
local cmd_args="--bridge --clientid $CLIENT_ID --wssshd-host $WSSSHD_HOST --wssshd-port $WSSSHD_PORT"
if [ "$DEBUG" = "1" ]; then
cmd_args="$cmd_args --debug"
fi
log_command "Command: $WSSSHT $cmd_args"
# Start wsssht in background
$WSSSHT $cmd_args &
WSSSHT_PID=$!
log_success "wsssht started with PID: $WSSSHT_PID"
log_info "Waiting for bridge mode to initialize..."
# Give it time to start
sleep 3
# Check if process is still running
if ! kill -0 $WSSSHT_PID 2>/dev/null; then
log_error "wsssht process failed to start or exited early"
return 1
fi
log_success "Bridge mode appears to be running"
}
# Function to send JSON command
send_json_command() {
local json_command="$1"
if [ -z "$json_command" ]; then
log_warning "Empty command, skipping"
return
fi
log_command "Sending: $json_command"
# Send command to wsssht's stdin
echo "$json_command" > /proc/$WSSSHT_PID/fd/0 2>/dev/null || {
log_error "Failed to send command to wsssht (PID: $WSSSHT_PID)"
log_error "Process may have exited"
return 1
}
log_success "Command sent successfully"
}
# Function to monitor responses
monitor_responses() {
log_info "Monitoring responses from wsssht..."
log_info "Press Ctrl+C to stop monitoring"
# Monitor process output
while kill -0 $WSSSHT_PID 2>/dev/null; do
# Try to read from process stdout
if [ -f /proc/$WSSSHT_PID/fd/1 ]; then
local line
if read -t 1 line < /proc/$WSSSHT_PID/fd/1 2>/dev/null; then
if [ -n "$line" ]; then
log_response "$line"
fi
fi
fi
sleep 0.1
done
log_info "wsssht process has exited"
}
# Function to cleanup
cleanup() {
log_info "Cleaning up..."
if [ -n "$WSSSHT_PID" ] && kill -0 $WSSSHT_PID 2>/dev/null; then
log_info "Terminating wsssht process (PID: $WSSSHT_PID)"
kill $WSSSHT_PID 2>/dev/null || true
wait $WSSSHT_PID 2>/dev/null || true
fi
log_success "Cleanup completed"
}
# Function to show usage
show_usage() {
cat << EOF
WebSocket SSH Tunnel - Interactive Bridge Mode Test
Usage: $0 [OPTIONS] [COMMAND]
Options:
-c, --client-id ID Client ID for the tunnel (default: testclient)
-h, --host HOST wssshd server hostname (default: mbetter.nexlab.net)
-p, --port PORT wssshd server port (default: 9898)
-d, --debug Enable debug output
--help Show this help message
Commands:
start Start bridge mode and enter interactive mode
status Send status command
quit Send quit command
monitor Monitor responses only
commands Show available JSON commands
Environment Variables:
CLIENT_ID Client ID (overrides -c)
WSSSHD_HOST wssshd hostname (overrides -h)
WSSSHD_PORT wssshd port (overrides -p)
DEBUG Enable debug (set to 1)
Examples:
$0 start
$0 --client-id myclient --host example.com start
$0 status
$0 commands
Interactive Mode:
Run '$0 start' to enter interactive mode where you can:
- Type JSON commands to send to wsssht
- See responses in real-time
- Use 'quit' or 'exit' to stop
- Use 'help' to see available commands
EOF
}
# Function for interactive mode
interactive_mode() {
log_info "Entering interactive mode..."
log_info "Type JSON commands to send to wsssht, or 'help' for commands, 'quit' to exit"
while true; do
echo -n "> "
read -r input
case "$input" in
"")
continue
;;
"quit"|"exit")
log_info "Exiting interactive mode"
break
;;
"help"|"commands")
show_commands
;;
"status")
send_json_command "{\"command\":\"status\",\"timestamp\":$(date +%s)}"
;;
"ping")
send_json_command "{\"command\":\"ping\",\"timestamp\":$(date +%s)}"
;;
*)
# Try to send as JSON command
if echo "$input" | jq . >/dev/null 2>&1; then
send_json_command "$input"
else
log_warning "Invalid JSON or unknown command: $input"
log_info "Type 'help' for available commands"
fi
;;
esac
done
}
# Parse command line arguments
COMMAND=""
while [[ $# -gt 0 ]]; do
case $1 in
-c|--client-id)
CLIENT_ID="$2"
shift 2
;;
-h|--host)
WSSSHD_HOST="$2"
shift 2
;;
-p|--port)
WSSSHD_PORT="$2"
shift 2
;;
-d|--debug)
DEBUG=1
shift
;;
--help)
show_usage
exit 0
;;
start|status|quit|monitor|commands)
COMMAND="$1"
shift
;;
*)
log_error "Unknown option: $1"
show_usage
exit 1
;;
esac
done
# Check if wsssht binary exists
if [ ! -x "$WSSSHT" ]; then
log_error "wsssht binary not found at: $WSSSHT"
log_error "Please build wsssht first or update WSSSHT path in this script"
exit 1
fi
# Set up cleanup trap
trap cleanup EXIT INT TERM
log_info "WebSocket SSH Tunnel - Interactive Bridge Mode Test"
log_info "==================================================="
# Handle commands
case "$COMMAND" in
"start")
if start_bridge; then
interactive_mode
fi
;;
"status")
if start_bridge; then
send_json_command "{\"command\":\"status\",\"timestamp\":$(date +%s)}"
sleep 2
fi
;;
"quit")
if start_bridge; then
send_json_command "{\"command\":\"quit\",\"timestamp\":$(date +%s)}"
sleep 2
fi
;;
"monitor")
if start_bridge; then
monitor_responses
fi
;;
"commands")
show_commands
;;
*)
log_info "No command specified, showing usage..."
echo
show_usage
;;
esac
log_success "Test script completed!"
\ No newline at end of file
#!/bin/bash
# WebSocket SSH Tunnel - Bridge Mode Test Script
# This script demonstrates how to use wsssht in bridge mode
# Bridge mode allows programmatic control via JSON stdin/stdout
set -e
# Configuration
WSSSHT="./wssshtools/wsssht" # Path to wsssht binary
CLIENT_ID="${CLIENT_ID:-testclient}"
WSSSHD_HOST="${WSSSHD_HOST:-mbetter.nexlab.net}"
WSSSHD_PORT="${WSSSHD_PORT:-9898}"
DEBUG="${DEBUG:-0}"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Logging functions
log_info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
log_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
log_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Function to send JSON command to wsssht
send_command() {
local command="$1"
echo "$command"
log_info "Sending command: $command"
}
# Function to test bridge mode
test_bridge_mode() {
log_info "Starting bridge mode test..."
log_info "Client ID: $CLIENT_ID"
log_info "WSSSHD Host: $WSSSHD_HOST"
log_info "WSSSHD Port: $WSSSHD_PORT"
# Build command arguments
local cmd_args="--bridge --clientid $CLIENT_ID --wssshd-host $WSSSHD_HOST --wssshd-port $WSSSHD_PORT"
if [ "$DEBUG" = "1" ]; then
cmd_args="$cmd_args --debug"
fi
log_info "Starting wsssht with command: $WSSSHT $cmd_args"
# Start wsssht in bridge mode with coprocess
coproc WSSSHT_PROC { $WSSSHT $cmd_args; }
# Get the process IDs
local wsssht_pid=$WSSSHT_PROC_PID
local wsssht_in=${WSSSHT_PROC[1]}
local wsssht_out=${WSSSHT_PROC[0]}
log_success "wsssht started with PID: $wsssht_pid"
# Function to read JSON response
read_response() {
local timeout=${1:-5}
local response=""
# Set up timeout
if command -v timeout >/dev/null 2>&1; then
response=$(timeout $timeout cat <&${wsssht_out} 2>/dev/null || true)
else
# Fallback for systems without timeout
response=$(head -1 <&${wsssht_out} 2>/dev/null || true)
fi
if [ -n "$response" ]; then
log_info "Received: $response"
echo "$response"
else
log_warning "No response received within $timeout seconds"
fi
}
# Wait for initial status message
log_info "Waiting for initial status message..."
sleep 2
# Read initial messages
while read -t 1 -u ${wsssht_out} line 2>/dev/null; do
if [ -n "$line" ]; then
log_info "Initial response: $line"
# Check if bridge is ready
if echo "$line" | grep -q '"type":"ready"'; then
log_success "Bridge mode is ready!"
break
fi
fi
done
# Test 1: Send a status command
log_info "Test 1: Sending status command"
send_command '{"command":"status","timestamp":'$(date +%s)'}' >&${wsssht_in}
sleep 1
read_response
# Test 2: Send a quit command
log_info "Test 2: Sending quit command"
send_command '{"command":"quit","timestamp":'$(date +%s)'}' >&${wsssht_in}
sleep 1
# Read final messages
while read -t 2 -u ${wsssht_out} line 2>/dev/null; do
if [ -n "$line" ]; then
log_info "Final response: $line"
fi
done
# Wait for process to finish
wait $wsssht_pid 2>/dev/null || true
log_success "Bridge mode test completed!"
}
# Function to show usage
show_usage() {
cat << EOF
WebSocket SSH Tunnel - Bridge Mode Test Script
Usage: $0 [OPTIONS]
Options:
-c, --client-id ID Client ID for the tunnel (default: testclient)
-h, --host HOST wssshd server hostname (default: mbetter.nexlab.net)
-p, --port PORT wssshd server port (default: 9898)
-d, --debug Enable debug output
--help Show this help message
Environment Variables:
CLIENT_ID Client ID (overrides -c)
WSSSHD_HOST wssshd hostname (overrides -h)
WSSSHD_PORT wssshd port (overrides -p)
DEBUG Enable debug (set to 1)
Examples:
$0
$0 --client-id myclient --host example.com --debug
CLIENT_ID=myclient WSSSHD_HOST=example.com $0
EOF
}
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
-c|--client-id)
CLIENT_ID="$2"
shift 2
;;
-h|--host)
WSSSHD_HOST="$2"
shift 2
;;
-p|--port)
WSSSHD_PORT="$2"
shift 2
;;
-d|--debug)
DEBUG=1
shift
;;
--help)
show_usage
exit 0
;;
*)
log_error "Unknown option: $1"
show_usage
exit 1
;;
esac
done
# Check if wsssht binary exists
if [ ! -x "$WSSSHT" ]; then
log_error "wsssht binary not found at: $WSSSHT"
log_error "Please build wsssht first or update WSSSHT path in this script"
exit 1
fi
log_info "WebSocket SSH Tunnel - Bridge Mode Test"
log_info "========================================"
# Run the test
test_bridge_mode
log_success "Test script completed successfully!"
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment