security improvements

This commit is contained in:
Fran Jurmanović
2025-06-29 21:59:41 +02:00
parent 7fdda06dba
commit caba5bae70
30 changed files with 3929 additions and 147 deletions

822
documentation/API.md Normal file
View File

@@ -0,0 +1,822 @@
# API Documentation for ACC Server Manager
## Overview
The ACC Server Manager provides a comprehensive REST API for managing Assetto Corsa Competizione dedicated servers. This API enables full control over server instances, configurations, user management, and monitoring through HTTP endpoints.
## Base URL
```
http://localhost:3000/api/v1
```
## Authentication
All API endpoints (except public ones) require authentication via JWT tokens.
### Authentication Header
```http
Authorization: Bearer <your-jwt-token>
```
### Token Expiration
- Default token lifetime: 24 hours
- Tokens should be refreshed before expiration
- Failed authentication returns HTTP 401
## Rate Limiting
The API implements multiple layers of rate limiting:
- **Global**: 100 requests per minute per IP
- **Authentication**: 5 attempts per 15 minutes per IP
- **API Endpoints**: 60 requests per minute per IP
Rate limit exceeded responses return HTTP 429 with retry information.
## Response Format
All API responses follow a consistent JSON format:
### Success Response
```json
{
"success": true,
"data": {
// Response data
},
"message": "Operation completed successfully"
}
```
### Error Response
```json
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Human readable error message",
"details": {}
}
}
```
## HTTP Status Codes
| Status Code | Description |
|-------------|-------------|
| 200 | OK - Request successful |
| 201 | Created - Resource created successfully |
| 400 | Bad Request - Invalid request data |
| 401 | Unauthorized - Authentication required |
| 403 | Forbidden - Insufficient permissions |
| 404 | Not Found - Resource not found |
| 409 | Conflict - Resource already exists |
| 422 | Unprocessable Entity - Validation failed |
| 429 | Too Many Requests - Rate limit exceeded |
| 500 | Internal Server Error - Server error |
## API Endpoints
### Authentication
#### Login
```http
POST /api/v1/auth/login
```
**Request Body:**
```json
{
"username": "string",
"password": "string"
}
```
**Response:**
```json
{
"success": true,
"data": {
"token": "jwt-token-string",
"user": {
"id": "uuid",
"username": "string",
"role": {
"id": "uuid",
"name": "string",
"permissions": []
}
}
}
}
```
#### Register User
```http
POST /api/v1/auth/register
```
*Requires: `user.create` permission*
**Request Body:**
```json
{
"username": "string",
"password": "string",
"roleId": "uuid"
}
```
#### Get Current User
```http
GET /api/v1/auth/me
```
*Requires: Authentication*
**Response:**
```json
{
"success": true,
"data": {
"id": "uuid",
"username": "string",
"role": {
"id": "uuid",
"name": "string",
"permissions": []
}
}
}
```
### Server Management
#### List Servers
```http
GET /api/v1/servers
```
*Requires: `server.read` permission*
**Query Parameters:**
- `page` (integer): Page number (default: 1)
- `limit` (integer): Items per page (default: 10)
- `search` (string): Search term
- `status` (string): Filter by status (running, stopped, error)
**Response:**
```json
{
"success": true,
"data": {
"servers": [
{
"id": 1,
"name": "string",
"ip": "string",
"port": 9600,
"path": "string",
"serviceName": "string",
"status": "string",
"dateCreated": "2024-01-01T00:00:00Z"
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 50,
"pages": 5
}
}
}
```
#### Create Server
```http
POST /api/v1/servers
```
*Requires: `server.create` permission*
**Request Body:**
```json
{
"name": "string",
"ip": "string",
"port": 9600,
"path": "string"
}
```
**Response:**
```json
{
"success": true,
"data": {
"id": 1,
"name": "string",
"ip": "string",
"port": 9600,
"path": "string",
"serviceName": "string",
"status": "created",
"dateCreated": "2024-01-01T00:00:00Z"
}
}
```
#### Get Server Details
```http
GET /api/v1/servers/{id}
```
*Requires: `server.read` permission*
**Path Parameters:**
- `id` (integer): Server ID
**Response:**
```json
{
"success": true,
"data": {
"id": 1,
"name": "string",
"ip": "string",
"port": 9600,
"path": "string",
"serviceName": "string",
"status": "string",
"dateCreated": "2024-01-01T00:00:00Z",
"configs": [],
"statistics": {}
}
}
```
#### Update Server
```http
PUT /api/v1/servers/{id}
```
*Requires: `server.update` permission*
**Path Parameters:**
- `id` (integer): Server ID
**Request Body:**
```json
{
"name": "string",
"ip": "string",
"port": 9600,
"path": "string"
}
```
#### Delete Server
```http
DELETE /api/v1/servers/{id}
```
*Requires: `server.delete` permission*
**Path Parameters:**
- `id` (integer): Server ID
#### Start Server
```http
POST /api/v1/servers/{id}/start
```
*Requires: `server.control` permission*
#### Stop Server
```http
POST /api/v1/servers/{id}/stop
```
*Requires: `server.control` permission*
#### Restart Server
```http
POST /api/v1/servers/{id}/restart
```
*Requires: `server.control` permission*
### Configuration Management
#### Get Configuration File
```http
GET /api/v1/servers/{id}/config/{file}
```
*Requires: `config.read` permission*
**Path Parameters:**
- `id` (integer): Server ID
- `file` (string): Configuration file name (configuration, event, eventRules, settings)
**Response:**
```json
{
"success": true,
"data": {
"file": "configuration",
"content": {},
"lastModified": "2024-01-01T00:00:00Z"
}
}
```
#### Update Configuration File
```http
PUT /api/v1/servers/{id}/config/{file}
```
*Requires: `config.update` permission*
**Path Parameters:**
- `id` (integer): Server ID
- `file` (string): Configuration file name
**Query Parameters:**
- `restart` (boolean): Restart server after update (default: false)
- `override` (boolean): Override validation warnings (default: false)
**Request Body:**
```json
{
"tcpPort": 9600,
"udpPort": 9600,
"maxConnections": 30,
"registerToLobby": 1,
"serverName": "My ACC Server",
"password": "",
"adminPassword": "admin123",
"trackMedalsRequirement": 0,
"safetyRatingRequirement": -1,
"racecraftRatingRequirement": -1,
"configVersion": 1
}
```
#### Validate Configuration
```http
POST /api/v1/servers/{id}/config/{file}/validate
```
*Requires: `config.read` permission*
**Request Body:** Configuration object to validate
**Response:**
```json
{
"success": true,
"data": {
"valid": true,
"errors": [],
"warnings": []
}
}
```
### Steam Integration
#### Get Steam Credentials
```http
GET /api/v1/steam/credentials
```
*Requires: `steam.read` permission*
**Response:**
```json
{
"success": true,
"data": {
"id": 1,
"username": "steam_username",
"dateCreated": "2024-01-01T00:00:00Z",
"lastUpdated": "2024-01-01T00:00:00Z"
}
}
```
#### Update Steam Credentials
```http
PUT /api/v1/steam/credentials
```
*Requires: `steam.update` permission*
**Request Body:**
```json
{
"username": "steam_username",
"password": "steam_password"
}
```
#### Install/Update Server
```http
POST /api/v1/steam/install
```
*Requires: `steam.install` permission*
**Request Body:**
```json
{
"serverId": 1,
"validate": true,
"beta": false
}
```
### User Management
#### List Users
```http
GET /api/v1/users
```
*Requires: `user.read` permission*
**Query Parameters:**
- `page` (integer): Page number
- `limit` (integer): Items per page
- `search` (string): Search term
**Response:**
```json
{
"success": true,
"data": {
"users": [
{
"id": "uuid",
"username": "string",
"role": {
"id": "uuid",
"name": "string"
},
"createdAt": "2024-01-01T00:00:00Z"
}
],
"pagination": {}
}
}
```
#### Create User
```http
POST /api/v1/users
```
*Requires: `user.create` permission*
#### Update User
```http
PUT /api/v1/users/{id}
```
*Requires: `user.update` permission*
#### Delete User
```http
DELETE /api/v1/users/{id}
```
*Requires: `user.delete` permission*
### Role and Permission Management
#### List Roles
```http
GET /api/v1/roles
```
*Requires: `role.read` permission*
#### Create Role
```http
POST /api/v1/roles
```
*Requires: `role.create` permission*
**Request Body:**
```json
{
"name": "string",
"description": "string",
"permissions": ["permission1", "permission2"]
}
```
#### List Permissions
```http
GET /api/v1/permissions
```
*Requires: `permission.read` permission*
**Response:**
```json
{
"success": true,
"data": [
{
"name": "server.create",
"description": "Create new servers",
"category": "server"
}
]
}
```
### Monitoring and Analytics
#### Get Server Statistics
```http
GET /api/v1/servers/{id}/stats
```
*Requires: `stats.read` permission*
**Query Parameters:**
- `from` (string): Start date (ISO 8601)
- `to` (string): End date (ISO 8601)
- `granularity` (string): hour, day, week, month
**Response:**
```json
{
"success": true,
"data": {
"totalPlaytime": 3600,
"playerCount": [],
"sessionTypes": [],
"dailyActivity": [],
"recentSessions": []
}
}
```
#### Get System Health
```http
GET /api/v1/system/health
```
*Public endpoint*
**Response:**
```json
{
"success": true,
"data": {
"status": "healthy",
"version": "1.0.0",
"uptime": 3600,
"database": "connected",
"services": {
"steam": "available",
"nssm": "available"
}
}
}
```
### Lookup Data
#### Get Tracks
```http
GET /api/v1/lookup/tracks
```
*Public endpoint*
**Response:**
```json
{
"success": true,
"data": [
{
"name": "monza",
"uniquePitBoxes": 29,
"privateServerSlots": 60
}
]
}
```
#### Get Car Models
```http
GET /api/v1/lookup/cars
```
*Public endpoint*
#### Get Driver Categories
```http
GET /api/v1/lookup/driver-categories
```
*Public endpoint*
#### Get Cup Categories
```http
GET /api/v1/lookup/cup-categories
```
*Public endpoint*
#### Get Session Types
```http
GET /api/v1/lookup/session-types
```
*Public endpoint*
## Webhooks
The API supports webhook notifications for server events:
### Server Status Changes
```json
{
"event": "server.status.changed",
"serverId": 1,
"serverName": "My Server",
"oldStatus": "stopped",
"newStatus": "running",
"timestamp": "2024-01-01T00:00:00Z"
}
```
### Configuration Updates
```json
{
"event": "server.config.updated",
"serverId": 1,
"serverName": "My Server",
"configFile": "configuration",
"userId": "uuid",
"timestamp": "2024-01-01T00:00:00Z"
}
```
## Error Codes
| Code | Description |
|------|-------------|
| `AUTH_REQUIRED` | Authentication required |
| `AUTH_INVALID` | Invalid credentials |
| `AUTH_EXPIRED` | Token expired |
| `PERMISSION_DENIED` | Insufficient permissions |
| `VALIDATION_FAILED` | Request validation failed |
| `RESOURCE_NOT_FOUND` | Requested resource not found |
| `RESOURCE_EXISTS` | Resource already exists |
| `RATE_LIMIT_EXCEEDED` | Rate limit exceeded |
| `SERVER_ERROR` | Internal server error |
| `SERVICE_UNAVAILABLE` | External service unavailable |
## SDK Examples
### JavaScript/Node.js
```javascript
const axios = require('axios');
class ACCServerManagerAPI {
constructor(baseUrl, token) {
this.baseUrl = baseUrl;
this.token = token;
this.client = axios.create({
baseURL: baseUrl,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
}
async getServers() {
const response = await this.client.get('/servers');
return response.data;
}
async createServer(serverData) {
const response = await this.client.post('/servers', serverData);
return response.data;
}
async updateConfig(serverId, file, config, restart = false) {
const response = await this.client.put(
`/servers/${serverId}/config/${file}?restart=${restart}`,
config
);
return response.data;
}
}
// Usage
const api = new ACCServerManagerAPI('http://localhost:3000/api/v1', 'your-jwt-token');
const servers = await api.getServers();
```
### Python
```python
import requests
class ACCServerManagerAPI:
def __init__(self, base_url, token):
self.base_url = base_url
self.headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
def get_servers(self):
response = requests.get(f'{self.base_url}/servers', headers=self.headers)
return response.json()
def create_server(self, server_data):
response = requests.post(
f'{self.base_url}/servers',
json=server_data,
headers=self.headers
)
return response.json()
# Usage
api = ACCServerManagerAPI('http://localhost:3000/api/v1', 'your-jwt-token')
servers = api.get_servers()
```
### Go
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type ACCServerManagerAPI struct {
BaseURL string
Token string
Client *http.Client
}
func NewACCServerManagerAPI(baseURL, token string) *ACCServerManagerAPI {
return &ACCServerManagerAPI{
BaseURL: baseURL,
Token: token,
Client: &http.Client{},
}
}
func (api *ACCServerManagerAPI) request(method, endpoint string, body interface{}) (*http.Response, error) {
var reqBody bytes.Buffer
if body != nil {
json.NewEncoder(&reqBody).Encode(body)
}
req, err := http.NewRequest(method, api.BaseURL+endpoint, &reqBody)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+api.Token)
req.Header.Set("Content-Type", "application/json")
return api.Client.Do(req)
}
func (api *ACCServerManagerAPI) GetServers() (interface{}, error) {
resp, err := api.request("GET", "/servers", nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result interface{}
json.NewDecoder(resp.Body).Decode(&result)
return result, nil
}
```
## Best Practices
### Authentication
1. Store JWT tokens securely (httpOnly cookies for web apps)
2. Implement token refresh mechanism
3. Handle authentication errors gracefully
4. Use HTTPS in production
### Rate Limiting
1. Implement exponential backoff for rate-limited requests
2. Cache responses when appropriate
3. Use batch operations when available
4. Monitor rate limit headers
### Error Handling
1. Always check response status codes
2. Handle network errors gracefully
3. Implement retry logic for transient errors
4. Log errors for debugging
### Performance
1. Use pagination for large datasets
2. Implement client-side caching
3. Use WebSockets for real-time updates
4. Compress request/response bodies
## Support
For API support:
- **Documentation**: Check this guide and interactive Swagger UI
- **Issues**: Report API bugs via GitHub Issues
- **Community**: Join community discussions for help
- **Professional Support**: Contact maintainers for enterprise support
---
**Note**: This API is versioned. Breaking changes will result in a new API version. Always specify the version in your requests.

View File

@@ -0,0 +1,395 @@
# Configuration Guide for ACC Server Manager
## Overview
This guide provides comprehensive information about configuring the ACC Server Manager application, including environment variables, server settings, security configurations, and advanced options.
## 📁 Configuration Files
### Environment Configuration (.env)
The primary configuration is handled through environment variables. Create a `.env` file in the root directory:
```bash
# Copy the example file
cp .env.example .env
```
### Configuration File Hierarchy
1. **Environment Variables** (highest priority)
2. **`.env` file** (medium priority)
3. **Default values** (lowest priority)
## 🔐 Security Configuration
### Required Security Variables
These variables are **mandatory** and the application will not start without them:
```env
# JWT Secret - Used for signing authentication tokens
# Generate with: openssl rand -base64 64
JWT_SECRET=your-super-secure-jwt-secret-minimum-64-characters-long
# Application Secrets - Used for internal encryption and security
# Generate with: openssl rand -hex 32
APP_SECRET=your-32-character-hex-secret-here
APP_SECRET_CODE=your-32-character-hex-secret-code-here
# Encryption Key - Used for AES-256 encryption (MUST be exactly 32 bytes)
# Generate with: openssl rand -hex 32
ENCRYPTION_KEY=your-exactly-32-byte-encryption-key-here
```
## 🌐 Server Configuration
### Basic Server Settings
```env
# HTTP server port
PORT=3000
# CORS allowed origin (comma-separated for multiple origins)
CORS_ALLOWED_ORIGIN=http://localhost:5173
# Database file name (SQLite)
DB_NAME=acc.db
# Default admin password for initial setup (change after first login)
PASSWORD=change-this-default-admin-password
```
**Note**: Most other server configuration options (timeouts, request limits, etc.) are handled by application defaults and don't require environment variables.
## 🗄️ Database Configuration
The application uses SQLite with minimal configuration required:
```env
# Database file name (only setting available via environment)
DB_NAME=acc.db
```
**Note**: Other database settings like connection timeouts, migration settings, and SQL logging are handled internally by the application and don't require environment variables.
## 🎮 Steam Integration
Steam integration settings are managed through the web interface and stored in the database as system configuration. No environment variables are required for Steam integration.
**Configuration via Web Interface:**
- SteamCMD executable path
- NSSM executable path
- Steam credentials (encrypted in database)
- Update schedules and preferences
**Default Values:**
- SteamCMD Path: `c:\steamcmd\steamcmd.exe`
- NSSM Path: `.\nssm.exe`
## 🔥 Windows Service Configuration
Windows service and firewall configurations are handled internally by the application:
**Service Management:**
- NSSM path configured via web interface
- Default service name prefix: `ACC-Server`
- Automatic service creation and management
**Firewall Management:**
- Automatic firewall rule creation
- Default TCP port range: 9600+
- Default UDP port range: 9600+
- Rule cleanup on server deletion
**No environment variables required** - all settings are managed through the system configuration interface.
## 📊 Logging Configuration
Logging is handled internally by the application with sensible defaults:
**Default Logging Behavior:**
- Log level: `info` (adjustable via code)
- Log format: Structured text format
- Log files: Automatic rotation and cleanup
- Security events: Automatically logged
- Error tracking: Comprehensive error logging
**No environment variables required** - logging configuration is built into the application.
## 🚦 Rate Limiting Configuration
Rate limiting is built into the application with secure defaults:
**Built-in Rate Limits:**
- Global: 100 requests per minute per IP
- Authentication: 5 attempts per 15 minutes per IP
- API endpoints: 60 requests per minute per IP
- Configuration updates: Protected with additional limits
**No environment variables required** - rate limiting is automatically applied with appropriate limits for security and performance.
## 📈 Monitoring Configuration
Monitoring features are built into the application:
**Available Monitoring:**
- Health check endpoint: `/health` (always enabled)
- Performance tracking: Built-in performance monitoring
- Error tracking: Automatic error logging and tracking
- Security monitoring: Authentication and authorization events
**No environment variables required** - monitoring is automatically enabled with appropriate defaults.
## 🔄 Backup Configuration
Backup functionality is handled internally:
**Automatic Backups:**
- Database backup before migrations
- Configuration file versioning
- Error recovery mechanisms
**Manual Backups:**
- Database files can be copied manually
- Configuration export/import via web interface
**No environment variables required** - backup features are built into the application workflow.
## 🧪 Development Configuration
### Development Mode Settings
```env
# Enable development mode (NEVER use in production)
DEV_MODE=false
# Enable debug endpoints
DEBUG_ENDPOINTS=false
# Enable hot reload (requires air)
HOT_RELOAD=false
# Disable security features for testing (DANGEROUS)
DISABLE_SECURITY=false
```
### Testing Configuration
```env
# Test database name
TEST_DB_NAME=acc_test.db
# Enable test fixtures
ENABLE_TEST_FIXTURES=false
# Test timeout in seconds
TEST_TIMEOUT=300
```
## 🏭 Production Configuration
### Production Deployment Settings
```env
# Production mode
PRODUCTION=true
# Enable HTTPS enforcement
FORCE_HTTPS=true
# Security-first configuration
SECURITY_STRICT=true
# Disable debug information
DISABLE_DEBUG_INFO=true
# Enable comprehensive monitoring
ENABLE_MONITORING=true
```
### Performance Optimization
```env
# Enable response compression
ENABLE_COMPRESSION=true
# Compression level (1-9)
COMPRESSION_LEVEL=6
# Enable response caching
ENABLE_CACHING=true
# Cache TTL in seconds
CACHE_TTL=300
# Maximum cache size in MB
CACHE_MAX_SIZE=100
```
## 🛠️ Advanced Configuration
### Custom Port Ranges
```env
# Custom TCP port ranges (comma-separated)
CUSTOM_TCP_PORTS=9600-9610,9700-9710
# Custom UDP port ranges (comma-separated)
CUSTOM_UDP_PORTS=9600-9610,9700-9710
# Exclude specific ports (comma-separated)
EXCLUDED_PORTS=9605,9705
```
### Custom Paths
```env
# Custom ACC server installation path
ACC_SERVER_PATH=C:\ACC_Server
# Custom configuration templates path
CONFIG_TEMPLATES_PATH=./templates
# Custom scripts path
SCRIPTS_PATH=./scripts
```
### Integration Settings
```env
# External API endpoints
EXTERNAL_API_ENABLED=false
EXTERNAL_API_URL=https://api.example.com
EXTERNAL_API_KEY=your-api-key-here
# Webhook notifications
WEBHOOK_ENABLED=false
WEBHOOK_URL=https://your-webhook-url.com
WEBHOOK_SECRET=your-webhook-secret
```
## 📋 Configuration Validation
### Validation Rules
The application automatically validates configuration on startup:
1. **Required Variables**: Must be present and non-empty
2. **Numeric Values**: Must be valid numbers within acceptable ranges
3. **File Paths**: Must be accessible and have appropriate permissions
4. **URLs**: Must be valid URL format
5. **Encryption Keys**: Must be exactly 32 bytes for AES-256
### Configuration Errors
Common configuration errors and solutions:
#### "JWT_SECRET must be at least 32 bytes long"
- **Solution**: Generate a longer JWT secret using `openssl rand -base64 64`
#### "ENCRYPTION_KEY must be exactly 32 bytes long"
- **Solution**: Generate a 32-byte key using `openssl rand -hex 32`
#### "Invalid port number"
- **Solution**: Ensure port numbers are between 1 and 65535
#### "SteamCMD not found"
- **Solution**: Install SteamCMD and update the `STEAMCMD_PATH` variable
## 🔧 Configuration Management
### Environment-Specific Configurations
#### Development (.env.development)
```env
DEV_MODE=true
LOG_LEVEL=debug
CORS_ALLOWED_ORIGIN=http://localhost:3000
```
#### Production (.env.production)
```env
PRODUCTION=true
FORCE_HTTPS=true
LOG_LEVEL=warn
SECURITY_STRICT=true
```
#### Testing (.env.test)
```env
DB_NAME=acc_test.db
LOG_LEVEL=error
DISABLE_RATE_LIMITING=true
```
### Configuration Templates
Create configuration templates for common setups:
#### Single Server Setup
```env
# Minimal configuration for single server
PORT=3000
DB_NAME=acc.db
SERVICE_NAME_PREFIX=ACC-Server
```
#### Multi-Server Setup
```env
# Configuration for multiple servers
AUTO_FIREWALL_RULES=true
PORT_RANGE_SIZE=20
SERVICE_START_TIMEOUT=120
```
#### High-Security Setup
```env
# Maximum security configuration
FORCE_HTTPS=true
RATE_LIMIT_AUTH=3
SESSION_TIMEOUT=30
MAX_LOGIN_ATTEMPTS=3
LOCKOUT_DURATION=30
SECURITY_STRICT=true
```
## 🚨 Security Best Practices
### Secret Management
1. **Never commit secrets to version control**
2. **Use environment-specific secret files**
3. **Rotate secrets regularly**
4. **Use secure secret generation methods**
5. **Limit access to configuration files**
### Production Security
1. **Enable HTTPS enforcement**
2. **Configure appropriate CORS origins**
3. **Set up proper rate limiting**
4. **Enable comprehensive logging**
5. **Regular security audits**
## 📞 Configuration Support
### Troubleshooting
For configuration issues:
1. Check the application logs for specific error messages
2. Validate environment variables using the built-in validation
3. Refer to the examples in `.env.example`
4. Test configuration changes in development first
### Getting Help
- **Documentation**: Check this guide and other documentation files
- **Issues**: Report configuration bugs via GitHub Issues
- **Community**: Ask questions in community discussions
- **Professional Support**: Contact maintainers for enterprise support
---
**Note**: Always test configuration changes in a development environment before applying them to production.

691
documentation/DEPLOYMENT.md Normal file
View File

@@ -0,0 +1,691 @@
# Deployment Guide for ACC Server Manager
## Overview
This guide provides comprehensive instructions for deploying the ACC Server Manager in various environments, from development to production. It covers security considerations, performance optimization, monitoring setup, and maintenance procedures.
## 🚀 Quick Start Deployment
### Prerequisites Checklist
- [ ] Windows 10/11 or Windows Server 2016+
- [ ] Go 1.23.0 or later installed
- [ ] Administrative privileges
- [ ] Valid Steam account
- [ ] Internet connection for Steam downloads
### Minimum System Requirements
| Component | Minimum | Recommended |
|-----------|---------|-------------|
| **CPU** | 2 cores | 4+ cores |
| **RAM** | 4 GB | 8+ GB |
| **Storage** | 10 GB free | 50+ GB SSD |
| **Network** | 10 Mbps | 100+ Mbps |
## 📦 Installation Methods
### Method 1: Binary Deployment (Recommended)
1. **Download Release Binary**
```bash
# Download the latest release from GitHub
# Extract to your installation directory
cd C:\ACC-Server-Manager
```
2. **Configure Environment**
```bash
copy .env.example .env
# Edit .env with your configuration
```
3. **Generate Secrets**
```bash
# Generate JWT secret
openssl rand -base64 64
# Generate app secrets
openssl rand -hex 32
# Generate encryption key
openssl rand -hex 32
```
4. **Run Application**
```bash
.\acc-server-manager.exe
```
### Method 2: Source Code Deployment
1. **Clone Repository**
```bash
git clone https://github.com/FJurmanovic/acc-server-manager.git
cd acc-server-manager
```
2. **Install Dependencies**
```bash
go mod download
go mod verify
```
3. **Build Application**
```bash
# Development build
go build -o acc-server-manager.exe cmd/api/main.go
# Production build (optimized)
go build -ldflags="-w -s" -o acc-server-manager.exe cmd/api/main.go
```
4. **Configure and Run**
```bash
copy .env.example .env
# Configure your .env file
.\acc-server-manager.exe
```
## 🔧 Environment Configuration
### Production Environment Variables
Create a production `.env` file:
```env
# ========================================
# PRODUCTION CONFIGURATION
# ========================================
# Security (REQUIRED - Generate unique values)
JWT_SECRET=your-production-jwt-secret-64-chars-minimum
APP_SECRET=your-production-app-secret-32-chars
APP_SECRET_CODE=your-production-secret-code-32-chars
ENCRYPTION_KEY=your-production-encryption-key-32-bytes
# Server Configuration
PORT=8080
HOST=0.0.0.0
PRODUCTION=true
FORCE_HTTPS=true
# Database
DB_NAME=acc_production.db
DB_PATH=./data
# CORS (Set to your actual domain)
CORS_ALLOWED_ORIGIN=https://yourdomain.com
# Security Settings
RATE_LIMIT_GLOBAL=1000
RATE_LIMIT_AUTH=10
SESSION_TIMEOUT=120
MAX_LOGIN_ATTEMPTS=5
LOCKOUT_DURATION=30
# Steam Configuration
STEAMCMD_PATH=C:\steamcmd\steamcmd.exe
NSSM_PATH=C:\nssm\nssm.exe
# Logging
LOG_LEVEL=warn
LOG_FILE=./logs/production.log
LOG_MAX_SIZE=100
LOG_MAX_FILES=10
# Monitoring
HEALTH_CHECK_ENABLED=true
METRICS_ENABLED=true
PERFORMANCE_MONITORING=true
# Backup
AUTO_BACKUP=true
BACKUP_INTERVAL=12
BACKUP_RETENTION=30
BACKUP_DIR=./backups
```
### Development Environment Variables
```env
# ========================================
# DEVELOPMENT CONFIGURATION
# ========================================
# Security (Use secure values even in dev)
JWT_SECRET=dev-jwt-secret-but-still-secure-64-chars-minimum
APP_SECRET=dev-app-secret-32-chars-here
APP_SECRET_CODE=dev-secret-code-32-chars-here
ENCRYPTION_KEY=dev-encryption-key-32-bytes-here
# Server Configuration
PORT=3000
HOST=localhost
DEV_MODE=true
DEBUG_ENDPOINTS=true
# Database
DB_NAME=acc_dev.db
# CORS
CORS_ALLOWED_ORIGIN=http://localhost:3000,http://localhost:5173
# Relaxed Security (Development Only)
RATE_LIMIT_GLOBAL=1000
DISABLE_SECURITY=false
# Logging
LOG_LEVEL=debug
LOG_COLORS=true
ENABLE_SQL_LOGGING=true
# Development Tools
HOT_RELOAD=true
ENABLE_TEST_FIXTURES=true
```
## 🔒 Security Hardening
### SSL/TLS Configuration
1. **Obtain SSL Certificate**
```bash
# Option 1: Let's Encrypt (Free)
certbot certonly --webroot -w /var/www/html -d yourdomain.com
# Option 2: Commercial Certificate
# Purchase and install certificate from CA
```
2. **Configure Reverse Proxy (Nginx)**
```nginx
server {
listen 443 ssl http2;
server_name yourdomain.com;
ssl_certificate /path/to/certificate.crt;
ssl_certificate_key /path/to/private.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE+AESGCM:ECDHE+AES256:ECDHE+AES128:!aNULL:!MD5:!DSS;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
# Redirect HTTP to HTTPS
server {
listen 80;
server_name yourdomain.com;
return 301 https://$server_name$request_uri;
}
```
3. **Configure Application for SSL**
```env
FORCE_HTTPS=true
CORS_ALLOWED_ORIGIN=https://yourdomain.com
```
### Firewall Configuration
1. **Windows Firewall Rules**
```powershell
# Allow application through Windows Firewall
New-NetFirewallRule -DisplayName "ACC Server Manager" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow
# Allow ACC server ports (adjust range as needed)
New-NetFirewallRule -DisplayName "ACC Servers TCP" -Direction Inbound -Protocol TCP -LocalPort 9600-9700 -Action Allow
New-NetFirewallRule -DisplayName "ACC Servers UDP" -Direction Inbound -Protocol UDP -LocalPort 9600-9700 -Action Allow
```
2. **Network Security Groups (Azure)**
```json
{
"securityRules": [
{
"name": "AllowHTTPS",
"properties": {
"protocol": "TCP",
"sourcePortRange": "*",
"destinationPortRange": "443",
"sourceAddressPrefix": "*",
"destinationAddressPrefix": "*",
"access": "Allow",
"priority": 1000,
"direction": "Inbound"
}
}
]
}
```
### User Access Control
1. **Create Dedicated Service Account**
```powershell
# Create service account
New-LocalUser -Name "ACCServiceUser" -Description "ACC Server Manager Service Account" -NoPassword
Add-LocalGroupMember -Group "Users" -Member "ACCServiceUser"
# Set permissions on application directory
icacls "C:\ACC-Server-Manager" /grant "ACCServiceUser:(OI)(CI)F"
```
2. **Configure Service Permissions**
```powershell
# Grant service logon rights
secedit /export /cfg security.inf
# Edit security.inf to add ACCServiceUser to SeServiceLogonRight
secedit /configure /db security.sdb /cfg security.inf
```
## 🏗️ Service Installation
### Windows Service with NSSM
1. **Install NSSM**
```bash
# Download NSSM from https://nssm.cc/
# Extract nssm.exe to C:\nssm\
```
2. **Create Service**
```powershell
# Install service
C:\nssm\nssm.exe install "ACCServerManager" "C:\ACC-Server-Manager\acc-server-manager.exe"
# Configure service
C:\nssm\nssm.exe set "ACCServerManager" DisplayName "ACC Server Manager"
C:\nssm\nssm.exe set "ACCServerManager" Description "Assetto Corsa Competizione Server Manager"
C:\nssm\nssm.exe set "ACCServerManager" Start SERVICE_AUTO_START
C:\nssm\nssm.exe set "ACCServerManager" AppDirectory "C:\ACC-Server-Manager"
C:\nssm\nssm.exe set "ACCServerManager" ObjectName ".\ACCServiceUser" "password"
# Configure logging
C:\nssm\nssm.exe set "ACCServerManager" AppStdout "C:\ACC-Server-Manager\logs\service.log"
C:\nssm\nssm.exe set "ACCServerManager" AppStderr "C:\ACC-Server-Manager\logs\service-error.log"
# Start service
C:\nssm\nssm.exe start "ACCServerManager"
```
3. **Service Management**
```powershell
# Check service status
Get-Service -Name "ACCServerManager"
# Start/Stop service
Start-Service -Name "ACCServerManager"
Stop-Service -Name "ACCServerManager"
# Remove service (if needed)
C:\nssm\nssm.exe remove "ACCServerManager" confirm
```
### Systemd Service (Linux/WSL)
```ini
[Unit]
Description=ACC Server Manager
After=network.target
[Service]
Type=simple
User=accmanager
WorkingDirectory=/opt/acc-server-manager
ExecStart=/opt/acc-server-manager/acc-server-manager
Restart=always
RestartSec=10
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
EnvironmentFile=/opt/acc-server-manager/.env
[Install]
WantedBy=multi-user.target
```
## 📊 Monitoring Setup
### Health Check Monitoring
1. **Configure Health Checks**
```env
HEALTH_CHECK_ENABLED=true
HEALTH_CHECK_PATH=/health
HEALTH_CHECK_TIMEOUT=10
```
2. **External Monitoring (UptimeRobot)**
```bash
# Monitor endpoint: https://yourdomain.com/health
# Expected response: 200 OK with JSON health status
```
### Log Management
1. **Log Rotation Configuration**
```env
LOG_MAX_SIZE=100
LOG_MAX_FILES=10
LOG_MAX_AGE=30
```
2. **Centralized Logging (Optional)**
```yaml
# docker-compose.yml for ELK Stack
version: '3'
services:
elasticsearch:
image: elasticsearch:7.14.0
logstash:
image: logstash:7.14.0
kibana:
image: kibana:7.14.0
```
### Performance Monitoring
1. **Enable Metrics**
```env
METRICS_ENABLED=true
METRICS_PORT=9090
PERFORMANCE_MONITORING=true
```
2. **Prometheus Configuration**
```yaml
# prometheus.yml
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'acc-server-manager'
static_configs:
- targets: ['localhost:9090']
```
## 🔄 Database Management
### Database Backup Strategy
1. **Automated Backups**
```env
AUTO_BACKUP=true
BACKUP_INTERVAL=12
BACKUP_RETENTION=30
BACKUP_DIR=./backups
BACKUP_COMPRESS=true
```
2. **Manual Backup**
```powershell
# Create manual backup
$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
Copy-Item "acc.db" "backups/acc-backup-$timestamp.db"
# Compress backup
Compress-Archive "backups/acc-backup-$timestamp.db" "backups/acc-backup-$timestamp.zip"
```
3. **Backup Verification**
```bash
# Test backup integrity
sqlite3 backup.db "PRAGMA integrity_check;"
```
### Database Migration
1. **Pre-Migration Backup**
```bash
# Always backup before migration
copy acc.db acc-pre-migration-backup.db
```
2. **Migration Process**
```bash
# Migration runs automatically on startup
# Check logs for migration status
tail -f logs/app.log | grep -i migration
```
## 🌐 Load Balancing (High Availability)
### Multiple Instance Setup
1. **Load Balancer Configuration (HAProxy)**
```haproxy
global
daemon
defaults
mode http
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
frontend acc_frontend
bind *:80
default_backend acc_servers
backend acc_servers
balance roundrobin
server acc1 10.0.0.10:8080 check
server acc2 10.0.0.11:8080 check
server acc3 10.0.0.12:8080 check
```
2. **Shared Database Setup**
```bash
# Use network-attached storage for database
# Mount shared volume on all instances
net use Z: \\fileserver\acc-shared
```
### Session Clustering
```env
# Redis for session storage
REDIS_URL=redis://localhost:6379
SESSION_STORE=redis
```
## 🔧 Maintenance Procedures
### Regular Maintenance Tasks
1. **Daily Tasks**
```powershell
# Check service status
Get-Service -Name "ACCServerManager"
# Check disk space
Get-WmiObject -Class Win32_LogicalDisk | Select-Object DeviceID, Size, FreeSpace
# Review error logs
Get-Content "logs/error.log" -Tail 50
```
2. **Weekly Tasks**
```powershell
# Update system patches
Install-Module PSWindowsUpdate
Get-WUInstall -AcceptAll -AutoReboot
# Clean old log files
Get-ChildItem "logs\" -Name "*.log.*" | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)} | Remove-Item
# Verify backup integrity
sqlite3 backups/latest.db "PRAGMA integrity_check;"
```
3. **Monthly Tasks**
```powershell
# Update dependencies
go get -u ./...
go mod tidy
# Security scan
go install github.com/securecodewarrior/gosec/v2/cmd/gosec@latest
gosec ./...
# Performance review
# Review metrics and optimize based on usage patterns
```
### Update Procedures
1. **Backup Current Installation**
```bash
# Stop service
Stop-Service -Name "ACCServerManager"
# Backup application
Copy-Item -Recurse "C:\ACC-Server-Manager" "C:\ACC-Server-Manager-Backup-$(Get-Date -Format 'yyyyMMdd')"
```
2. **Deploy New Version**
```bash
# Download new version
# Replace executable
# Update configuration if needed
# Start service
Start-Service -Name "ACCServerManager"
```
3. **Rollback Procedure**
```bash
# Stop service
Stop-Service -Name "ACCServerManager"
# Restore backup
Remove-Item -Recurse "C:\ACC-Server-Manager"
Copy-Item -Recurse "C:\ACC-Server-Manager-Backup-$(Get-Date -Format 'yyyyMMdd')" "C:\ACC-Server-Manager"
# Start service
Start-Service -Name "ACCServerManager"
```
## 🐛 Troubleshooting
### Common Issues
1. **Service Won't Start**
```powershell
# Check service status
Get-Service -Name "ACCServerManager"
# Check service logs
Get-Content "logs/service-error.log" -Tail 50
# Check Windows Event Log
Get-EventLog -LogName System -Source "ACCServerManager" -Newest 10
```
2. **Database Connection Issues**
```bash
# Check database file permissions
icacls acc.db
# Test database connection
sqlite3 acc.db ".tables"
# Check for database locks
lsof acc.db # Linux
```
3. **Steam Integration Issues**
```bash
# Verify SteamCMD installation
C:\steamcmd\steamcmd.exe +quit
# Check Steam credentials
# Review Steam-related logs
```
### Performance Issues
1. **High CPU Usage**
```bash
# Check for resource-intensive operations
# Monitor process performance
Get-Process -Name "acc-server-manager" | Select-Object CPU, WorkingSet
```
2. **Memory Leaks**
```bash
# Monitor memory usage over time
# Enable detailed memory profiling
go tool pprof http://localhost:8080/debug/pprof/heap
```
3. **Database Performance**
```sql
-- Analyze database performance
PRAGMA table_info(servers);
EXPLAIN QUERY PLAN SELECT * FROM servers WHERE status = 'running';
```
## 📞 Support and Resources
### Documentation Resources
- [README.md](../README.md) - Getting started guide
- [SECURITY.md](SECURITY.md) - Security guidelines
- [API.md](API.md) - API documentation
- [CONFIGURATION.md](CONFIGURATION.md) - Configuration reference
### Community Support
- **GitHub Issues** - Bug reports and feature requests
- **Discord Community** - Real-time community support
- **Wiki** - Community-maintained documentation
### Professional Support
- **Enterprise Support** - Professional deployment assistance
- **Consulting Services** - Custom implementation and optimization
- **Training** - Team training and best practices
### Emergency Contacts
```
Production Issues: support@yourdomain.com
Security Issues: security@yourdomain.com
Emergency Hotline: +1-XXX-XXX-XXXX
```
## 📋 Deployment Checklist
### Pre-Deployment
- [ ] System requirements verified
- [ ] Dependencies installed
- [ ] Secrets generated and secured
- [ ] Configuration reviewed
- [ ] Security hardening applied
- [ ] Backup strategy implemented
- [ ] Monitoring configured
### Post-Deployment
- [ ] Service running successfully
- [ ] Health checks passing
- [ ] Logs being written correctly
- [ ] Database accessible
- [ ] API endpoints responding
- [ ] Frontend integration working
- [ ] Monitoring alerts configured
- [ ] Documentation updated
### Production Readiness
- [ ] SSL/TLS configured
- [ ] Firewall rules applied
- [ ] Performance monitoring active
- [ ] Backup procedures tested
- [ ] Update procedures documented
- [ ] Disaster recovery plan created
- [ ] Team training completed
---
**Remember**: Always test deployments in a staging environment before applying to production!

264
documentation/SECURITY.md Normal file
View File

@@ -0,0 +1,264 @@
# Security Guide for ACC Server Manager
## Overview
This document outlines the security features, best practices, and requirements for the ACC Server Manager application. Following these guidelines is essential for maintaining a secure deployment.
## 🔐 Authentication & Authorization
### JWT Token Security
- **Secret Key**: Must be at least 32 bytes long and cryptographically secure
- **Token Expiration**: Default 24 hours, configurable via environment
- **Refresh Strategy**: Implement token refresh before expiration
- **Storage**: Store tokens securely (httpOnly cookies recommended for web)
### Password Security
- **Hashing**: Uses bcrypt with cost factor 12
- **Requirements**: Minimum 8 characters, must include uppercase, lowercase, digit, and special character
- **Validation**: Real-time strength validation during registration/update
- **Storage**: Never store plain text passwords
### Rate Limiting
- **Global**: 100 requests per minute per IP
- **Authentication**: 5 attempts per 15 minutes per IP+User-Agent
- **API Endpoints**: 60 requests per minute per IP
- **Customizable**: Configurable via environment variables
## 🛡️ Security Headers
The application automatically sets the following security headers:
- `X-Content-Type-Options: nosniff`
- `X-Frame-Options: DENY`
- `X-XSS-Protection: 1; mode=block`
- `Referrer-Policy: strict-origin-when-cross-origin`
- `Content-Security-Policy: [configured policy]`
- `Permissions-Policy: [restricted permissions]`
## 🔒 Data Protection
### Encryption
- **Algorithm**: AES-256-GCM for sensitive data
- **Key Management**: 32-byte keys from environment variables
- **Usage**: Steam credentials and other sensitive configuration data
### Database Security
- **SQLite**: Default database with file-level security
- **Migrations**: Automatic password security upgrades
- **Backup**: Encrypted backups with retention policies
## 🌐 Network Security
### HTTPS
- **Production**: HTTPS enforced in production environments
- **Certificates**: Use valid SSL/TLS certificates
- **Redirection**: Automatic HTTP to HTTPS redirect
### CORS Configuration
- **Origins**: Configured per environment
- **Headers**: Properly configured for API access
- **Credentials**: Enabled for authenticated requests
### Firewall Rules
- **Automatic**: Creates Windows Firewall rules for server ports
- **Management**: Centralized firewall rule management
- **Cleanup**: Automatic rule removal when servers are deleted
## 🚨 Input Validation & Sanitization
### Request Validation
- **Content-Type**: Validates expected content types
- **Size Limits**: 10MB request body limit
- **User-Agent**: Blocks suspicious user agents
- **Timeout**: 30-second request timeout
### Input Sanitization
- **XSS Prevention**: Removes dangerous HTML/JavaScript patterns
- **SQL Injection**: Uses parameterized queries
- **Path Traversal**: Validates file paths and names
## 📊 Monitoring & Logging
### Security Events
- **Authentication**: All login attempts (success/failure)
- **Authorization**: Permission checks and violations
- **Rate Limiting**: Blocked requests and patterns
- **Suspicious Activity**: Automated threat detection
### Log Security
- **Sensitive Data**: Never logs passwords or tokens
- **Format**: Structured logging with security context
- **Retention**: Configurable log retention policies
- **Access**: Restricted access to log files
## ⚙️ Environment Configuration
### Required Environment Variables
```bash
# Critical Security Settings
JWT_SECRET=<64-character-base64-string>
APP_SECRET=<32-character-hex-string>
APP_SECRET_CODE=<32-character-hex-string>
ENCRYPTION_KEY=<32-character-hex-string>
# Security Features
FORCE_HTTPS=true
RATE_LIMIT_GLOBAL=100
RATE_LIMIT_AUTH=5
SESSION_TIMEOUT=60
MAX_LOGIN_ATTEMPTS=5
LOCKOUT_DURATION=15
```
### Secret Generation
Generate secure secrets using:
```bash
# JWT Secret (Base64, 64 bytes)
openssl rand -base64 64
# Application Secrets (Hex, 32 bytes)
openssl rand -hex 32
# Encryption Key (Hex, 32 bytes)
openssl rand -hex 32
```
## 🔄 Security Migrations
### Password Security Upgrade
The application includes an automatic migration that:
1. Upgrades old encrypted passwords to bcrypt hashes
2. Maintains data integrity during the process
3. Provides rollback protection
4. Logs migration status and errors
### Migration Safety
- **Backup**: Automatically creates password backups
- **Validation**: Verifies password strength requirements
- **Recovery**: Handles corrupted or invalid passwords
- **Logging**: Detailed migration logs for auditing
## 🚀 Deployment Security
### Production Checklist
- [ ] Generate unique secrets for production
- [ ] Enable HTTPS with valid certificates
- [ ] Configure appropriate CORS origins
- [ ] Set up proper firewall rules
- [ ] Enable security monitoring and alerting
- [ ] Configure secure backup strategies
- [ ] Review and adjust rate limits
- [ ] Set up log monitoring and analysis
- [ ] Test security configurations
- [ ] Document security procedures
### Container Security (if applicable)
- **Base Images**: Use official, minimal base images
- **User Privileges**: Run as non-root user
- **Secrets**: Use container secret management
- **Network**: Isolate containers appropriately
## 🔍 Security Testing
### Automated Testing
- **Dependencies**: Regular security scanning of dependencies
- **SAST**: Static application security testing
- **DAST**: Dynamic application security testing
- **Penetration Testing**: Regular security assessments
### Manual Testing
- **Authentication Bypass**: Test authentication mechanisms
- **Authorization**: Verify permission controls
- **Input Validation**: Test input sanitization
- **Rate Limiting**: Verify rate limiting effectiveness
## 🚨 Incident Response
### Security Incident Procedures
1. **Detection**: Monitor logs and alerts
2. **Assessment**: Evaluate impact and scope
3. **Containment**: Isolate affected systems
4. **Eradication**: Remove threats and vulnerabilities
5. **Recovery**: Restore normal operations
6. **Lessons Learned**: Document and improve
### Emergency Contacts
- **Security Team**: [Configure your security team contacts]
- **System Administrators**: [Configure admin contacts]
- **Management**: [Configure management contacts]
## 📋 Security Maintenance
### Regular Tasks
- **Weekly**: Review security logs and alerts
- **Monthly**: Update dependencies and security patches
- **Quarterly**: Security configuration review
- **Annually**: Comprehensive security assessment
### Monitoring
- **Failed Logins**: Monitor authentication failures
- **Rate Limit Hits**: Track rate limiting events
- **Error Patterns**: Identify suspicious error patterns
- **Performance**: Monitor for DoS attacks
## 🔗 Additional Resources
### Security Standards
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework)
- [CIS Controls](https://www.cisecurity.org/controls/)
### Go Security
- [Go Security Policy](https://golang.org/security)
- [Secure Coding Practices](https://github.com/OWASP/Go-SCP)
### Dependencies
- [Fiber Security](https://docs.gofiber.io/api/middleware/helmet)
- [GORM Security](https://gorm.io/docs/security.html)
## 📞 Support
For security questions or concerns:
- **Security Issues**: Report via private channels
- **Documentation**: Refer to this guide and code comments
- **Updates**: Monitor security advisories for dependencies
## 🔄 Version History
- **v1.0.0**: Initial security implementation
- **v1.1.0**: Added password security migration
- **v1.2.0**: Enhanced rate limiting and monitoring
---
**Important**: This security guide should be reviewed and updated regularly as the application evolves and new security threats emerge.