# Remux: Secure Remote Command Execution

Remux is a secure remote command execution system with fine-grained, capability-based access control. Execute commands on remote hosts safely with policies that define exactly what users can do.

## Key Features

✅ **Capability-Based Access Control** - Fine-grained permissions beyond simple allow/deny
✅ **Policy-Driven Security** - Define what can execute, what files can be accessed, what output is allowed
✅ **Audit Logging** - Complete audit trail of all commands and results in structured JSON format
✅ **Connection Resilience** - Circuit breaker pattern with exponential backoff for reliable remote execution
✅ **Concurrent Operations** - Multiple commands per connection with proper stream multiplexing
✅ **Rate Limiting** - Per-client token bucket algorithm to prevent abuse
✅ **Pipeline Support** - Safe execution of piped commands with capability validation
✅ **Configuration Flexibility** - YAML/JSON policy files with environment variable expansion
✅ **Claude Code Integration** - Designed for seamless integration with Claude Code analysis

## Installation

```bash
# Clone or navigate to the repository
cd remux

# Install in development mode
pip install -e .

# Verify installation
remux --version
remux --help
```

## Quick Start

```bash
# 1. Initialize configuration
remux config init

# 2. Start the daemon with audit logging
remux daemon start --audit-log-dir ~/.rpipe/logs

# 3. Check daemon status
remux daemon status

# 4. List available policies
remux policy list

# 5. Execute a command with read-only policy
remux client run example.com cat /var/log/syslog

# 6. View audit logs
remux daemon logs --follow
```

## Command Structure

```
remux [global-options] <command> [subcommand] [options]

Global Options:
  -v, --verbose       Enable verbose logging
  --version           Show version
  -h, --help          Show help

Commands:
  daemon              Daemon management (start, stop, status, logs)
  policy              Policy management (list, show, validate, create)
  client              Client operations (run, batch)
  config              Configuration (show, init)
  status              Status & monitoring (info, health)
```

## Five Main Categories

### 1. **Daemon Management** - `remux daemon`

```bash
remux daemon start                              # Start daemon
remux daemon stop                               # Stop daemon
remux daemon status                             # Check status
remux daemon logs --follow                      # View audit logs
remux daemon logs --level ERROR                 # View only errors
```

### 2. **Policy Management** - `remux policy`

```bash
remux policy list                               # List policies
remux policy show read_only                     # Show policy details
remux policy validate policies.yaml             # Validate file
remux policy create my_policy --template read_only  # Create policy
```

### 3. **Client Operations** - `remux client`

```bash
remux client run host.example.com cat /var/log/syslog           # Run command
remux client batch host.example.com --commands-file cmds.txt    # Batch operations
```

### 4. **Configuration** - `remux config`

```bash
remux config show                               # Show configuration
remux config init                               # Initialize config
```

### 5. **Status & Monitoring** - `remux status`

```bash
remux status info                               # System information
remux status health                             # Health check
```

## Documentation

The project includes comprehensive documentation:

| Document | Purpose |
|----------|---------|
| **CLI_REFERENCE.md** | Complete command-line reference with all options and examples |
| **GETTING_STARTED.md** | Quick start guide for first-time users |
| **USING_WITH_CLAUDE_CODE.md** | Integration patterns with Claude Code for analysis |
| **CLAUDE_CODE_EXAMPLES.md** | Real-world usage examples and workflows |
| **REMUX_CLI_SUMMARY.md** | Overview of the CLI binary |
| **IMPLEMENTATION_SUMMARY.md** | Technical architecture and design |
| **CLAUDE.md** | Specification document for Claude developers |

## Using with Claude Code

Remux is optimized for integration with Claude Code. Pipe command output to Claude for expert analysis:

```bash
# Get expert analysis of policies
remux policy list | claude-code --task "explain each policy"

# Diagnose errors
remux daemon logs --level ERROR | claude-code --task "what do these errors mean?"

# Design new policies
remux policy show read_only | claude-code --task "create a custom policy based on this"

# Troubleshoot issues
remux daemon status | claude-code --task "daemon not running, help me debug"

# Production deployment guidance
remux config show | claude-code --task "I'm deploying to production. What should I change?"
```

