# b0esche.cloud Security Guide

This document describes the security architecture, configurations, and best practices for b0esche.cloud.

## Security Architecture Overview

```
                              Internet
                                  │
                                  ▼
                        ┌─────────────────┐
                        │   Traefik       │ ← Only public entrypoint
                        │  (443, 80)      │   TLS termination
                        └────────┬────────┘
                                 │
                 ┌───────────────┼───────────────┐
                 ▼               ▼               ▼
          ┌──────────┐    ┌──────────┐    ┌──────────┐
          │ Flutter  │    │  Go API  │    │Collabora │
          │  Web     │    │ Backend  │    │ Online   │
          └──────────┘    └────┬─────┘    └──────────┘
                               │
                 ┌─────────────┼─────────────┐
                 ▼             ▼             ▼
          ┌──────────┐  ┌──────────┐  ┌──────────┐
          │PostgreSQL│  │Nextcloud │  │  Redis   │
          │(internal)│  │(storage) │  │(sessions)│
          └──────────┘  └──────────┘  └──────────┘
```

## Authentication Security

### Primary: Passkeys (WebAuthn)

- **Protocol**: WebAuthn/FIDO2 standard
- **Cryptography**: ECDSA with P-256 or RSA with 2048+ bits
- **Origin Binding**: Strictly bound to `https://b0esche.cloud`
- **RP ID**: `b0esche.cloud`
- **Challenge Generation**: 32 bytes of cryptographically secure random data
- **Challenge Expiry**: 60 seconds

### Fallback: Password Authentication

- **Hashing**: Argon2id (OWASP recommended parameters)
  - Time: 2 iterations
  - Memory: 19 MB
  - Threads: 1
  - Key Length: 32 bytes
- **Password Requirements**: Minimum 8 characters (enforced server-side)

### Session Management

- **Token Format**: JWT (HS256)
- **Token Lifetime**: 15 minutes (auto-refresh enabled)
- **Session Storage**: Database-backed with revocation support
- **Session Validation**: Every request validates session is not revoked

## Authorization

### Role-Based Access Control (RBAC)

| Role | Level | Permissions |
|------|-------|-------------|
| superadmin | 3 | Full system access, user management |
| admin | 2 | Organization management, user roles |
| user | 1 | Personal files, org membership |

### Organization Scoping

- All file operations are scoped to authenticated user + organization
- Membership verification on every org-scoped request
- Permission checks via middleware pipeline

## API Security

### Rate Limiting

- **General Endpoints**: 100 requests/minute per IP
- **Auth Endpoints**: 10 requests/minute per IP (brute-force protection)
- **Implementation**: Sliding window algorithm

### Input Validation

- **Path Traversal Prevention**: All file paths are sanitized
  - `..` sequences are rejected
  - Paths are cleaned and normalized
- **UUID Validation**: All IDs are validated as proper UUIDs
- **File Size Limits**: 32MB maximum upload size

### Output Security

- **No Stack Traces**: Error responses never include stack traces
- **Structured Errors**: Consistent error format with codes:
  - `UNAUTHENTICATED` (401)
  - `PERMISSION_DENIED` (403)
  - `NOT_FOUND` (404)
  - `INVALID_ARGUMENT` (400)
  - `INTERNAL` (500)
- **No Secrets in Logs**: Passwords and tokens are never logged

### Security Headers

The application sets comprehensive security headers:

- **X-Content-Type-Options**: `nosniff` - Prevents MIME type sniffing
- **X-Frame-Options**: `DENY` - Prevents clickjacking (except for WOPI endpoints)
- **X-XSS-Protection**: `1; mode=block` - Enables XSS filtering
- **Content-Security-Policy**: Restrictive policy allowing only necessary sources
- **Referrer-Policy**: `strict-origin-when-cross-origin` - Controls referrer information
- **CORS**: Restricted to allowed origins with credentials support

## Network Security

### TLS Configuration

- **Protocol**: TLS 1.2 minimum (TLS 1.3 preferred)
- **Certificate**: Let's Encrypt (auto-renewed via DNS-01 challenge)
- **HSTS**: Enabled with 1-year max-age

### CORS Policy

- **Allowed Origins**: 
  - `https://b0esche.cloud`
  - `https://www.b0esche.cloud`
  - `https://*.b0esche.cloud`
- **Credentials**: Allowed
- **Methods**: GET, POST, PUT, PATCH, DELETE, OPTIONS
- **Max Age**: 3600 seconds

### Port Exposure

| Port | Service | Exposed To |
|------|---------|------------|
| 443 | Traefik (HTTPS) | Internet |
| 80 | Traefik (HTTP→HTTPS) | Internet |
| 22 | SSH | Internet (key-only) |
| 8080 | Go Backend | Internal only |
| 5432 | PostgreSQL | Internal only |
| 9980 | Collabora | Internal only |

## Secure Development Practices

### Code Security Checklist

- [ ] No hardcoded secrets
- [ ] No debug logging of sensitive data
- [ ] Input validation on all endpoints
- [ ] Path sanitization for file operations
- [ ] Parameterized SQL queries (no string concatenation)
- [ ] Error responses don't leak internal details

### Deployment Security

- [ ] Production secrets via environment variables only
- [ ] `.env` files excluded from git
- [ ] Docker containers run as non-root where possible
- [ ] Regular dependency updates

## Incident Response

### Logging

All security-relevant events are logged:
- Login attempts (success/failure)
- Session creation/revocation
- Permission denials
- Rate limit violations
- File access (view/edit/delete)

### Log Format

```
[LEVEL] req_id=<uuid> user_id=<uuid> org_id=<uuid> action=<string>: message
```

### Audit Trail

The `activities` table stores:
- User actions (file operations, org changes)
- Timestamps
- Associated resources
- Success/failure status

## Security Contacts

For security issues, contact the system administrator directly.
Do not report security vulnerabilities in public issue trackers.

## Changelog

| Date | Change |
|------|--------|
| 2026-01-13 | Initial security documentation |
| 2026-01-13 | Removed debug password logging |
| 2026-01-13 | Added rate limiting |
| 2026-01-13 | Added path traversal protection |
