# Authentication Guide
Security and authentication documentation for V-Queue server.
## Overview
V-Queue server supports HTTP Basic Authentication to protect access to queues. When enabled, all API endpoints (except `/health`) require valid credentials.
## Authentication Mechanism
### HTTP Basic Authentication
Standard HTTP Basic Authentication as defined in [RFC 7617](https://tools.ietf.org/html/rfc7617).
**Format**:
```
Authorization: Basic <base64(username:password)>
```
### Protected Endpoints
When authentication is enabled, these endpoints require credentials:
- `GET /api/v1/queues` - List queues
- `GET /api/v1/queues/{queue}` - Queue information
- `GET /api/v1/queues/{queue}/consumers` - List consumers
- `GET /api/v1/queues/{queue}/consumers/{consumer}/messages` - Consume messages
- `POST /api/v1/queues/{queue}/consumers/{consumer}/commit` - Commit position
### Unprotected Endpoints
These endpoints are always accessible:
- `GET /health` - Health check
## Configuration
### Enabling Authentication
In `v-queue-server.toml`:
```toml
# Enable authentication
auth_enabled = true
# Define user accounts
[users]
admin = "secure_password_123"
app1 = "app1_secret_key"
consumer_service = "consumer_pass"
```
Restart server to apply changes.
### Disabling Authentication
**Option 1** - Configuration file:
```toml
auth_enabled = false
```
**Option 2** - Command line:
```bash
v-queue-server --no-auth
```
**Note**: `--no-auth` flag overrides config file setting.
## User Management
### Adding Users
Edit configuration file and add user to `[users]` section:
```toml
[users]
existing_user = "password1"
new_user = "password2" # Add this line
```
Restart server.
### Removing Users
Remove user line from configuration:
```toml
[users]
keep_this_user = "password1"
# remove_this_user = "password2" # Removed
```
Restart server.
### Changing Passwords
Update password in configuration:
```toml
[users]
admin = "new_secure_password" # Changed from old password
```
Restart server.
**Important**: All existing sessions with old password will fail immediately.
## Using Authentication
### cURL
**Option 1** - Username and password:
```bash
curl -u username:password http://localhost:9093/api/v1/queues
```
**Option 2** - Authorization header:
```bash
# Generate base64 credentials
curl -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" \
http://localhost:9093/api/v1/queues
```
**Option 3** - Netrc file:
Create `~/.netrc`:
```
machine localhost
login username
password password
```
Set permissions:
```bash
chmod 600 ~/.netrc
```
Use with curl:
```bash
curl --netrc http://localhost:9093/api/v1/queues
```
### Python
**Option 1** - Using `requests.auth`:
```python
import requests
from requests.auth import HTTPBasicAuth
response = requests.get(
"http://localhost:9093/api/v1/queues",
auth=HTTPBasicAuth("username", "password")
)
```
**Option 2** - Tuple shorthand:
```python
import requests
response = requests.get(
"http://localhost:9093/api/v1/queues",
auth=("username", "password")
)
```
**Option 3** - Manual header:
```python
import requests
import base64
credentials = base64.b64encode(b"username:password").decode()
response = requests.get(
"http://localhost:9093/api/v1/queues",
headers={"Authorization": f"Basic {credentials}"}
)
```
### JavaScript (Node.js)
**Using axios**:
```javascript
const axios = require('axios');
const client = axios.create({
baseURL: 'http://localhost:9093/api/v1',
auth: {
username: 'username',
password: 'password'
}
});
const response = await client.get('/queues');
```
**Using fetch** (Node.js 18+):
```javascript
const credentials = Buffer.from('username:password').toString('base64');
const response = await fetch('http://localhost:9093/api/v1/queues', {
headers: {
'Authorization': `Basic ${credentials}`
}
});
```
### Rust
**Using reqwest**:
```rust
use reqwest::blocking::Client;
let client = Client::new();
let response = client
.get("http://localhost:9093/api/v1/queues")
.basic_auth("username", Some("password"))
.send()?;
```
### Java
**Using HttpURLConnection**:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
String credentials = "username:password";
String encoded = Base64.getEncoder().encodeToString(credentials.getBytes());
URL url = new URL("http://localhost:9093/api/v1/queues");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Basic " + encoded);
```
## Security Best Practices
### Password Security
1. **Use Strong Passwords**:
- Minimum 16 characters
- Mix of uppercase, lowercase, numbers, symbols
- Use password generator
- Example: `Kp9#mX2$nQ5@vL8&`
2. **Avoid Common Passwords**:
- ❌ `password`, `admin`, `123456`
- ❌ Dictionary words
- ❌ Personal information
3. **Unique Passwords per User**:
- Each service should have unique credentials
- Don't share passwords across environments
### Configuration File Security
Protect configuration file containing passwords:
```bash
# Set restrictive permissions
chmod 600 v-queue-server.toml
chown vqueue:vqueue v-queue-server.toml
# Verify
ls -la v-queue-server.toml
# Output: -rw------- 1 vqueue vqueue ...
```
**Important**: Only owner can read/write the file.
### Network Security
1. **Use HTTPS**:
- Basic Auth sends credentials in base64 (not encrypted)
- Use HTTPS reverse proxy (nginx, caddy)
- Example nginx config:
```nginx
server {
listen 443 ssl;
server_name vqueue.example.com;
ssl_certificate /etc/ssl/certs/vqueue.crt;
ssl_certificate_key /etc/ssl/private/vqueue.key;
location / {
proxy_pass http://localhost:9093;
proxy_set_header Authorization $http_authorization;
proxy_pass_header Authorization;
}
}
```
2. **Firewall Rules**:
```bash
# Allow only from specific IPs
sudo ufw allow from 192.168.1.0/24 to any port 9093
# Or bind to localhost and use reverse proxy
v-queue-server --bind 127.0.0.1:9093
```
3. **VPN Access**:
- For remote access, use VPN
- Don't expose to public internet
### Credential Management
1. **Environment Variables**:
Don't hardcode credentials in code:
```python
# Bad
auth = ("admin", "password123")
# Good
import os
auth = (os.getenv("VQUEUE_USER"), os.getenv("VQUEUE_PASS"))
```
2. **Secrets Management**:
Use secrets management tools:
```bash
# Using HashiCorp Vault
vault kv get secret/vqueue/credentials
# Using Kubernetes secrets
3. **Configuration Management**:
Use tools like Ansible, Chef, or Puppet to manage configs:
```yaml
# Ansible example
- name: Deploy vqueue config
template:
src: vqueue-server.toml.j2
dest: /etc/vqueue/server.toml
mode: '0600'
owner: vqueue
group: vqueue
vars:
admin_password: "{{ vault_vqueue_admin_password }}"
```
## Authentication Errors
### 401 Unauthorized
**Cause**: Missing or invalid credentials.
**Response**:
```json
{
"error": "Unauthorized"
}
```
**Solutions**:
1. Verify username and password are correct
2. Check configuration file has user defined
3. Ensure server was restarted after config changes
4. Verify credentials encoding (base64)
**Example**:
```bash
# Wrong password
curl -u admin:wrong_password http://localhost:9093/api/v1/queues
# Response: 401 Unauthorized
# Correct password
curl -u admin:correct_password http://localhost:9093/api/v1/queues
# Response: 200 OK with queue list
```
### Missing Authorization Header
**Request without auth**:
```bash
curl http://localhost:9093/api/v1/queues
```
**Response**: `401 Unauthorized`
**Fix**: Add authentication:
```bash
curl -u username:password http://localhost:9093/api/v1/queues
```
## Development vs Production
### Development Setup
For local development, disable authentication:
```bash
v-queue-server --no-auth
```
Or in config:
```toml
auth_enabled = false
```
**Advantages**:
- Faster development
- Easier testing
- No credential management
**Only use in**:
- Local development
- Isolated test environments
- Internal networks with other security layers
### Production Setup
Always enable authentication in production:
```toml
auth_enabled = true
[users]
production_app = "{{ strong_password_from_secrets }}"
monitoring = "{{ another_strong_password }}"
```
**Additional measures**:
- HTTPS reverse proxy
- Firewall rules
- Network isolation
- Monitoring and logging
- Regular password rotation
## Monitoring Authentication
### Log Failed Attempts
Enable debug logging to see authentication failures:
```bash
v-queue-server --log-level debug
```
Log output:
```
WARN auth: Authentication failed for user: unknown_user
WARN auth: Invalid password for user: admin
```
### Track Usage
Monitor which users are accessing the system:
```bash
# Parse logs for successful authentications
```
## Limitations
### Current Limitations
1. **No Role-Based Access Control (RBAC)**:
- All authenticated users have same permissions
- Cannot restrict per queue or operation
2. **Plain Text Passwords**:
- Passwords stored in config file
- Not hashed or encrypted
- Rely on file permissions
3. **No API Keys**:
- Only username/password
- No token-based authentication
4. **No Password Expiration**:
- Passwords don't expire
- Manual rotation required
5. **No Audit Logging**:
- Limited tracking of who accessed what
- No detailed access logs
### Future Enhancements
Potential improvements:
- Token-based authentication (JWT)
- Role-based access control
- API key support
- Password hashing (bcrypt, argon2)
- OAuth2 integration
- Audit logging
- Rate limiting per user
- Password expiration policies
## Migration Scenarios
### Enabling Auth on Existing Installation
1. **Backup current config**:
```bash
cp v-queue-server.toml v-queue-server.toml.backup
```
2. **Update config**:
```toml
auth_enabled = true
[users]
admin = "new_secure_password"
```
3. **Restart server**:
```bash
sudo systemctl restart v-queue-server
```
4. **Update clients** with credentials:
```python
# Old (no auth)
client.get("/queues")
# New (with auth)
client.get("/queues", auth=("admin", "new_secure_password"))
```
5. **Test thoroughly** before production deployment.
### Rotating Passwords
1. **Generate new password**
2. **Update config** with new password
3. **Restart server**
4. **Update all clients** (may cause temporary failures)
5. **Verify all clients working**
**Zero-downtime rotation** not currently supported. Consider:
- Maintenance window
- Blue-green deployment
- Temporary dual authentication (future feature)
## Next Steps
- [API Reference](05-api-reference.md)
- [Client Examples](07-client-examples.md)
- [Troubleshooting](09-troubleshooting.md)