# Configuration Guide This document explains how to configure the Rust web application using environment variables and configuration files. ## Overview The application uses environment variables loaded from a `.env` file for configuration. This approach provides flexibility for different deployment environments while keeping sensitive data secure. ## Environment File Setup 1. **Copy the example file:** ```bash cp .env.example .env ``` 2. **Edit the configuration:** ```bash # Edit with your preferred editor nano .env # or vim .env ``` ## Configuration Options ### Server Configuration | Variable | Type | Default | Description | |----------|------|---------|-------------| | `SERVER_PROTOCOL` | string | `http` | Server protocol (`http` or `https`) | | `SERVER_HOST` | string | `127.0.0.1` | Server host address | | `SERVER_PORT` | integer | `3030` | Server port number | | `ENVIRONMENT` | string | `DEV` | Environment mode (`DEV` or `PROD`) | | `LOG_LEVEL` | string | `info` | Log level (`error`, `warn`, `info`, `debug`, `trace`) | | `RELOAD_PORT` | integer | `3031` | Port for development hot reload | ### TLS Configuration | Variable | Type | Default | Description | |----------|------|---------|-------------| | `TLS_CERT_PATH` | string | `./certs/cert.pem` | Path to TLS certificate file | | `TLS_KEY_PATH` | string | `./certs/key.pem` | Path to TLS private key file | **Note:** TLS configuration is only used when `SERVER_PROTOCOL=https` ### Static Files | Variable | Type | Default | Description | |----------|------|---------|-------------| | `STATIC_DIR` | string | `target/site` | Static files directory | | `ASSETS_DIR` | string | `public` | Assets directory | | `SITE_PKG_DIR` | string | `pkg` | Site package directory | ### Security & Features | Variable | Type | Default | Description | |----------|------|---------|-------------| | `CORS_ALLOWED_ORIGINS` | string | `http://localhost:3030,http://127.0.0.1:3030` | Comma-separated list of allowed CORS origins | | `SESSION_SECRET` | string | `change-this-in-production` | Secret key for session management | | `ENABLE_METRICS` | boolean | `false` | Enable metrics collection | | `ENABLE_HEALTH_CHECK` | boolean | `true` | Enable health check endpoints | | `ENABLE_COMPRESSION` | boolean | `true` | Enable response compression | ### Email Configuration | Variable | Type | Default | Description | |----------|------|---------|-------------| | `EMAIL_ENABLED` | boolean | `true` | Enable/disable email functionality | | `EMAIL_PROVIDER` | string | `console` | Email provider (`smtp`, `sendgrid`, `console`) | | `EMAIL_FROM_ADDRESS` | string | `noreply@yourapp.com` | Default sender email address | | `EMAIL_FROM_NAME` | string | `Your App Name` | Default sender name | | `EMAIL_TEMPLATE_DIR` | string | `templates/email` | Email template directory | | `SMTP_HOST` | string | `smtp.gmail.com` | SMTP server host | | `SMTP_PORT` | integer | `587` | SMTP server port | | `SMTP_USERNAME` | string | - | SMTP username | | `SMTP_PASSWORD` | string | - | SMTP password | | `SMTP_USE_TLS` | boolean | `false` | Use TLS encryption | | `SMTP_USE_STARTTLS` | boolean | `true` | Use STARTTLS encryption | | `SENDGRID_API_KEY` | string | - | SendGrid API key | | `SENDGRID_ENDPOINT` | string | `https://api.sendgrid.com/v3/mail/send` | SendGrid API endpoint | ## Protocol Configuration ### HTTP Configuration For standard HTTP deployment: ```env SERVER_PROTOCOL=http SERVER_HOST=0.0.0.0 SERVER_PORT=3030 ``` ### HTTPS Configuration For HTTPS deployment with TLS encryption: ```env SERVER_PROTOCOL=https SERVER_HOST=0.0.0.0 SERVER_PORT=3030 TLS_CERT_PATH=./certs/cert.pem TLS_KEY_PATH=./certs/key.pem ``` ## TLS Certificate Setup ### Development (Self-Signed Certificates) 1. **Generate certificates automatically:** ```bash ./scripts/generate_certs.sh ``` 2. **Or use the setup script:** ```bash ./scripts/setup_dev.sh ``` ### Production (Valid Certificates) 1. **Obtain certificates from a Certificate Authority (CA)** 2. **Using Let's Encrypt (recommended):** ```bash # Install certbot sudo apt-get install certbot # Ubuntu/Debian brew install certbot # macOS # Generate certificate sudo certbot certonly --standalone -d yourdomain.com ``` 3. **Update .env file:** ```env TLS_CERT_PATH=/etc/letsencrypt/live/yourdomain.com/fullchain.pem TLS_KEY_PATH=/etc/letsencrypt/live/yourdomain.com/privkey.pem ``` ## Environment-Specific Configuration ### Development Environment ```env SERVER_PROTOCOL=http SERVER_HOST=127.0.0.1 SERVER_PORT=3030 ENVIRONMENT=DEV LOG_LEVEL=debug ENABLE_METRICS=false ENABLE_HEALTH_CHECK=true ENABLE_COMPRESSION=false ``` ### Production Environment ```env SERVER_PROTOCOL=https SERVER_HOST=0.0.0.0 SERVER_PORT=443 ENVIRONMENT=PROD LOG_LEVEL=info ENABLE_METRICS=true ENABLE_HEALTH_CHECK=true ENABLE_COMPRESSION=true TLS_CERT_PATH=/etc/ssl/certs/your-cert.pem TLS_KEY_PATH=/etc/ssl/private/your-key.pem SESSION_SECRET=your-secure-random-secret-key ``` ## Validation & Error Handling The application validates configuration on startup: - **Port validation:** Ensures port numbers are valid (1-65535) - **TLS validation:** Verifies certificate and key files exist when HTTPS is enabled - **Path validation:** Checks that specified directories exist - **Security validation:** Warns about insecure defaults in production ## Configuration Loading Order 1. **Environment variables** (highest priority) 2. **`.env` file** in the project root 3. **Default values** (lowest priority) ## Security Best Practices ### Development - Use HTTP for local development - Keep default session secrets for development - Enable debug logging ### Production - **Always use HTTPS** in production - **Generate secure session secrets:** Use a cryptographically secure random string - **Restrict CORS origins:** Only allow necessary domains - **Use proper TLS certificates:** Avoid self-signed certificates - **Set appropriate log levels:** Use `info` or `warn` to avoid sensitive data in logs - **Enable compression:** Reduces bandwidth usage - **Monitor with metrics:** Enable metrics collection for monitoring ## Example Configurations ### Local Development ```env SERVER_PROTOCOL=http SERVER_HOST=127.0.0.1 SERVER_PORT=3030 ENVIRONMENT=DEV LOG_LEVEL=debug ``` ### Docker Development ```env SERVER_PROTOCOL=http SERVER_HOST=0.0.0.0 SERVER_PORT=3030 ENVIRONMENT=DEV LOG_LEVEL=info ``` ### Production with Load Balancer ```env # App runs on HTTP behind HTTPS load balancer SERVER_PROTOCOL=http SERVER_HOST=0.0.0.0 SERVER_PORT=8080 ENVIRONMENT=PROD LOG_LEVEL=info ENABLE_METRICS=true ``` ### Production with Direct HTTPS ```env # App handles HTTPS directly SERVER_PROTOCOL=https SERVER_HOST=0.0.0.0 SERVER_PORT=443 ENVIRONMENT=PROD LOG_LEVEL=info ENABLE_METRICS=true TLS_CERT_PATH=/etc/ssl/certs/fullchain.pem TLS_KEY_PATH=/etc/ssl/private/privkey.pem # Email configuration for production EMAIL_ENABLED=true EMAIL_PROVIDER=sendgrid EMAIL_FROM_ADDRESS=noreply@yourdomain.com EMAIL_FROM_NAME=Your Production App SENDGRID_API_KEY=your-sendgrid-api-key ``` ### Development with Email Testing ```env # Development with console email output SERVER_PROTOCOL=http SERVER_HOST=127.0.0.1 SERVER_PORT=3030 ENVIRONMENT=DEV LOG_LEVEL=debug # Email configuration for development EMAIL_ENABLED=true EMAIL_PROVIDER=console EMAIL_FROM_ADDRESS=dev@localhost EMAIL_FROM_NAME=Dev App ``` ### Staging with SMTP Testing ```env # Staging environment with email testing SERVER_PROTOCOL=https SERVER_HOST=0.0.0.0 SERVER_PORT=443 ENVIRONMENT=PROD LOG_LEVEL=info # Email configuration for staging EMAIL_ENABLED=true EMAIL_PROVIDER=smtp EMAIL_FROM_ADDRESS=staging@yourdomain.com EMAIL_FROM_NAME=Staging App SMTP_HOST=smtp.mailtrap.io SMTP_PORT=2525 SMTP_USERNAME=your-mailtrap-username SMTP_PASSWORD=your-mailtrap-password ``` ## Environment Variables Reference ### Required Variables None - all variables have sensible defaults. ### Optional Variables All configuration variables are optional and have defaults suitable for development. ### Sensitive Variables - `SESSION_SECRET`: Should be changed in production - `TLS_KEY_PATH`: Path to private key file - `SMTP_PASSWORD`: SMTP server password or app password - `SENDGRID_API_KEY`: SendGrid API key for email delivery - Database credentials (if using databases) - API keys (if using external APIs) ## Troubleshooting ### Common Issues 1. **Port already in use:** ``` Error: Failed to bind to address ``` Solution: Change `SERVER_PORT` to an available port 2. **TLS certificate not found:** ``` Error: TLS certificate file not found ``` Solution: Generate certificates or correct the `TLS_CERT_PATH` 3. **Permission denied:** ``` Error: Permission denied ``` Solution: Run with appropriate permissions or use a port > 1024 4. **Email delivery failed:** ``` Error: Failed to send email ``` Solution: Check email provider configuration and credentials 5. **Email template not found:** ``` Error: Template not found ``` Solution: Verify template directory structure and file naming ### Configuration Validation Run the application with invalid configuration to see validation errors: ```bash # The application will show configuration errors on startup cargo run ``` ### Testing Configuration 1. **HTTP setup:** ```bash curl http://127.0.0.1:3030/ ``` 2. **HTTPS setup:** ```bash curl -k https://127.0.0.1:3030/ ``` 3. **Email functionality:** ```bash # Test contact form submission curl -X POST http://127.0.0.1:3030/api/contact \ -H "Content-Type: application/json" \ -d '{"name":"Test User","email":"test@example.com","subject":"Test","message":"Test message"}' ``` ## Advanced Configuration ### Custom Certificate Paths ```env TLS_CERT_PATH=/custom/path/to/cert.pem TLS_KEY_PATH=/custom/path/to/key.pem ``` ### Multiple Domains For applications serving multiple domains, configure CORS appropriately: ```env CORS_ALLOWED_ORIGINS=https://domain1.com,https://domain2.com,https://www.domain1.com # Email configuration EMAIL_ENABLED=true EMAIL_PROVIDER=sendgrid EMAIL_FROM_ADDRESS=noreply@yourdomain.com SENDGRID_API_KEY=your-sendgrid-api-key ``` ## Email Provider Configuration ### Console Provider (Development) For development and testing, the console provider prints emails to the terminal: ```env EMAIL_ENABLED=true EMAIL_PROVIDER=console EMAIL_FROM_ADDRESS=noreply@yourapp.com EMAIL_FROM_NAME=Your App Name ``` ### SMTP Provider For standard SMTP servers (Gmail, Outlook, custom servers): ```env EMAIL_ENABLED=true EMAIL_PROVIDER=smtp EMAIL_FROM_ADDRESS=noreply@yourdomain.com EMAIL_FROM_NAME=Your Production App SMTP_HOST=smtp.gmail.com SMTP_PORT=587 SMTP_USERNAME=your-email@gmail.com SMTP_PASSWORD=your-app-specific-password SMTP_USE_STARTTLS=true ``` #### Gmail Configuration For Gmail, you need to use App Passwords: 1. Enable 2-Factor Authentication 2. Generate an App Password 3. Use the App Password in `SMTP_PASSWORD` ```env SMTP_HOST=smtp.gmail.com SMTP_PORT=587 SMTP_USERNAME=your-email@gmail.com SMTP_PASSWORD=your-16-char-app-password SMTP_USE_STARTTLS=true ``` #### Outlook Configuration ```env SMTP_HOST=smtp-mail.outlook.com SMTP_PORT=587 SMTP_USERNAME=your-email@outlook.com SMTP_PASSWORD=your-password SMTP_USE_STARTTLS=true ``` ### SendGrid Provider For production email delivery using SendGrid: ```env EMAIL_ENABLED=true EMAIL_PROVIDER=sendgrid EMAIL_FROM_ADDRESS=noreply@yourdomain.com EMAIL_FROM_NAME=Your Production App SENDGRID_API_KEY=your-sendgrid-api-key ``` ## Email Template Structure The email system uses internationalized templates with automatic language fallback: ### Template Directory Structure ``` templates/email/ ├── en_/ # English templates (default) │ ├── html/ # HTML email templates │ │ ├── contact.hbs # Contact form template │ │ └── notification.hbs # Notification template │ └── text/ # Plain text templates │ ├── contact.hbs │ └── notification.hbs ├── es_/ # Spanish templates │ ├── html/ │ └── text/ └── README.md # Template documentation ``` ### Template Configuration ```env EMAIL_TEMPLATE_DIR=templates/email ``` ### Language Detection The system automatically detects language preferences from: 1. **User Profile**: Authenticated user's saved language preference 2. **Request Headers**: `Accept-Language` HTTP header 3. **Default Fallback**: English (`en`) ### Template Variables Common template variables available in all email templates: - `{{name}}` - User's name - `{{email}}` - User's email address - `{{subject}}` - Message subject - `{{message}}` - Message content - `{{submitted_at}}` - Submission timestamp - `{{form_type}}` - Type of form (contact, support, etc.) - `{{ip_address}}` - Sender's IP address (optional) - `{{user_agent}}` - Browser information (optional) ### Custom Handlebars Helpers - `{{date_format submitted_at "%B %d, %Y at %I:%M %p UTC"}}` - Format dates - `{{capitalize form_type}}` - Capitalize first letter - `{{truncate user_agent 100}}` - Truncate text to specified length - `{{default action_text "Click Here"}}` - Provide default values - `{{url_encode email}}` - URL encode text ### Development with HTTPS To test HTTPS locally: 1. Generate self-signed certificates 2. Configure HTTPS in .env 3. Accept browser security warnings 4. Or add certificates to your system's trust store ## Migration from Previous Versions If migrating from a version without environment-based configuration: 1. Create `.env` file from `.env.example` 2. Review and update configuration values 3. Test the application startup 4. Update any deployment scripts to use new configuration ## Support For configuration issues: 1. Check the application logs for validation errors 2. Verify file permissions for certificate files 3. Ensure all paths are correct and accessible 4. Review the security settings for production deployments ## Email Template Development ### Creating New Templates 1. **Create language directory:** ```bash mkdir -p templates/email/fr_/html mkdir -p templates/email/fr_/text ``` 2. **Add template files:** ```bash # Create French contact template touch templates/email/fr_/html/contact.hbs touch templates/email/fr_/text/contact.hbs ``` 3. **Template content example:** ```handlebars
Nom: {{name}}
Email: {{email}}
Sujet: {{subject}}
Message:
{{message}}
Envoyé le: {{date_format submitted_at "%d %B %Y à %H:%M UTC"}}
``` ### Testing Email Templates 1. **Use console provider for development:** ```env EMAIL_PROVIDER=console ``` 2. **Test with different languages:** ```bash # Test French template curl -H "Accept-Language: fr-FR,fr;q=0.9" \ -X POST http://127.0.0.1:3030/api/contact \ -d '{"name":"Test","email":"test@example.com","subject":"Test","message":"Test"}' ``` ### Security Best Practices 1. **Never commit sensitive email credentials** 2. **Use environment variables for API keys** 3. **Enable STARTTLS for SMTP connections** 4. **Use App Passwords for Gmail** 5. **Regularly rotate API keys** 6. **Monitor email sending quotas** ## Related Documentation - [Email Templates](templates/email/README.md) - Detailed email template documentation - [DaisyUI Integration](DAISYUI_INTEGRATION.md) - UI component configuration - [README.md](README.md) - General project information - [Development Setup](scripts/setup_dev.sh) - Automated setup script