# VPN Implementation & Troubleshooting Guide

## Overview
This document explains the ProtonVPN integration, common issues, and how to diagnose and fix IP/DNS leaks.

## Architecture

### How It Works
1. **OpenVPN in Docker**: OpenVPN runs inside the Docker container with `NET_ADMIN` and `NET_RAW` capabilities
2. **TUN Interface**: Creates a virtual network interface (`tun0`) for VPN traffic
3. **DNS Override**: Updates `/etc/resolv.conf` with ProtonVPN DNS servers (10.2.0.1, 10.2.0.2)
4. **Traffic Routing**: All container traffic is routed through the VPN tunnel
5. **Kill Switch**: Iptables rules prevent traffic from leaking outside VPN

## Common Issues & Solutions

### Issue 1: Real IP Address Visible
**Symptoms**: When connected to VPN, checking IP shows your real IP instead of VPN IP

**Causes**:
- VPN tunnel not established properly
- Traffic not routed through `tun0` interface
- Firewall rules not blocking non-VPN traffic

**Diagnosis**:
```bash
# Check if VPN interface exists
ip addr show tun0

# Check routing table
ip route

# Should show: default via X.X.X.X dev tun0

# Check public IP
curl https://api.ipify.org
```

**Solutions**:
1. **Verify VPN is connected**: Check backend logs for "Initialization Sequence Completed"
2. **Check routing**: Ensure default route goes through `tun0`
3. **Restart VPN connection**: Disconnect and reconnect

### Issue 2: DNS Leaks
**Symptoms**: DNS queries go to your ISP instead of VPN DNS servers

**Causes**:
- `/etc/resolv.conf` not updated properly
- DNS script not executing
- Container DNS override by Docker

**Diagnosis**:
```bash
# Check DNS servers in use
cat /etc/resolv.conf

# Should show ProtonVPN DNS:
# nameserver 10.2.0.1
# nameserver 10.2.0.2

# Test DNS resolution
nslookup google.com
```

**Solutions**:
1. **Check DNS script**: Verify `/etc/openvpn/update-resolv-conf` exists and is executable
2. **Manual DNS update**:
   ```bash
   echo "nameserver 10.2.0.1" > /etc/resolv.conf
   echo "nameserver 10.2.0.2" >> /etc/resolv.conf
   ```
3. **Rebuild container**: Ensures DNS script is properly installed

### Issue 3: VPN Connects but No Traffic
**Symptoms**: VPN shows connected but no internet access

**Causes**:
- Firewall rules too restrictive
- VPN server blocking traffic
- Authentication issues

**Diagnosis**:
```bash
# Check VPN process
ps aux | grep openvpn

# Check iptables rules
iptables -L OUTPUT -n -v

# Test connectivity through VPN
ping -I tun0 8.8.8.8
```

**Solutions**:
1. **Check credentials**: Ensure ProtonVPN username/password are correct
2. **Try different server**: Switch to another country/server
3. **Check firewall**: Verify iptables rules allow VPN traffic

### Issue 4: Container Networking Issues
**Symptoms**: Cannot access application after VPN connects

**Causes**:
- Container ports not properly exposed
- Docker network conflicts
- Firewall blocking incoming connections

**Solutions**:
1. **Check capabilities**: Ensure docker-compose has `NET_ADMIN` and `NET_RAW`:
   ```yaml
   cap_add:
     - NET_ADMIN
     - NET_RAW
   ```

2. **Verify port mapping**:
   ```yaml
   ports:
     - "12345:12345"
   ```

## VPN Configuration Details

### OpenVPN Config
```conf
client
dev tun
proto udp
remote [server] 1194
cipher AES-256-GCM
auth SHA512

# DNS Settings
dhcp-option DNS 10.2.0.1
dhcp-option DNS 10.2.0.2
block-outside-dns

# Routing
redirect-gateway def1 bypass-dhcp

# Kill Switch
script-security 2
up /etc/openvpn/update-resolv-conf
down /etc/openvpn/update-resolv-conf
```

### DNS Update Script
Location: `/etc/openvpn/update-resolv-conf`

This script:
- Parses OpenVPN's `foreign_option_*` environment variables
- Updates `/etc/resolv.conf` with VPN DNS on connect
- Restores default DNS on disconnect