See **USING_WITH_CLAUDE_CODE.md** for detailed integration patterns.

## Core Concepts

### Capabilities

Instead of allow/deny lists, remux uses **capabilities** - specific operations a policy allows:

```yaml
policies:
  read_only:
    capabilities:
      - operation: read_file
        resource: /var/log/**/*
      - operation: execute_binary
        resource: cat|grep|tail|head
      - operation: write_stdout
        resource: null    # All output allowed
```

### Security by Default

- **Policies are allowlists**: Only permitted operations execute
- **Path matching respects directory boundaries**: `*` matches within directory, `**` matches recursively
- **Pipes are validated**: Each stage in a pipeline is checked against capabilities
- **All operations audited**: Complete audit trail in structured JSON format

### Connection Resilience

Remux automatically handles network issues:

- **Circuit breaker**: Prevents cascading failures when hosts are down
- **Exponential backoff**: Intelligent retry with jitter to avoid thundering herd
- **Per-host tracking**: Each host has independent circuit breaker state

### Rate Limiting

Protects against abuse with per-client token bucket:

- **Configurable limits**: Requests per second and burst capacity
- **Per-client quotas**: Each client gets independent budget
- **Observable state**: Check remaining quota and reset as needed

## Architecture

Remux consists of:

- **Command Parser** (`rpipe/command_parser.py`) - Safely parse and validate commands
- **Pipe Parser** (`rpipe/pipe_parser.py`) - Handle pipelines with capability validation
- **Policy System** (`rpipe/policy*.py`) - Define and enforce access control
- **Daemon** (`rpipe/daemon.py`) - Background process managing remote connections
- **Client Session** (`rpipe/client_session.py`) - Concurrent command execution per connection
- **Connection Manager** (`rpipe/connection_manager.py`) - Resilient remote connections
- **Audit Logger** (`rpipe/audit.py`) - Structured JSON audit trail
- **Rate Limiter** (`rpipe/rate_limiter.py`) - Per-client quota enforcement
- **CLI** (`rpipe/cli.py`) - Command-line interface with comprehensive help

## Testing

The project includes 419 tests covering all features:

```bash
# Run all tests
pytest

# Run specific test module
pytest rpipe/tests/test_cli.py

# Run with coverage
pytest --cov=rpipe

# Run verbose output
pytest -v
```

Test coverage includes:
- Command and pipe parsing safety
- Policy validation and enforcement
- Audit logging correctness
- Client session management
- Connection resilience
- Rate limiting accuracy
- Configuration loading
- CLI command handling

## Environment Variables

Configure remux with environment variables:

```bash
RPIPE_SOCKET="/tmp/remux.sock"              # Daemon socket path
RPIPE_KNOWN_HOSTS="~/.ssh/known_hosts"      # SSH host keys
RPIPE_AUDIT_LOG_DIR="~/.rpipe/logs"         # Audit log directory
RPIPE_POLICY_CONFIG="policies.yaml"         # Policy file
```

## Exit Codes

- `0` - Success
- `1` - Error or command failed
- `2` - Invalid arguments

## Security Considerations

### Design Principles

1. **Explicit is better than implicit** - Capabilities are allowlists, not denylists
2. **Conservative parsing** - Commands are rejected if they use unsupported syntax
3. **Audit everything** - All operations logged for compliance and debugging
4. **Fail safely** - Network errors don't bypass policy checks
5. **Per-client isolation** - Rate limits and circuit breakers track clients independently

### Policy Best Practices

1. **Start restrictive** - Use `restrictive` template and add capabilities as needed
2. **Name clearly** - Policy names should indicate their purpose
3. **Document resources** - Comment why each capability is needed
4. **Review regularly** - Audit logs show which policies are actually used
5. **Test before deployment** - Use `remux policy validate` before production

