Skip to content

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

  1. Transport Security
  2. HTTPS recommended for production
  3. HTTP/2 support with h2c for development
  4. Configurable TLS settings

  5. Authentication & Authorization

  6. JWT-based authentication with RS256 (4096-bit RSA)
  7. API key authentication for service accounts
  8. Role-Based Access Control (RBAC)
  9. Multi-tenancy with organization isolation

  10. Data Protection

  11. Bcrypt password hashing (cost factor: 12)
  12. Secure token storage
  13. Automatic token rotation
  14. Database-level encryption support

  15. Attack Prevention

  16. Rate limiting on all endpoints
  17. CSRF protection
  18. SQL injection prevention
  19. XSS protection headers
  20. Clickjacking prevention

Authentication

JWT Authentication

Ocmonica uses RS256 (RSA with SHA-256) for JWT signing, providing asymmetric encryption with strong security guarantees.

Token Types:

  1. Access Tokens
  2. Short-lived (default: 15 minutes)
  3. Carry user identity and permissions
  4. Cannot be revoked (rely on expiration)
  5. Automatically refreshed when threshold reached

  6. Refresh Tokens

  7. Long-lived (default: 7 days)
  8. Stored in database for revocation
  9. Single-use with automatic rotation
  10. 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:

  1. Admin (System Role)
  2. All permissions: file:*, org:*, user:*
  3. Can manage all resources
  4. Cannot be modified or deleted

  5. Member (System Role)

  6. Limited permissions: file:read, file:write, org:read
  7. Default role for new users
  8. Cannot be deleted

  9. Custom Roles

  10. Organization-specific
  11. Configurable permissions
  12. 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):

auth:
  password:
    min_length: 8
    require_upper: true
    require_symbol: true

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:

  1. Current password is verified
  2. New password is validated against policy
  3. Password is hashed with bcrypt
  4. All refresh tokens are revoked (security measure)
  5. User must re-authenticate

Rate Limiting

Global Rate Limits

Applied to all endpoints:

Rate: 100 requests per minute per IP
Burst: 20 requests

Authentication Endpoints

Stricter limits on sensitive endpoints:

Login & Registration:

Rate: 5 requests per minute per IP
Burst: 2 requests

Other Auth Operations (refresh, logout):

Rate: 10 requests per minute per IP
Burst: 5 requests

Rate Limit Headers

Responses include standard rate limit headers:

  • X-RateLimit-Limit: Maximum requests per window
  • X-RateLimit-Remaining: Requests remaining
  • X-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

  1. Content-Security-Policy
    default-src 'self'; frame-ancestors 'none'
    
  2. Prevents XSS attacks
  3. Blocks framing (clickjacking protection)

  4. X-Frame-Options

    DENY
    

  5. Additional clickjacking protection
  6. Prevents embedding in frames/iframes

  7. X-Content-Type-Options

    nosniff
    

  8. Prevents MIME type sniffing
  9. Reduces XSS attack surface

  10. Strict-Transport-Security (HSTS)

    max-age=63072000; includeSubDomains; preload
    

  11. Forces HTTPS for 2 years
  12. Includes all subdomains
  13. Eligible for browser preload lists

  14. Referrer-Policy

    strict-origin-when-cross-origin
    

  15. Limits referrer information leakage
  16. 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)

export OCMONICA_DEFAULT_ADMIN_PASSWORD="your-secure-password"
./ocmonica

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

  1. Always use HTTPS in production
  2. Secure secret storage - Use environment variables or secrets managers
  3. Database security - Use authentication, restrict network access, enable encryption
  4. Key rotation - Rotate JWT signing keys and API keys periodically

Application Security

  1. Regular updates - Keep dependencies updated, monitor security advisories
  2. Audit logging - Enable comprehensive logging, monitor authentication attempts
  3. Least privilege - Grant minimal necessary permissions
  4. 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 attempts
  • ocmonica_rate_limit_hits_total - Rate limit violations
  • ocmonica_token_refreshes_total - Token refresh rate
  • ocmonica_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:

  1. DO NOT open a public GitHub issue
  2. DO NOT disclose the vulnerability publicly
  3. 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

Additional Resources