Security Architecture¶
Last Updated: 2025-11-25
Ocmonica implements a multi-layered security model designed to protect data and prevent unauthorized access. This document outlines our security features, best practices, and vulnerability reporting procedures.
Security Features¶
Multi-Layered Security Architecture¶
- Transport Security
- HTTPS recommended for production
- HTTP/2 support with h2c for development
-
Configurable TLS settings
-
Authentication & Authorization
- JWT-based authentication with RS256 (4096-bit RSA)
- API key authentication for service accounts
- Role-Based Access Control (RBAC)
-
Multi-tenancy with organization isolation
-
Data Protection
- Bcrypt password hashing (cost factor: 12)
- Secure token storage
- Automatic token rotation
-
Database-level encryption support
-
Attack Prevention
- Rate limiting on all endpoints
- CSRF protection
- SQL injection prevention
- XSS protection headers
- Clickjacking prevention
Authentication¶
JWT Authentication¶
Ocmonica uses RS256 (RSA with SHA-256) for JWT signing, providing asymmetric encryption with strong security guarantees.
Token Types:
- Access Tokens
- Short-lived (default: 15 minutes)
- Carry user identity and permissions
- Cannot be revoked (rely on expiration)
-
Automatically refreshed when threshold reached
-
Refresh Tokens
- Long-lived (default: 7 days)
- Stored in database for revocation
- Single-use with automatic rotation
- Can be revoked individually or in bulk
Key Management:
# Generate RSA key pair (4096-bit)
openssl genrsa -out jwtRS256.key 4096
openssl rsa -in jwtRS256.key -pubout -out jwtRS256.key.pub
# Secure key storage (0600 permissions)
chmod 600 jwtRS256.key
chmod 644 jwtRS256.key.pub
Configuration:
auth:
enabled: true
jwt:
private_key_path: "./keys/jwtRS256.key"
public_key_path: "./keys/jwtRS256.key.pub"
access_ttl: "15m"
refresh_ttl: "168h" # 7 days
refresh_token_rotation: true
issuer: "ocmonica"
API Key Authentication¶
For service-to-service authentication and automation:
Features:
- Per-user API keys with custom names
- Scoped permissions (subset of user permissions)
- Expiration dates
- Last-used tracking
- Individual and bulk revocation
Best Practices:
- Store API keys in environment variables or secrets manager
- Use short expiration periods where possible
- Rotate keys regularly
- Revoke unused keys immediately
- Never commit keys to version control
Creating an API Key:
# Via REST API
curl -X POST http://localhost:8080/api/v1/api-keys \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "CI/CD Pipeline",
"expires_at": "2025-12-31T23:59:59Z"
}'
Media File Authentication¶
Media files (images, videos, audio) are streamed via /api/v1/files/:id/stream?token=${accessToken}.
Security Characteristics:
- JWT token in query parameter (15-minute TTL)
- Log scrubbing removes tokens from access logs
- HTTPS enforced (HSTS header)
- Referrer-Policy prevents token leakage
Threat Model:
- ✅ Protects against: Unauthorized access, cross-org access, token theft (short TTL)
- ⚠️ Does not protect against: Server log exposure (mitigated by scrubbing), browser history
Risk Assessment: Acceptable for private enterprise application
Implementation Details:
- Log scrubbing middleware (
LogScrubberMiddleware) removes tokens from logged URLs - Tokens appear as
token=***REDACTED***in server logs - Short TTL (15 minutes) limits exposure window
- Automatic token rotation on refresh
Authorization¶
Role-Based Access Control (RBAC)¶
Ocmonica implements a flexible RBAC system with organization-scoped permissions.
Permission Model:
| Resource | Permissions | Description |
|---|---|---|
file |
read, write, delete |
File operations |
org |
read, write, admin |
Organization management |
user |
read, write, admin |
User management |
Built-in Roles:
- Admin (System Role)
- All permissions:
file:*,org:*,user:* - Can manage all resources
-
Cannot be modified or deleted
-
Member (System Role)
- Limited permissions:
file:read,file:write,org:read - Default role for new users
-
Cannot be deleted
-
Custom Roles
- Organization-specific
- Configurable permissions
- Can be created, updated, deleted by admins
Permission Checking:
Permissions are enforced at multiple levels:
- Middleware (REST API)
- Interceptors (gRPC)
- Service layer (business logic)
Multi-Tenancy¶
Organization Isolation:
- Users belong to one or more organizations
- Each user has a role per organization
- Resources are scoped to organizations
- Cross-organization access is prevented
Primary Organization:
- Each user has one primary organization
- Used as default context
- Can be changed by user
Password Policy¶
Requirements¶
Default password policy (configurable):
Password Rules:
- Minimum 8 characters (configurable)
- At least one uppercase letter (configurable)
- At least one special symbol (configurable)
- No maximum length limit
- No password history enforcement (future feature)
Storage¶
- Algorithm: bcrypt
- Cost Factor: 12 (2^12 = 4096 iterations)
- Salt: Automatically generated per password
- No reversible encryption: Passwords cannot be recovered
Password Changes¶
When a user changes their password:
- Current password is verified
- New password is validated against policy
- Password is hashed with bcrypt
- All refresh tokens are revoked (security measure)
- User must re-authenticate
Rate Limiting¶
Global Rate Limits¶
Applied to all endpoints:
Authentication Endpoints¶
Stricter limits on sensitive endpoints:
Login & Registration:
Other Auth Operations (refresh, logout):
Rate Limit Headers¶
Responses include standard rate limit headers:
X-RateLimit-Limit: Maximum requests per windowX-RateLimit-Remaining: Requests remainingX-RateLimit-Reset: Unix timestamp when limit resets
Customization¶
Rate limits can be configured via environment variables:
# Global rate limit (requests per minute)
OCMONICA_RATE_LIMIT_GLOBAL=100
# Auth endpoints rate limit
OCMONICA_RATE_LIMIT_AUTH=5
Security Headers¶
Ocmonica implements OWASP-recommended security headers:
HTTP Headers¶
- Content-Security-Policy
- Prevents XSS attacks
-
Blocks framing (clickjacking protection)
-
X-Frame-Options
- Additional clickjacking protection
-
Prevents embedding in frames/iframes
-
X-Content-Type-Options
- Prevents MIME type sniffing
-
Reduces XSS attack surface
-
Strict-Transport-Security (HSTS)
- Forces HTTPS for 2 years
- Includes all subdomains
-
Eligible for browser preload lists
-
Referrer-Policy
- Limits referrer information leakage
- Balances privacy and functionality
CSRF Protection¶
Cross-Site Request Forgery protection is implemented:
- Double-submit cookie pattern for REST API
- Token validation on state-changing operations
- SameSite cookie attribute
- Origin/Referer header validation
Default Credentials¶
Bootstrap Admin User¶
On first startup, Ocmonica creates:
- Default organization:
default - Default admin user:
admin - Default password:
admin123
Security Warning
CRITICAL: Change the default admin password immediately in production!
Production Deployment¶
Option 1: Environment Variable (Recommended)
Option 2: Change After First Login
curl -X POST http://localhost:8080/api/v1/auth/change-password \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"current_password": "admin123",
"new_password": "your-secure-password"
}'
Best Practices¶
Deployment¶
- Always use HTTPS in production
- Secure secret storage - Use environment variables or secrets managers
- Database security - Use authentication, restrict network access, enable encryption
- Key rotation - Rotate JWT signing keys and API keys periodically
Application Security¶
- Regular updates - Keep dependencies updated, monitor security advisories
- Audit logging - Enable comprehensive logging, monitor authentication attempts
- Least privilege - Grant minimal necessary permissions
- Input validation - All user input is validated
Threat Model¶
Protected Against¶
✅ SQL Injection - Parameterized queries ✅ XSS - Content Security Policy + escaping ✅ CSRF - Double-submit cookie pattern ✅ Clickjacking - X-Frame-Options + CSP ✅ Brute Force - Rate limiting ✅ Session Hijacking - Secure token storage ✅ Password Cracking - Bcrypt with high cost ✅ Token Replay - Token expiration + rotation
Additional Considerations¶
⚠️ DDoS Protection: Consider using Cloudflare or AWS Shield ⚠️ Insider Threats: Implement audit logging and access reviews ⚠️ Supply Chain: Regularly audit dependencies for vulnerabilities
Monitoring & Alerting¶
Security Metrics¶
Monitor these metrics via Prometheus/Grafana:
ocmonica_auth_attempts_total{status="failure"}- Failed login attemptsocmonica_rate_limit_hits_total- Rate limit violationsocmonica_token_refreshes_total- Token refresh rateocmonica_api_key_usage_total- API key usage
Alert Conditions¶
Set up alerts for:
- Unusual number of failed login attempts
- Spike in rate limit hits
- Unexpected admin actions
- Database connection errors
- High request latency
Reporting Vulnerabilities¶
Responsible Disclosure¶
We take security seriously. If you discover a security vulnerability:
- DO NOT open a public GitHub issue
- DO NOT disclose the vulnerability publicly
- DO email security@ocmonica.dev with details
Response Timeline¶
- 24 hours: Initial acknowledgment
- 72 hours: Preliminary assessment
- 7 days: Detailed response with timeline
- 30 days: Fix deployed (for confirmed vulnerabilities)
Security Checklist¶
Pre-Production¶
- Change default admin password
- Generate production JWT keys (4096-bit)
- Configure HTTPS/TLS
- Set secure password policy
- Enable rate limiting
- Configure CORS properly
- Set up monitoring and alerting
- Review and harden database access
Post-Deployment¶
- Monitor authentication metrics
- Review access logs regularly
- Rotate JWT keys quarterly
- Update dependencies monthly
- Conduct security audits annually