### Deployment Checklist

- [ ] SSH host keys configured (`remux daemon start --known-hosts ~/.ssh/known_hosts`)
- [ ] Audit logging enabled (`remux daemon start --audit-log-dir /var/log/remux`)
- [ ] Policies validated (`remux policy validate policies.yaml`)
- [ ] Daemon status verified (`remux daemon status && remux status health`)
- [ ] Audit logs monitored (`remux daemon logs --follow`)
- [ ] Rate limits configured for your workload
- [ ] Team trained on policy usage

## Troubleshooting

### Daemon not starting

```bash
# Check socket directory exists
mkdir -p ~/.rpipe

# Try starting in foreground for error messages
remux daemon start --foreground

# Check for port conflicts
lsof -i :5555  # or your configured port
```

### Commands being denied

```bash
# Check audit logs for why
remux daemon logs --level DENY

# Show the policy being used
remux policy show policy_name

# Ask Claude for analysis
remux daemon logs --level DENY | claude-code --task "why are these being denied?"
```

### SSH connection errors

```bash
# Verify known_hosts is configured
ls -la ~/.ssh/known_hosts

# Check daemon logs for SSH errors
remux daemon logs --level ERROR | grep -i ssh

# Add host to known_hosts manually
ssh-keyscan example.com >> ~/.ssh/known_hosts
```

## Examples

### Example 1: Read-Only Log Access

```bash
# Create policy for log access
remux policy create log_reader --template read_only

# Execute command
remux client run prod-web.example.com \
  "tail -f /var/log/nginx/access.log" \
  --policy log_reader

# Monitor what was accessed
remux daemon logs | grep log_reader
```

### Example 2: Health Checks

```bash
# Create commands file
cat > health_checks.txt << 'EOF'
ps aux | grep python
df -h /
free -m
systemctl status app
EOF

# Run on all servers
remux client batch prod-db.example.com --commands-file health_checks.txt
remux client batch prod-web.example.com --commands-file health_checks.txt

# Analyze with Claude
remux daemon logs | claude-code --task "Are these servers healthy?"
```

### Example 3: Production Deployment

```bash
# 1. Initialize
remux config init

# 2. Create policies
remux policy create production --template read_only --output production.yaml
remux policy create database --template write_capable --output production.yaml

# 3. Validate
remux policy validate production.yaml

# 4. Get security review
remux config show | claude-code --task "Security review for production?"

# 5. Deploy
remux daemon start \
  --known-hosts ~/.ssh/known_hosts \
  --audit-log-dir /var/log/remux

# 6. Verify
remux daemon status && remux status health
```

## Contributing

Contributions welcome! Please:

1. Read CLAUDE.md for specification details
2. Write tests for new features
3. Validate changes with `pytest`
4. Document new capabilities
5. Update audit logging for new operations

## License

MIT License - See LICENSE file for details

## Support

For help:

```bash
# Get help on any command
remux --help
remux daemon --help
remux daemon start --help

# Check current status
remux daemon status
remux status health

# Analyze with Claude Code
remux daemon logs | claude-code --task "help me understand this"
```

## Next Steps

1. **Install**: `pip install -e .`
2. **Configure**: `remux config init`
3. **Read Guide**: See `GETTING_STARTED.md`
4. **View Examples**: See `CLAUDE_CODE_EXAMPLES.md`
5. **Deploy**: Follow the deployment checklist above

## Resources

- **Installation**: See above
- **Quick Start**: Run `remux --help`
- **Complete Reference**: See `CLI_REFERENCE.md`
- **Architecture**: See `IMPLEMENTATION_SUMMARY.md`
- **Claude Code Integration**: See `USING_WITH_CLAUDE_CODE.md`
- **Examples**: See `CLAUDE_CODE_EXAMPLES.md`
- **Technical Spec**: See `CLAUDE.md`

---

**Remux**: Secure. Auditable. Flexible. Built for remote command execution with confidence.