### Firewall Rules (Kill Switch)
```bash
# Allow loopback
iptables -A OUTPUT -o lo -j ACCEPT

# Allow established connections
iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow DNS (needed to resolve VPN server)
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT

# Allow VPN tunnel traffic
iptables -A OUTPUT -o tun+ -j ACCEPT

# Everything else is blocked (implicit)
```

## Testing & Verification

### Using the Web UI
1. **Connect to VPN** in Settings > VPN
2. **Click "Check IP"** button when connected
3. **Verify**:
   - Public IP is different from your real IP
   - Location matches VPN country
   - ISP is ProtonVPN or VPN provider
   - DNS servers are `10.2.0.1`, `10.2.0.2`
   - VPN Interface shows "Active"

### Using API Endpoints

#### Check IP
```bash
curl -H "Authorization: Bearer YOUR_TOKEN" \
  http://localhost:12345/api/vpn/check-ip
```

#### Full Diagnostics
```bash
curl -H "Authorization: Bearer YOUR_TOKEN" \
  http://localhost:12345/api/vpn/diagnostics
```

### Manual Testing
```bash
# Get current IP
curl https://api.ipify.org

# Get IP info
curl https://ipinfo.io/json

# Check DNS
cat /etc/resolv.conf

# Check VPN interface
ip addr show tun0

# Check routing
ip route | grep default
```

## ProtonVPN Free Tier Servers

The implementation uses ProtonVPN free tier servers:
- 🇺🇸 US: us-free-01.protonvpn.net
- 🇳🇱 NL: nl-free-01.protonvpn.net
- 🇯🇵 JP: jp-free-01.protonvpn.net
- 🇬🇧 GB: uk-free-01.protonvpn.net
- 🇩🇪 DE: de-free-01.protonvpn.net
- 🇫🇷 FR: fr-free-01.protonvpn.net
- 🇨🇦 CA: ca-free-01.protonvpn.net
- 🇨🇭 CH: ch-free-01.protonvpn.net
- 🇸🇪 SE: se-free-01.protonvpn.net
- 🇷🇴 RO: ro-free-01.protonvpn.net

## Security Considerations

### Credential Storage
- Credentials encrypted using AES-256-CBC
- Encryption key derived from JWT secret
- Stored in SQLite database

### Traffic Isolation
- All traffic routes through VPN when connected
- Kill switch prevents leaks if VPN drops
- DNS forced to VPN DNS servers

### Limitations
- VPN runs per-user (not container-wide)
- Free tier has speed limitations
- Some streaming services may detect VPN

## Troubleshooting Checklist

When VPN isn't working:

- [ ] Check VPN status shows "connected"
- [ ] Verify `tun0` interface exists (`ip addr show tun0`)
- [ ] Check routing table has VPN route (`ip route`)
- [ ] Verify DNS is set to VPN DNS (`cat /etc/resolv.conf`)
- [ ] Test IP shows VPN IP (`curl https://api.ipify.org`)
- [ ] Check OpenVPN logs for errors
- [ ] Verify Docker capabilities (`NET_ADMIN`, `NET_RAW`)
- [ ] Try different VPN server/country
- [ ] Rebuild Docker container
- [ ] Check ProtonVPN credentials are valid

## Known Issues

### IPv6 Leaks
**Issue**: IPv6 traffic may bypass VPN  
**Workaround**: Disable IPv6 or use `pull-filter ignore ifconfig-ipv6` in config

### Docker DNS Override
**Issue**: Docker may override `/etc/resolv.conf`  
**Workaround**: DNS script updates it on VPN connect

### Multiple Users
**Issue**: Each user gets their own VPN connection  
**Note**: This is by design for per-user VPN routing

## Getting Help

If issues persist:
1. Check backend logs: `docker logs streamflow`
2. Run diagnostics: `/api/vpn/diagnostics`
3. Verify OpenVPN logs in container
4. Check ProtonVPN account status
5. Review Docker network configuration

## References
- [ProtonVPN OpenVPN Config](https://protonvpn.com/support/linux-openvpn/)
- [OpenVPN Documentation](https://openvpn.net/community-resources/)
- [Docker Networking](https://docs.docker.com/network/)
- [iptables Tutorial](https://www.netfilter.org/documentation/)
